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