[tsan] use FunctionBlackList
[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 "FunctionBlackList.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Function.h"
30 #include "llvm/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/IRBuilder.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/Utils/ModuleUtils.h"
38 #include "llvm/Type.h"
39
40 using namespace llvm;
41
42 static cl::opt<std::string>  ClBlackListFile("tsan-blacklist",
43        cl::desc("Blacklist file"), cl::Hidden);
44
45 namespace {
46 /// ThreadSanitizer: instrument the code in module to find races.
47 struct ThreadSanitizer : public FunctionPass {
48   ThreadSanitizer();
49   bool runOnFunction(Function &F);
50   bool doInitialization(Module &M);
51   bool instrumentLoadOrStore(Instruction *I);
52   static char ID;  // Pass identification, replacement for typeid.
53
54  private:
55   TargetData *TD;
56   OwningPtr<FunctionBlackList> BL;
57   // Callbacks to run-time library are computed in doInitialization.
58   Value *TsanFuncEntry;
59   Value *TsanFuncExit;
60   // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
61   static const size_t kNumberOfAccessSizes = 5;
62   Value *TsanRead[kNumberOfAccessSizes];
63   Value *TsanWrite[kNumberOfAccessSizes];
64 };
65 }  // namespace
66
67 char ThreadSanitizer::ID = 0;
68 INITIALIZE_PASS(ThreadSanitizer, "tsan",
69     "ThreadSanitizer: detects data races.",
70     false, false)
71
72 ThreadSanitizer::ThreadSanitizer()
73   : FunctionPass(ID),
74   TD(NULL) {
75 }
76
77 FunctionPass *llvm::createThreadSanitizerPass() {
78   return new ThreadSanitizer();
79 }
80
81 bool ThreadSanitizer::doInitialization(Module &M) {
82   TD = getAnalysisIfAvailable<TargetData>();
83   if (!TD)
84     return false;
85   BL.reset(new FunctionBlackList(ClBlackListFile));
86
87   // Always insert a call to __tsan_init into the module's CTORs.
88   IRBuilder<> IRB(M.getContext());
89   Value *TsanInit = M.getOrInsertFunction("__tsan_init",
90                                           IRB.getVoidTy(), NULL);
91   appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
92
93   // Initialize the callbacks.
94   TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", IRB.getVoidTy(),
95                                         IRB.getInt8PtrTy(), NULL);
96   TsanFuncExit = M.getOrInsertFunction("__tsan_func_exit", IRB.getVoidTy(),
97                                        NULL);
98   for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
99     SmallString<32> ReadName("__tsan_read");
100     ReadName += itostr(1 << i);
101     TsanRead[i] = M.getOrInsertFunction(ReadName, IRB.getVoidTy(),
102                                         IRB.getInt8PtrTy(), NULL);
103     SmallString<32> WriteName("__tsan_write");
104     WriteName += itostr(1 << i);
105     TsanWrite[i] = M.getOrInsertFunction(WriteName, IRB.getVoidTy(),
106                                          IRB.getInt8PtrTy(), NULL);
107   }
108   return true;
109 }
110
111 bool ThreadSanitizer::runOnFunction(Function &F) {
112   if (!TD) return false;
113   if (BL->isIn(F)) return false;
114   SmallVector<Instruction*, 8> RetVec;
115   SmallVector<Instruction*, 8> LoadsAndStores;
116   bool Res = false;
117   bool HasCalls = false;
118
119   // Traverse all instructions, collect loads/stores/returns, check for calls.
120   for (Function::iterator FI = F.begin(), FE = F.end();
121        FI != FE; ++FI) {
122     BasicBlock &BB = *FI;
123     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
124          BI != BE; ++BI) {
125       if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
126         LoadsAndStores.push_back(BI);
127       else if (isa<ReturnInst>(BI))
128         RetVec.push_back(BI);
129       else if (isa<CallInst>(BI) || isa<InvokeInst>(BI))
130         HasCalls = true;
131     }
132   }
133
134   // We have collected all loads and stores.
135   // FIXME: many of these accesses do not need to be checked for races
136   // (e.g. variables that do not escape, etc).
137
138   // Instrument memory accesses.
139   for (size_t i = 0, n = LoadsAndStores.size(); i < n; ++i) {
140     Res |= instrumentLoadOrStore(LoadsAndStores[i]);
141   }
142
143   // Instrument function entry/exit points if there were instrumented accesses.
144   if (Res || HasCalls) {
145     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
146     Value *ReturnAddress = IRB.CreateCall(
147         Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
148         IRB.getInt32(0));
149     IRB.CreateCall(TsanFuncEntry, ReturnAddress);
150     for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
151       IRBuilder<> IRBRet(RetVec[i]);
152       IRBRet.CreateCall(TsanFuncExit);
153     }
154   }
155   return Res;
156 }
157
158 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
159   IRBuilder<> IRB(I);
160   bool IsWrite = isa<StoreInst>(*I);
161   Value *Addr = IsWrite
162       ? cast<StoreInst>(I)->getPointerOperand()
163       : cast<LoadInst>(I)->getPointerOperand();
164   Type *OrigPtrTy = Addr->getType();
165   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
166   assert(OrigTy->isSized());
167   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
168   if (TypeSize != 8  && TypeSize != 16 &&
169       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
170     // Ignore all unusual sizes.
171     return false;
172   }
173   size_t Idx = CountTrailingZeros_32(TypeSize / 8);
174   assert(Idx < kNumberOfAccessSizes);
175   Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
176   IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
177   return true;
178 }