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