tsan: handle vptr loads specially
[oota-llvm.git] / lib / Transforms / Instrumentation / ThreadSanitizer.cpp
1 //===-- 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
24 #include "llvm/Transforms/Instrumentation.h"
25 #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"
30 #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"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BlackList.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
45
46 using namespace llvm;
47
48 static cl::opt<std::string>  ClBlacklistFile("tsan-blacklist",
49        cl::desc("Blacklist file"), cl::Hidden);
50 static cl::opt<bool>  ClInstrumentMemoryAccesses(
51     "tsan-instrument-memory-accesses", cl::init(true),
52     cl::desc("Instrument memory accesses"), cl::Hidden);
53 static cl::opt<bool>  ClInstrumentFuncEntryExit(
54     "tsan-instrument-func-entry-exit", cl::init(true),
55     cl::desc("Instrument function entry and exit"), cl::Hidden);
56 static cl::opt<bool>  ClInstrumentAtomics(
57     "tsan-instrument-atomics", cl::init(true),
58     cl::desc("Instrument atomics"), cl::Hidden);
59
60 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
61 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
62 STATISTIC(NumOmittedReadsBeforeWrite,
63           "Number of reads ignored due to following writes");
64 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
65 STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
66 STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
67 STATISTIC(NumOmittedReadsFromConstantGlobals,
68           "Number of reads from constant globals");
69 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
70
71 namespace {
72
73 /// ThreadSanitizer: instrument the code in module to find races.
74 struct ThreadSanitizer : public FunctionPass {
75   ThreadSanitizer(StringRef BlacklistFile = StringRef())
76       : FunctionPass(ID),
77         TD(0),
78         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
79                                             : BlacklistFile) { }
80   const char *getPassName() const;
81   bool runOnFunction(Function &F);
82   bool doInitialization(Module &M);
83   static char ID;  // Pass identification, replacement for typeid.
84
85  private:
86   void initializeCallbacks(Module &M);
87   bool instrumentLoadOrStore(Instruction *I);
88   bool instrumentAtomic(Instruction *I);
89   void chooseInstructionsToInstrument(SmallVectorImpl<Instruction*> &Local,
90                                       SmallVectorImpl<Instruction*> &All);
91   bool addrPointsToConstantData(Value *Addr);
92   int getMemoryAccessFuncIndex(Value *Addr);
93
94   DataLayout *TD;
95   SmallString<64> BlacklistFile;
96   OwningPtr<BlackList> BL;
97   IntegerType *OrdTy;
98   // Callbacks to run-time library are computed in doInitialization.
99   Function *TsanFuncEntry;
100   Function *TsanFuncExit;
101   // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
102   static const size_t kNumberOfAccessSizes = 5;
103   Function *TsanRead[kNumberOfAccessSizes];
104   Function *TsanWrite[kNumberOfAccessSizes];
105   Function *TsanAtomicLoad[kNumberOfAccessSizes];
106   Function *TsanAtomicStore[kNumberOfAccessSizes];
107   Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
108   Function *TsanAtomicCAS[kNumberOfAccessSizes];
109   Function *TsanAtomicThreadFence;
110   Function *TsanAtomicSignalFence;
111   Function *TsanVptrUpdate;
112   Function *TsanVptrLoad;
113 };
114 }  // namespace
115
116 char ThreadSanitizer::ID = 0;
117 INITIALIZE_PASS(ThreadSanitizer, "tsan",
118     "ThreadSanitizer: detects data races.",
119     false, false)
120
121 const char *ThreadSanitizer::getPassName() const {
122   return "ThreadSanitizer";
123 }
124
125 FunctionPass *llvm::createThreadSanitizerPass(StringRef BlacklistFile) {
126   return new ThreadSanitizer(BlacklistFile);
127 }
128
129 static 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
136 void ThreadSanitizer::initializeCallbacks(Module &M) {
137   IRBuilder<> IRB(M.getContext());
138   // Initialize the callbacks.
139   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();
144   for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
145     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));
167
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";
184       else if (op == AtomicRMWInst::Nand)
185         NamePart = "_fetch_nand";
186       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(
196         AtomicCASName, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, NULL));
197   }
198   TsanVptrUpdate = checkInterfaceFunction(M.getOrInsertFunction(
199       "__tsan_vptr_update", IRB.getVoidTy(), IRB.getInt8PtrTy(),
200       IRB.getInt8PtrTy(), NULL));
201   TsanVptrLoad = checkInterfaceFunction(M.getOrInsertFunction(
202       "__tsan_vptr_read", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
203   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));
207 }
208
209 bool ThreadSanitizer::doInitialization(Module &M) {
210   TD = getAnalysisIfAvailable<DataLayout>();
211   if (!TD)
212     return false;
213   BL.reset(new BlackList(BlacklistFile));
214
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
221   return true;
222 }
223
224 static 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
234 bool 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.
242       NumOmittedReadsFromConstantGlobals++;
243       return true;
244     }
245   } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
246     if (isVtableAccess(L)) {
247       // Reads from a vtable pointer can not race with any writes.
248       NumOmittedReadsFromVtable++;
249       return true;
250     }
251   }
252   return false;
253 }
254
255 // 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.
266 void ThreadSanitizer::chooseInstructionsToInstrument(
267     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);
278       Value *Addr = Load->getPointerOperand();
279       if (WriteTargets.count(Addr)) {
280         // We will write to this temp, so no reason to analyze the read.
281         NumOmittedReadsBeforeWrite++;
282         continue;
283       }
284       if (addrPointsToConstantData(Addr)) {
285         // Addr points to some constant data -- it can not race with any writes.
286         continue;
287       }
288     }
289     All.push_back(I);
290   }
291   Local.clear();
292 }
293
294 static bool isAtomic(Instruction *I) {
295   if (LoadInst *LI = dyn_cast<LoadInst>(I))
296     return LI->isAtomic() && LI->getSynchScope() == CrossThread;
297   if (StoreInst *SI = dyn_cast<StoreInst>(I))
298     return SI->isAtomic() && SI->getSynchScope() == CrossThread;
299   if (isa<AtomicRMWInst>(I))
300     return true;
301   if (isa<AtomicCmpXchgInst>(I))
302     return true;
303   if (isa<FenceInst>(I))
304     return true;
305   return false;
306 }
307
308 bool ThreadSanitizer::runOnFunction(Function &F) {
309   if (!TD) return false;
310   if (BL->isIn(F)) return false;
311   initializeCallbacks(*F.getParent());
312   SmallVector<Instruction*, 8> RetVec;
313   SmallVector<Instruction*, 8> AllLoadsAndStores;
314   SmallVector<Instruction*, 8> LocalLoadsAndStores;
315   SmallVector<Instruction*, 8> AtomicAccesses;
316   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) {
325       if (isAtomic(BI))
326         AtomicAccesses.push_back(BI);
327       else if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
328         LocalLoadsAndStores.push_back(BI);
329       else if (isa<ReturnInst>(BI))
330         RetVec.push_back(BI);
331       else if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
332         HasCalls = true;
333         chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
334       }
335     }
336     chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
337   }
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.
344   if (ClInstrumentMemoryAccesses)
345     for (size_t i = 0, n = AllLoadsAndStores.size(); i < n; ++i) {
346       Res |= instrumentLoadOrStore(AllLoadsAndStores[i]);
347     }
348
349   // Instrument atomic memory accesses.
350   if (ClInstrumentAtomics)
351     for (size_t i = 0, n = AtomicAccesses.size(); i < n; ++i) {
352       Res |= instrumentAtomic(AtomicAccesses[i]);
353     }
354
355   // Instrument function entry/exit points if there were instrumented accesses.
356   if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
357     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     }
366     Res = true;
367   }
368   return Res;
369 }
370
371 bool 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();
377   int Idx = getMemoryAccessFuncIndex(Addr);
378   if (Idx < 0)
379     return false;
380   if (IsWrite && isVtableAccess(I)) {
381     DEBUG(dbgs() << "  VPTR : " << *I << "\n");
382     Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
383     // StoredValue does not necessary have a pointer type.
384     if (isa<IntegerType>(StoredValue->getType()))
385       StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
386     // Call TsanVptrUpdate.
387     IRB.CreateCall2(TsanVptrUpdate,
388                     IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
389                     IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
390     NumInstrumentedVtableWrites++;
391     return true;
392   }
393   if (!IsWrite && isVtableAccess(I)) {
394     IRB.CreateCall(TsanVptrLoad,
395                    IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
396     NumInstrumentedVtableReads++;
397     return true;
398   }
399   Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
400   IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
401   if (IsWrite) NumInstrumentedWrites++;
402   else         NumInstrumentedReads++;
403   return true;
404 }
405
406 static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
407   uint32_t v = 0;
408   switch (ord) {
409     case NotAtomic:              assert(false);
410     case Unordered:              // Fall-through.
411     case Monotonic:              v = 0; break;
412     // case Consume:                v = 1; break;  // Not specified yet.
413     case Acquire:                v = 2; break;
414     case Release:                v = 3; break;
415     case AcquireRelease:         v = 4; break;
416     case SequentiallyConsistent: v = 5; break;
417   }
418   return IRB->getInt32(v);
419 }
420
421 static 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;
427     // case Consume:                v = 1; break;  // Not specified yet.
428     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:
440 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
441 // The following page contains more background information:
442 // http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
443
444 bool 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);
454     Type *PtrTy = Ty->getPointerTo();
455     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);
469     Type *PtrTy = Ty->getPointerTo();
470     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);
476   } 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),
505                      createOrdering(&IRB, CASI->getOrdering()),
506                      createFailOrdering(&IRB, CASI->getOrdering())};
507     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);
515   }
516   return true;
517 }
518
519 int 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 }