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