blob: 40e0908cf5c5e2ecb09d8cd1053f33d9e6c2e2ed [file] [log] [blame]
Kostya Serebryany60ebb1942012-02-13 22:50:51 +00001//===-- ThreadSanitizer.cpp - race detector -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of ThreadSanitizer, a race detector.
11//
12// The tool is under development, for the details about previous versions see
13// http://code.google.com/p/data-race-test
14//
15// The instrumentation phase is quite simple:
16// - Insert calls to run-time library before every memory access.
17// - Optimizations may apply to avoid instrumenting some of the accesses.
18// - Insert calls at function entry/exit.
19// The rest is handled by the run-time library.
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "tsan"
23
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Type.h"
Kostya Serebryany6e590e32012-03-14 23:33:24 +000038#include "llvm/Support/CommandLine.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000039#include "llvm/Support/Debug.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000040#include "llvm/Support/MathExtras.h"
Kostya Serebryany52eb69922012-03-26 17:35:03 +000041#include "llvm/Support/raw_ostream.h"
Kostya Serebryanye5079222012-04-27 07:31:53 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000043#include "llvm/Transforms/Utils/BlackList.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000044#include "llvm/Transforms/Utils/ModuleUtils.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000045
46using namespace llvm;
47
Alexey Samsonovf045df12012-12-28 09:30:44 +000048static cl::opt<std::string> ClBlacklistFile("tsan-blacklist",
Kostya Serebryany6e590e32012-03-14 23:33:24 +000049 cl::desc("Blacklist file"), cl::Hidden);
Kostya Serebryany41d876c2012-10-04 05:28:50 +000050static cl::opt<bool> ClInstrumentMemoryAccesses(
51 "tsan-instrument-memory-accesses", cl::init(true),
52 cl::desc("Instrument memory accesses"), cl::Hidden);
53static cl::opt<bool> ClInstrumentFuncEntryExit(
54 "tsan-instrument-func-entry-exit", cl::init(true),
55 cl::desc("Instrument function entry and exit"), cl::Hidden);
56static cl::opt<bool> ClInstrumentAtomics(
57 "tsan-instrument-atomics", cl::init(true),
58 cl::desc("Instrument atomics"), cl::Hidden);
Kostya Serebryany6e590e32012-03-14 23:33:24 +000059
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +000060STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
61STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Alexey Samsonov1dfe9b52012-08-30 13:47:13 +000062STATISTIC(NumOmittedReadsBeforeWrite,
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +000063 "Number of reads ignored due to following writes");
64STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
65STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
Dmitry Vyukovab78ac12013-03-22 08:51:22 +000066STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +000067STATISTIC(NumOmittedReadsFromConstantGlobals,
68 "Number of reads from constant globals");
69STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
Kostya Serebryany2076af02012-04-10 18:18:56 +000070
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000071namespace {
Kostya Serebryany2076af02012-04-10 18:18:56 +000072
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000073/// ThreadSanitizer: instrument the code in module to find races.
74struct ThreadSanitizer : public FunctionPass {
Alexey Samsonovf045df12012-12-28 09:30:44 +000075 ThreadSanitizer(StringRef BlacklistFile = StringRef())
76 : FunctionPass(ID),
77 TD(0),
78 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
79 : BlacklistFile) { }
Kostya Serebryanye5079222012-04-27 07:31:53 +000080 const char *getPassName() const;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000081 bool runOnFunction(Function &F);
82 bool doInitialization(Module &M);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000083 static char ID; // Pass identification, replacement for typeid.
84
85 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +000086 void initializeCallbacks(Module &M);
Kostya Serebryanye5079222012-04-27 07:31:53 +000087 bool instrumentLoadOrStore(Instruction *I);
88 bool instrumentAtomic(Instruction *I);
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +000089 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction*> &Local,
90 SmallVectorImpl<Instruction*> &All);
Kostya Serebryanycff60c12012-04-10 22:29:17 +000091 bool addrPointsToConstantData(Value *Addr);
Kostya Serebryanye5079222012-04-27 07:31:53 +000092 int getMemoryAccessFuncIndex(Value *Addr);
Kostya Serebryany2076af02012-04-10 18:18:56 +000093
Micah Villmow3574eca2012-10-08 16:38:25 +000094 DataLayout *TD;
Alexey Samsonovf045df12012-12-28 09:30:44 +000095 SmallString<64> BlacklistFile;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000096 OwningPtr<BlackList> BL;
Kostya Serebryanye5079222012-04-27 07:31:53 +000097 IntegerType *OrdTy;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000098 // Callbacks to run-time library are computed in doInitialization.
Kostya Serebryanye5079222012-04-27 07:31:53 +000099 Function *TsanFuncEntry;
100 Function *TsanFuncExit;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000101 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
Kostya Serebryany3eccaa62012-02-14 00:52:07 +0000102 static const size_t kNumberOfAccessSizes = 5;
Kostya Serebryanye5079222012-04-27 07:31:53 +0000103 Function *TsanRead[kNumberOfAccessSizes];
104 Function *TsanWrite[kNumberOfAccessSizes];
105 Function *TsanAtomicLoad[kNumberOfAccessSizes];
106 Function *TsanAtomicStore[kNumberOfAccessSizes];
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000107 Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
108 Function *TsanAtomicCAS[kNumberOfAccessSizes];
109 Function *TsanAtomicThreadFence;
110 Function *TsanAtomicSignalFence;
Kostya Serebryanye5079222012-04-27 07:31:53 +0000111 Function *TsanVptrUpdate;
Dmitry Vyukovab78ac12013-03-22 08:51:22 +0000112 Function *TsanVptrLoad;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000113};
114} // namespace
115
116char ThreadSanitizer::ID = 0;
117INITIALIZE_PASS(ThreadSanitizer, "tsan",
118 "ThreadSanitizer: detects data races.",
119 false, false)
120
Kostya Serebryanye5079222012-04-27 07:31:53 +0000121const char *ThreadSanitizer::getPassName() const {
122 return "ThreadSanitizer";
123}
124
Alexey Samsonovf045df12012-12-28 09:30:44 +0000125FunctionPass *llvm::createThreadSanitizerPass(StringRef BlacklistFile) {
126 return new ThreadSanitizer(BlacklistFile);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000127}
128
Kostya Serebryanye5079222012-04-27 07:31:53 +0000129static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
130 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
131 return F;
132 FuncOrBitcast->dump();
133 report_fatal_error("ThreadSanitizer interface function redefined");
134}
135
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000136void ThreadSanitizer::initializeCallbacks(Module &M) {
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000137 IRBuilder<> IRB(M.getContext());
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000138 // Initialize the callbacks.
Kostya Serebryanye5079222012-04-27 07:31:53 +0000139 TsanFuncEntry = checkInterfaceFunction(M.getOrInsertFunction(
140 "__tsan_func_entry", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
141 TsanFuncExit = checkInterfaceFunction(M.getOrInsertFunction(
142 "__tsan_func_exit", IRB.getVoidTy(), NULL));
143 OrdTy = IRB.getInt32Ty();
Kostya Serebryany3eccaa62012-02-14 00:52:07 +0000144 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
Kostya Serebryanye5079222012-04-27 07:31:53 +0000145 const size_t ByteSize = 1 << i;
146 const size_t BitSize = ByteSize * 8;
147 SmallString<32> ReadName("__tsan_read" + itostr(ByteSize));
148 TsanRead[i] = checkInterfaceFunction(M.getOrInsertFunction(
149 ReadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
150
151 SmallString<32> WriteName("__tsan_write" + itostr(ByteSize));
152 TsanWrite[i] = checkInterfaceFunction(M.getOrInsertFunction(
153 WriteName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
154
155 Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
156 Type *PtrTy = Ty->getPointerTo();
157 SmallString<32> AtomicLoadName("__tsan_atomic" + itostr(BitSize) +
158 "_load");
159 TsanAtomicLoad[i] = checkInterfaceFunction(M.getOrInsertFunction(
160 AtomicLoadName, Ty, PtrTy, OrdTy, NULL));
161
162 SmallString<32> AtomicStoreName("__tsan_atomic" + itostr(BitSize) +
163 "_store");
164 TsanAtomicStore[i] = checkInterfaceFunction(M.getOrInsertFunction(
165 AtomicStoreName, IRB.getVoidTy(), PtrTy, Ty, OrdTy,
166 NULL));
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000167
168 for (int op = AtomicRMWInst::FIRST_BINOP;
169 op <= AtomicRMWInst::LAST_BINOP; ++op) {
170 TsanAtomicRMW[op][i] = NULL;
171 const char *NamePart = NULL;
172 if (op == AtomicRMWInst::Xchg)
173 NamePart = "_exchange";
174 else if (op == AtomicRMWInst::Add)
175 NamePart = "_fetch_add";
176 else if (op == AtomicRMWInst::Sub)
177 NamePart = "_fetch_sub";
178 else if (op == AtomicRMWInst::And)
179 NamePart = "_fetch_and";
180 else if (op == AtomicRMWInst::Or)
181 NamePart = "_fetch_or";
182 else if (op == AtomicRMWInst::Xor)
183 NamePart = "_fetch_xor";
Dmitry Vyukovb10675e2012-11-27 08:09:25 +0000184 else if (op == AtomicRMWInst::Nand)
185 NamePart = "_fetch_nand";
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000186 else
187 continue;
188 SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
189 TsanAtomicRMW[op][i] = checkInterfaceFunction(M.getOrInsertFunction(
190 RMWName, Ty, PtrTy, Ty, OrdTy, NULL));
191 }
192
193 SmallString<32> AtomicCASName("__tsan_atomic" + itostr(BitSize) +
194 "_compare_exchange_val");
195 TsanAtomicCAS[i] = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov6702e532012-11-26 11:36:19 +0000196 AtomicCASName, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, NULL));
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000197 }
Kostya Serebryanye5079222012-04-27 07:31:53 +0000198 TsanVptrUpdate = checkInterfaceFunction(M.getOrInsertFunction(
199 "__tsan_vptr_update", IRB.getVoidTy(), IRB.getInt8PtrTy(),
200 IRB.getInt8PtrTy(), NULL));
Dmitry Vyukovab78ac12013-03-22 08:51:22 +0000201 TsanVptrLoad = checkInterfaceFunction(M.getOrInsertFunction(
202 "__tsan_vptr_read", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000203 TsanAtomicThreadFence = checkInterfaceFunction(M.getOrInsertFunction(
204 "__tsan_atomic_thread_fence", IRB.getVoidTy(), OrdTy, NULL));
205 TsanAtomicSignalFence = checkInterfaceFunction(M.getOrInsertFunction(
206 "__tsan_atomic_signal_fence", IRB.getVoidTy(), OrdTy, NULL));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000207}
208
209bool ThreadSanitizer::doInitialization(Module &M) {
210 TD = getAnalysisIfAvailable<DataLayout>();
211 if (!TD)
212 return false;
Alexey Samsonovf045df12012-12-28 09:30:44 +0000213 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000214
215 // Always insert a call to __tsan_init into the module's CTORs.
216 IRBuilder<> IRB(M.getContext());
217 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
218 IRB.getVoidTy(), NULL);
219 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
220
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000221 return true;
222}
223
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000224static bool isVtableAccess(Instruction *I) {
225 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa)) {
226 if (Tag->getNumOperands() < 1) return false;
227 if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
228 if (Tag1->getString() == "vtable pointer") return true;
229 }
230 }
231 return false;
232}
233
234bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
235 // If this is a GEP, just analyze its pointer operand.
236 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
237 Addr = GEP->getPointerOperand();
238
239 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
240 if (GV->isConstant()) {
241 // Reads from constant globals can not race with any writes.
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +0000242 NumOmittedReadsFromConstantGlobals++;
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000243 return true;
244 }
Alexey Samsonov1dfe9b52012-08-30 13:47:13 +0000245 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000246 if (isVtableAccess(L)) {
247 // Reads from a vtable pointer can not race with any writes.
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +0000248 NumOmittedReadsFromVtable++;
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000249 return true;
250 }
251 }
252 return false;
253}
254
Kostya Serebryany2076af02012-04-10 18:18:56 +0000255// Instrumenting some of the accesses may be proven redundant.
256// Currently handled:
257// - read-before-write (within same BB, no calls between)
258//
259// We do not handle some of the patterns that should not survive
260// after the classic compiler optimizations.
261// E.g. two reads from the same temp should be eliminated by CSE,
262// two writes should be eliminated by DSE, etc.
263//
264// 'Local' is a vector of insns within the same BB (no calls between).
265// 'All' is a vector of insns that will be instrumented.
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000266void ThreadSanitizer::chooseInstructionsToInstrument(
Kostya Serebryany2076af02012-04-10 18:18:56 +0000267 SmallVectorImpl<Instruction*> &Local,
268 SmallVectorImpl<Instruction*> &All) {
269 SmallSet<Value*, 8> WriteTargets;
270 // Iterate from the end.
271 for (SmallVectorImpl<Instruction*>::reverse_iterator It = Local.rbegin(),
272 E = Local.rend(); It != E; ++It) {
273 Instruction *I = *It;
274 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
275 WriteTargets.insert(Store->getPointerOperand());
276 } else {
277 LoadInst *Load = cast<LoadInst>(I);
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000278 Value *Addr = Load->getPointerOperand();
279 if (WriteTargets.count(Addr)) {
Kostya Serebryany2076af02012-04-10 18:18:56 +0000280 // We will write to this temp, so no reason to analyze the read.
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +0000281 NumOmittedReadsBeforeWrite++;
Kostya Serebryany2076af02012-04-10 18:18:56 +0000282 continue;
283 }
Kostya Serebryanycff60c12012-04-10 22:29:17 +0000284 if (addrPointsToConstantData(Addr)) {
285 // Addr points to some constant data -- it can not race with any writes.
286 continue;
287 }
Kostya Serebryany2076af02012-04-10 18:18:56 +0000288 }
289 All.push_back(I);
290 }
291 Local.clear();
292}
293
Kostya Serebryanye5079222012-04-27 07:31:53 +0000294static bool isAtomic(Instruction *I) {
295 if (LoadInst *LI = dyn_cast<LoadInst>(I))
296 return LI->isAtomic() && LI->getSynchScope() == CrossThread;
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000297 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Kostya Serebryanye5079222012-04-27 07:31:53 +0000298 return SI->isAtomic() && SI->getSynchScope() == CrossThread;
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000299 if (isa<AtomicRMWInst>(I))
Kostya Serebryanye5079222012-04-27 07:31:53 +0000300 return true;
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000301 if (isa<AtomicCmpXchgInst>(I))
Kostya Serebryanye5079222012-04-27 07:31:53 +0000302 return true;
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000303 if (isa<FenceInst>(I))
304 return true;
Kostya Serebryanye5079222012-04-27 07:31:53 +0000305 return false;
306}
307
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000308bool ThreadSanitizer::runOnFunction(Function &F) {
309 if (!TD) return false;
Kostya Serebryany6e590e32012-03-14 23:33:24 +0000310 if (BL->isIn(F)) return false;
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000311 initializeCallbacks(*F.getParent());
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000312 SmallVector<Instruction*, 8> RetVec;
Kostya Serebryany2076af02012-04-10 18:18:56 +0000313 SmallVector<Instruction*, 8> AllLoadsAndStores;
314 SmallVector<Instruction*, 8> LocalLoadsAndStores;
Kostya Serebryanye5079222012-04-27 07:31:53 +0000315 SmallVector<Instruction*, 8> AtomicAccesses;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000316 bool Res = false;
317 bool HasCalls = false;
318
319 // Traverse all instructions, collect loads/stores/returns, check for calls.
320 for (Function::iterator FI = F.begin(), FE = F.end();
321 FI != FE; ++FI) {
322 BasicBlock &BB = *FI;
323 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
324 BI != BE; ++BI) {
Kostya Serebryanye5079222012-04-27 07:31:53 +0000325 if (isAtomic(BI))
326 AtomicAccesses.push_back(BI);
327 else if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
Kostya Serebryany2076af02012-04-10 18:18:56 +0000328 LocalLoadsAndStores.push_back(BI);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000329 else if (isa<ReturnInst>(BI))
330 RetVec.push_back(BI);
Kostya Serebryany2076af02012-04-10 18:18:56 +0000331 else if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000332 HasCalls = true;
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000333 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryany2076af02012-04-10 18:18:56 +0000334 }
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000335 }
Kostya Serebryany37cb9ac2012-05-02 13:12:19 +0000336 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000337 }
338
339 // We have collected all loads and stores.
340 // FIXME: many of these accesses do not need to be checked for races
341 // (e.g. variables that do not escape, etc).
342
343 // Instrument memory accesses.
Kostya Serebryany41d876c2012-10-04 05:28:50 +0000344 if (ClInstrumentMemoryAccesses)
345 for (size_t i = 0, n = AllLoadsAndStores.size(); i < n; ++i) {
346 Res |= instrumentLoadOrStore(AllLoadsAndStores[i]);
347 }
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000348
Kostya Serebryanye5079222012-04-27 07:31:53 +0000349 // Instrument atomic memory accesses.
Kostya Serebryany41d876c2012-10-04 05:28:50 +0000350 if (ClInstrumentAtomics)
351 for (size_t i = 0, n = AtomicAccesses.size(); i < n; ++i) {
352 Res |= instrumentAtomic(AtomicAccesses[i]);
353 }
Kostya Serebryanye5079222012-04-27 07:31:53 +0000354
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000355 // Instrument function entry/exit points if there were instrumented accesses.
Kostya Serebryany41d876c2012-10-04 05:28:50 +0000356 if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000357 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
358 Value *ReturnAddress = IRB.CreateCall(
359 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
360 IRB.getInt32(0));
361 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
362 for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
363 IRBuilder<> IRBRet(RetVec[i]);
364 IRBRet.CreateCall(TsanFuncExit);
365 }
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000366 Res = true;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000367 }
368 return Res;
369}
370
371bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
372 IRBuilder<> IRB(I);
373 bool IsWrite = isa<StoreInst>(*I);
374 Value *Addr = IsWrite
375 ? cast<StoreInst>(I)->getPointerOperand()
376 : cast<LoadInst>(I)->getPointerOperand();
Kostya Serebryanye5079222012-04-27 07:31:53 +0000377 int Idx = getMemoryAccessFuncIndex(Addr);
378 if (Idx < 0)
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000379 return false;
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000380 if (IsWrite && isVtableAccess(I)) {
Kostya Serebryany4a002ab2012-07-05 09:07:31 +0000381 DEBUG(dbgs() << " VPTR : " << *I << "\n");
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000382 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
Kostya Serebryany4a002ab2012-07-05 09:07:31 +0000383 // StoredValue does not necessary have a pointer type.
384 if (isa<IntegerType>(StoredValue->getType()))
385 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
386 // Call TsanVptrUpdate.
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000387 IRB.CreateCall2(TsanVptrUpdate,
388 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
389 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +0000390 NumInstrumentedVtableWrites++;
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000391 return true;
392 }
Dmitry Vyukovab78ac12013-03-22 08:51:22 +0000393 if (!IsWrite && isVtableAccess(I)) {
394 IRB.CreateCall(TsanVptrLoad,
395 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
396 NumInstrumentedVtableReads++;
397 return true;
398 }
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000399 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
400 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
Kostya Serebryany2d5fdf82012-04-23 08:44:59 +0000401 if (IsWrite) NumInstrumentedWrites++;
402 else NumInstrumentedReads++;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000403 return true;
404}
Kostya Serebryanye5079222012-04-27 07:31:53 +0000405
406static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
407 uint32_t v = 0;
408 switch (ord) {
409 case NotAtomic: assert(false);
410 case Unordered: // Fall-through.
Dmitry Vyukovc2e9ca12012-11-09 14:12:16 +0000411 case Monotonic: v = 0; break;
Dmitry Vyukov9a33f9f2012-11-26 14:55:26 +0000412 // case Consume: v = 1; break; // Not specified yet.
Dmitry Vyukovc2e9ca12012-11-09 14:12:16 +0000413 case Acquire: v = 2; break;
414 case Release: v = 3; break;
415 case AcquireRelease: v = 4; break;
416 case SequentiallyConsistent: v = 5; break;
Kostya Serebryanye5079222012-04-27 07:31:53 +0000417 }
Dmitry Vyukovc2e9ca12012-11-09 14:12:16 +0000418 return IRB->getInt32(v);
Kostya Serebryanye5079222012-04-27 07:31:53 +0000419}
420
Dmitry Vyukov6702e532012-11-26 11:36:19 +0000421static ConstantInt *createFailOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
422 uint32_t v = 0;
423 switch (ord) {
424 case NotAtomic: assert(false);
425 case Unordered: // Fall-through.
426 case Monotonic: v = 0; break;
Dmitry Vyukov9a33f9f2012-11-26 14:55:26 +0000427 // case Consume: v = 1; break; // Not specified yet.
Dmitry Vyukov6702e532012-11-26 11:36:19 +0000428 case Acquire: v = 2; break;
429 case Release: v = 0; break;
430 case AcquireRelease: v = 2; break;
431 case SequentiallyConsistent: v = 5; break;
432 }
433 return IRB->getInt32(v);
434}
435
436// Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
437// standards. For background see C++11 standard. A slightly older, publically
438// available draft of the standard (not entirely up-to-date, but close enough
439// for casual browsing) is available here:
Matt Beaumont-Gay70af9092012-11-26 16:27:22 +0000440// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
Dmitry Vyukov6702e532012-11-26 11:36:19 +0000441// The following page contains more background information:
442// http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
443
Kostya Serebryanye5079222012-04-27 07:31:53 +0000444bool ThreadSanitizer::instrumentAtomic(Instruction *I) {
445 IRBuilder<> IRB(I);
446 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
447 Value *Addr = LI->getPointerOperand();
448 int Idx = getMemoryAccessFuncIndex(Addr);
449 if (Idx < 0)
450 return false;
451 const size_t ByteSize = 1 << Idx;
452 const size_t BitSize = ByteSize * 8;
453 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmowb8bce922012-10-24 17:25:11 +0000454 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanye5079222012-04-27 07:31:53 +0000455 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
456 createOrdering(&IRB, LI->getOrdering())};
457 CallInst *C = CallInst::Create(TsanAtomicLoad[Idx],
458 ArrayRef<Value*>(Args));
459 ReplaceInstWithInst(I, C);
460
461 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
462 Value *Addr = SI->getPointerOperand();
463 int Idx = getMemoryAccessFuncIndex(Addr);
464 if (Idx < 0)
465 return false;
466 const size_t ByteSize = 1 << Idx;
467 const size_t BitSize = ByteSize * 8;
468 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmowb8bce922012-10-24 17:25:11 +0000469 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanye5079222012-04-27 07:31:53 +0000470 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
471 IRB.CreateIntCast(SI->getValueOperand(), Ty, false),
472 createOrdering(&IRB, SI->getOrdering())};
473 CallInst *C = CallInst::Create(TsanAtomicStore[Idx],
474 ArrayRef<Value*>(Args));
475 ReplaceInstWithInst(I, C);
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000476 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
477 Value *Addr = RMWI->getPointerOperand();
478 int Idx = getMemoryAccessFuncIndex(Addr);
479 if (Idx < 0)
480 return false;
481 Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
482 if (F == NULL)
483 return false;
484 const size_t ByteSize = 1 << Idx;
485 const size_t BitSize = ByteSize * 8;
486 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
487 Type *PtrTy = Ty->getPointerTo();
488 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
489 IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
490 createOrdering(&IRB, RMWI->getOrdering())};
491 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
492 ReplaceInstWithInst(I, C);
493 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
494 Value *Addr = CASI->getPointerOperand();
495 int Idx = getMemoryAccessFuncIndex(Addr);
496 if (Idx < 0)
497 return false;
498 const size_t ByteSize = 1 << Idx;
499 const size_t BitSize = ByteSize * 8;
500 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
501 Type *PtrTy = Ty->getPointerTo();
502 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
503 IRB.CreateIntCast(CASI->getCompareOperand(), Ty, false),
504 IRB.CreateIntCast(CASI->getNewValOperand(), Ty, false),
Dmitry Vyukov6702e532012-11-26 11:36:19 +0000505 createOrdering(&IRB, CASI->getOrdering()),
506 createFailOrdering(&IRB, CASI->getOrdering())};
Dmitry Vyukov9f8a90b2012-11-09 12:55:36 +0000507 CallInst *C = CallInst::Create(TsanAtomicCAS[Idx], ArrayRef<Value*>(Args));
508 ReplaceInstWithInst(I, C);
509 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
510 Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
511 Function *F = FI->getSynchScope() == SingleThread ?
512 TsanAtomicSignalFence : TsanAtomicThreadFence;
513 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
514 ReplaceInstWithInst(I, C);
Kostya Serebryanye5079222012-04-27 07:31:53 +0000515 }
516 return true;
517}
518
519int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr) {
520 Type *OrigPtrTy = Addr->getType();
521 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
522 assert(OrigTy->isSized());
523 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
524 if (TypeSize != 8 && TypeSize != 16 &&
525 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
526 NumAccessesWithBadSize++;
527 // Ignore all unusual sizes.
528 return -1;
529 }
530 size_t Idx = CountTrailingZeros_32(TypeSize / 8);
531 assert(Idx < kNumberOfAccessSizes);
532 return Idx;
533}