blob: 233f7f68b6ea403dfc13a1eb55753c5f1e485113 [file] [log] [blame]
Kostya Serebryanye2a0e412012-02-13 22:50:51 +00001//===-- ThreadSanitizer.cpp - race detector -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of ThreadSanitizer, a race detector.
11//
12// The tool is under development, for the details about previous versions see
13// http://code.google.com/p/data-race-test
14//
15// The instrumentation phase is quite simple:
16// - Insert calls to run-time library before every memory access.
17// - Optimizations may apply to avoid instrumenting some of the accesses.
18// - Insert calls at function entry/exit.
19// The rest is handled by the run-time library.
20//===----------------------------------------------------------------------===//
21
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/StringExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
Kostya Serebryany463aa812013-03-28 11:21:13 +000031#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Kostya Serebryanyabad0022012-03-14 23:33:24 +000037#include "llvm/Support/CommandLine.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000038#include "llvm/Support/Debug.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000039#include "llvm/Support/MathExtras.h"
Kostya Serebryany6f8a7762012-03-26 17:35:03 +000040#include "llvm/Support/raw_ostream.h"
Kostya Serebryanya1259772012-04-27 07:31:53 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne015370e2013-07-09 22:02:49 +000043#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000044
45using namespace llvm;
46
Chandler Carruth964daaa2014-04-22 02:55:47 +000047#define DEBUG_TYPE "tsan"
48
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000049static cl::opt<std::string> ClBlacklistFile("tsan-blacklist",
Kostya Serebryanyabad0022012-03-14 23:33:24 +000050 cl::desc("Blacklist file"), cl::Hidden);
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +000051static cl::opt<bool> ClInstrumentMemoryAccesses(
52 "tsan-instrument-memory-accesses", cl::init(true),
53 cl::desc("Instrument memory accesses"), cl::Hidden);
54static cl::opt<bool> ClInstrumentFuncEntryExit(
55 "tsan-instrument-func-entry-exit", cl::init(true),
56 cl::desc("Instrument function entry and exit"), cl::Hidden);
57static cl::opt<bool> ClInstrumentAtomics(
58 "tsan-instrument-atomics", cl::init(true),
59 cl::desc("Instrument atomics"), cl::Hidden);
Kostya Serebryany463aa812013-03-28 11:21:13 +000060static cl::opt<bool> ClInstrumentMemIntrinsics(
61 "tsan-instrument-memintrinsics", cl::init(true),
62 cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
Kostya Serebryanyabad0022012-03-14 23:33:24 +000063
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000064STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
65STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Alexey Samsonovf54e3aa2012-08-30 13:47:13 +000066STATISTIC(NumOmittedReadsBeforeWrite,
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000067 "Number of reads ignored due to following writes");
68STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
69STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +000070STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000071STATISTIC(NumOmittedReadsFromConstantGlobals,
72 "Number of reads from constant globals");
73STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
Kostya Serebryanybf2de802012-04-10 18:18:56 +000074
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000075namespace {
Kostya Serebryanybf2de802012-04-10 18:18:56 +000076
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000077/// ThreadSanitizer: instrument the code in module to find races.
78struct ThreadSanitizer : public FunctionPass {
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000079 ThreadSanitizer(StringRef BlacklistFile = StringRef())
80 : FunctionPass(ID),
Craig Topperf40110f2014-04-25 05:29:35 +000081 DL(nullptr),
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000082 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
83 : BlacklistFile) { }
Craig Topper3e4c6972014-03-05 09:10:37 +000084 const char *getPassName() const override;
85 bool runOnFunction(Function &F) override;
86 bool doInitialization(Module &M) override;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000087 static char ID; // Pass identification, replacement for typeid.
88
89 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +000090 void initializeCallbacks(Module &M);
Kostya Serebryanya1259772012-04-27 07:31:53 +000091 bool instrumentLoadOrStore(Instruction *I);
92 bool instrumentAtomic(Instruction *I);
Kostya Serebryany463aa812013-03-28 11:21:13 +000093 bool instrumentMemIntrinsic(Instruction *I);
Kostya Serebryanyae7188d2012-05-02 13:12:19 +000094 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction*> &Local,
95 SmallVectorImpl<Instruction*> &All);
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +000096 bool addrPointsToConstantData(Value *Addr);
Kostya Serebryanya1259772012-04-27 07:31:53 +000097 int getMemoryAccessFuncIndex(Value *Addr);
Kostya Serebryanybf2de802012-04-10 18:18:56 +000098
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000099 const DataLayout *DL;
Kostya Serebryany463aa812013-03-28 11:21:13 +0000100 Type *IntptrTy;
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000101 SmallString<64> BlacklistFile;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000102 std::unique_ptr<SpecialCaseList> BL;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000103 IntegerType *OrdTy;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000104 // Callbacks to run-time library are computed in doInitialization.
Kostya Serebryanya1259772012-04-27 07:31:53 +0000105 Function *TsanFuncEntry;
106 Function *TsanFuncExit;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000107 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
Kostya Serebryanya8531ee2012-02-14 00:52:07 +0000108 static const size_t kNumberOfAccessSizes = 5;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000109 Function *TsanRead[kNumberOfAccessSizes];
110 Function *TsanWrite[kNumberOfAccessSizes];
111 Function *TsanAtomicLoad[kNumberOfAccessSizes];
112 Function *TsanAtomicStore[kNumberOfAccessSizes];
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000113 Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
114 Function *TsanAtomicCAS[kNumberOfAccessSizes];
115 Function *TsanAtomicThreadFence;
116 Function *TsanAtomicSignalFence;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000117 Function *TsanVptrUpdate;
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000118 Function *TsanVptrLoad;
Kostya Serebryany463aa812013-03-28 11:21:13 +0000119 Function *MemmoveFn, *MemcpyFn, *MemsetFn;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000120};
121} // namespace
122
123char ThreadSanitizer::ID = 0;
124INITIALIZE_PASS(ThreadSanitizer, "tsan",
125 "ThreadSanitizer: detects data races.",
126 false, false)
127
Kostya Serebryanya1259772012-04-27 07:31:53 +0000128const char *ThreadSanitizer::getPassName() const {
129 return "ThreadSanitizer";
130}
131
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000132FunctionPass *llvm::createThreadSanitizerPass(StringRef BlacklistFile) {
133 return new ThreadSanitizer(BlacklistFile);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000134}
135
Kostya Serebryanya1259772012-04-27 07:31:53 +0000136static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
137 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
138 return F;
139 FuncOrBitcast->dump();
140 report_fatal_error("ThreadSanitizer interface function redefined");
141}
142
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000143void ThreadSanitizer::initializeCallbacks(Module &M) {
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000144 IRBuilder<> IRB(M.getContext());
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000145 // Initialize the callbacks.
Kostya Serebryanya1259772012-04-27 07:31:53 +0000146 TsanFuncEntry = checkInterfaceFunction(M.getOrInsertFunction(
147 "__tsan_func_entry", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
148 TsanFuncExit = checkInterfaceFunction(M.getOrInsertFunction(
149 "__tsan_func_exit", IRB.getVoidTy(), NULL));
150 OrdTy = IRB.getInt32Ty();
Kostya Serebryanya8531ee2012-02-14 00:52:07 +0000151 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
Kostya Serebryanya1259772012-04-27 07:31:53 +0000152 const size_t ByteSize = 1 << i;
153 const size_t BitSize = ByteSize * 8;
154 SmallString<32> ReadName("__tsan_read" + itostr(ByteSize));
155 TsanRead[i] = checkInterfaceFunction(M.getOrInsertFunction(
156 ReadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
157
158 SmallString<32> WriteName("__tsan_write" + itostr(ByteSize));
159 TsanWrite[i] = checkInterfaceFunction(M.getOrInsertFunction(
160 WriteName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
161
162 Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
163 Type *PtrTy = Ty->getPointerTo();
164 SmallString<32> AtomicLoadName("__tsan_atomic" + itostr(BitSize) +
165 "_load");
166 TsanAtomicLoad[i] = checkInterfaceFunction(M.getOrInsertFunction(
167 AtomicLoadName, Ty, PtrTy, OrdTy, NULL));
168
169 SmallString<32> AtomicStoreName("__tsan_atomic" + itostr(BitSize) +
170 "_store");
171 TsanAtomicStore[i] = checkInterfaceFunction(M.getOrInsertFunction(
172 AtomicStoreName, IRB.getVoidTy(), PtrTy, Ty, OrdTy,
173 NULL));
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000174
175 for (int op = AtomicRMWInst::FIRST_BINOP;
176 op <= AtomicRMWInst::LAST_BINOP; ++op) {
Craig Topperf40110f2014-04-25 05:29:35 +0000177 TsanAtomicRMW[op][i] = nullptr;
178 const char *NamePart = nullptr;
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000179 if (op == AtomicRMWInst::Xchg)
180 NamePart = "_exchange";
181 else if (op == AtomicRMWInst::Add)
182 NamePart = "_fetch_add";
183 else if (op == AtomicRMWInst::Sub)
184 NamePart = "_fetch_sub";
185 else if (op == AtomicRMWInst::And)
186 NamePart = "_fetch_and";
187 else if (op == AtomicRMWInst::Or)
188 NamePart = "_fetch_or";
189 else if (op == AtomicRMWInst::Xor)
190 NamePart = "_fetch_xor";
Dmitry Vyukova878e742012-11-27 08:09:25 +0000191 else if (op == AtomicRMWInst::Nand)
192 NamePart = "_fetch_nand";
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000193 else
194 continue;
195 SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
196 TsanAtomicRMW[op][i] = checkInterfaceFunction(M.getOrInsertFunction(
197 RMWName, Ty, PtrTy, Ty, OrdTy, NULL));
198 }
199
200 SmallString<32> AtomicCASName("__tsan_atomic" + itostr(BitSize) +
201 "_compare_exchange_val");
202 TsanAtomicCAS[i] = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000203 AtomicCASName, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, NULL));
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000204 }
Kostya Serebryanya1259772012-04-27 07:31:53 +0000205 TsanVptrUpdate = checkInterfaceFunction(M.getOrInsertFunction(
206 "__tsan_vptr_update", IRB.getVoidTy(), IRB.getInt8PtrTy(),
207 IRB.getInt8PtrTy(), NULL));
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000208 TsanVptrLoad = checkInterfaceFunction(M.getOrInsertFunction(
209 "__tsan_vptr_read", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000210 TsanAtomicThreadFence = checkInterfaceFunction(M.getOrInsertFunction(
211 "__tsan_atomic_thread_fence", IRB.getVoidTy(), OrdTy, NULL));
212 TsanAtomicSignalFence = checkInterfaceFunction(M.getOrInsertFunction(
213 "__tsan_atomic_signal_fence", IRB.getVoidTy(), OrdTy, NULL));
Kostya Serebryany463aa812013-03-28 11:21:13 +0000214
215 MemmoveFn = checkInterfaceFunction(M.getOrInsertFunction(
216 "memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
217 IRB.getInt8PtrTy(), IntptrTy, NULL));
218 MemcpyFn = checkInterfaceFunction(M.getOrInsertFunction(
219 "memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
220 IntptrTy, NULL));
221 MemsetFn = checkInterfaceFunction(M.getOrInsertFunction(
222 "memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
223 IntptrTy, NULL));
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000224}
225
226bool ThreadSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000227 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
228 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000229 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000230 DL = &DLP->getDataLayout();
Alexey Samsonove4b5fb82013-08-12 11:46:09 +0000231 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000232
233 // Always insert a call to __tsan_init into the module's CTORs.
234 IRBuilder<> IRB(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000235 IntptrTy = IRB.getIntPtrTy(DL);
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000236 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
237 IRB.getVoidTy(), NULL);
238 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
239
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000240 return true;
241}
242
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000243static bool isVtableAccess(Instruction *I) {
Manman Rend8c68b12013-09-06 22:47:05 +0000244 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
245 return Tag->isTBAAVtableAccess();
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000246 return false;
247}
248
249bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
250 // If this is a GEP, just analyze its pointer operand.
251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
252 Addr = GEP->getPointerOperand();
253
254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
255 if (GV->isConstant()) {
256 // Reads from constant globals can not race with any writes.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000257 NumOmittedReadsFromConstantGlobals++;
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000258 return true;
259 }
Alexey Samsonovf54e3aa2012-08-30 13:47:13 +0000260 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000261 if (isVtableAccess(L)) {
262 // Reads from a vtable pointer can not race with any writes.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000263 NumOmittedReadsFromVtable++;
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000264 return true;
265 }
266 }
267 return false;
268}
269
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000270// Instrumenting some of the accesses may be proven redundant.
271// Currently handled:
272// - read-before-write (within same BB, no calls between)
273//
274// We do not handle some of the patterns that should not survive
275// after the classic compiler optimizations.
276// E.g. two reads from the same temp should be eliminated by CSE,
277// two writes should be eliminated by DSE, etc.
278//
279// 'Local' is a vector of insns within the same BB (no calls between).
280// 'All' is a vector of insns that will be instrumented.
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000281void ThreadSanitizer::chooseInstructionsToInstrument(
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000282 SmallVectorImpl<Instruction*> &Local,
283 SmallVectorImpl<Instruction*> &All) {
284 SmallSet<Value*, 8> WriteTargets;
285 // Iterate from the end.
286 for (SmallVectorImpl<Instruction*>::reverse_iterator It = Local.rbegin(),
287 E = Local.rend(); It != E; ++It) {
288 Instruction *I = *It;
289 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
290 WriteTargets.insert(Store->getPointerOperand());
291 } else {
292 LoadInst *Load = cast<LoadInst>(I);
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000293 Value *Addr = Load->getPointerOperand();
294 if (WriteTargets.count(Addr)) {
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000295 // We will write to this temp, so no reason to analyze the read.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000296 NumOmittedReadsBeforeWrite++;
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000297 continue;
298 }
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000299 if (addrPointsToConstantData(Addr)) {
300 // Addr points to some constant data -- it can not race with any writes.
301 continue;
302 }
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000303 }
304 All.push_back(I);
305 }
306 Local.clear();
307}
308
Kostya Serebryanya1259772012-04-27 07:31:53 +0000309static bool isAtomic(Instruction *I) {
310 if (LoadInst *LI = dyn_cast<LoadInst>(I))
311 return LI->isAtomic() && LI->getSynchScope() == CrossThread;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000312 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000313 return SI->isAtomic() && SI->getSynchScope() == CrossThread;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000314 if (isa<AtomicRMWInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000315 return true;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000316 if (isa<AtomicCmpXchgInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000317 return true;
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000318 if (isa<FenceInst>(I))
319 return true;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000320 return false;
321}
322
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000323bool ThreadSanitizer::runOnFunction(Function &F) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000324 if (!DL) return false;
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000325 initializeCallbacks(*F.getParent());
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000326 SmallVector<Instruction*, 8> RetVec;
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000327 SmallVector<Instruction*, 8> AllLoadsAndStores;
328 SmallVector<Instruction*, 8> LocalLoadsAndStores;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000329 SmallVector<Instruction*, 8> AtomicAccesses;
Kostya Serebryany463aa812013-03-28 11:21:13 +0000330 SmallVector<Instruction*, 8> MemIntrinCalls;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000331 bool Res = false;
332 bool HasCalls = false;
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000333 bool SanitizeFunction =
334 F.hasFnAttribute(Attribute::SanitizeThread) && !BL->isIn(F);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000335
336 // Traverse all instructions, collect loads/stores/returns, check for calls.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000337 for (auto &BB : F) {
338 for (auto &Inst : BB) {
339 if (isAtomic(&Inst))
340 AtomicAccesses.push_back(&Inst);
341 else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
342 LocalLoadsAndStores.push_back(&Inst);
343 else if (isa<ReturnInst>(Inst))
344 RetVec.push_back(&Inst);
345 else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
346 if (isa<MemIntrinsic>(Inst))
347 MemIntrinCalls.push_back(&Inst);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000348 HasCalls = true;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000349 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000350 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000351 }
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000352 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000353 }
354
355 // We have collected all loads and stores.
356 // FIXME: many of these accesses do not need to be checked for races
357 // (e.g. variables that do not escape, etc).
358
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000359 // Instrument memory accesses only if we want to report bugs in the function.
360 if (ClInstrumentMemoryAccesses && SanitizeFunction)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000361 for (auto Inst : AllLoadsAndStores) {
362 Res |= instrumentLoadOrStore(Inst);
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000363 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000364
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000365 // Instrument atomic memory accesses in any case (they can be used to
366 // implement synchronization).
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000367 if (ClInstrumentAtomics)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000368 for (auto Inst : AtomicAccesses) {
369 Res |= instrumentAtomic(Inst);
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000370 }
Kostya Serebryanya1259772012-04-27 07:31:53 +0000371
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000372 if (ClInstrumentMemIntrinsics && SanitizeFunction)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000373 for (auto Inst : MemIntrinCalls) {
374 Res |= instrumentMemIntrinsic(Inst);
Kostya Serebryany463aa812013-03-28 11:21:13 +0000375 }
376
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000377 // Instrument function entry/exit points if there were instrumented accesses.
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000378 if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000379 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
380 Value *ReturnAddress = IRB.CreateCall(
381 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
382 IRB.getInt32(0));
383 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
Alexey Samsonova02e6642014-05-29 18:40:48 +0000384 for (auto RetInst : RetVec) {
385 IRBuilder<> IRBRet(RetInst);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000386 IRBRet.CreateCall(TsanFuncExit);
387 }
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000388 Res = true;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000389 }
390 return Res;
391}
392
393bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
394 IRBuilder<> IRB(I);
395 bool IsWrite = isa<StoreInst>(*I);
396 Value *Addr = IsWrite
397 ? cast<StoreInst>(I)->getPointerOperand()
398 : cast<LoadInst>(I)->getPointerOperand();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000399 int Idx = getMemoryAccessFuncIndex(Addr);
400 if (Idx < 0)
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000401 return false;
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000402 if (IsWrite && isVtableAccess(I)) {
Kostya Serebryanye36ae682012-07-05 09:07:31 +0000403 DEBUG(dbgs() << " VPTR : " << *I << "\n");
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000404 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
Kostya Serebryany08b9cf52013-12-02 08:07:15 +0000405 // StoredValue may be a vector type if we are storing several vptrs at once.
406 // In this case, just take the first element of the vector since this is
407 // enough to find vptr races.
408 if (isa<VectorType>(StoredValue->getType()))
409 StoredValue = IRB.CreateExtractElement(
410 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
Kostya Serebryany2460c3f2013-12-05 15:03:02 +0000411 if (StoredValue->getType()->isIntegerTy())
412 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
Kostya Serebryanye36ae682012-07-05 09:07:31 +0000413 // Call TsanVptrUpdate.
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000414 IRB.CreateCall2(TsanVptrUpdate,
415 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
Kostya Serebryany2460c3f2013-12-05 15:03:02 +0000416 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000417 NumInstrumentedVtableWrites++;
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000418 return true;
419 }
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000420 if (!IsWrite && isVtableAccess(I)) {
421 IRB.CreateCall(TsanVptrLoad,
422 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
423 NumInstrumentedVtableReads++;
424 return true;
425 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000426 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
427 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000428 if (IsWrite) NumInstrumentedWrites++;
429 else NumInstrumentedReads++;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000430 return true;
431}
Kostya Serebryanya1259772012-04-27 07:31:53 +0000432
433static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
434 uint32_t v = 0;
435 switch (ord) {
436 case NotAtomic: assert(false);
437 case Unordered: // Fall-through.
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000438 case Monotonic: v = 0; break;
Dmitry Vyukov93e67b62012-11-26 14:55:26 +0000439 // case Consume: v = 1; break; // Not specified yet.
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000440 case Acquire: v = 2; break;
441 case Release: v = 3; break;
442 case AcquireRelease: v = 4; break;
443 case SequentiallyConsistent: v = 5; break;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000444 }
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000445 return IRB->getInt32(v);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000446}
447
Kostya Serebryany463aa812013-03-28 11:21:13 +0000448// If a memset intrinsic gets inlined by the code gen, we will miss races on it.
449// So, we either need to ensure the intrinsic is not inlined, or instrument it.
450// We do not instrument memset/memmove/memcpy intrinsics (too complicated),
451// instead we simply replace them with regular function calls, which are then
452// intercepted by the run-time.
453// Since tsan is running after everyone else, the calls should not be
454// replaced back with intrinsics. If that becomes wrong at some point,
455// we will need to call e.g. __tsan_memset to avoid the intrinsics.
456bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
457 IRBuilder<> IRB(I);
458 if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
459 IRB.CreateCall3(MemsetFn,
460 IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
461 IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
462 IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false));
463 I->eraseFromParent();
464 } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
465 IRB.CreateCall3(isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
466 IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
467 IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
468 IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false));
469 I->eraseFromParent();
470 }
471 return false;
472}
473
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000474// Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
Alp Tokercb402912014-01-24 17:20:08 +0000475// standards. For background see C++11 standard. A slightly older, publicly
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000476// available draft of the standard (not entirely up-to-date, but close enough
477// for casual browsing) is available here:
Matt Beaumont-Gay000a3952012-11-26 16:27:22 +0000478// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000479// The following page contains more background information:
480// http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
481
Kostya Serebryanya1259772012-04-27 07:31:53 +0000482bool ThreadSanitizer::instrumentAtomic(Instruction *I) {
483 IRBuilder<> IRB(I);
484 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
485 Value *Addr = LI->getPointerOperand();
486 int Idx = getMemoryAccessFuncIndex(Addr);
487 if (Idx < 0)
488 return false;
489 const size_t ByteSize = 1 << Idx;
490 const size_t BitSize = ByteSize * 8;
491 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmow51e72462012-10-24 17:25:11 +0000492 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000493 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
494 createOrdering(&IRB, LI->getOrdering())};
495 CallInst *C = CallInst::Create(TsanAtomicLoad[Idx],
496 ArrayRef<Value*>(Args));
497 ReplaceInstWithInst(I, C);
498
499 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
500 Value *Addr = SI->getPointerOperand();
501 int Idx = getMemoryAccessFuncIndex(Addr);
502 if (Idx < 0)
503 return false;
504 const size_t ByteSize = 1 << Idx;
505 const size_t BitSize = ByteSize * 8;
506 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmow51e72462012-10-24 17:25:11 +0000507 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000508 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
509 IRB.CreateIntCast(SI->getValueOperand(), Ty, false),
510 createOrdering(&IRB, SI->getOrdering())};
511 CallInst *C = CallInst::Create(TsanAtomicStore[Idx],
512 ArrayRef<Value*>(Args));
513 ReplaceInstWithInst(I, C);
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000514 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
515 Value *Addr = RMWI->getPointerOperand();
516 int Idx = getMemoryAccessFuncIndex(Addr);
517 if (Idx < 0)
518 return false;
519 Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
Craig Topperf40110f2014-04-25 05:29:35 +0000520 if (!F)
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000521 return false;
522 const size_t ByteSize = 1 << Idx;
523 const size_t BitSize = ByteSize * 8;
524 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
525 Type *PtrTy = Ty->getPointerTo();
526 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
527 IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
528 createOrdering(&IRB, RMWI->getOrdering())};
529 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
530 ReplaceInstWithInst(I, C);
531 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
532 Value *Addr = CASI->getPointerOperand();
533 int Idx = getMemoryAccessFuncIndex(Addr);
534 if (Idx < 0)
535 return false;
536 const size_t ByteSize = 1 << Idx;
537 const size_t BitSize = ByteSize * 8;
538 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
539 Type *PtrTy = Ty->getPointerTo();
540 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
541 IRB.CreateIntCast(CASI->getCompareOperand(), Ty, false),
542 IRB.CreateIntCast(CASI->getNewValOperand(), Ty, false),
Tim Northovere94a5182014-03-11 10:48:52 +0000543 createOrdering(&IRB, CASI->getSuccessOrdering()),
544 createOrdering(&IRB, CASI->getFailureOrdering())};
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000545 CallInst *C = CallInst::Create(TsanAtomicCAS[Idx], ArrayRef<Value*>(Args));
546 ReplaceInstWithInst(I, C);
547 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
548 Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
549 Function *F = FI->getSynchScope() == SingleThread ?
550 TsanAtomicSignalFence : TsanAtomicThreadFence;
551 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
552 ReplaceInstWithInst(I, C);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000553 }
554 return true;
555}
556
557int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr) {
558 Type *OrigPtrTy = Addr->getType();
559 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
560 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000562 if (TypeSize != 8 && TypeSize != 16 &&
563 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
564 NumAccessesWithBadSize++;
565 // Ignore all unusual sizes.
566 return -1;
567 }
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000568 size_t Idx = countTrailingZeros(TypeSize / 8);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000569 assert(Idx < kNumberOfAccessSizes);
570 return Idx;
571}