1 //===-- ThreadSanitizer.cpp - race detector -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of ThreadSanitizer, a race detector.
10 //
11 // The tool is under development, for the details about previous versions see
12 // http://code.google.com/p/data-race-test
13 //
14 // The instrumentation phase is quite simple:
15 //   - Insert calls to run-time library before every memory access.
16 //      - Optimizations may apply to avoid instrumenting some of the accesses.
17 //   - Insert calls at function entry/exit.
18 // The rest is handled by the run-time library.
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/Optional.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/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/ProfileData/InstrProf.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Transforms/Utils/ModuleUtils.h"
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "tsan"
56 
57 static cl::opt<bool> ClInstrumentMemoryAccesses(
58     "tsan-instrument-memory-accesses", cl::init(true),
59     cl::desc("Instrument memory accesses"), cl::Hidden);
60 static cl::opt<bool>
61     ClInstrumentFuncEntryExit("tsan-instrument-func-entry-exit", cl::init(true),
62                               cl::desc("Instrument function entry and exit"),
63                               cl::Hidden);
64 static cl::opt<bool> ClHandleCxxExceptions(
65     "tsan-handle-cxx-exceptions", cl::init(true),
66     cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"),
67     cl::Hidden);
68 static cl::opt<bool> ClInstrumentAtomics("tsan-instrument-atomics",
69                                          cl::init(true),
70                                          cl::desc("Instrument atomics"),
71                                          cl::Hidden);
72 static cl::opt<bool> ClInstrumentMemIntrinsics(
73     "tsan-instrument-memintrinsics", cl::init(true),
74     cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
75 static cl::opt<bool> ClDistinguishVolatile(
76     "tsan-distinguish-volatile", cl::init(false),
77     cl::desc("Emit special instrumentation for accesses to volatiles"),
78     cl::Hidden);
79 static cl::opt<bool> ClInstrumentReadBeforeWrite(
80     "tsan-instrument-read-before-write", cl::init(false),
81     cl::desc("Do not eliminate read instrumentation for read-before-writes"),
82     cl::Hidden);
83 static cl::opt<bool> ClCompoundReadBeforeWrite(
84     "tsan-compound-read-before-write", cl::init(false),
85     cl::desc("Emit special compound instrumentation for reads-before-writes"),
86     cl::Hidden);
87 
88 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
89 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
90 STATISTIC(NumOmittedReadsBeforeWrite,
91           "Number of reads ignored due to following writes");
92 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
93 STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
94 STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
95 STATISTIC(NumOmittedReadsFromConstantGlobals,
96           "Number of reads from constant globals");
97 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
98 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
99 
100 const char kTsanModuleCtorName[] = "tsan.module_ctor";
101 const char kTsanInitName[] = "__tsan_init";
102 
103 namespace {
104 
105 /// ThreadSanitizer: instrument the code in module to find races.
106 ///
107 /// Instantiating ThreadSanitizer inserts the tsan runtime library API function
108 /// declarations into the module if they don't exist already. Instantiating
109 /// ensures the __tsan_init function is in the list of global constructors for
110 /// the module.
111 struct ThreadSanitizer {
112   ThreadSanitizer() {
113     // Sanity check options and warn user.
114     if (ClInstrumentReadBeforeWrite && ClCompoundReadBeforeWrite) {
115       errs()
116           << "warning: Option -tsan-compound-read-before-write has no effect "
117              "when -tsan-instrument-read-before-write is set.\n";
118     }
119   }
120 
121   bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
122 
123 private:
124   // Internal Instruction wrapper that contains more information about the
125   // Instruction from prior analysis.
126   struct InstructionInfo {
127     // Instrumentation emitted for this instruction is for a compounded set of
128     // read and write operations in the same basic block.
129     static constexpr unsigned kCompoundRW = (1U << 0);
130 
131     explicit InstructionInfo(Instruction *Inst) : Inst(Inst) {}
132 
133     Instruction *Inst;
134     unsigned Flags = 0;
135   };
136 
137   void initialize(Module &M);
138   bool instrumentLoadOrStore(const InstructionInfo &II, const DataLayout &DL);
139   bool instrumentAtomic(Instruction *I, const DataLayout &DL);
140   bool instrumentMemIntrinsic(Instruction *I);
141   void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
142                                       SmallVectorImpl<InstructionInfo> &All,
143                                       const DataLayout &DL);
144   bool addrPointsToConstantData(Value *Addr);
145   int getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr, const DataLayout &DL);
146   void InsertRuntimeIgnores(Function &F);
147 
148   Type *IntptrTy;
149   FunctionCallee TsanFuncEntry;
150   FunctionCallee TsanFuncExit;
151   FunctionCallee TsanIgnoreBegin;
152   FunctionCallee TsanIgnoreEnd;
153   // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
154   static const size_t kNumberOfAccessSizes = 5;
155   FunctionCallee TsanRead[kNumberOfAccessSizes];
156   FunctionCallee TsanWrite[kNumberOfAccessSizes];
157   FunctionCallee TsanUnalignedRead[kNumberOfAccessSizes];
158   FunctionCallee TsanUnalignedWrite[kNumberOfAccessSizes];
159   FunctionCallee TsanVolatileRead[kNumberOfAccessSizes];
160   FunctionCallee TsanVolatileWrite[kNumberOfAccessSizes];
161   FunctionCallee TsanUnalignedVolatileRead[kNumberOfAccessSizes];
162   FunctionCallee TsanUnalignedVolatileWrite[kNumberOfAccessSizes];
163   FunctionCallee TsanCompoundRW[kNumberOfAccessSizes];
164   FunctionCallee TsanUnalignedCompoundRW[kNumberOfAccessSizes];
165   FunctionCallee TsanAtomicLoad[kNumberOfAccessSizes];
166   FunctionCallee TsanAtomicStore[kNumberOfAccessSizes];
167   FunctionCallee TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1]
168                               [kNumberOfAccessSizes];
169   FunctionCallee TsanAtomicCAS[kNumberOfAccessSizes];
170   FunctionCallee TsanAtomicThreadFence;
171   FunctionCallee TsanAtomicSignalFence;
172   FunctionCallee TsanVptrUpdate;
173   FunctionCallee TsanVptrLoad;
174   FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;
175 };
176 
177 struct ThreadSanitizerLegacyPass : FunctionPass {
178   ThreadSanitizerLegacyPass() : FunctionPass(ID) {
179     initializeThreadSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
180   }
181   StringRef getPassName() const override;
182   void getAnalysisUsage(AnalysisUsage &AU) const override;
183   bool runOnFunction(Function &F) override;
184   bool doInitialization(Module &M) override;
185   static char ID; // Pass identification, replacement for typeid.
186 private:
187   Optional<ThreadSanitizer> TSan;
188 };
189 
190 void insertModuleCtor(Module &M) {
191   getOrCreateSanitizerCtorAndInitFunctions(
192       M, kTsanModuleCtorName, kTsanInitName, /*InitArgTypes=*/{},
193       /*InitArgs=*/{},
194       // This callback is invoked when the functions are created the first
195       // time. Hook them into the global ctors list in that case:
196       [&](Function *Ctor, FunctionCallee) { appendToGlobalCtors(M, Ctor, 0); });
197 }
198 
199 }  // namespace
200 
201 PreservedAnalyses ThreadSanitizerPass::run(Function &F,
202                                            FunctionAnalysisManager &FAM) {
203   ThreadSanitizer TSan;
204   if (TSan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))
205     return PreservedAnalyses::none();
206   return PreservedAnalyses::all();
207 }
208 
209 PreservedAnalyses ThreadSanitizerPass::run(Module &M,
210                                            ModuleAnalysisManager &MAM) {
211   insertModuleCtor(M);
212   return PreservedAnalyses::none();
213 }
214 
215 char ThreadSanitizerLegacyPass::ID = 0;
216 INITIALIZE_PASS_BEGIN(ThreadSanitizerLegacyPass, "tsan",
217                       "ThreadSanitizer: detects data races.", false, false)
218 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
219 INITIALIZE_PASS_END(ThreadSanitizerLegacyPass, "tsan",
220                     "ThreadSanitizer: detects data races.", false, false)
221 
222 StringRef ThreadSanitizerLegacyPass::getPassName() const {
223   return "ThreadSanitizerLegacyPass";
224 }
225 
226 void ThreadSanitizerLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
227   AU.addRequired<TargetLibraryInfoWrapperPass>();
228 }
229 
230 bool ThreadSanitizerLegacyPass::doInitialization(Module &M) {
231   insertModuleCtor(M);
232   TSan.emplace();
233   return true;
234 }
235 
236 bool ThreadSanitizerLegacyPass::runOnFunction(Function &F) {
237   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
238   TSan->sanitizeFunction(F, TLI);
239   return true;
240 }
241 
242 FunctionPass *llvm::createThreadSanitizerLegacyPassPass() {
243   return new ThreadSanitizerLegacyPass();
244 }
245 
246 void ThreadSanitizer::initialize(Module &M) {
247   const DataLayout &DL = M.getDataLayout();
248   IntptrTy = DL.getIntPtrType(M.getContext());
249 
250   IRBuilder<> IRB(M.getContext());
251   AttributeList Attr;
252   Attr = Attr.addAttribute(M.getContext(), AttributeList::FunctionIndex,
253                            Attribute::NoUnwind);
254   // Initialize the callbacks.
255   TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", Attr,
256                                         IRB.getVoidTy(), IRB.getInt8PtrTy());
257   TsanFuncExit =
258       M.getOrInsertFunction("__tsan_func_exit", Attr, IRB.getVoidTy());
259   TsanIgnoreBegin = M.getOrInsertFunction("__tsan_ignore_thread_begin", Attr,
260                                           IRB.getVoidTy());
261   TsanIgnoreEnd =
262       M.getOrInsertFunction("__tsan_ignore_thread_end", Attr, IRB.getVoidTy());
263   IntegerType *OrdTy = IRB.getInt32Ty();
264   for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
265     const unsigned ByteSize = 1U << i;
266     const unsigned BitSize = ByteSize * 8;
267     std::string ByteSizeStr = utostr(ByteSize);
268     std::string BitSizeStr = utostr(BitSize);
269     SmallString<32> ReadName("__tsan_read" + ByteSizeStr);
270     TsanRead[i] = M.getOrInsertFunction(ReadName, Attr, IRB.getVoidTy(),
271                                         IRB.getInt8PtrTy());
272 
273     SmallString<32> WriteName("__tsan_write" + ByteSizeStr);
274     TsanWrite[i] = M.getOrInsertFunction(WriteName, Attr, IRB.getVoidTy(),
275                                          IRB.getInt8PtrTy());
276 
277     SmallString<64> UnalignedReadName("__tsan_unaligned_read" + ByteSizeStr);
278     TsanUnalignedRead[i] = M.getOrInsertFunction(
279         UnalignedReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
280 
281     SmallString<64> UnalignedWriteName("__tsan_unaligned_write" + ByteSizeStr);
282     TsanUnalignedWrite[i] = M.getOrInsertFunction(
283         UnalignedWriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
284 
285     SmallString<64> VolatileReadName("__tsan_volatile_read" + ByteSizeStr);
286     TsanVolatileRead[i] = M.getOrInsertFunction(
287         VolatileReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
288 
289     SmallString<64> VolatileWriteName("__tsan_volatile_write" + ByteSizeStr);
290     TsanVolatileWrite[i] = M.getOrInsertFunction(
291         VolatileWriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
292 
293     SmallString<64> UnalignedVolatileReadName("__tsan_unaligned_volatile_read" +
294                                               ByteSizeStr);
295     TsanUnalignedVolatileRead[i] = M.getOrInsertFunction(
296         UnalignedVolatileReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
297 
298     SmallString<64> UnalignedVolatileWriteName(
299         "__tsan_unaligned_volatile_write" + ByteSizeStr);
300     TsanUnalignedVolatileWrite[i] = M.getOrInsertFunction(
301         UnalignedVolatileWriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
302 
303     SmallString<64> CompoundRWName("__tsan_read_write" + ByteSizeStr);
304     TsanCompoundRW[i] = M.getOrInsertFunction(
305         CompoundRWName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
306 
307     SmallString<64> UnalignedCompoundRWName("__tsan_unaligned_read_write" +
308                                             ByteSizeStr);
309     TsanUnalignedCompoundRW[i] = M.getOrInsertFunction(
310         UnalignedCompoundRWName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy());
311 
312     Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
313     Type *PtrTy = Ty->getPointerTo();
314     SmallString<32> AtomicLoadName("__tsan_atomic" + BitSizeStr + "_load");
315     TsanAtomicLoad[i] =
316         M.getOrInsertFunction(AtomicLoadName, Attr, Ty, PtrTy, OrdTy);
317 
318     SmallString<32> AtomicStoreName("__tsan_atomic" + BitSizeStr + "_store");
319     TsanAtomicStore[i] = M.getOrInsertFunction(
320         AtomicStoreName, Attr, IRB.getVoidTy(), PtrTy, Ty, OrdTy);
321 
322     for (unsigned Op = AtomicRMWInst::FIRST_BINOP;
323          Op <= AtomicRMWInst::LAST_BINOP; ++Op) {
324       TsanAtomicRMW[Op][i] = nullptr;
325       const char *NamePart = nullptr;
326       if (Op == AtomicRMWInst::Xchg)
327         NamePart = "_exchange";
328       else if (Op == AtomicRMWInst::Add)
329         NamePart = "_fetch_add";
330       else if (Op == AtomicRMWInst::Sub)
331         NamePart = "_fetch_sub";
332       else if (Op == AtomicRMWInst::And)
333         NamePart = "_fetch_and";
334       else if (Op == AtomicRMWInst::Or)
335         NamePart = "_fetch_or";
336       else if (Op == AtomicRMWInst::Xor)
337         NamePart = "_fetch_xor";
338       else if (Op == AtomicRMWInst::Nand)
339         NamePart = "_fetch_nand";
340       else
341         continue;
342       SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
343       TsanAtomicRMW[Op][i] =
344           M.getOrInsertFunction(RMWName, Attr, Ty, PtrTy, Ty, OrdTy);
345     }
346 
347     SmallString<32> AtomicCASName("__tsan_atomic" + BitSizeStr +
348                                   "_compare_exchange_val");
349     TsanAtomicCAS[i] = M.getOrInsertFunction(AtomicCASName, Attr, Ty, PtrTy, Ty,
350                                              Ty, OrdTy, OrdTy);
351   }
352   TsanVptrUpdate =
353       M.getOrInsertFunction("__tsan_vptr_update", Attr, IRB.getVoidTy(),
354                             IRB.getInt8PtrTy(), IRB.getInt8PtrTy());
355   TsanVptrLoad = M.getOrInsertFunction("__tsan_vptr_read", Attr,
356                                        IRB.getVoidTy(), IRB.getInt8PtrTy());
357   TsanAtomicThreadFence = M.getOrInsertFunction("__tsan_atomic_thread_fence",
358                                                 Attr, IRB.getVoidTy(), OrdTy);
359   TsanAtomicSignalFence = M.getOrInsertFunction("__tsan_atomic_signal_fence",
360                                                 Attr, IRB.getVoidTy(), OrdTy);
361 
362   MemmoveFn =
363       M.getOrInsertFunction("memmove", Attr, IRB.getInt8PtrTy(),
364                             IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy);
365   MemcpyFn =
366       M.getOrInsertFunction("memcpy", Attr, IRB.getInt8PtrTy(),
367                             IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy);
368   MemsetFn =
369       M.getOrInsertFunction("memset", Attr, IRB.getInt8PtrTy(),
370                             IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy);
371 }
372 
373 static bool isVtableAccess(Instruction *I) {
374   if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
375     return Tag->isTBAAVtableAccess();
376   return false;
377 }
378 
379 // Do not instrument known races/"benign races" that come from compiler
380 // instrumentatin. The user has no way of suppressing them.
381 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
382   // Peel off GEPs and BitCasts.
383   Addr = Addr->stripInBoundsOffsets();
384 
385   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
386     if (GV->hasSection()) {
387       StringRef SectionName = GV->getSection();
388       // Check if the global is in the PGO counters section.
389       auto OF = Triple(M->getTargetTriple()).getObjectFormat();
390       if (SectionName.endswith(
391               getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
392         return false;
393     }
394 
395     // Check if the global is private gcov data.
396     if (GV->getName().startswith("__llvm_gcov") ||
397         GV->getName().startswith("__llvm_gcda"))
398       return false;
399   }
400 
401   // Do not instrument acesses from different address spaces; we cannot deal
402   // with them.
403   if (Addr) {
404     Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
405     if (PtrTy->getPointerAddressSpace() != 0)
406       return false;
407   }
408 
409   return true;
410 }
411 
412 bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
413   // If this is a GEP, just analyze its pointer operand.
414   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
415     Addr = GEP->getPointerOperand();
416 
417   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
418     if (GV->isConstant()) {
419       // Reads from constant globals can not race with any writes.
420       NumOmittedReadsFromConstantGlobals++;
421       return true;
422     }
423   } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
424     if (isVtableAccess(L)) {
425       // Reads from a vtable pointer can not race with any writes.
426       NumOmittedReadsFromVtable++;
427       return true;
428     }
429   }
430   return false;
431 }
432 
433 // Instrumenting some of the accesses may be proven redundant.
434 // Currently handled:
435 //  - read-before-write (within same BB, no calls between)
436 //  - not captured variables
437 //
438 // We do not handle some of the patterns that should not survive
439 // after the classic compiler optimizations.
440 // E.g. two reads from the same temp should be eliminated by CSE,
441 // two writes should be eliminated by DSE, etc.
442 //
443 // 'Local' is a vector of insns within the same BB (no calls between).
444 // 'All' is a vector of insns that will be instrumented.
445 void ThreadSanitizer::chooseInstructionsToInstrument(
446     SmallVectorImpl<Instruction *> &Local,
447     SmallVectorImpl<InstructionInfo> &All, const DataLayout &DL) {
448   DenseMap<Value *, size_t> WriteTargets; // Map of addresses to index in All
449   // Iterate from the end.
450   for (Instruction *I : reverse(Local)) {
451     const bool IsWrite = isa<StoreInst>(*I);
452     Value *Addr = IsWrite ? cast<StoreInst>(I)->getPointerOperand()
453                           : cast<LoadInst>(I)->getPointerOperand();
454 
455     if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
456       continue;
457 
458     if (!IsWrite) {
459       const auto WriteEntry = WriteTargets.find(Addr);
460       if (!ClInstrumentReadBeforeWrite && WriteEntry != WriteTargets.end()) {
461         auto &WI = All[WriteEntry->second];
462         // If we distinguish volatile accesses and if either the read or write
463         // is volatile, do not omit any instrumentation.
464         const bool AnyVolatile =
465             ClDistinguishVolatile && (cast<LoadInst>(I)->isVolatile() ||
466                                       cast<StoreInst>(WI.Inst)->isVolatile());
467         if (!AnyVolatile) {
468           // We will write to this temp, so no reason to analyze the read.
469           // Mark the write instruction as compound.
470           WI.Flags |= InstructionInfo::kCompoundRW;
471           NumOmittedReadsBeforeWrite++;
472           continue;
473         }
474       }
475 
476       if (addrPointsToConstantData(Addr)) {
477         // Addr points to some constant data -- it can not race with any writes.
478         continue;
479       }
480     }
481 
482     if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&
483         !PointerMayBeCaptured(Addr, true, true)) {
484       // The variable is addressable but not captured, so it cannot be
485       // referenced from a different thread and participate in a data race
486       // (see llvm/Analysis/CaptureTracking.h for details).
487       NumOmittedNonCaptured++;
488       continue;
489     }
490 
491     // Instrument this instruction.
492     All.emplace_back(I);
493     if (IsWrite) {
494       // For read-before-write and compound instrumentation we only need one
495       // write target, and we can override any previous entry if it exists.
496       WriteTargets[Addr] = All.size() - 1;
497     }
498   }
499   Local.clear();
500 }
501 
502 static bool isAtomic(Instruction *I) {
503   // TODO: Ask TTI whether synchronization scope is between threads.
504   if (LoadInst *LI = dyn_cast<LoadInst>(I))
505     return LI->isAtomic() && LI->getSyncScopeID() != SyncScope::SingleThread;
506   if (StoreInst *SI = dyn_cast<StoreInst>(I))
507     return SI->isAtomic() && SI->getSyncScopeID() != SyncScope::SingleThread;
508   if (isa<AtomicRMWInst>(I))
509     return true;
510   if (isa<AtomicCmpXchgInst>(I))
511     return true;
512   if (isa<FenceInst>(I))
513     return true;
514   return false;
515 }
516 
517 void ThreadSanitizer::InsertRuntimeIgnores(Function &F) {
518   IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
519   IRB.CreateCall(TsanIgnoreBegin);
520   EscapeEnumerator EE(F, "tsan_ignore_cleanup", ClHandleCxxExceptions);
521   while (IRBuilder<> *AtExit = EE.Next()) {
522     AtExit->CreateCall(TsanIgnoreEnd);
523   }
524 }
525 
526 bool ThreadSanitizer::sanitizeFunction(Function &F,
527                                        const TargetLibraryInfo &TLI) {
528   // This is required to prevent instrumenting call to __tsan_init from within
529   // the module constructor.
530   if (F.getName() == kTsanModuleCtorName)
531     return false;
532   // Naked functions can not have prologue/epilogue
533   // (__tsan_func_entry/__tsan_func_exit) generated, so don't instrument them at
534   // all.
535   if (F.hasFnAttribute(Attribute::Naked))
536     return false;
537   initialize(*F.getParent());
538   SmallVector<InstructionInfo, 8> AllLoadsAndStores;
539   SmallVector<Instruction*, 8> LocalLoadsAndStores;
540   SmallVector<Instruction*, 8> AtomicAccesses;
541   SmallVector<Instruction*, 8> MemIntrinCalls;
542   bool Res = false;
543   bool HasCalls = false;
544   bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);
545   const DataLayout &DL = F.getParent()->getDataLayout();
546 
547   // Traverse all instructions, collect loads/stores/returns, check for calls.
548   for (auto &BB : F) {
549     for (auto &Inst : BB) {
550       if (isAtomic(&Inst))
551         AtomicAccesses.push_back(&Inst);
552       else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
553         LocalLoadsAndStores.push_back(&Inst);
554       else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
555         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
556           maybeMarkSanitizerLibraryCallNoBuiltin(CI, &TLI);
557         if (isa<MemIntrinsic>(Inst))
558           MemIntrinCalls.push_back(&Inst);
559         HasCalls = true;
560         chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
561                                        DL);
562       }
563     }
564     chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
565   }
566 
567   // We have collected all loads and stores.
568   // FIXME: many of these accesses do not need to be checked for races
569   // (e.g. variables that do not escape, etc).
570 
571   // Instrument memory accesses only if we want to report bugs in the function.
572   if (ClInstrumentMemoryAccesses && SanitizeFunction)
573     for (const auto &II : AllLoadsAndStores) {
574       Res |= instrumentLoadOrStore(II, DL);
575     }
576 
577   // Instrument atomic memory accesses in any case (they can be used to
578   // implement synchronization).
579   if (ClInstrumentAtomics)
580     for (auto Inst : AtomicAccesses) {
581       Res |= instrumentAtomic(Inst, DL);
582     }
583 
584   if (ClInstrumentMemIntrinsics && SanitizeFunction)
585     for (auto Inst : MemIntrinCalls) {
586       Res |= instrumentMemIntrinsic(Inst);
587     }
588 
589   if (F.hasFnAttribute("sanitize_thread_no_checking_at_run_time")) {
590     assert(!F.hasFnAttribute(Attribute::SanitizeThread));
591     if (HasCalls)
592       InsertRuntimeIgnores(F);
593   }
594 
595   // Instrument function entry/exit points if there were instrumented accesses.
596   if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
597     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
598     Value *ReturnAddress = IRB.CreateCall(
599         Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
600         IRB.getInt32(0));
601     IRB.CreateCall(TsanFuncEntry, ReturnAddress);
602 
603     EscapeEnumerator EE(F, "tsan_cleanup", ClHandleCxxExceptions);
604     while (IRBuilder<> *AtExit = EE.Next()) {
605       AtExit->CreateCall(TsanFuncExit, {});
606     }
607     Res = true;
608   }
609   return Res;
610 }
611 
612 bool ThreadSanitizer::instrumentLoadOrStore(const InstructionInfo &II,
613                                             const DataLayout &DL) {
614   IRBuilder<> IRB(II.Inst);
615   const bool IsWrite = isa<StoreInst>(*II.Inst);
616   Value *Addr = IsWrite ? cast<StoreInst>(II.Inst)->getPointerOperand()
617                         : cast<LoadInst>(II.Inst)->getPointerOperand();
618   Type *OrigTy = getLoadStoreType(II.Inst);
619 
620   // swifterror memory addresses are mem2reg promoted by instruction selection.
621   // As such they cannot have regular uses like an instrumentation function and
622   // it makes no sense to track them as memory.
623   if (Addr->isSwiftError())
624     return false;
625 
626   int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);
627   if (Idx < 0)
628     return false;
629   if (IsWrite && isVtableAccess(II.Inst)) {
630     LLVM_DEBUG(dbgs() << "  VPTR : " << *II.Inst << "\n");
631     Value *StoredValue = cast<StoreInst>(II.Inst)->getValueOperand();
632     // StoredValue may be a vector type if we are storing several vptrs at once.
633     // In this case, just take the first element of the vector since this is
634     // enough to find vptr races.
635     if (isa<VectorType>(StoredValue->getType()))
636       StoredValue = IRB.CreateExtractElement(
637           StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
638     if (StoredValue->getType()->isIntegerTy())
639       StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
640     // Call TsanVptrUpdate.
641     IRB.CreateCall(TsanVptrUpdate,
642                    {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
643                     IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
644     NumInstrumentedVtableWrites++;
645     return true;
646   }
647   if (!IsWrite && isVtableAccess(II.Inst)) {
648     IRB.CreateCall(TsanVptrLoad,
649                    IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
650     NumInstrumentedVtableReads++;
651     return true;
652   }
653 
654   const unsigned Alignment = IsWrite ? cast<StoreInst>(II.Inst)->getAlignment()
655                                      : cast<LoadInst>(II.Inst)->getAlignment();
656   const bool IsCompoundRW =
657       ClCompoundReadBeforeWrite && (II.Flags & InstructionInfo::kCompoundRW);
658   const bool IsVolatile = ClDistinguishVolatile &&
659                           (IsWrite ? cast<StoreInst>(II.Inst)->isVolatile()
660                                    : cast<LoadInst>(II.Inst)->isVolatile());
661   assert((!IsVolatile || !IsCompoundRW) && "Compound volatile invalid!");
662 
663   const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
664   FunctionCallee OnAccessFunc = nullptr;
665   if (Alignment == 0 || Alignment >= 8 || (Alignment % (TypeSize / 8)) == 0) {
666     if (IsCompoundRW)
667       OnAccessFunc = TsanCompoundRW[Idx];
668     else if (IsVolatile)
669       OnAccessFunc = IsWrite ? TsanVolatileWrite[Idx] : TsanVolatileRead[Idx];
670     else
671       OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
672   } else {
673     if (IsCompoundRW)
674       OnAccessFunc = TsanUnalignedCompoundRW[Idx];
675     else if (IsVolatile)
676       OnAccessFunc = IsWrite ? TsanUnalignedVolatileWrite[Idx]
677                              : TsanUnalignedVolatileRead[Idx];
678     else
679       OnAccessFunc = IsWrite ? TsanUnalignedWrite[Idx] : TsanUnalignedRead[Idx];
680   }
681   IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
682   if (IsCompoundRW || IsWrite)
683     NumInstrumentedWrites++;
684   if (IsCompoundRW || !IsWrite)
685     NumInstrumentedReads++;
686   return true;
687 }
688 
689 static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
690   uint32_t v = 0;
691   switch (ord) {
692     case AtomicOrdering::NotAtomic:
693       llvm_unreachable("unexpected atomic ordering!");
694     case AtomicOrdering::Unordered:              LLVM_FALLTHROUGH;
695     case AtomicOrdering::Monotonic:              v = 0; break;
696     // Not specified yet:
697     // case AtomicOrdering::Consume:                v = 1; break;
698     case AtomicOrdering::Acquire:                v = 2; break;
699     case AtomicOrdering::Release:                v = 3; break;
700     case AtomicOrdering::AcquireRelease:         v = 4; break;
701     case AtomicOrdering::SequentiallyConsistent: v = 5; break;
702   }
703   return IRB->getInt32(v);
704 }
705 
706 // If a memset intrinsic gets inlined by the code gen, we will miss races on it.
707 // So, we either need to ensure the intrinsic is not inlined, or instrument it.
708 // We do not instrument memset/memmove/memcpy intrinsics (too complicated),
709 // instead we simply replace them with regular function calls, which are then
710 // intercepted by the run-time.
711 // Since tsan is running after everyone else, the calls should not be
712 // replaced back with intrinsics. If that becomes wrong at some point,
713 // we will need to call e.g. __tsan_memset to avoid the intrinsics.
714 bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
715   IRBuilder<> IRB(I);
716   if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
717     IRB.CreateCall(
718         MemsetFn,
719         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
720          IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
721          IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
722     I->eraseFromParent();
723   } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
724     IRB.CreateCall(
725         isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
726         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
727          IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
728          IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
729     I->eraseFromParent();
730   }
731   return false;
732 }
733 
734 // Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
735 // standards.  For background see C++11 standard.  A slightly older, publicly
736 // available draft of the standard (not entirely up-to-date, but close enough
737 // for casual browsing) is available here:
738 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
739 // The following page contains more background information:
740 // http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
741 
742 bool ThreadSanitizer::instrumentAtomic(Instruction *I, const DataLayout &DL) {
743   IRBuilder<> IRB(I);
744   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
745     Value *Addr = LI->getPointerOperand();
746     Type *OrigTy = LI->getType();
747     int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);
748     if (Idx < 0)
749       return false;
750     const unsigned ByteSize = 1U << Idx;
751     const unsigned BitSize = ByteSize * 8;
752     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
753     Type *PtrTy = Ty->getPointerTo();
754     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
755                      createOrdering(&IRB, LI->getOrdering())};
756     Value *C = IRB.CreateCall(TsanAtomicLoad[Idx], Args);
757     Value *Cast = IRB.CreateBitOrPointerCast(C, OrigTy);
758     I->replaceAllUsesWith(Cast);
759   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
760     Value *Addr = SI->getPointerOperand();
761     int Idx =
762         getMemoryAccessFuncIndex(SI->getValueOperand()->getType(), Addr, DL);
763     if (Idx < 0)
764       return false;
765     const unsigned ByteSize = 1U << Idx;
766     const unsigned BitSize = ByteSize * 8;
767     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
768     Type *PtrTy = Ty->getPointerTo();
769     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
770                      IRB.CreateBitOrPointerCast(SI->getValueOperand(), Ty),
771                      createOrdering(&IRB, SI->getOrdering())};
772     CallInst *C = CallInst::Create(TsanAtomicStore[Idx], Args);
773     ReplaceInstWithInst(I, C);
774   } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
775     Value *Addr = RMWI->getPointerOperand();
776     int Idx =
777         getMemoryAccessFuncIndex(RMWI->getValOperand()->getType(), Addr, DL);
778     if (Idx < 0)
779       return false;
780     FunctionCallee F = TsanAtomicRMW[RMWI->getOperation()][Idx];
781     if (!F)
782       return false;
783     const unsigned ByteSize = 1U << Idx;
784     const unsigned BitSize = ByteSize * 8;
785     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
786     Type *PtrTy = Ty->getPointerTo();
787     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
788                      IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
789                      createOrdering(&IRB, RMWI->getOrdering())};
790     CallInst *C = CallInst::Create(F, Args);
791     ReplaceInstWithInst(I, C);
792   } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
793     Value *Addr = CASI->getPointerOperand();
794     Type *OrigOldValTy = CASI->getNewValOperand()->getType();
795     int Idx = getMemoryAccessFuncIndex(OrigOldValTy, Addr, DL);
796     if (Idx < 0)
797       return false;
798     const unsigned ByteSize = 1U << Idx;
799     const unsigned BitSize = ByteSize * 8;
800     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
801     Type *PtrTy = Ty->getPointerTo();
802     Value *CmpOperand =
803       IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
804     Value *NewOperand =
805       IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
806     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
807                      CmpOperand,
808                      NewOperand,
809                      createOrdering(&IRB, CASI->getSuccessOrdering()),
810                      createOrdering(&IRB, CASI->getFailureOrdering())};
811     CallInst *C = IRB.CreateCall(TsanAtomicCAS[Idx], Args);
812     Value *Success = IRB.CreateICmpEQ(C, CmpOperand);
813     Value *OldVal = C;
814     if (Ty != OrigOldValTy) {
815       // The value is a pointer, so we need to cast the return value.
816       OldVal = IRB.CreateIntToPtr(C, OrigOldValTy);
817     }
818 
819     Value *Res =
820       IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
821     Res = IRB.CreateInsertValue(Res, Success, 1);
822 
823     I->replaceAllUsesWith(Res);
824     I->eraseFromParent();
825   } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
826     Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
827     FunctionCallee F = FI->getSyncScopeID() == SyncScope::SingleThread
828                            ? TsanAtomicSignalFence
829                            : TsanAtomicThreadFence;
830     CallInst *C = CallInst::Create(F, Args);
831     ReplaceInstWithInst(I, C);
832   }
833   return true;
834 }
835 
836 int ThreadSanitizer::getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr,
837                                               const DataLayout &DL) {
838   assert(OrigTy->isSized());
839   assert(
840       cast<PointerType>(Addr->getType())->isOpaqueOrPointeeTypeMatches(OrigTy));
841   uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
842   if (TypeSize != 8  && TypeSize != 16 &&
843       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
844     NumAccessesWithBadSize++;
845     // Ignore all unusual sizes.
846     return -1;
847   }
848   size_t Idx = countTrailingZeros(TypeSize / 8);
849   assert(Idx < kNumberOfAccessSizes);
850   return Idx;
851 }
852