blob: 957afc4e9c2618347994995c92fc95f09081cf38 [file] [log] [blame]
Kostya Serebryanye2a0e412012-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Transforms/Instrumentation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SmallSet.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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
Kostya Serebryany463aa812013-03-28 11:21:13 +000031#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Type.h"
Kostya Serebryanyabad0022012-03-14 23:33:24 +000037#include "llvm/Support/CommandLine.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000038#include "llvm/Support/Debug.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000039#include "llvm/Support/MathExtras.h"
Kostya Serebryany6f8a7762012-03-26 17:35:03 +000040#include "llvm/Support/raw_ostream.h"
Kostya Serebryanya1259772012-04-27 07:31:53 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000042#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne015370e2013-07-09 22:02:49 +000043#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000044
45using namespace llvm;
46
Chandler Carruth964daaa2014-04-22 02:55:47 +000047#define DEBUG_TYPE "tsan"
48
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +000049static cl::opt<bool> ClInstrumentMemoryAccesses(
50 "tsan-instrument-memory-accesses", cl::init(true),
51 cl::desc("Instrument memory accesses"), cl::Hidden);
52static cl::opt<bool> ClInstrumentFuncEntryExit(
53 "tsan-instrument-func-entry-exit", cl::init(true),
54 cl::desc("Instrument function entry and exit"), cl::Hidden);
55static cl::opt<bool> ClInstrumentAtomics(
56 "tsan-instrument-atomics", cl::init(true),
57 cl::desc("Instrument atomics"), cl::Hidden);
Kostya Serebryany463aa812013-03-28 11:21:13 +000058static cl::opt<bool> ClInstrumentMemIntrinsics(
59 "tsan-instrument-memintrinsics", cl::init(true),
60 cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
Kostya Serebryanyabad0022012-03-14 23:33:24 +000061
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000062STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
63STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Alexey Samsonovf54e3aa2012-08-30 13:47:13 +000064STATISTIC(NumOmittedReadsBeforeWrite,
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000065 "Number of reads ignored due to following writes");
66STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
67STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +000068STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +000069STATISTIC(NumOmittedReadsFromConstantGlobals,
70 "Number of reads from constant globals");
71STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
Kostya Serebryanybf2de802012-04-10 18:18:56 +000072
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000073namespace {
Kostya Serebryanybf2de802012-04-10 18:18:56 +000074
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000075/// ThreadSanitizer: instrument the code in module to find races.
76struct ThreadSanitizer : public FunctionPass {
Alexey Samsonov6d8bab82014-06-02 18:08:27 +000077 ThreadSanitizer() : FunctionPass(ID), DL(nullptr) {}
Craig Topper3e4c6972014-03-05 09:10:37 +000078 const char *getPassName() const override;
79 bool runOnFunction(Function &F) override;
80 bool doInitialization(Module &M) override;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000081 static char ID; // Pass identification, replacement for typeid.
82
83 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +000084 void initializeCallbacks(Module &M);
Kostya Serebryanya1259772012-04-27 07:31:53 +000085 bool instrumentLoadOrStore(Instruction *I);
86 bool instrumentAtomic(Instruction *I);
Kostya Serebryany463aa812013-03-28 11:21:13 +000087 bool instrumentMemIntrinsic(Instruction *I);
Kostya Serebryanyae7188d2012-05-02 13:12:19 +000088 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction*> &Local,
89 SmallVectorImpl<Instruction*> &All);
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +000090 bool addrPointsToConstantData(Value *Addr);
Kostya Serebryanya1259772012-04-27 07:31:53 +000091 int getMemoryAccessFuncIndex(Value *Addr);
Kostya Serebryanybf2de802012-04-10 18:18:56 +000092
Rafael Espindolaaeff8a92014-02-24 23:12:18 +000093 const DataLayout *DL;
Kostya Serebryany463aa812013-03-28 11:21:13 +000094 Type *IntptrTy;
Kostya Serebryanya1259772012-04-27 07:31:53 +000095 IntegerType *OrdTy;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000096 // Callbacks to run-time library are computed in doInitialization.
Kostya Serebryanya1259772012-04-27 07:31:53 +000097 Function *TsanFuncEntry;
98 Function *TsanFuncExit;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +000099 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
Kostya Serebryanya8531ee2012-02-14 00:52:07 +0000100 static const size_t kNumberOfAccessSizes = 5;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000101 Function *TsanRead[kNumberOfAccessSizes];
102 Function *TsanWrite[kNumberOfAccessSizes];
103 Function *TsanAtomicLoad[kNumberOfAccessSizes];
104 Function *TsanAtomicStore[kNumberOfAccessSizes];
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000105 Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
106 Function *TsanAtomicCAS[kNumberOfAccessSizes];
107 Function *TsanAtomicThreadFence;
108 Function *TsanAtomicSignalFence;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000109 Function *TsanVptrUpdate;
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000110 Function *TsanVptrLoad;
Kostya Serebryany463aa812013-03-28 11:21:13 +0000111 Function *MemmoveFn, *MemcpyFn, *MemsetFn;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000112};
113} // namespace
114
115char ThreadSanitizer::ID = 0;
116INITIALIZE_PASS(ThreadSanitizer, "tsan",
117 "ThreadSanitizer: detects data races.",
118 false, false)
119
Kostya Serebryanya1259772012-04-27 07:31:53 +0000120const char *ThreadSanitizer::getPassName() const {
121 return "ThreadSanitizer";
122}
123
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000124FunctionPass *llvm::createThreadSanitizerPass() {
125 return new ThreadSanitizer();
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000126}
127
Kostya Serebryanya1259772012-04-27 07:31:53 +0000128static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
129 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
130 return F;
131 FuncOrBitcast->dump();
132 report_fatal_error("ThreadSanitizer interface function redefined");
133}
134
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000135void ThreadSanitizer::initializeCallbacks(Module &M) {
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000136 IRBuilder<> IRB(M.getContext());
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000137 // Initialize the callbacks.
Kostya Serebryanya1259772012-04-27 07:31:53 +0000138 TsanFuncEntry = checkInterfaceFunction(M.getOrInsertFunction(
139 "__tsan_func_entry", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
140 TsanFuncExit = checkInterfaceFunction(M.getOrInsertFunction(
141 "__tsan_func_exit", IRB.getVoidTy(), NULL));
142 OrdTy = IRB.getInt32Ty();
Kostya Serebryanya8531ee2012-02-14 00:52:07 +0000143 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
Kostya Serebryanya1259772012-04-27 07:31:53 +0000144 const size_t ByteSize = 1 << i;
145 const size_t BitSize = ByteSize * 8;
146 SmallString<32> ReadName("__tsan_read" + itostr(ByteSize));
147 TsanRead[i] = checkInterfaceFunction(M.getOrInsertFunction(
148 ReadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
149
150 SmallString<32> WriteName("__tsan_write" + itostr(ByteSize));
151 TsanWrite[i] = checkInterfaceFunction(M.getOrInsertFunction(
152 WriteName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
153
154 Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
155 Type *PtrTy = Ty->getPointerTo();
156 SmallString<32> AtomicLoadName("__tsan_atomic" + itostr(BitSize) +
157 "_load");
158 TsanAtomicLoad[i] = checkInterfaceFunction(M.getOrInsertFunction(
159 AtomicLoadName, Ty, PtrTy, OrdTy, NULL));
160
161 SmallString<32> AtomicStoreName("__tsan_atomic" + itostr(BitSize) +
162 "_store");
163 TsanAtomicStore[i] = checkInterfaceFunction(M.getOrInsertFunction(
164 AtomicStoreName, IRB.getVoidTy(), PtrTy, Ty, OrdTy,
165 NULL));
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000166
167 for (int op = AtomicRMWInst::FIRST_BINOP;
168 op <= AtomicRMWInst::LAST_BINOP; ++op) {
Craig Topperf40110f2014-04-25 05:29:35 +0000169 TsanAtomicRMW[op][i] = nullptr;
170 const char *NamePart = nullptr;
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000171 if (op == AtomicRMWInst::Xchg)
172 NamePart = "_exchange";
173 else if (op == AtomicRMWInst::Add)
174 NamePart = "_fetch_add";
175 else if (op == AtomicRMWInst::Sub)
176 NamePart = "_fetch_sub";
177 else if (op == AtomicRMWInst::And)
178 NamePart = "_fetch_and";
179 else if (op == AtomicRMWInst::Or)
180 NamePart = "_fetch_or";
181 else if (op == AtomicRMWInst::Xor)
182 NamePart = "_fetch_xor";
Dmitry Vyukova878e742012-11-27 08:09:25 +0000183 else if (op == AtomicRMWInst::Nand)
184 NamePart = "_fetch_nand";
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000185 else
186 continue;
187 SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
188 TsanAtomicRMW[op][i] = checkInterfaceFunction(M.getOrInsertFunction(
189 RMWName, Ty, PtrTy, Ty, OrdTy, NULL));
190 }
191
192 SmallString<32> AtomicCASName("__tsan_atomic" + itostr(BitSize) +
193 "_compare_exchange_val");
194 TsanAtomicCAS[i] = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000195 AtomicCASName, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, NULL));
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000196 }
Kostya Serebryanya1259772012-04-27 07:31:53 +0000197 TsanVptrUpdate = checkInterfaceFunction(M.getOrInsertFunction(
198 "__tsan_vptr_update", IRB.getVoidTy(), IRB.getInt8PtrTy(),
199 IRB.getInt8PtrTy(), NULL));
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000200 TsanVptrLoad = checkInterfaceFunction(M.getOrInsertFunction(
201 "__tsan_vptr_read", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000202 TsanAtomicThreadFence = checkInterfaceFunction(M.getOrInsertFunction(
203 "__tsan_atomic_thread_fence", IRB.getVoidTy(), OrdTy, NULL));
204 TsanAtomicSignalFence = checkInterfaceFunction(M.getOrInsertFunction(
205 "__tsan_atomic_signal_fence", IRB.getVoidTy(), OrdTy, NULL));
Kostya Serebryany463aa812013-03-28 11:21:13 +0000206
207 MemmoveFn = checkInterfaceFunction(M.getOrInsertFunction(
208 "memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
209 IRB.getInt8PtrTy(), IntptrTy, NULL));
210 MemcpyFn = checkInterfaceFunction(M.getOrInsertFunction(
211 "memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
212 IntptrTy, NULL));
213 MemsetFn = checkInterfaceFunction(M.getOrInsertFunction(
214 "memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
215 IntptrTy, NULL));
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000216}
217
218bool ThreadSanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000219 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
220 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000221 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000222 DL = &DLP->getDataLayout();
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000223
224 // Always insert a call to __tsan_init into the module's CTORs.
225 IRBuilder<> IRB(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000226 IntptrTy = IRB.getIntPtrTy(DL);
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000227 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
228 IRB.getVoidTy(), NULL);
229 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
230
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000231 return true;
232}
233
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000234static bool isVtableAccess(Instruction *I) {
Manman Rend8c68b12013-09-06 22:47:05 +0000235 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
236 return Tag->isTBAAVtableAccess();
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000237 return false;
238}
239
240bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
241 // If this is a GEP, just analyze its pointer operand.
242 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
243 Addr = GEP->getPointerOperand();
244
245 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
246 if (GV->isConstant()) {
247 // Reads from constant globals can not race with any writes.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000248 NumOmittedReadsFromConstantGlobals++;
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000249 return true;
250 }
Alexey Samsonovf54e3aa2012-08-30 13:47:13 +0000251 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000252 if (isVtableAccess(L)) {
253 // Reads from a vtable pointer can not race with any writes.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000254 NumOmittedReadsFromVtable++;
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000255 return true;
256 }
257 }
258 return false;
259}
260
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000261// Instrumenting some of the accesses may be proven redundant.
262// Currently handled:
263// - read-before-write (within same BB, no calls between)
264//
265// We do not handle some of the patterns that should not survive
266// after the classic compiler optimizations.
267// E.g. two reads from the same temp should be eliminated by CSE,
268// two writes should be eliminated by DSE, etc.
269//
270// 'Local' is a vector of insns within the same BB (no calls between).
271// 'All' is a vector of insns that will be instrumented.
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000272void ThreadSanitizer::chooseInstructionsToInstrument(
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000273 SmallVectorImpl<Instruction*> &Local,
274 SmallVectorImpl<Instruction*> &All) {
275 SmallSet<Value*, 8> WriteTargets;
276 // Iterate from the end.
277 for (SmallVectorImpl<Instruction*>::reverse_iterator It = Local.rbegin(),
278 E = Local.rend(); It != E; ++It) {
279 Instruction *I = *It;
280 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
281 WriteTargets.insert(Store->getPointerOperand());
282 } else {
283 LoadInst *Load = cast<LoadInst>(I);
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000284 Value *Addr = Load->getPointerOperand();
285 if (WriteTargets.count(Addr)) {
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000286 // We will write to this temp, so no reason to analyze the read.
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000287 NumOmittedReadsBeforeWrite++;
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000288 continue;
289 }
Kostya Serebryany5ba61ac2012-04-10 22:29:17 +0000290 if (addrPointsToConstantData(Addr)) {
291 // Addr points to some constant data -- it can not race with any writes.
292 continue;
293 }
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000294 }
295 All.push_back(I);
296 }
297 Local.clear();
298}
299
Kostya Serebryanya1259772012-04-27 07:31:53 +0000300static bool isAtomic(Instruction *I) {
301 if (LoadInst *LI = dyn_cast<LoadInst>(I))
302 return LI->isAtomic() && LI->getSynchScope() == CrossThread;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000303 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000304 return SI->isAtomic() && SI->getSynchScope() == CrossThread;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000305 if (isa<AtomicRMWInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000306 return true;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000307 if (isa<AtomicCmpXchgInst>(I))
Kostya Serebryanya1259772012-04-27 07:31:53 +0000308 return true;
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000309 if (isa<FenceInst>(I))
310 return true;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000311 return false;
312}
313
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000314bool ThreadSanitizer::runOnFunction(Function &F) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 if (!DL) return false;
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000316 initializeCallbacks(*F.getParent());
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000317 SmallVector<Instruction*, 8> RetVec;
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000318 SmallVector<Instruction*, 8> AllLoadsAndStores;
319 SmallVector<Instruction*, 8> LocalLoadsAndStores;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000320 SmallVector<Instruction*, 8> AtomicAccesses;
Kostya Serebryany463aa812013-03-28 11:21:13 +0000321 SmallVector<Instruction*, 8> MemIntrinCalls;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000322 bool Res = false;
323 bool HasCalls = false;
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000324 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000325
326 // Traverse all instructions, collect loads/stores/returns, check for calls.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000327 for (auto &BB : F) {
328 for (auto &Inst : BB) {
329 if (isAtomic(&Inst))
330 AtomicAccesses.push_back(&Inst);
331 else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
332 LocalLoadsAndStores.push_back(&Inst);
333 else if (isa<ReturnInst>(Inst))
334 RetVec.push_back(&Inst);
335 else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
336 if (isa<MemIntrinsic>(Inst))
337 MemIntrinCalls.push_back(&Inst);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000338 HasCalls = true;
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000339 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryanybf2de802012-04-10 18:18:56 +0000340 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000341 }
Kostya Serebryanyae7188d2012-05-02 13:12:19 +0000342 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000343 }
344
345 // We have collected all loads and stores.
346 // FIXME: many of these accesses do not need to be checked for races
347 // (e.g. variables that do not escape, etc).
348
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000349 // Instrument memory accesses only if we want to report bugs in the function.
350 if (ClInstrumentMemoryAccesses && SanitizeFunction)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000351 for (auto Inst : AllLoadsAndStores) {
352 Res |= instrumentLoadOrStore(Inst);
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000353 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000354
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000355 // Instrument atomic memory accesses in any case (they can be used to
356 // implement synchronization).
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000357 if (ClInstrumentAtomics)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000358 for (auto Inst : AtomicAccesses) {
359 Res |= instrumentAtomic(Inst);
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000360 }
Kostya Serebryanya1259772012-04-27 07:31:53 +0000361
Alexey Samsonovd3828b82014-05-31 00:11:37 +0000362 if (ClInstrumentMemIntrinsics && SanitizeFunction)
Alexey Samsonova02e6642014-05-29 18:40:48 +0000363 for (auto Inst : MemIntrinCalls) {
364 Res |= instrumentMemIntrinsic(Inst);
Kostya Serebryany463aa812013-03-28 11:21:13 +0000365 }
366
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000367 // Instrument function entry/exit points if there were instrumented accesses.
Kostya Serebryanyd23b18f2012-10-04 05:28:50 +0000368 if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000369 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
370 Value *ReturnAddress = IRB.CreateCall(
371 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
372 IRB.getInt32(0));
373 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
Alexey Samsonova02e6642014-05-29 18:40:48 +0000374 for (auto RetInst : RetVec) {
375 IRBuilder<> IRBRet(RetInst);
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000376 IRBRet.CreateCall(TsanFuncExit);
377 }
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000378 Res = true;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000379 }
380 return Res;
381}
382
383bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
384 IRBuilder<> IRB(I);
385 bool IsWrite = isa<StoreInst>(*I);
386 Value *Addr = IsWrite
387 ? cast<StoreInst>(I)->getPointerOperand()
388 : cast<LoadInst>(I)->getPointerOperand();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000389 int Idx = getMemoryAccessFuncIndex(Addr);
390 if (Idx < 0)
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000391 return false;
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000392 if (IsWrite && isVtableAccess(I)) {
Kostya Serebryanye36ae682012-07-05 09:07:31 +0000393 DEBUG(dbgs() << " VPTR : " << *I << "\n");
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000394 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
Kostya Serebryany08b9cf52013-12-02 08:07:15 +0000395 // StoredValue may be a vector type if we are storing several vptrs at once.
396 // In this case, just take the first element of the vector since this is
397 // enough to find vptr races.
398 if (isa<VectorType>(StoredValue->getType()))
399 StoredValue = IRB.CreateExtractElement(
400 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
Kostya Serebryany2460c3f2013-12-05 15:03:02 +0000401 if (StoredValue->getType()->isIntegerTy())
402 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
Kostya Serebryanye36ae682012-07-05 09:07:31 +0000403 // Call TsanVptrUpdate.
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000404 IRB.CreateCall2(TsanVptrUpdate,
405 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
Kostya Serebryany2460c3f2013-12-05 15:03:02 +0000406 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000407 NumInstrumentedVtableWrites++;
Kostya Serebryany6f8a7762012-03-26 17:35:03 +0000408 return true;
409 }
Dmitry Vyukov55e63ef2013-03-22 08:51:22 +0000410 if (!IsWrite && isVtableAccess(I)) {
411 IRB.CreateCall(TsanVptrLoad,
412 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
413 NumInstrumentedVtableReads++;
414 return true;
415 }
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000416 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
417 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
Kostya Serebryany5a4b7a22012-04-23 08:44:59 +0000418 if (IsWrite) NumInstrumentedWrites++;
419 else NumInstrumentedReads++;
Kostya Serebryanye2a0e412012-02-13 22:50:51 +0000420 return true;
421}
Kostya Serebryanya1259772012-04-27 07:31:53 +0000422
423static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
424 uint32_t v = 0;
425 switch (ord) {
426 case NotAtomic: assert(false);
427 case Unordered: // Fall-through.
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000428 case Monotonic: v = 0; break;
Dmitry Vyukov93e67b62012-11-26 14:55:26 +0000429 // case Consume: v = 1; break; // Not specified yet.
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000430 case Acquire: v = 2; break;
431 case Release: v = 3; break;
432 case AcquireRelease: v = 4; break;
433 case SequentiallyConsistent: v = 5; break;
Kostya Serebryanya1259772012-04-27 07:31:53 +0000434 }
Dmitry Vyukov0044e382012-11-09 14:12:16 +0000435 return IRB->getInt32(v);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000436}
437
Kostya Serebryany463aa812013-03-28 11:21:13 +0000438// If a memset intrinsic gets inlined by the code gen, we will miss races on it.
439// So, we either need to ensure the intrinsic is not inlined, or instrument it.
440// We do not instrument memset/memmove/memcpy intrinsics (too complicated),
441// instead we simply replace them with regular function calls, which are then
442// intercepted by the run-time.
443// Since tsan is running after everyone else, the calls should not be
444// replaced back with intrinsics. If that becomes wrong at some point,
445// we will need to call e.g. __tsan_memset to avoid the intrinsics.
446bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
447 IRBuilder<> IRB(I);
448 if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
449 IRB.CreateCall3(MemsetFn,
450 IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
451 IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
452 IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false));
453 I->eraseFromParent();
454 } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
455 IRB.CreateCall3(isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
456 IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
457 IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
458 IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false));
459 I->eraseFromParent();
460 }
461 return false;
462}
463
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000464// Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
Alp Tokercb402912014-01-24 17:20:08 +0000465// standards. For background see C++11 standard. A slightly older, publicly
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000466// available draft of the standard (not entirely up-to-date, but close enough
467// for casual browsing) is available here:
Matt Beaumont-Gay000a3952012-11-26 16:27:22 +0000468// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
Dmitry Vyukov12b5cb92012-11-26 11:36:19 +0000469// The following page contains more background information:
470// http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
471
Kostya Serebryanya1259772012-04-27 07:31:53 +0000472bool ThreadSanitizer::instrumentAtomic(Instruction *I) {
473 IRBuilder<> IRB(I);
474 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
475 Value *Addr = LI->getPointerOperand();
476 int Idx = getMemoryAccessFuncIndex(Addr);
477 if (Idx < 0)
478 return false;
479 const size_t ByteSize = 1 << Idx;
480 const size_t BitSize = ByteSize * 8;
481 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmow51e72462012-10-24 17:25:11 +0000482 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000483 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
484 createOrdering(&IRB, LI->getOrdering())};
485 CallInst *C = CallInst::Create(TsanAtomicLoad[Idx],
486 ArrayRef<Value*>(Args));
487 ReplaceInstWithInst(I, C);
488
489 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
490 Value *Addr = SI->getPointerOperand();
491 int Idx = getMemoryAccessFuncIndex(Addr);
492 if (Idx < 0)
493 return false;
494 const size_t ByteSize = 1 << Idx;
495 const size_t BitSize = ByteSize * 8;
496 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
Micah Villmow51e72462012-10-24 17:25:11 +0000497 Type *PtrTy = Ty->getPointerTo();
Kostya Serebryanya1259772012-04-27 07:31:53 +0000498 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
499 IRB.CreateIntCast(SI->getValueOperand(), Ty, false),
500 createOrdering(&IRB, SI->getOrdering())};
501 CallInst *C = CallInst::Create(TsanAtomicStore[Idx],
502 ArrayRef<Value*>(Args));
503 ReplaceInstWithInst(I, C);
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000504 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
505 Value *Addr = RMWI->getPointerOperand();
506 int Idx = getMemoryAccessFuncIndex(Addr);
507 if (Idx < 0)
508 return false;
509 Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
Craig Topperf40110f2014-04-25 05:29:35 +0000510 if (!F)
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000511 return false;
512 const size_t ByteSize = 1 << Idx;
513 const size_t BitSize = ByteSize * 8;
514 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
515 Type *PtrTy = Ty->getPointerTo();
516 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
517 IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
518 createOrdering(&IRB, RMWI->getOrdering())};
519 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
520 ReplaceInstWithInst(I, C);
521 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
522 Value *Addr = CASI->getPointerOperand();
523 int Idx = getMemoryAccessFuncIndex(Addr);
524 if (Idx < 0)
525 return false;
526 const size_t ByteSize = 1 << Idx;
527 const size_t BitSize = ByteSize * 8;
528 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
529 Type *PtrTy = Ty->getPointerTo();
530 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
531 IRB.CreateIntCast(CASI->getCompareOperand(), Ty, false),
532 IRB.CreateIntCast(CASI->getNewValOperand(), Ty, false),
Tim Northovere94a5182014-03-11 10:48:52 +0000533 createOrdering(&IRB, CASI->getSuccessOrdering()),
534 createOrdering(&IRB, CASI->getFailureOrdering())};
Dmitry Vyukov92b9e1d2012-11-09 12:55:36 +0000535 CallInst *C = CallInst::Create(TsanAtomicCAS[Idx], ArrayRef<Value*>(Args));
536 ReplaceInstWithInst(I, C);
537 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
538 Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
539 Function *F = FI->getSynchScope() == SingleThread ?
540 TsanAtomicSignalFence : TsanAtomicThreadFence;
541 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
542 ReplaceInstWithInst(I, C);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000543 }
544 return true;
545}
546
547int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr) {
548 Type *OrigPtrTy = Addr->getType();
549 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
550 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000551 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000552 if (TypeSize != 8 && TypeSize != 16 &&
553 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
554 NumAccessesWithBadSize++;
555 // Ignore all unusual sizes.
556 return -1;
557 }
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000558 size_t Idx = countTrailingZeros(TypeSize / 8);
Kostya Serebryanya1259772012-04-27 07:31:53 +0000559 assert(Idx < kNumberOfAccessSizes);
560 return Idx;
561}