1 //===-- 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 
22 #include "llvm/Transforms/Instrumentation.h"
23 #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"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/ProfileData/InstrProf.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "tsan"
53 
54 static cl::opt<bool>  ClInstrumentMemoryAccesses(
55     "tsan-instrument-memory-accesses", cl::init(true),
56     cl::desc("Instrument memory accesses"), cl::Hidden);
57 static cl::opt<bool>  ClInstrumentFuncEntryExit(
58     "tsan-instrument-func-entry-exit", cl::init(true),
59     cl::desc("Instrument function entry and exit"), cl::Hidden);
60 static cl::opt<bool>  ClHandleCxxExceptions(
61     "tsan-handle-cxx-exceptions", cl::init(true),
62     cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"),
63     cl::Hidden);
64 static cl::opt<bool>  ClInstrumentAtomics(
65     "tsan-instrument-atomics", cl::init(true),
66     cl::desc("Instrument atomics"), cl::Hidden);
67 static cl::opt<bool>  ClInstrumentMemIntrinsics(
68     "tsan-instrument-memintrinsics", cl::init(true),
69     cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
70 
71 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
72 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
73 STATISTIC(NumOmittedReadsBeforeWrite,
74           "Number of reads ignored due to following writes");
75 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
76 STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
77 STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
78 STATISTIC(NumOmittedReadsFromConstantGlobals,
79           "Number of reads from constant globals");
80 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
81 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
82 
83 static const char *const kTsanModuleCtorName = "tsan.module_ctor";
84 static const char *const kTsanInitName = "__tsan_init";
85 
86 namespace {
87 
88 /// ThreadSanitizer: instrument the code in module to find races.
89 struct ThreadSanitizer : public FunctionPass {
90   ThreadSanitizer() : FunctionPass(ID) {}
91   StringRef getPassName() const override;
92   void getAnalysisUsage(AnalysisUsage &AU) const override;
93   bool runOnFunction(Function &F) override;
94   bool doInitialization(Module &M) override;
95   static char ID;  // Pass identification, replacement for typeid.
96 
97  private:
98   void initializeCallbacks(Module &M);
99   bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
100   bool instrumentAtomic(Instruction *I, const DataLayout &DL);
101   bool instrumentMemIntrinsic(Instruction *I);
102   void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
103                                       SmallVectorImpl<Instruction *> &All,
104                                       const DataLayout &DL);
105   bool addrPointsToConstantData(Value *Addr);
106   int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
107   void InsertRuntimeIgnores(Function &F);
108 
109   Type *IntptrTy;
110   IntegerType *OrdTy;
111   // Callbacks to run-time library are computed in doInitialization.
112   Function *TsanFuncEntry;
113   Function *TsanFuncExit;
114   Function *TsanIgnoreBegin;
115   Function *TsanIgnoreEnd;
116   // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
117   static const size_t kNumberOfAccessSizes = 5;
118   Function *TsanRead[kNumberOfAccessSizes];
119   Function *TsanWrite[kNumberOfAccessSizes];
120   Function *TsanUnalignedRead[kNumberOfAccessSizes];
121   Function *TsanUnalignedWrite[kNumberOfAccessSizes];
122   Function *TsanAtomicLoad[kNumberOfAccessSizes];
123   Function *TsanAtomicStore[kNumberOfAccessSizes];
124   Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
125   Function *TsanAtomicCAS[kNumberOfAccessSizes];
126   Function *TsanAtomicThreadFence;
127   Function *TsanAtomicSignalFence;
128   Function *TsanVptrUpdate;
129   Function *TsanVptrLoad;
130   Function *MemmoveFn, *MemcpyFn, *MemsetFn;
131   Function *TsanCtorFunction;
132 };
133 }  // namespace
134 
135 char ThreadSanitizer::ID = 0;
136 INITIALIZE_PASS_BEGIN(
137     ThreadSanitizer, "tsan",
138     "ThreadSanitizer: detects data races.",
139     false, false)
140 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
141 INITIALIZE_PASS_END(
142     ThreadSanitizer, "tsan",
143     "ThreadSanitizer: detects data races.",
144     false, false)
145 
146 StringRef ThreadSanitizer::getPassName() const { return "ThreadSanitizer"; }
147 
148 void ThreadSanitizer::getAnalysisUsage(AnalysisUsage &AU) const {
149   AU.addRequired<TargetLibraryInfoWrapperPass>();
150 }
151 
152 FunctionPass *llvm::createThreadSanitizerPass() {
153   return new ThreadSanitizer();
154 }
155 
156 void ThreadSanitizer::initializeCallbacks(Module &M) {
157   IRBuilder<> IRB(M.getContext());
158   AttributeList Attr;
159   Attr = Attr.addAttribute(M.getContext(), AttributeList::FunctionIndex,
160                            Attribute::NoUnwind);
161   // Initialize the callbacks.
162   TsanFuncEntry = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
163       "__tsan_func_entry", Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
164   TsanFuncExit = checkSanitizerInterfaceFunction(
165       M.getOrInsertFunction("__tsan_func_exit", Attr, IRB.getVoidTy()));
166   TsanIgnoreBegin = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
167       "__tsan_ignore_thread_begin", Attr, IRB.getVoidTy()));
168   TsanIgnoreEnd = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
169       "__tsan_ignore_thread_end", Attr, IRB.getVoidTy()));
170   OrdTy = IRB.getInt32Ty();
171   for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
172     const unsigned ByteSize = 1U << i;
173     const unsigned BitSize = ByteSize * 8;
174     std::string ByteSizeStr = utostr(ByteSize);
175     std::string BitSizeStr = utostr(BitSize);
176     SmallString<32> ReadName("__tsan_read" + ByteSizeStr);
177     TsanRead[i] = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
178         ReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
179 
180     SmallString<32> WriteName("__tsan_write" + ByteSizeStr);
181     TsanWrite[i] = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
182         WriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
183 
184     SmallString<64> UnalignedReadName("__tsan_unaligned_read" + ByteSizeStr);
185     TsanUnalignedRead[i] =
186         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
187             UnalignedReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
188 
189     SmallString<64> UnalignedWriteName("__tsan_unaligned_write" + ByteSizeStr);
190     TsanUnalignedWrite[i] =
191         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
192             UnalignedWriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
193 
194     Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
195     Type *PtrTy = Ty->getPointerTo();
196     SmallString<32> AtomicLoadName("__tsan_atomic" + BitSizeStr + "_load");
197     TsanAtomicLoad[i] = checkSanitizerInterfaceFunction(
198         M.getOrInsertFunction(AtomicLoadName, Attr, Ty, PtrTy, OrdTy));
199 
200     SmallString<32> AtomicStoreName("__tsan_atomic" + BitSizeStr + "_store");
201     TsanAtomicStore[i] = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
202         AtomicStoreName, Attr, IRB.getVoidTy(), PtrTy, Ty, OrdTy));
203 
204     for (int op = AtomicRMWInst::FIRST_BINOP;
205         op <= AtomicRMWInst::LAST_BINOP; ++op) {
206       TsanAtomicRMW[op][i] = nullptr;
207       const char *NamePart = nullptr;
208       if (op == AtomicRMWInst::Xchg)
209         NamePart = "_exchange";
210       else if (op == AtomicRMWInst::Add)
211         NamePart = "_fetch_add";
212       else if (op == AtomicRMWInst::Sub)
213         NamePart = "_fetch_sub";
214       else if (op == AtomicRMWInst::And)
215         NamePart = "_fetch_and";
216       else if (op == AtomicRMWInst::Or)
217         NamePart = "_fetch_or";
218       else if (op == AtomicRMWInst::Xor)
219         NamePart = "_fetch_xor";
220       else if (op == AtomicRMWInst::Nand)
221         NamePart = "_fetch_nand";
222       else
223         continue;
224       SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
225       TsanAtomicRMW[op][i] = checkSanitizerInterfaceFunction(
226           M.getOrInsertFunction(RMWName, Attr, Ty, PtrTy, Ty, OrdTy));
227     }
228 
229     SmallString<32> AtomicCASName("__tsan_atomic" + BitSizeStr +
230                                   "_compare_exchange_val");
231     TsanAtomicCAS[i] = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
232         AtomicCASName, Attr, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy));
233   }
234   TsanVptrUpdate = checkSanitizerInterfaceFunction(
235       M.getOrInsertFunction("__tsan_vptr_update", Attr, IRB.getVoidTy(),
236                             IRB.getInt8PtrTy(), IRB.getInt8PtrTy()));
237   TsanVptrLoad = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
238       "__tsan_vptr_read", Attr, IRB.getVoidTy(), IRB.getInt8PtrTy()));
239   TsanAtomicThreadFence = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
240       "__tsan_atomic_thread_fence", Attr, IRB.getVoidTy(), OrdTy));
241   TsanAtomicSignalFence = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
242       "__tsan_atomic_signal_fence", Attr, IRB.getVoidTy(), OrdTy));
243 
244   MemmoveFn = checkSanitizerInterfaceFunction(
245       M.getOrInsertFunction("memmove", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
246                             IRB.getInt8PtrTy(), IntptrTy));
247   MemcpyFn = checkSanitizerInterfaceFunction(
248       M.getOrInsertFunction("memcpy", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
249                             IRB.getInt8PtrTy(), IntptrTy));
250   MemsetFn = checkSanitizerInterfaceFunction(
251       M.getOrInsertFunction("memset", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
252                             IRB.getInt32Ty(), IntptrTy));
253 }
254 
255 bool ThreadSanitizer::doInitialization(Module &M) {
256   const DataLayout &DL = M.getDataLayout();
257   IntptrTy = DL.getIntPtrType(M.getContext());
258   std::tie(TsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
259       M, kTsanModuleCtorName, kTsanInitName, /*InitArgTypes=*/{},
260       /*InitArgs=*/{});
261 
262   appendToGlobalCtors(M, TsanCtorFunction, 0);
263 
264   return true;
265 }
266 
267 static bool isVtableAccess(Instruction *I) {
268   if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
269     return Tag->isTBAAVtableAccess();
270   return false;
271 }
272 
273 // Do not instrument known races/"benign races" that come from compiler
274 // instrumentatin. The user has no way of suppressing them.
275 static bool shouldInstrumentReadWriteFromAddress(Value *Addr) {
276   // Peel off GEPs and BitCasts.
277   Addr = Addr->stripInBoundsOffsets();
278 
279   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
280     if (GV->hasSection()) {
281       StringRef SectionName = GV->getSection();
282       // Check if the global is in the PGO counters section.
283       if (SectionName.endswith(getInstrProfCountersSectionName(
284             /*AddSegment=*/false)))
285         return false;
286     }
287 
288     // Check if the global is private gcov data.
289     if (GV->getName().startswith("__llvm_gcov") ||
290         GV->getName().startswith("__llvm_gcda"))
291       return false;
292   }
293 
294   // Do not instrument acesses from different address spaces; we cannot deal
295   // with them.
296   if (Addr) {
297     Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
298     if (PtrTy->getPointerAddressSpace() != 0)
299       return false;
300   }
301 
302   return true;
303 }
304 
305 bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
306   // If this is a GEP, just analyze its pointer operand.
307   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
308     Addr = GEP->getPointerOperand();
309 
310   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
311     if (GV->isConstant()) {
312       // Reads from constant globals can not race with any writes.
313       NumOmittedReadsFromConstantGlobals++;
314       return true;
315     }
316   } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
317     if (isVtableAccess(L)) {
318       // Reads from a vtable pointer can not race with any writes.
319       NumOmittedReadsFromVtable++;
320       return true;
321     }
322   }
323   return false;
324 }
325 
326 // Instrumenting some of the accesses may be proven redundant.
327 // Currently handled:
328 //  - read-before-write (within same BB, no calls between)
329 //  - not captured variables
330 //
331 // We do not handle some of the patterns that should not survive
332 // after the classic compiler optimizations.
333 // E.g. two reads from the same temp should be eliminated by CSE,
334 // two writes should be eliminated by DSE, etc.
335 //
336 // 'Local' is a vector of insns within the same BB (no calls between).
337 // 'All' is a vector of insns that will be instrumented.
338 void ThreadSanitizer::chooseInstructionsToInstrument(
339     SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
340     const DataLayout &DL) {
341   SmallSet<Value*, 8> WriteTargets;
342   // Iterate from the end.
343   for (Instruction *I : reverse(Local)) {
344     if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
345       Value *Addr = Store->getPointerOperand();
346       if (!shouldInstrumentReadWriteFromAddress(Addr))
347         continue;
348       WriteTargets.insert(Addr);
349     } else {
350       LoadInst *Load = cast<LoadInst>(I);
351       Value *Addr = Load->getPointerOperand();
352       if (!shouldInstrumentReadWriteFromAddress(Addr))
353         continue;
354       if (WriteTargets.count(Addr)) {
355         // We will write to this temp, so no reason to analyze the read.
356         NumOmittedReadsBeforeWrite++;
357         continue;
358       }
359       if (addrPointsToConstantData(Addr)) {
360         // Addr points to some constant data -- it can not race with any writes.
361         continue;
362       }
363     }
364     Value *Addr = isa<StoreInst>(*I)
365         ? cast<StoreInst>(I)->getPointerOperand()
366         : cast<LoadInst>(I)->getPointerOperand();
367     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
368         !PointerMayBeCaptured(Addr, true, true)) {
369       // The variable is addressable but not captured, so it cannot be
370       // referenced from a different thread and participate in a data race
371       // (see llvm/Analysis/CaptureTracking.h for details).
372       NumOmittedNonCaptured++;
373       continue;
374     }
375     All.push_back(I);
376   }
377   Local.clear();
378 }
379 
380 static bool isAtomic(Instruction *I) {
381   if (LoadInst *LI = dyn_cast<LoadInst>(I))
382     return LI->isAtomic() && LI->getSynchScope() == CrossThread;
383   if (StoreInst *SI = dyn_cast<StoreInst>(I))
384     return SI->isAtomic() && SI->getSynchScope() == CrossThread;
385   if (isa<AtomicRMWInst>(I))
386     return true;
387   if (isa<AtomicCmpXchgInst>(I))
388     return true;
389   if (isa<FenceInst>(I))
390     return true;
391   return false;
392 }
393 
394 void ThreadSanitizer::InsertRuntimeIgnores(Function &F) {
395   IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
396   IRB.CreateCall(TsanIgnoreBegin);
397   EscapeEnumerator EE(F, "tsan_ignore_cleanup", ClHandleCxxExceptions);
398   while (IRBuilder<> *AtExit = EE.Next()) {
399     AtExit->CreateCall(TsanIgnoreEnd);
400   }
401 }
402 
403 bool ThreadSanitizer::runOnFunction(Function &F) {
404   // This is required to prevent instrumenting call to __tsan_init from within
405   // the module constructor.
406   if (&F == TsanCtorFunction)
407     return false;
408   initializeCallbacks(*F.getParent());
409   SmallVector<Instruction*, 8> AllLoadsAndStores;
410   SmallVector<Instruction*, 8> LocalLoadsAndStores;
411   SmallVector<Instruction*, 8> AtomicAccesses;
412   SmallVector<Instruction*, 8> MemIntrinCalls;
413   bool Res = false;
414   bool HasCalls = false;
415   bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);
416   const DataLayout &DL = F.getParent()->getDataLayout();
417   const TargetLibraryInfo *TLI =
418       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
419 
420   // Traverse all instructions, collect loads/stores/returns, check for calls.
421   for (auto &BB : F) {
422     for (auto &Inst : BB) {
423       if (isAtomic(&Inst))
424         AtomicAccesses.push_back(&Inst);
425       else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
426         LocalLoadsAndStores.push_back(&Inst);
427       else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
428         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
429           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
430         if (isa<MemIntrinsic>(Inst))
431           MemIntrinCalls.push_back(&Inst);
432         HasCalls = true;
433         chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
434                                        DL);
435       }
436     }
437     chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
438   }
439 
440   // We have collected all loads and stores.
441   // FIXME: many of these accesses do not need to be checked for races
442   // (e.g. variables that do not escape, etc).
443 
444   // Instrument memory accesses only if we want to report bugs in the function.
445   if (ClInstrumentMemoryAccesses && SanitizeFunction)
446     for (auto Inst : AllLoadsAndStores) {
447       Res |= instrumentLoadOrStore(Inst, DL);
448     }
449 
450   // Instrument atomic memory accesses in any case (they can be used to
451   // implement synchronization).
452   if (ClInstrumentAtomics)
453     for (auto Inst : AtomicAccesses) {
454       Res |= instrumentAtomic(Inst, DL);
455     }
456 
457   if (ClInstrumentMemIntrinsics && SanitizeFunction)
458     for (auto Inst : MemIntrinCalls) {
459       Res |= instrumentMemIntrinsic(Inst);
460     }
461 
462   if (F.hasFnAttribute("sanitize_thread_no_checking_at_run_time")) {
463     assert(!F.hasFnAttribute(Attribute::SanitizeThread));
464     if (HasCalls)
465       InsertRuntimeIgnores(F);
466   }
467 
468   // Instrument function entry/exit points if there were instrumented accesses.
469   if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
470     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
471     Value *ReturnAddress = IRB.CreateCall(
472         Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
473         IRB.getInt32(0));
474     IRB.CreateCall(TsanFuncEntry, ReturnAddress);
475 
476     EscapeEnumerator EE(F, "tsan_cleanup", ClHandleCxxExceptions);
477     while (IRBuilder<> *AtExit = EE.Next()) {
478       AtExit->CreateCall(TsanFuncExit, {});
479     }
480     Res = true;
481   }
482   return Res;
483 }
484 
485 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I,
486                                             const DataLayout &DL) {
487   IRBuilder<> IRB(I);
488   bool IsWrite = isa<StoreInst>(*I);
489   Value *Addr = IsWrite
490       ? cast<StoreInst>(I)->getPointerOperand()
491       : cast<LoadInst>(I)->getPointerOperand();
492 
493   // swifterror memory addresses are mem2reg promoted by instruction selection.
494   // As such they cannot have regular uses like an instrumentation function and
495   // it makes no sense to track them as memory.
496   if (Addr->isSwiftError())
497     return false;
498 
499   int Idx = getMemoryAccessFuncIndex(Addr, DL);
500   if (Idx < 0)
501     return false;
502   if (IsWrite && isVtableAccess(I)) {
503     DEBUG(dbgs() << "  VPTR : " << *I << "\n");
504     Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
505     // StoredValue may be a vector type if we are storing several vptrs at once.
506     // In this case, just take the first element of the vector since this is
507     // enough to find vptr races.
508     if (isa<VectorType>(StoredValue->getType()))
509       StoredValue = IRB.CreateExtractElement(
510           StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
511     if (StoredValue->getType()->isIntegerTy())
512       StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
513     // Call TsanVptrUpdate.
514     IRB.CreateCall(TsanVptrUpdate,
515                    {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
516                     IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
517     NumInstrumentedVtableWrites++;
518     return true;
519   }
520   if (!IsWrite && isVtableAccess(I)) {
521     IRB.CreateCall(TsanVptrLoad,
522                    IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
523     NumInstrumentedVtableReads++;
524     return true;
525   }
526   const unsigned Alignment = IsWrite
527       ? cast<StoreInst>(I)->getAlignment()
528       : cast<LoadInst>(I)->getAlignment();
529   Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
530   const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
531   Value *OnAccessFunc = nullptr;
532   if (Alignment == 0 || Alignment >= 8 || (Alignment % (TypeSize / 8)) == 0)
533     OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
534   else
535     OnAccessFunc = IsWrite ? TsanUnalignedWrite[Idx] : TsanUnalignedRead[Idx];
536   IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
537   if (IsWrite) NumInstrumentedWrites++;
538   else         NumInstrumentedReads++;
539   return true;
540 }
541 
542 static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
543   uint32_t v = 0;
544   switch (ord) {
545     case AtomicOrdering::NotAtomic:
546       llvm_unreachable("unexpected atomic ordering!");
547     case AtomicOrdering::Unordered:              LLVM_FALLTHROUGH;
548     case AtomicOrdering::Monotonic:              v = 0; break;
549     // Not specified yet:
550     // case AtomicOrdering::Consume:                v = 1; break;
551     case AtomicOrdering::Acquire:                v = 2; break;
552     case AtomicOrdering::Release:                v = 3; break;
553     case AtomicOrdering::AcquireRelease:         v = 4; break;
554     case AtomicOrdering::SequentiallyConsistent: v = 5; break;
555   }
556   return IRB->getInt32(v);
557 }
558 
559 // If a memset intrinsic gets inlined by the code gen, we will miss races on it.
560 // So, we either need to ensure the intrinsic is not inlined, or instrument it.
561 // We do not instrument memset/memmove/memcpy intrinsics (too complicated),
562 // instead we simply replace them with regular function calls, which are then
563 // intercepted by the run-time.
564 // Since tsan is running after everyone else, the calls should not be
565 // replaced back with intrinsics. If that becomes wrong at some point,
566 // we will need to call e.g. __tsan_memset to avoid the intrinsics.
567 bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
568   IRBuilder<> IRB(I);
569   if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
570     IRB.CreateCall(
571         MemsetFn,
572         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
573          IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
574          IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
575     I->eraseFromParent();
576   } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
577     IRB.CreateCall(
578         isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
579         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
580          IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
581          IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
582     I->eraseFromParent();
583   }
584   return false;
585 }
586 
587 // Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
588 // standards.  For background see C++11 standard.  A slightly older, publicly
589 // available draft of the standard (not entirely up-to-date, but close enough
590 // for casual browsing) is available here:
591 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
592 // The following page contains more background information:
593 // http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
594 
595 bool ThreadSanitizer::instrumentAtomic(Instruction *I, const DataLayout &DL) {
596   IRBuilder<> IRB(I);
597   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
598     Value *Addr = LI->getPointerOperand();
599     int Idx = getMemoryAccessFuncIndex(Addr, DL);
600     if (Idx < 0)
601       return false;
602     const unsigned ByteSize = 1U << Idx;
603     const unsigned BitSize = ByteSize * 8;
604     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
605     Type *PtrTy = Ty->getPointerTo();
606     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
607                      createOrdering(&IRB, LI->getOrdering())};
608     Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
609     Value *C = IRB.CreateCall(TsanAtomicLoad[Idx], Args);
610     Value *Cast = IRB.CreateBitOrPointerCast(C, OrigTy);
611     I->replaceAllUsesWith(Cast);
612   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
613     Value *Addr = SI->getPointerOperand();
614     int Idx = getMemoryAccessFuncIndex(Addr, DL);
615     if (Idx < 0)
616       return false;
617     const unsigned ByteSize = 1U << Idx;
618     const unsigned BitSize = ByteSize * 8;
619     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
620     Type *PtrTy = Ty->getPointerTo();
621     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
622                      IRB.CreateBitOrPointerCast(SI->getValueOperand(), Ty),
623                      createOrdering(&IRB, SI->getOrdering())};
624     CallInst *C = CallInst::Create(TsanAtomicStore[Idx], Args);
625     ReplaceInstWithInst(I, C);
626   } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
627     Value *Addr = RMWI->getPointerOperand();
628     int Idx = getMemoryAccessFuncIndex(Addr, DL);
629     if (Idx < 0)
630       return false;
631     Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
632     if (!F)
633       return false;
634     const unsigned ByteSize = 1U << Idx;
635     const unsigned BitSize = ByteSize * 8;
636     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
637     Type *PtrTy = Ty->getPointerTo();
638     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
639                      IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
640                      createOrdering(&IRB, RMWI->getOrdering())};
641     CallInst *C = CallInst::Create(F, Args);
642     ReplaceInstWithInst(I, C);
643   } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
644     Value *Addr = CASI->getPointerOperand();
645     int Idx = getMemoryAccessFuncIndex(Addr, DL);
646     if (Idx < 0)
647       return false;
648     const unsigned ByteSize = 1U << Idx;
649     const unsigned BitSize = ByteSize * 8;
650     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
651     Type *PtrTy = Ty->getPointerTo();
652     Value *CmpOperand =
653       IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
654     Value *NewOperand =
655       IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
656     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
657                      CmpOperand,
658                      NewOperand,
659                      createOrdering(&IRB, CASI->getSuccessOrdering()),
660                      createOrdering(&IRB, CASI->getFailureOrdering())};
661     CallInst *C = IRB.CreateCall(TsanAtomicCAS[Idx], Args);
662     Value *Success = IRB.CreateICmpEQ(C, CmpOperand);
663     Value *OldVal = C;
664     Type *OrigOldValTy = CASI->getNewValOperand()->getType();
665     if (Ty != OrigOldValTy) {
666       // The value is a pointer, so we need to cast the return value.
667       OldVal = IRB.CreateIntToPtr(C, OrigOldValTy);
668     }
669 
670     Value *Res =
671       IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
672     Res = IRB.CreateInsertValue(Res, Success, 1);
673 
674     I->replaceAllUsesWith(Res);
675     I->eraseFromParent();
676   } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
677     Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
678     Function *F = FI->getSynchScope() == SingleThread ?
679         TsanAtomicSignalFence : TsanAtomicThreadFence;
680     CallInst *C = CallInst::Create(F, Args);
681     ReplaceInstWithInst(I, C);
682   }
683   return true;
684 }
685 
686 int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr,
687                                               const DataLayout &DL) {
688   Type *OrigPtrTy = Addr->getType();
689   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
690   assert(OrigTy->isSized());
691   uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
692   if (TypeSize != 8  && TypeSize != 16 &&
693       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
694     NumAccessesWithBadSize++;
695     // Ignore all unusual sizes.
696     return -1;
697   }
698   size_t Idx = countTrailingZeros(TypeSize / 8);
699   assert(Idx < kNumberOfAccessSizes);
700   return Idx;
701 }
702