LLVM  4.0.0
ThreadSanitizer.cpp
Go to the documentation of this file.
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 
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"
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"
42 #include "llvm/Support/Debug.h"
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "tsan"
53 
55  "tsan-instrument-memory-accesses", cl::init(true),
56  cl::desc("Instrument memory accesses"), cl::Hidden);
58  "tsan-instrument-func-entry-exit", cl::init(true),
59  cl::desc("Instrument function entry and exit"), cl::Hidden);
61  "tsan-handle-cxx-exceptions", cl::init(true),
62  cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"),
63  cl::Hidden);
65  "tsan-instrument-atomics", cl::init(true),
66  cl::desc("Instrument atomics"), cl::Hidden);
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,
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];
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;
137  ThreadSanitizer, "tsan",
138  "ThreadSanitizer: detects data races.",
139  false, false)
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 {
150 }
151 
153  return new ThreadSanitizer();
154 }
155 
156 void ThreadSanitizer::initializeCallbacks(Module &M) {
157  IRBuilder<> IRB(M.getContext());
158  AttributeSet Attr;
159  Attr = Attr.addAttribute(M.getContext(), AttributeSet::FunctionIndex, Attribute::NoUnwind);
160  // Initialize the callbacks.
162  "__tsan_func_entry", Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
163  TsanFuncExit = checkSanitizerInterfaceFunction(
164  M.getOrInsertFunction("__tsan_func_exit", Attr, IRB.getVoidTy(), nullptr));
166  "__tsan_ignore_thread_begin", Attr, IRB.getVoidTy(), nullptr));
168  "__tsan_ignore_thread_end", Attr, IRB.getVoidTy(), nullptr));
169  OrdTy = IRB.getInt32Ty();
170  for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
171  const unsigned ByteSize = 1U << i;
172  const unsigned BitSize = ByteSize * 8;
173  std::string ByteSizeStr = utostr(ByteSize);
174  std::string BitSizeStr = utostr(BitSize);
175  SmallString<32> ReadName("__tsan_read" + ByteSizeStr);
177  ReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
178 
179  SmallString<32> WriteName("__tsan_write" + ByteSizeStr);
181  WriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
182 
183  SmallString<64> UnalignedReadName("__tsan_unaligned_read" + ByteSizeStr);
184  TsanUnalignedRead[i] =
186  UnalignedReadName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
187 
188  SmallString<64> UnalignedWriteName("__tsan_unaligned_write" + ByteSizeStr);
189  TsanUnalignedWrite[i] =
191  UnalignedWriteName, Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
192 
193  Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
194  Type *PtrTy = Ty->getPointerTo();
195  SmallString<32> AtomicLoadName("__tsan_atomic" + BitSizeStr + "_load");
196  TsanAtomicLoad[i] = checkSanitizerInterfaceFunction(
197  M.getOrInsertFunction(AtomicLoadName, Attr, Ty, PtrTy, OrdTy, nullptr));
198 
199  SmallString<32> AtomicStoreName("__tsan_atomic" + BitSizeStr + "_store");
201  AtomicStoreName, Attr, IRB.getVoidTy(), PtrTy, Ty, OrdTy, nullptr));
202 
203  for (int op = AtomicRMWInst::FIRST_BINOP;
205  TsanAtomicRMW[op][i] = nullptr;
206  const char *NamePart = nullptr;
207  if (op == AtomicRMWInst::Xchg)
208  NamePart = "_exchange";
209  else if (op == AtomicRMWInst::Add)
210  NamePart = "_fetch_add";
211  else if (op == AtomicRMWInst::Sub)
212  NamePart = "_fetch_sub";
213  else if (op == AtomicRMWInst::And)
214  NamePart = "_fetch_and";
215  else if (op == AtomicRMWInst::Or)
216  NamePart = "_fetch_or";
217  else if (op == AtomicRMWInst::Xor)
218  NamePart = "_fetch_xor";
219  else if (op == AtomicRMWInst::Nand)
220  NamePart = "_fetch_nand";
221  else
222  continue;
223  SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
224  TsanAtomicRMW[op][i] = checkSanitizerInterfaceFunction(
225  M.getOrInsertFunction(RMWName, Attr, Ty, PtrTy, Ty, OrdTy, nullptr));
226  }
227 
228  SmallString<32> AtomicCASName("__tsan_atomic" + BitSizeStr +
229  "_compare_exchange_val");
231  AtomicCASName, Attr, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, nullptr));
232  }
233  TsanVptrUpdate = checkSanitizerInterfaceFunction(
234  M.getOrInsertFunction("__tsan_vptr_update", Attr, IRB.getVoidTy(),
235  IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), nullptr));
237  "__tsan_vptr_read", Attr, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
238  TsanAtomicThreadFence = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
239  "__tsan_atomic_thread_fence", Attr, IRB.getVoidTy(), OrdTy, nullptr));
240  TsanAtomicSignalFence = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
241  "__tsan_atomic_signal_fence", Attr, IRB.getVoidTy(), OrdTy, nullptr));
242 
244  M.getOrInsertFunction("memmove", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
245  IRB.getInt8PtrTy(), IntptrTy, nullptr));
247  M.getOrInsertFunction("memcpy", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
248  IRB.getInt8PtrTy(), IntptrTy, nullptr));
250  M.getOrInsertFunction("memset", Attr, IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
251  IRB.getInt32Ty(), IntptrTy, nullptr));
252 }
253 
254 bool ThreadSanitizer::doInitialization(Module &M) {
255  const DataLayout &DL = M.getDataLayout();
256  IntptrTy = DL.getIntPtrType(M.getContext());
257  std::tie(TsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
258  M, kTsanModuleCtorName, kTsanInitName, /*InitArgTypes=*/{},
259  /*InitArgs=*/{});
260 
261  appendToGlobalCtors(M, TsanCtorFunction, 0);
262 
263  return true;
264 }
265 
266 static bool isVtableAccess(Instruction *I) {
268  return Tag->isTBAAVtableAccess();
269  return false;
270 }
271 
272 // Do not instrument known races/"benign races" that come from compiler
273 // instrumentatin. The user has no way of suppressing them.
275  // Peel off GEPs and BitCasts.
276  Addr = Addr->stripInBoundsOffsets();
277 
278  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
279  if (GV->hasSection()) {
280  StringRef SectionName = GV->getSection();
281  // Check if the global is in the PGO counters section.
283  /*AddSegment=*/false)))
284  return false;
285  }
286 
287  // Check if the global is private gcov data.
288  if (GV->getName().startswith("__llvm_gcov") ||
289  GV->getName().startswith("__llvm_gcda"))
290  return false;
291  }
292 
293  // Do not instrument acesses from different address spaces; we cannot deal
294  // with them.
295  if (Addr) {
296  Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
297  if (PtrTy->getPointerAddressSpace() != 0)
298  return false;
299  }
300 
301  return true;
302 }
303 
304 bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
305  // If this is a GEP, just analyze its pointer operand.
306  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
307  Addr = GEP->getPointerOperand();
308 
309  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
310  if (GV->isConstant()) {
311  // Reads from constant globals can not race with any writes.
312  NumOmittedReadsFromConstantGlobals++;
313  return true;
314  }
315  } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
316  if (isVtableAccess(L)) {
317  // Reads from a vtable pointer can not race with any writes.
318  NumOmittedReadsFromVtable++;
319  return true;
320  }
321  }
322  return false;
323 }
324 
325 // Instrumenting some of the accesses may be proven redundant.
326 // Currently handled:
327 // - read-before-write (within same BB, no calls between)
328 // - not captured variables
329 //
330 // We do not handle some of the patterns that should not survive
331 // after the classic compiler optimizations.
332 // E.g. two reads from the same temp should be eliminated by CSE,
333 // two writes should be eliminated by DSE, etc.
334 //
335 // 'Local' is a vector of insns within the same BB (no calls between).
336 // 'All' is a vector of insns that will be instrumented.
337 void ThreadSanitizer::chooseInstructionsToInstrument(
339  const DataLayout &DL) {
340  SmallSet<Value*, 8> WriteTargets;
341  // Iterate from the end.
342  for (Instruction *I : reverse(Local)) {
343  if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
344  Value *Addr = Store->getPointerOperand();
346  continue;
347  WriteTargets.insert(Addr);
348  } else {
349  LoadInst *Load = cast<LoadInst>(I);
350  Value *Addr = Load->getPointerOperand();
352  continue;
353  if (WriteTargets.count(Addr)) {
354  // We will write to this temp, so no reason to analyze the read.
355  NumOmittedReadsBeforeWrite++;
356  continue;
357  }
358  if (addrPointsToConstantData(Addr)) {
359  // Addr points to some constant data -- it can not race with any writes.
360  continue;
361  }
362  }
363  Value *Addr = isa<StoreInst>(*I)
364  ? cast<StoreInst>(I)->getPointerOperand()
366  if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
367  !PointerMayBeCaptured(Addr, true, true)) {
368  // The variable is addressable but not captured, so it cannot be
369  // referenced from a different thread and participate in a data race
370  // (see llvm/Analysis/CaptureTracking.h for details).
371  NumOmittedNonCaptured++;
372  continue;
373  }
374  All.push_back(I);
375  }
376  Local.clear();
377 }
378 
379 static bool isAtomic(Instruction *I) {
380  if (LoadInst *LI = dyn_cast<LoadInst>(I))
381  return LI->isAtomic() && LI->getSynchScope() == CrossThread;
382  if (StoreInst *SI = dyn_cast<StoreInst>(I))
383  return SI->isAtomic() && SI->getSynchScope() == CrossThread;
384  if (isa<AtomicRMWInst>(I))
385  return true;
386  if (isa<AtomicCmpXchgInst>(I))
387  return true;
388  if (isa<FenceInst>(I))
389  return true;
390  return false;
391 }
392 
393 void ThreadSanitizer::InsertRuntimeIgnores(Function &F) {
395  IRB.CreateCall(TsanIgnoreBegin);
396  EscapeEnumerator EE(F, "tsan_ignore_cleanup", ClHandleCxxExceptions);
397  while (IRBuilder<> *AtExit = EE.Next()) {
398  AtExit->CreateCall(TsanIgnoreEnd);
399  }
400 }
401 
402 bool ThreadSanitizer::runOnFunction(Function &F) {
403  // This is required to prevent instrumenting call to __tsan_init from within
404  // the module constructor.
405  if (&F == TsanCtorFunction)
406  return false;
407  initializeCallbacks(*F.getParent());
408  SmallVector<Instruction*, 8> AllLoadsAndStores;
409  SmallVector<Instruction*, 8> LocalLoadsAndStores;
410  SmallVector<Instruction*, 8> AtomicAccesses;
411  SmallVector<Instruction*, 8> MemIntrinCalls;
412  bool Res = false;
413  bool HasCalls = false;
414  bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);
415  const DataLayout &DL = F.getParent()->getDataLayout();
416  const TargetLibraryInfo *TLI =
417  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
418 
419  // Traverse all instructions, collect loads/stores/returns, check for calls.
420  for (auto &BB : F) {
421  for (auto &Inst : BB) {
422  if (isAtomic(&Inst))
423  AtomicAccesses.push_back(&Inst);
424  else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
425  LocalLoadsAndStores.push_back(&Inst);
426  else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
427  if (CallInst *CI = dyn_cast<CallInst>(&Inst))
429  if (isa<MemIntrinsic>(Inst))
430  MemIntrinCalls.push_back(&Inst);
431  HasCalls = true;
432  chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
433  DL);
434  }
435  }
436  chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
437  }
438 
439  // We have collected all loads and stores.
440  // FIXME: many of these accesses do not need to be checked for races
441  // (e.g. variables that do not escape, etc).
442 
443  // Instrument memory accesses only if we want to report bugs in the function.
444  if (ClInstrumentMemoryAccesses && SanitizeFunction)
445  for (auto Inst : AllLoadsAndStores) {
446  Res |= instrumentLoadOrStore(Inst, DL);
447  }
448 
449  // Instrument atomic memory accesses in any case (they can be used to
450  // implement synchronization).
452  for (auto Inst : AtomicAccesses) {
453  Res |= instrumentAtomic(Inst, DL);
454  }
455 
456  if (ClInstrumentMemIntrinsics && SanitizeFunction)
457  for (auto Inst : MemIntrinCalls) {
458  Res |= instrumentMemIntrinsic(Inst);
459  }
460 
461  if (F.hasFnAttribute("sanitize_thread_no_checking_at_run_time")) {
462  assert(!F.hasFnAttribute(Attribute::SanitizeThread));
463  if (HasCalls)
464  InsertRuntimeIgnores(F);
465  }
466 
467  // Instrument function entry/exit points if there were instrumented accesses.
468  if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
469  IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
470  Value *ReturnAddress = IRB.CreateCall(
471  Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
472  IRB.getInt32(0));
473  IRB.CreateCall(TsanFuncEntry, ReturnAddress);
474 
475  EscapeEnumerator EE(F, "tsan_cleanup", ClHandleCxxExceptions);
476  while (IRBuilder<> *AtExit = EE.Next()) {
477  AtExit->CreateCall(TsanFuncExit, {});
478  }
479  Res = true;
480  }
481  return Res;
482 }
483 
484 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I,
485  const DataLayout &DL) {
486  IRBuilder<> IRB(I);
487  bool IsWrite = isa<StoreInst>(*I);
488  Value *Addr = IsWrite
489  ? cast<StoreInst>(I)->getPointerOperand()
491 
492  // swifterror memory addresses are mem2reg promoted by instruction selection.
493  // As such they cannot have regular uses like an instrumentation function and
494  // it makes no sense to track them as memory.
495  if (Addr->isSwiftError())
496  return false;
497 
498  int Idx = getMemoryAccessFuncIndex(Addr, DL);
499  if (Idx < 0)
500  return false;
501  if (IsWrite && isVtableAccess(I)) {
502  DEBUG(dbgs() << " VPTR : " << *I << "\n");
503  Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
504  // StoredValue may be a vector type if we are storing several vptrs at once.
505  // In this case, just take the first element of the vector since this is
506  // enough to find vptr races.
507  if (isa<VectorType>(StoredValue->getType()))
508  StoredValue = IRB.CreateExtractElement(
509  StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
510  if (StoredValue->getType()->isIntegerTy())
511  StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
512  // Call TsanVptrUpdate.
513  IRB.CreateCall(TsanVptrUpdate,
514  {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
515  IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
516  NumInstrumentedVtableWrites++;
517  return true;
518  }
519  if (!IsWrite && isVtableAccess(I)) {
520  IRB.CreateCall(TsanVptrLoad,
521  IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
522  NumInstrumentedVtableReads++;
523  return true;
524  }
525  const unsigned Alignment = IsWrite
526  ? cast<StoreInst>(I)->getAlignment()
527  : cast<LoadInst>(I)->getAlignment();
528  Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
529  const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
530  Value *OnAccessFunc = nullptr;
531  if (Alignment == 0 || Alignment >= 8 || (Alignment % (TypeSize / 8)) == 0)
532  OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
533  else
534  OnAccessFunc = IsWrite ? TsanUnalignedWrite[Idx] : TsanUnalignedRead[Idx];
535  IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
536  if (IsWrite) NumInstrumentedWrites++;
537  else NumInstrumentedReads++;
538  return true;
539 }
540 
542  uint32_t v = 0;
543  switch (ord) {
545  llvm_unreachable("unexpected atomic ordering!");
547  case AtomicOrdering::Monotonic: v = 0; break;
548  // Not specified yet:
549  // case AtomicOrdering::Consume: v = 1; break;
550  case AtomicOrdering::Acquire: v = 2; break;
551  case AtomicOrdering::Release: v = 3; break;
552  case AtomicOrdering::AcquireRelease: v = 4; break;
553  case AtomicOrdering::SequentiallyConsistent: v = 5; break;
554  }
555  return IRB->getInt32(v);
556 }
557 
558 // If a memset intrinsic gets inlined by the code gen, we will miss races on it.
559 // So, we either need to ensure the intrinsic is not inlined, or instrument it.
560 // We do not instrument memset/memmove/memcpy intrinsics (too complicated),
561 // instead we simply replace them with regular function calls, which are then
562 // intercepted by the run-time.
563 // Since tsan is running after everyone else, the calls should not be
564 // replaced back with intrinsics. If that becomes wrong at some point,
565 // we will need to call e.g. __tsan_memset to avoid the intrinsics.
566 bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
567  IRBuilder<> IRB(I);
568  if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
569  IRB.CreateCall(
570  MemsetFn,
571  {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
572  IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
573  IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
574  I->eraseFromParent();
575  } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
576  IRB.CreateCall(
577  isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
578  {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
579  IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
580  IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
581  I->eraseFromParent();
582  }
583  return false;
584 }
585 
586 // Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
587 // standards. For background see C++11 standard. A slightly older, publicly
588 // available draft of the standard (not entirely up-to-date, but close enough
589 // for casual browsing) is available here:
590 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
591 // The following page contains more background information:
592 // http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
593 
594 bool ThreadSanitizer::instrumentAtomic(Instruction *I, const DataLayout &DL) {
595  IRBuilder<> IRB(I);
596  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
597  Value *Addr = LI->getPointerOperand();
598  int Idx = getMemoryAccessFuncIndex(Addr, DL);
599  if (Idx < 0)
600  return false;
601  const unsigned ByteSize = 1U << Idx;
602  const unsigned BitSize = ByteSize * 8;
603  Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
604  Type *PtrTy = Ty->getPointerTo();
605  Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
606  createOrdering(&IRB, LI->getOrdering())};
607  Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
608  Value *C = IRB.CreateCall(TsanAtomicLoad[Idx], Args);
609  Value *Cast = IRB.CreateBitOrPointerCast(C, OrigTy);
610  I->replaceAllUsesWith(Cast);
611  } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
612  Value *Addr = SI->getPointerOperand();
613  int Idx = getMemoryAccessFuncIndex(Addr, DL);
614  if (Idx < 0)
615  return false;
616  const unsigned ByteSize = 1U << Idx;
617  const unsigned BitSize = ByteSize * 8;
618  Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
619  Type *PtrTy = Ty->getPointerTo();
620  Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
621  IRB.CreateBitOrPointerCast(SI->getValueOperand(), Ty),
622  createOrdering(&IRB, SI->getOrdering())};
623  CallInst *C = CallInst::Create(TsanAtomicStore[Idx], Args);
624  ReplaceInstWithInst(I, C);
625  } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
626  Value *Addr = RMWI->getPointerOperand();
627  int Idx = getMemoryAccessFuncIndex(Addr, DL);
628  if (Idx < 0)
629  return false;
630  Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
631  if (!F)
632  return false;
633  const unsigned ByteSize = 1U << Idx;
634  const unsigned BitSize = ByteSize * 8;
635  Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
636  Type *PtrTy = Ty->getPointerTo();
637  Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
638  IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
639  createOrdering(&IRB, RMWI->getOrdering())};
640  CallInst *C = CallInst::Create(F, Args);
641  ReplaceInstWithInst(I, C);
642  } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
643  Value *Addr = CASI->getPointerOperand();
644  int Idx = getMemoryAccessFuncIndex(Addr, DL);
645  if (Idx < 0)
646  return false;
647  const unsigned ByteSize = 1U << Idx;
648  const unsigned BitSize = ByteSize * 8;
649  Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
650  Type *PtrTy = Ty->getPointerTo();
651  Value *CmpOperand =
652  IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
653  Value *NewOperand =
654  IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
655  Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
656  CmpOperand,
657  NewOperand,
658  createOrdering(&IRB, CASI->getSuccessOrdering()),
659  createOrdering(&IRB, CASI->getFailureOrdering())};
660  CallInst *C = IRB.CreateCall(TsanAtomicCAS[Idx], Args);
661  Value *Success = IRB.CreateICmpEQ(C, CmpOperand);
662  Value *OldVal = C;
663  Type *OrigOldValTy = CASI->getNewValOperand()->getType();
664  if (Ty != OrigOldValTy) {
665  // The value is a pointer, so we need to cast the return value.
666  OldVal = IRB.CreateIntToPtr(C, OrigOldValTy);
667  }
668 
669  Value *Res =
670  IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
671  Res = IRB.CreateInsertValue(Res, Success, 1);
672 
673  I->replaceAllUsesWith(Res);
674  I->eraseFromParent();
675  } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
676  Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
677  Function *F = FI->getSynchScope() == SingleThread ?
678  TsanAtomicSignalFence : TsanAtomicThreadFence;
679  CallInst *C = CallInst::Create(F, Args);
680  ReplaceInstWithInst(I, C);
681  }
682  return true;
683 }
684 
685 int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr,
686  const DataLayout &DL) {
687  Type *OrigPtrTy = Addr->getType();
688  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
689  assert(OrigTy->isSized());
690  uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
691  if (TypeSize != 8 && TypeSize != 16 &&
692  TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
693  NumAccessesWithBadSize++;
694  // Ignore all unusual sizes.
695  return -1;
696  }
697  size_t Idx = countTrailingZeros(TypeSize / 8);
698  assert(Idx < kNumberOfAccessSizes);
699  return Idx;
700 }
MachineLoop * L
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:76
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool endswith(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:276
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
STATISTIC(NumFunctions,"Total number of functions")
size_t i
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
An instruction for ordering other memory operations.
Definition: Instructions.h:430
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:504
This class represents a function call, abstracting a target machine's calling convention.
This file contains the declarations for metadata subclasses.
This class wraps the llvm.memset intrinsic.
Metadata node.
Definition: Metadata.h:830
An instruction for reading from memory.
Definition: Instructions.h:164
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:669
Hexagon Common GEP
#define op(i)
static cl::opt< bool > ClInstrumentAtomics("tsan-instrument-atomics", cl::init(true), cl::desc("Instrument atomics"), cl::Hidden)
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
static Value * getPointerOperand(Instruction &Inst)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:32
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:588
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:380
AtomicOrdering
Atomic ordering for LLVM's memory model.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
static unsigned getAlignment(GlobalVariable *GV)
#define F(x, y, z)
Definition: MD5.cpp:51
ThreadSanitizer false
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:79
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:949
An instruction for storing to memory.
Definition: Instructions.h:300
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:401
Type * getScalarType() const LLVM_READONLY
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.cpp:44
std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type cast(const Y &Val)
Definition: Casting.h:221
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:254
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:830
static const size_t kNumberOfAccessSizes
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:111
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeSet AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:123
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:399
static const char *const kTsanModuleCtorName
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
Value * stripInBoundsOffsets()
Strip off pointer casts and inbounds GEPs.
Definition: Value.cpp:544
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass * createThreadSanitizerPass()
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getPointerOperand()
Definition: Instructions.h:270
Class to represent integer types.
Definition: DerivedTypes.h:39
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:80
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1337
static std::string itostr(int64_t X)
Definition: StringExtras.h:95
static cl::opt< bool > ClInstrumentFuncEntryExit("tsan-instrument-func-entry-exit", cl::init(true), cl::desc("Instrument function entry and exit"), cl::Hidden)
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
static bool isAtomic(Instruction *I)
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:385
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:213
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:64
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:709
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer's init function from it.
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:175
bool isSwiftError() const
Return true if this value is a swifterror value.
Definition: Value.cpp:675
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:307
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:173
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:558
static ConstantInt * createOrdering(IRBuilder<> *IRB, AtomicOrdering ord)
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:84
const BasicBlock & getEntryBlock() const
Definition: Function.h:519
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:195
static cl::opt< bool > ClHandleCxxExceptions("tsan-handle-cxx-exceptions", cl::init(true), cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"), cl::Hidden)
static bool shouldInstrumentReadWriteFromAddress(Value *Addr)
#define Success
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
INITIALIZE_PASS_BEGIN(ThreadSanitizer,"tsan","ThreadSanitizer: detects data races.", false, false) INITIALIZE_PASS_END(ThreadSanitizer
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:226
StringRef getInstrProfCountersSectionName(bool AddSegment)
Return the name of data section containing profile counter variables.
Definition: InstrProf.h:42
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:169
#define I(x, y, z)
Definition: MD5.cpp:54
static cl::opt< bool > ClInstrumentMemoryAccesses("tsan-instrument-memory-accesses", cl::init(true), cl::desc("Instrument memory accesses"), cl::Hidden)
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1579
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition: Local.cpp:2068
const char SectionName[]
Definition: AMDGPUPTNote.h:24
static cl::opt< bool > ClInstrumentMemIntrinsics("tsan-instrument-memintrinsics", cl::init(true), cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char *const kTsanInitName
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
LLVM Value Representation.
Definition: Value.h:71
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:239
#define DEBUG(X)
Definition: Debug.h:100
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:678
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:479
static bool isVtableAccess(Instruction *I)
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222