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