886621ff7f1e6ed51a15804201f9e141a1d778b0
[c11llvm.git] / CDSPass.cpp
1 //===-- CDSPass.cpp - xxx -------------------------------===//
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 modified version of ThreadSanitizer.cpp, a part of 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 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/Pass.h"
36 #include "llvm/ProfileData/InstrProf.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/AtomicOrdering.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include <vector>
45
46 #define DEBUG_TYPE "CDS"
47 using namespace llvm;
48
49 #include "getPosition.hpp"
50
51 #define FUNCARRAYSIZE 4
52
53 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
54 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
55 // STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
56 // STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
57
58 STATISTIC(NumOmittedReadsBeforeWrite,
59           "Number of reads ignored due to following writes");
60 STATISTIC(NumOmittedReadsFromConstantGlobals,
61           "Number of reads from constant globals");
62 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
63 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
64
65 Type * Int8Ty;
66 Type * Int16Ty;
67 Type * Int32Ty;
68 Type * Int64Ty;
69 Type * OrdTy;
70
71 Type * Int8PtrTy;
72 Type * Int16PtrTy;
73 Type * Int32PtrTy;
74 Type * Int64PtrTy;
75
76 Type * VoidTy;
77
78 Constant * CDSLoad[FUNCARRAYSIZE];
79 Constant * CDSStore[FUNCARRAYSIZE];
80 Constant * CDSAtomicInit[FUNCARRAYSIZE];
81 Constant * CDSAtomicLoad[FUNCARRAYSIZE];
82 Constant * CDSAtomicStore[FUNCARRAYSIZE];
83 Constant * CDSAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][FUNCARRAYSIZE];
84 Constant * CDSAtomicCAS_V1[FUNCARRAYSIZE];
85 Constant * CDSAtomicCAS_V2[FUNCARRAYSIZE];
86 Constant * CDSAtomicThreadFence;
87
88 bool start = false;
89
90 int getAtomicOrderIndex(AtomicOrdering order){
91   switch (order) {
92     case AtomicOrdering::Monotonic: 
93       return (int)AtomicOrderingCABI::relaxed;
94 //  case AtomicOrdering::Consume:         // not specified yet
95 //    return AtomicOrderingCABI::consume;
96     case AtomicOrdering::Acquire: 
97       return (int)AtomicOrderingCABI::acquire;
98     case AtomicOrdering::Release: 
99       return (int)AtomicOrderingCABI::release;
100     case AtomicOrdering::AcquireRelease: 
101       return (int)AtomicOrderingCABI::acq_rel;
102     case AtomicOrdering::SequentiallyConsistent: 
103       return (int)AtomicOrderingCABI::seq_cst;
104     default:
105       // unordered or Not Atomic
106       return -1;
107   }
108 }
109
110 int getTypeSize(Type* type) {
111   if (type == Int8PtrTy) {
112     return sizeof(char)*8;
113   } else if (type == Int16PtrTy) {
114     return sizeof(short)*8;
115   } else if (type == Int32PtrTy) {
116     return sizeof(int)*8;
117   } else if (type == Int64PtrTy) {
118     return sizeof(long long int)*8;
119   } else {
120     return sizeof(void*)*8;
121   }
122
123   return -1;
124 }
125
126 static int sizetoindex(int size) {
127   switch(size) {
128     case 8:     return 0;
129     case 16:    return 1;
130     case 32:    return 2;
131     case 64:    return 3;
132   }
133   return -1;
134 }
135
136 namespace {
137   struct CDSPass : public FunctionPass {
138     static char ID;
139     CDSPass() : FunctionPass(ID) {}
140     bool runOnFunction(Function &F) override; 
141
142   private:
143     void initializeCallbacks(Module &M);
144     bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
145     bool instrumentAtomic(Instruction *I, const DataLayout &DL);
146     bool instrumentAtomicCall(CallInst *CI, const DataLayout &DL);
147     void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
148                                       SmallVectorImpl<Instruction *> &All,
149                                       const DataLayout &DL);
150     bool addrPointsToConstantData(Value *Addr);
151     int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
152   };
153 }
154
155 static bool isVtableAccess(Instruction *I) {
156   if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
157     return Tag->isTBAAVtableAccess();
158   return false;
159 }
160
161 #include "initializeCallbacks.hpp"
162 #include "isAtomicCall.hpp"
163 #include "instrumentAtomicCall.hpp"
164
165 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
166   // Peel off GEPs and BitCasts.
167   Addr = Addr->stripInBoundsOffsets();
168
169   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
170     if (GV->hasSection()) {
171       StringRef SectionName = GV->getSection();
172       // Check if the global is in the PGO counters section.
173       auto OF = Triple(M->getTargetTriple()).getObjectFormat();
174       if (SectionName.endswith(
175               getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
176         return false;
177     }
178
179     // Check if the global is private gcov data.
180     if (GV->getName().startswith("__llvm_gcov") ||
181         GV->getName().startswith("__llvm_gcda"))
182       return false;
183   }
184
185   // Do not instrument acesses from different address spaces; we cannot deal
186   // with them.
187   if (Addr) {
188     Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
189     if (PtrTy->getPointerAddressSpace() != 0)
190       return false;
191   }
192
193   return true;
194 }
195
196 bool CDSPass::addrPointsToConstantData(Value *Addr) {
197   // If this is a GEP, just analyze its pointer operand.
198   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
199     Addr = GEP->getPointerOperand();
200
201   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
202     if (GV->isConstant()) {
203       // Reads from constant globals can not race with any writes.
204       NumOmittedReadsFromConstantGlobals++;
205       return true;
206     }
207   } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
208     if (isVtableAccess(L)) {
209       // Reads from a vtable pointer can not race with any writes.
210       NumOmittedReadsFromVtable++;
211       return true;
212     }
213   }
214   return false;
215 }
216
217 bool CDSPass::runOnFunction(Function &F) {
218   if (F.getName() == "main") {
219     F.setName("user_main");
220     errs() << "main replaced by user_main\n";
221   }
222
223   if (true) {
224     initializeCallbacks( *F.getParent() );
225
226     SmallVector<Instruction*, 8> AllLoadsAndStores;
227     SmallVector<Instruction*, 8> LocalLoadsAndStores;
228     SmallVector<Instruction*, 8> AtomicAccesses;
229
230     std::vector<Instruction *> worklist;
231
232     bool Res = false;
233     const DataLayout &DL = F.getParent()->getDataLayout();
234
235     errs() << "--- " << F.getName() << "---\n";
236
237     for (auto &B : F) {
238       for (auto &I : B) {
239         if ( (&I)->isAtomic() || isAtomicCall(&I) ) {
240           AtomicAccesses.push_back(&I);
241         } else if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
242           LocalLoadsAndStores.push_back(&I);
243         } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
244           // not implemented yet
245         }
246       }
247
248       chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
249     }
250
251     for (auto Inst : AllLoadsAndStores) {
252 //      Res |= instrumentLoadOrStore(Inst, DL);
253 //      errs() << "load and store are replaced\n";
254     }
255
256     for (auto Inst : AtomicAccesses) {
257       Res |= instrumentAtomic(Inst, DL);
258     }
259
260     if (F.getName() == "user_main") {
261       // F.dump();
262     }
263
264   }
265
266   return false;
267 }
268
269 void CDSPass::chooseInstructionsToInstrument(
270     SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
271     const DataLayout &DL) {
272   SmallPtrSet<Value*, 8> WriteTargets;
273   // Iterate from the end.
274   for (Instruction *I : reverse(Local)) {
275     if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
276       Value *Addr = Store->getPointerOperand();
277       if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
278         continue;
279       WriteTargets.insert(Addr);
280     } else {
281       LoadInst *Load = cast<LoadInst>(I);
282       Value *Addr = Load->getPointerOperand();
283       if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
284         continue;
285       if (WriteTargets.count(Addr)) {
286         // We will write to this temp, so no reason to analyze the read.
287         NumOmittedReadsBeforeWrite++;
288         continue;
289       }
290       if (addrPointsToConstantData(Addr)) {
291         // Addr points to some constant data -- it can not race with any writes.
292         continue;
293       }
294     }
295     Value *Addr = isa<StoreInst>(*I)
296         ? cast<StoreInst>(I)->getPointerOperand()
297         : cast<LoadInst>(I)->getPointerOperand();
298     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
299         !PointerMayBeCaptured(Addr, true, true)) {
300       // The variable is addressable but not captured, so it cannot be
301       // referenced from a different thread and participate in a data race
302       // (see llvm/Analysis/CaptureTracking.h for details).
303       NumOmittedNonCaptured++;
304       continue;
305     }
306     All.push_back(I);
307   }
308   Local.clear();
309 }
310
311
312 bool CDSPass::instrumentLoadOrStore(Instruction *I,
313                                             const DataLayout &DL) {
314   IRBuilder<> IRB(I);
315   bool IsWrite = isa<StoreInst>(*I);
316   Value *Addr = IsWrite
317       ? cast<StoreInst>(I)->getPointerOperand()
318       : cast<LoadInst>(I)->getPointerOperand();
319
320   // swifterror memory addresses are mem2reg promoted by instruction selection.
321   // As such they cannot have regular uses like an instrumentation function and
322   // it makes no sense to track them as memory.
323   if (Addr->isSwiftError())
324     return false;
325
326   int size = getTypeSize(Addr->getType());
327   int index = sizetoindex(size);
328
329 //  not supported by CDS yet
330 /*  if (IsWrite && isVtableAccess(I)) {
331     LLVM_DEBUG(dbgs() << "  VPTR : " << *I << "\n");
332     Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
333     // StoredValue may be a vector type if we are storing several vptrs at once.
334     // In this case, just take the first element of the vector since this is
335     // enough to find vptr races.
336     if (isa<VectorType>(StoredValue->getType()))
337       StoredValue = IRB.CreateExtractElement(
338           StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
339     if (StoredValue->getType()->isIntegerTy())
340       StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
341     // Call TsanVptrUpdate.
342     IRB.CreateCall(TsanVptrUpdate,
343                    {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
344                     IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
345     NumInstrumentedVtableWrites++;
346     return true;
347   }
348
349   if (!IsWrite && isVtableAccess(I)) {
350     IRB.CreateCall(TsanVptrLoad,
351                    IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
352     NumInstrumentedVtableReads++;
353     return true;
354   }
355 */
356
357   Value *OnAccessFunc = nullptr;
358   OnAccessFunc = IsWrite ? CDSStore[index] : CDSLoad[index];
359   
360   Type *ArgType = IRB.CreatePointerCast(Addr, Addr->getType())->getType();
361
362   if ( ArgType != Int8PtrTy && ArgType != Int16PtrTy && 
363                 ArgType != Int32PtrTy && ArgType != Int64PtrTy ) {
364         //errs() << "A load or store of type ";
365         //errs() << *ArgType;
366         //errs() << " is passed in\n";
367         return false;   // if other types of load or stores are passed in
368   }
369   IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, Addr->getType()));
370   if (IsWrite) NumInstrumentedWrites++;
371   else         NumInstrumentedReads++;
372   return true;
373 }
374
375 // todo: replace getTypeSize with the getMemoryAccessFuncIndex
376 bool CDSPass::instrumentAtomic(Instruction * I, const DataLayout &DL) {
377   IRBuilder<> IRB(I);
378   // LLVMContext &Ctx = IRB.getContext();
379
380   if (auto *CI = dyn_cast<CallInst>(I)) {
381     return instrumentAtomicCall(CI, DL);
382   }
383
384   Value *position = getPosition(I, IRB);
385
386   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
387     int atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
388
389     Value *val = SI->getValueOperand();
390     Value *ptr = SI->getPointerOperand();
391     Value *order = ConstantInt::get(OrdTy, atomic_order_index);
392     Value *args[] = {ptr, val, order, position};
393
394     int size=getTypeSize(ptr->getType());
395     int index=sizetoindex(size);
396
397     Instruction* funcInst=CallInst::Create(CDSAtomicStore[index], args);
398     ReplaceInstWithInst(SI, funcInst);
399 //    errs() << "Store replaced\n";
400   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
401     int atomic_order_index = getAtomicOrderIndex(LI->getOrdering());
402
403     Value *ptr = LI->getPointerOperand();
404     Value *order = ConstantInt::get(OrdTy, atomic_order_index);
405     Value *args[] = {ptr, order, position};
406
407     int size=getTypeSize(ptr->getType());
408     int index=sizetoindex(size);
409
410     Instruction* funcInst=CallInst::Create(CDSAtomicLoad[index], args);
411     ReplaceInstWithInst(LI, funcInst);
412 //    errs() << "Load Replaced\n";
413   } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
414     int atomic_order_index = getAtomicOrderIndex(RMWI->getOrdering());
415
416     Value *val = RMWI->getValOperand();
417     Value *ptr = RMWI->getPointerOperand();
418     Value *order = ConstantInt::get(OrdTy, atomic_order_index);
419     Value *args[] = {ptr, val, order, position};
420
421     int size = getTypeSize(ptr->getType());
422     int index = sizetoindex(size);
423
424     Instruction* funcInst = CallInst::Create(CDSAtomicRMW[RMWI->getOperation()][index], args);
425     ReplaceInstWithInst(RMWI, funcInst);
426 //    errs() << RMWI->getOperationName(RMWI->getOperation());
427 //    errs() << " replaced\n";
428   } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
429     IRBuilder<> IRB(CASI);
430
431     Value *Addr = CASI->getPointerOperand();
432
433     int size = getTypeSize(Addr->getType());
434     int index = sizetoindex(size);
435     const unsigned ByteSize = 1U << index;
436     const unsigned BitSize = ByteSize * 8;
437     Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
438     Type *PtrTy = Ty->getPointerTo();
439
440     Value *CmpOperand = IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
441     Value *NewOperand = IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
442
443     int atomic_order_index_succ = getAtomicOrderIndex(CASI->getSuccessOrdering());
444     int atomic_order_index_fail = getAtomicOrderIndex(CASI->getFailureOrdering());
445     Value *order_succ = ConstantInt::get(OrdTy, atomic_order_index_succ);
446     Value *order_fail = ConstantInt::get(OrdTy, atomic_order_index_fail);
447
448     Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
449                      CmpOperand, NewOperand,
450                      order_succ, order_fail, position};
451
452     CallInst *funcInst = IRB.CreateCall(CDSAtomicCAS_V1[index], Args);
453     Value *Success = IRB.CreateICmpEQ(funcInst, CmpOperand);
454
455     Value *OldVal = funcInst;
456     Type *OrigOldValTy = CASI->getNewValOperand()->getType();
457     if (Ty != OrigOldValTy) {
458       // The value is a pointer, so we need to cast the return value.
459       OldVal = IRB.CreateIntToPtr(funcInst, OrigOldValTy);
460     }
461
462     Value *Res =
463       IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
464     Res = IRB.CreateInsertValue(Res, Success, 1);
465
466     I->replaceAllUsesWith(Res);
467     I->eraseFromParent();
468   } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
469     int atomic_order_index = getAtomicOrderIndex(FI->getOrdering());
470     Value *order = ConstantInt::get(OrdTy, atomic_order_index);
471     Value *Args[] = {order, position};
472
473     CallInst *funcInst = CallInst::Create(CDSAtomicThreadFence, Args);
474     ReplaceInstWithInst(FI, funcInst);
475 //    errs() << "Thread Fences replaced\n";
476   }
477   return true;
478 }
479
480 int CDSPass::getMemoryAccessFuncIndex(Value *Addr,
481                                               const DataLayout &DL) {
482   Type *OrigPtrTy = Addr->getType();
483   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
484   assert(OrigTy->isSized());
485   uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
486   if (TypeSize != 8  && TypeSize != 16 &&
487       TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
488     // NumAccessesWithBadSize++;
489     // Ignore all unusual sizes.
490     return -1;
491   }
492   size_t Idx = countTrailingZeros(TypeSize / 8);
493   // assert(Idx < FUNCARRAYSIZE);
494   return Idx;
495 }
496
497
498 char CDSPass::ID = 0;
499
500 // Automatically enable the pass.
501 static void registerCDSPass(const PassManagerBuilder &,
502                          legacy::PassManagerBase &PM) {
503   PM.add(new CDSPass());
504 }
505 static RegisterStandardPasses 
506         RegisterMyPass(PassManagerBuilder::EP_OptimizerLast,
507 registerCDSPass);