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