Add instrumentation for memory intrinsic instructions
[c11llvm.git] / CDSPass.cpp
1 //===-- CDSPass.cpp - xxx -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file is a modified version of ThreadSanitizer.cpp, a part of a race detector.
12 //
13 // The tool is under development, for the details about previous versions see
14 // http://code.google.com/p/data-race-test
15 //
16 // The instrumentation phase is quite simple:
17 //   - Insert calls to run-time library before every memory access.
18 //      - Optimizations may apply to avoid instrumenting some of the accesses.
19 //   - Insert calls at function entry/exit.
20 // The rest is handled by the run-time library.
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/LegacyPassManager.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/Pass.h"
38 #include "llvm/ProfileData/InstrProf.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
45 // #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include <vector>
48
49 using namespace llvm;
50
51 #define DEBUG_TYPE "CDS"
52 #include <llvm/IR/DebugLoc.h>
53
54 Value *getPosition( Instruction * I, IRBuilder <> IRB, bool print = false)
55 {
56         const DebugLoc & debug_location = I->getDebugLoc ();
57         std::string position_string;
58         {
59                 llvm::raw_string_ostream position_stream (position_string);
60                 debug_location . print (position_stream);
61         }
62
63         if (print) {
64                 errs() << position_string << "\n";
65         }
66
67         return IRB.CreateGlobalStringPtr (position_string);
68 }
69
70 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
71 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
72 STATISTIC(NumOmittedReadsBeforeWrite,
73           "Number of reads ignored due to following writes");
74 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
75 // STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
76 // STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
77 STATISTIC(NumOmittedReadsFromConstantGlobals,
78           "Number of reads from constant globals");
79 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
80 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
81
82 // static const char *const kCDSModuleCtorName = "cds.module_ctor";
83 // static const char *const kCDSInitName = "cds_init";
84
85 Type * OrdTy;
86 Type * IntPtrTy;
87 Type * Int8PtrTy;
88 Type * Int16PtrTy;
89 Type * Int32PtrTy;
90 Type * Int64PtrTy;
91
92 Type * VoidTy;
93
94 static const size_t kNumberOfAccessSizes = 4;
95
96 int getAtomicOrderIndex(AtomicOrdering order) {
97         switch (order) {
98                 case AtomicOrdering::Monotonic: 
99                         return (int)AtomicOrderingCABI::relaxed;
100                 //  case AtomicOrdering::Consume:         // not specified yet
101                 //    return AtomicOrderingCABI::consume;
102                 case AtomicOrdering::Acquire: 
103                         return (int)AtomicOrderingCABI::acquire;
104                 case AtomicOrdering::Release: 
105                         return (int)AtomicOrderingCABI::release;
106                 case AtomicOrdering::AcquireRelease: 
107                         return (int)AtomicOrderingCABI::acq_rel;
108                 case AtomicOrdering::SequentiallyConsistent: 
109                         return (int)AtomicOrderingCABI::seq_cst;
110                 default:
111                         // unordered or Not Atomic
112                         return -1;
113         }
114 }
115
116 AtomicOrderingCABI indexToAtomicOrder(int index) {
117         switch (index) {
118                 case 0:
119                         return AtomicOrderingCABI::relaxed;
120                 case 1:
121                         return AtomicOrderingCABI::consume;
122                 case 2:
123                         return AtomicOrderingCABI::acquire;
124                 case 3:
125                         return AtomicOrderingCABI::release;
126                 case 4:
127                         return AtomicOrderingCABI::acq_rel;
128                 case 5:
129                         return AtomicOrderingCABI::seq_cst;
130                 default:
131                         errs() << "Bad Atomic index\n";
132                         return AtomicOrderingCABI::seq_cst;
133         }
134 }
135
136 /* According to atomic_base.h: __cmpexch_failure_order */
137 int AtomicCasFailureOrderIndex(int index) {
138         AtomicOrderingCABI succ_order = indexToAtomicOrder(index);
139         AtomicOrderingCABI fail_order;
140         if (succ_order == AtomicOrderingCABI::acq_rel)
141                 fail_order = AtomicOrderingCABI::acquire;
142         else if (succ_order == AtomicOrderingCABI::release) 
143                 fail_order = AtomicOrderingCABI::relaxed;
144         else
145                 fail_order = succ_order;
146
147         return (int) fail_order;
148 }
149
150 /* The original function checkSanitizerInterfaceFunction was defined
151  * in llvm/Transforms/Utils/ModuleUtils.h
152  */
153 static Function * checkCDSPassInterfaceFunction(Constant *FuncOrBitcast) {
154         if (isa<Function>(FuncOrBitcast))
155                 return cast<Function>(FuncOrBitcast);
156         FuncOrBitcast->print(errs());
157         errs() << '\n';
158         std::string Err;
159         raw_string_ostream Stream(Err);
160         Stream << "CDSPass interface function redefined: " << *FuncOrBitcast;
161         report_fatal_error(Err);
162 }
163
164 namespace {
165         struct CDSPass : public FunctionPass {
166                 CDSPass() : FunctionPass(ID) {}
167                 StringRef getPassName() const override;
168                 bool runOnFunction(Function &F) override;
169                 bool doInitialization(Module &M) override;
170                 static char ID;
171
172         private:
173                 void initializeCallbacks(Module &M);
174                 bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
175                 bool instrumentVolatile(Instruction *I, const DataLayout &DL);
176                 bool instrumentMemIntrinsic(Instruction *I);
177                 bool isAtomicCall(Instruction *I);
178                 bool instrumentAtomic(Instruction *I, const DataLayout &DL);
179                 bool instrumentAtomicCall(CallInst *CI, const DataLayout &DL);
180                 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
181                                                                                         SmallVectorImpl<Instruction *> &All,
182                                                                                         const DataLayout &DL);
183                 bool addrPointsToConstantData(Value *Addr);
184                 int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
185
186                 Function * CDSFuncEntry;
187                 Function * CDSFuncExit;
188
189                 Function * CDSLoad[kNumberOfAccessSizes];
190                 Function * CDSStore[kNumberOfAccessSizes];
191                 Function * CDSVolatileLoad[kNumberOfAccessSizes];
192                 Function * CDSVolatileStore[kNumberOfAccessSizes];
193                 Function * CDSAtomicInit[kNumberOfAccessSizes];
194                 Function * CDSAtomicLoad[kNumberOfAccessSizes];
195                 Function * CDSAtomicStore[kNumberOfAccessSizes];
196                 Function * CDSAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
197                 Function * CDSAtomicCAS_V1[kNumberOfAccessSizes];
198                 Function * CDSAtomicCAS_V2[kNumberOfAccessSizes];
199                 Function * CDSAtomicThreadFence;
200                 Function * MemmoveFn, * MemcpyFn, * MemsetFn;
201                 // Function * CDSCtorFunction;
202
203                 std::vector<StringRef> AtomicFuncNames;
204                 std::vector<StringRef> PartialAtomicFuncNames;
205         };
206 }
207
208 StringRef CDSPass::getPassName() const {
209         return "CDSPass";
210 }
211
212 void CDSPass::initializeCallbacks(Module &M) {
213         LLVMContext &Ctx = M.getContext();
214         AttributeList Attr;
215         Attr = Attr.addAttribute(Ctx, AttributeList::FunctionIndex,
216                         Attribute::NoUnwind);
217
218         Type * Int1Ty = Type::getInt1Ty(Ctx);
219         Type * Int32Ty = Type::getInt32Ty(Ctx);
220         OrdTy = Type::getInt32Ty(Ctx);
221
222         Int8PtrTy  = Type::getInt8PtrTy(Ctx);
223         Int16PtrTy = Type::getInt16PtrTy(Ctx);
224         Int32PtrTy = Type::getInt32PtrTy(Ctx);
225         Int64PtrTy = Type::getInt64PtrTy(Ctx);
226
227         VoidTy = Type::getVoidTy(Ctx);
228
229         CDSFuncEntry = checkCDSPassInterfaceFunction(
230                                                 M.getOrInsertFunction("cds_func_entry", 
231                                                 Attr, VoidTy, Int8PtrTy));
232         CDSFuncExit = checkCDSPassInterfaceFunction(
233                                                 M.getOrInsertFunction("cds_func_exit", 
234                                                 Attr, VoidTy, Int8PtrTy));
235
236         // Get the function to call from our untime library.
237         for (unsigned i = 0; i < kNumberOfAccessSizes; i++) {
238                 const unsigned ByteSize = 1U << i;
239                 const unsigned BitSize = ByteSize * 8;
240
241                 std::string ByteSizeStr = utostr(ByteSize);
242                 std::string BitSizeStr = utostr(BitSize);
243
244                 Type *Ty = Type::getIntNTy(Ctx, BitSize);
245                 Type *PtrTy = Ty->getPointerTo();
246
247                 // uint8_t cds_atomic_load8 (void * obj, int atomic_index)
248                 // void cds_atomic_store8 (void * obj, int atomic_index, uint8_t val)
249                 SmallString<32> LoadName("cds_load" + BitSizeStr);
250                 SmallString<32> StoreName("cds_store" + BitSizeStr);
251                 SmallString<32> VolatileLoadName("cds_volatile_load" + BitSizeStr);
252                 SmallString<32> VolatileStoreName("cds_volatile_store" + BitSizeStr);
253                 SmallString<32> AtomicInitName("cds_atomic_init" + BitSizeStr);
254                 SmallString<32> AtomicLoadName("cds_atomic_load" + BitSizeStr);
255                 SmallString<32> AtomicStoreName("cds_atomic_store" + BitSizeStr);
256
257                 CDSLoad[i]  = checkCDSPassInterfaceFunction(
258                                                         M.getOrInsertFunction(LoadName, Attr, VoidTy, PtrTy));
259                 CDSStore[i] = checkCDSPassInterfaceFunction(
260                                                         M.getOrInsertFunction(StoreName, Attr, VoidTy, PtrTy));
261                 CDSVolatileLoad[i]  = checkCDSPassInterfaceFunction(
262                                                                 M.getOrInsertFunction(VolatileLoadName,
263                                                                 Attr, Ty, PtrTy, Int8PtrTy));
264                 CDSVolatileStore[i] = checkCDSPassInterfaceFunction(
265                                                                 M.getOrInsertFunction(VolatileStoreName, 
266                                                                 Attr, VoidTy, PtrTy, Ty, Int8PtrTy));
267                 CDSAtomicInit[i] = checkCDSPassInterfaceFunction(
268                                                         M.getOrInsertFunction(AtomicInitName, 
269                                                         Attr, VoidTy, PtrTy, Ty, Int8PtrTy));
270                 CDSAtomicLoad[i]  = checkCDSPassInterfaceFunction(
271                                                                 M.getOrInsertFunction(AtomicLoadName, 
272                                                                 Attr, Ty, PtrTy, OrdTy, Int8PtrTy));
273                 CDSAtomicStore[i] = checkCDSPassInterfaceFunction(
274                                                                 M.getOrInsertFunction(AtomicStoreName, 
275                                                                 Attr, VoidTy, PtrTy, Ty, OrdTy, Int8PtrTy));
276
277                 for (int op = AtomicRMWInst::FIRST_BINOP; 
278                         op <= AtomicRMWInst::LAST_BINOP; ++op) {
279                         CDSAtomicRMW[op][i] = nullptr;
280                         std::string NamePart;
281
282                         if (op == AtomicRMWInst::Xchg)
283                                 NamePart = "_exchange";
284                         else if (op == AtomicRMWInst::Add) 
285                                 NamePart = "_fetch_add";
286                         else if (op == AtomicRMWInst::Sub)
287                                 NamePart = "_fetch_sub";
288                         else if (op == AtomicRMWInst::And)
289                                 NamePart = "_fetch_and";
290                         else if (op == AtomicRMWInst::Or)
291                                 NamePart = "_fetch_or";
292                         else if (op == AtomicRMWInst::Xor)
293                                 NamePart = "_fetch_xor";
294                         else
295                                 continue;
296
297                         SmallString<32> AtomicRMWName("cds_atomic" + NamePart + BitSizeStr);
298                         CDSAtomicRMW[op][i] = checkCDSPassInterfaceFunction(
299                                                                         M.getOrInsertFunction(AtomicRMWName, 
300                                                                         Attr, Ty, PtrTy, Ty, OrdTy, Int8PtrTy));
301                 }
302
303                 // only supportes strong version
304                 SmallString<32> AtomicCASName_V1("cds_atomic_compare_exchange" + BitSizeStr + "_v1");
305                 SmallString<32> AtomicCASName_V2("cds_atomic_compare_exchange" + BitSizeStr + "_v2");
306                 CDSAtomicCAS_V1[i] = checkCDSPassInterfaceFunction(
307                                                                 M.getOrInsertFunction(AtomicCASName_V1, 
308                                                                 Attr, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, Int8PtrTy));
309                 CDSAtomicCAS_V2[i] = checkCDSPassInterfaceFunction(
310                                                                 M.getOrInsertFunction(AtomicCASName_V2, 
311                                                                 Attr, Int1Ty, PtrTy, PtrTy, Ty, OrdTy, OrdTy, Int8PtrTy));
312         }
313
314         CDSAtomicThreadFence = checkCDSPassInterfaceFunction(
315                         M.getOrInsertFunction("cds_atomic_thread_fence", Attr, VoidTy, OrdTy, Int8PtrTy));
316
317         MemmoveFn = checkCDSPassInterfaceFunction(
318                                         M.getOrInsertFunction("memmove", Attr, Int8PtrTy, Int8PtrTy,
319                                         Int8PtrTy, IntPtrTy));
320         MemcpyFn = checkCDSPassInterfaceFunction(
321                                         M.getOrInsertFunction("memcpy", Attr, Int8PtrTy, Int8PtrTy,
322                                         Int8PtrTy, IntPtrTy));
323         MemsetFn = checkCDSPassInterfaceFunction(
324                                         M.getOrInsertFunction("memset", Attr, Int8PtrTy, Int8PtrTy,
325                                         Int32Ty, IntPtrTy));
326 }
327
328 bool CDSPass::doInitialization(Module &M) {
329         const DataLayout &DL = M.getDataLayout();
330         IntPtrTy = DL.getIntPtrType(M.getContext());
331         
332         // createSanitizerCtorAndInitFunctions is defined in "llvm/Transforms/Utils/ModuleUtils.h"
333         // We do not support it yet
334         /*
335         std::tie(CDSCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
336                         M, kCDSModuleCtorName, kCDSInitName, {}, {});
337
338         appendToGlobalCtors(M, CDSCtorFunction, 0);
339         */
340
341         AtomicFuncNames = 
342         {
343                 "atomic_init", "atomic_load", "atomic_store", 
344                 "atomic_fetch_", "atomic_exchange", "atomic_compare_exchange_"
345         };
346
347         PartialAtomicFuncNames = 
348         { 
349                 "load", "store", "fetch", "exchange", "compare_exchange_" 
350         };
351
352         return true;
353 }
354
355 static bool isVtableAccess(Instruction *I) {
356         if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
357                 return Tag->isTBAAVtableAccess();
358         return false;
359 }
360
361 // Do not instrument known races/"benign races" that come from compiler
362 // instrumentatin. The user has no way of suppressing them.
363 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
364         // Peel off GEPs and BitCasts.
365         Addr = Addr->stripInBoundsOffsets();
366
367         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
368                 if (GV->hasSection()) {
369                         StringRef SectionName = GV->getSection();
370                         // Check if the global is in the PGO counters section.
371                         auto OF = Triple(M->getTargetTriple()).getObjectFormat();
372                         if (SectionName.endswith(
373                               getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
374                                 return false;
375                 }
376
377                 // Check if the global is private gcov data.
378                 if (GV->getName().startswith("__llvm_gcov") ||
379                 GV->getName().startswith("__llvm_gcda"))
380                 return false;
381         }
382
383         // Do not instrument acesses from different address spaces; we cannot deal
384         // with them.
385         if (Addr) {
386                 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
387                 if (PtrTy->getPointerAddressSpace() != 0)
388                         return false;
389         }
390
391         return true;
392 }
393
394 bool CDSPass::addrPointsToConstantData(Value *Addr) {
395         // If this is a GEP, just analyze its pointer operand.
396         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
397                 Addr = GEP->getPointerOperand();
398
399         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
400                 if (GV->isConstant()) {
401                         // Reads from constant globals can not race with any writes.
402                         NumOmittedReadsFromConstantGlobals++;
403                         return true;
404                 }
405         } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
406                 if (isVtableAccess(L)) {
407                         // Reads from a vtable pointer can not race with any writes.
408                         NumOmittedReadsFromVtable++;
409                         return true;
410                 }
411         }
412         return false;
413 }
414
415 void CDSPass::chooseInstructionsToInstrument(
416         SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
417         const DataLayout &DL) {
418         SmallPtrSet<Value*, 8> WriteTargets;
419         // Iterate from the end.
420         for (Instruction *I : reverse(Local)) {
421                 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
422                         Value *Addr = Store->getPointerOperand();
423                         if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
424                                 continue;
425                         WriteTargets.insert(Addr);
426                 } else {
427                         LoadInst *Load = cast<LoadInst>(I);
428                         Value *Addr = Load->getPointerOperand();
429                         if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
430                                 continue;
431                         if (WriteTargets.count(Addr)) {
432                                 // We will write to this temp, so no reason to analyze the read.
433                                 NumOmittedReadsBeforeWrite++;
434                                 continue;
435                         }
436                         if (addrPointsToConstantData(Addr)) {
437                                 // Addr points to some constant data -- it can not race with any writes.
438                                 continue;
439                         }
440                 }
441                 Value *Addr = isa<StoreInst>(*I)
442                         ? cast<StoreInst>(I)->getPointerOperand()
443                         : cast<LoadInst>(I)->getPointerOperand();
444                 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
445                                 !PointerMayBeCaptured(Addr, true, true)) {
446                         // The variable is addressable but not captured, so it cannot be
447                         // referenced from a different thread and participate in a data race
448                         // (see llvm/Analysis/CaptureTracking.h for details).
449                         NumOmittedNonCaptured++;
450                         continue;
451                 }
452                 All.push_back(I);
453         }
454         Local.clear();
455 }
456
457 /* Not implemented
458 void CDSPass::InsertRuntimeIgnores(Function &F) {
459         IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
460         IRB.CreateCall(CDSIgnoreBegin);
461         EscapeEnumerator EE(F, "cds_ignore_cleanup", ClHandleCxxExceptions);
462         while (IRBuilder<> *AtExit = EE.Next()) {
463                 AtExit->CreateCall(CDSIgnoreEnd);
464         }
465 }*/
466
467 bool CDSPass::runOnFunction(Function &F) {
468         if (F.getName() == "main") {
469                 F.setName("user_main");
470                 errs() << "main replaced by user_main\n";
471         }
472
473         initializeCallbacks( *F.getParent() );
474         SmallVector<Instruction*, 8> AllLoadsAndStores;
475         SmallVector<Instruction*, 8> LocalLoadsAndStores;
476         SmallVector<Instruction*, 8> VolatileLoadsAndStores;
477         SmallVector<Instruction*, 8> AtomicAccesses;
478         SmallVector<Instruction*, 8> MemIntrinCalls;
479
480         bool Res = false;
481         bool HasAtomic = false;
482         bool HasVolatile = false;
483         const DataLayout &DL = F.getParent()->getDataLayout();
484
485         for (auto &BB : F) {
486                 for (auto &Inst : BB) {
487                         if ( (&Inst)->isAtomic() || isAtomicCall(&Inst) ) {
488                                 AtomicAccesses.push_back(&Inst);
489                                 HasAtomic = true;
490                         } else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
491                                 LoadInst *LI = dyn_cast<LoadInst>(&Inst);
492                                 StoreInst *SI = dyn_cast<StoreInst>(&Inst);
493                                 bool isVolatile = ( LI ? LI->isVolatile() : SI->isVolatile() );
494
495                                 if (isVolatile) {
496                                         VolatileLoadsAndStores.push_back(&Inst);
497                                         HasVolatile = true;
498                                 } else
499                                         LocalLoadsAndStores.push_back(&Inst);
500                         } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
501                                 if (isa<MemIntrinsic>(Inst))
502                                         MemIntrinCalls.push_back(&Inst);
503
504                                 /*if (CallInst *CI = dyn_cast<CallInst>(&Inst))
505                                         maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
506                                 */
507
508                                 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
509                                         DL);
510                         }
511                 }
512
513                 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
514         }
515
516         for (auto Inst : AllLoadsAndStores) {
517                 Res |= instrumentLoadOrStore(Inst, DL);
518         }
519
520         for (auto Inst : VolatileLoadsAndStores) {
521                 Res |= instrumentVolatile(Inst, DL);
522         }
523
524         for (auto Inst : AtomicAccesses) {
525                 Res |= instrumentAtomic(Inst, DL);
526         }
527
528         for (auto Inst : MemIntrinCalls) {
529                 Res |= instrumentMemIntrinsic(Inst);
530         }
531
532         // Only instrument functions that contain atomics or volatiles
533         if (Res && ( HasAtomic || HasVolatile) ) {
534                 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
535                 /* Unused for now
536                 Value *ReturnAddress = IRB.CreateCall(
537                         Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
538                         IRB.getInt32(0));
539                 */
540
541                 Value * FuncName = IRB.CreateGlobalStringPtr(F.getName());
542                 IRB.CreateCall(CDSFuncEntry, FuncName);
543
544                 EscapeEnumerator EE(F, "cds_cleanup", true);
545                 while (IRBuilder<> *AtExit = EE.Next()) {
546                   AtExit->CreateCall(CDSFuncExit, FuncName);
547                 }
548
549                 Res = true;
550         }
551
552         return false;
553 }
554
555 bool CDSPass::instrumentLoadOrStore(Instruction *I,
556                                                                         const DataLayout &DL) {
557         IRBuilder<> IRB(I);
558         bool IsWrite = isa<StoreInst>(*I);
559         Value *Addr = IsWrite
560                 ? cast<StoreInst>(I)->getPointerOperand()
561                 : cast<LoadInst>(I)->getPointerOperand();
562
563         // swifterror memory addresses are mem2reg promoted by instruction selection.
564         // As such they cannot have regular uses like an instrumentation function and
565         // it makes no sense to track them as memory.
566         if (Addr->isSwiftError())
567         return false;
568
569         int Idx = getMemoryAccessFuncIndex(Addr, DL);
570         if (Idx < 0)
571                 return false;
572
573 //  not supported by CDS yet
574 /*  if (IsWrite && isVtableAccess(I)) {
575     LLVM_DEBUG(dbgs() << "  VPTR : " << *I << "\n");
576     Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
577     // StoredValue may be a vector type if we are storing several vptrs at once.
578     // In this case, just take the first element of the vector since this is
579     // enough to find vptr races.
580     if (isa<VectorType>(StoredValue->getType()))
581       StoredValue = IRB.CreateExtractElement(
582           StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
583     if (StoredValue->getType()->isIntegerTy())
584       StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
585     // Call TsanVptrUpdate.
586     IRB.CreateCall(TsanVptrUpdate,
587                    {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
588                     IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
589     NumInstrumentedVtableWrites++;
590     return true;
591   }
592
593   if (!IsWrite && isVtableAccess(I)) {
594     IRB.CreateCall(TsanVptrLoad,
595                    IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
596     NumInstrumentedVtableReads++;
597     return true;
598   }
599 */
600
601         Value *OnAccessFunc = nullptr;
602         OnAccessFunc = IsWrite ? CDSStore[Idx] : CDSLoad[Idx];
603
604         Type *ArgType = IRB.CreatePointerCast(Addr, Addr->getType())->getType();
605
606         if ( ArgType != Int8PtrTy && ArgType != Int16PtrTy && 
607                         ArgType != Int32PtrTy && ArgType != Int64PtrTy ) {
608                 // if other types of load or stores are passed in
609                 return false;   
610         }
611
612         IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, Addr->getType()));
613         if (IsWrite) NumInstrumentedWrites++;
614         else         NumInstrumentedReads++;
615         return true;
616 }
617
618 bool CDSPass::instrumentVolatile(Instruction * I, const DataLayout &DL) {
619         IRBuilder<> IRB(I);
620         Value *position = getPosition(I, IRB);
621
622         if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
623                 assert( LI->isVolatile() );
624                 Value *Addr = LI->getPointerOperand();
625                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
626                 if (Idx < 0)
627                         return false;
628
629                 Value *args[] = {Addr, position};
630                 Instruction* funcInst = CallInst::Create(CDSVolatileLoad[Idx], args);
631                 ReplaceInstWithInst(LI, funcInst);
632         } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
633                 assert( SI->isVolatile() );
634                 Value *Addr = SI->getPointerOperand();
635                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
636                 if (Idx < 0)
637                         return false;
638
639                 Value *val = SI->getValueOperand();
640                 Value *args[] = {Addr, val, position};
641                 Instruction* funcInst = CallInst::Create(CDSVolatileStore[Idx], args);
642                 ReplaceInstWithInst(SI, funcInst);
643         } else {
644                 return false;
645         }
646
647         return true;
648 }
649
650 bool CDSPass::instrumentMemIntrinsic(Instruction *I) {
651         IRBuilder<> IRB(I);
652         if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
653                 IRB.CreateCall(
654                         MemsetFn,
655                         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
656                          IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
657                          IRB.CreateIntCast(M->getArgOperand(2), IntPtrTy, false)});
658                 I->eraseFromParent();
659         } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
660                 IRB.CreateCall(
661                         isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
662                         {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
663                          IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
664                          IRB.CreateIntCast(M->getArgOperand(2), IntPtrTy, false)});
665                 I->eraseFromParent();
666         }
667         return false;
668 }
669
670 bool CDSPass::instrumentAtomic(Instruction * I, const DataLayout &DL) {
671         IRBuilder<> IRB(I);
672
673         if (auto *CI = dyn_cast<CallInst>(I)) {
674                 return instrumentAtomicCall(CI, DL);
675         }
676
677         Value *position = getPosition(I, IRB);
678
679         if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
680                 Value *Addr = LI->getPointerOperand();
681                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
682                 if (Idx < 0)
683                         return false;
684
685                 int atomic_order_index = getAtomicOrderIndex(LI->getOrdering());
686                 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
687                 Value *args[] = {Addr, order, position};
688                 Instruction* funcInst = CallInst::Create(CDSAtomicLoad[Idx], args);
689                 ReplaceInstWithInst(LI, funcInst);
690         } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
691                 Value *Addr = SI->getPointerOperand();
692                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
693                 if (Idx < 0)
694                         return false;
695
696                 int atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
697                 Value *val = SI->getValueOperand();
698                 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
699                 Value *args[] = {Addr, val, order, position};
700                 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
701                 ReplaceInstWithInst(SI, funcInst);
702         } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
703                 Value *Addr = RMWI->getPointerOperand();
704                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
705                 if (Idx < 0)
706                         return false;
707
708                 int atomic_order_index = getAtomicOrderIndex(RMWI->getOrdering());
709                 Value *val = RMWI->getValOperand();
710                 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
711                 Value *args[] = {Addr, val, order, position};
712                 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[RMWI->getOperation()][Idx], args);
713                 ReplaceInstWithInst(RMWI, funcInst);
714         } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
715                 IRBuilder<> IRB(CASI);
716
717                 Value *Addr = CASI->getPointerOperand();
718                 int Idx=getMemoryAccessFuncIndex(Addr, DL);
719                 if (Idx < 0)
720                         return false;
721
722                 const unsigned ByteSize = 1U << Idx;
723                 const unsigned BitSize = ByteSize * 8;
724                 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
725                 Type *PtrTy = Ty->getPointerTo();
726
727                 Value *CmpOperand = IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
728                 Value *NewOperand = IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
729
730                 int atomic_order_index_succ = getAtomicOrderIndex(CASI->getSuccessOrdering());
731                 int atomic_order_index_fail = getAtomicOrderIndex(CASI->getFailureOrdering());
732                 Value *order_succ = ConstantInt::get(OrdTy, atomic_order_index_succ);
733                 Value *order_fail = ConstantInt::get(OrdTy, atomic_order_index_fail);
734
735                 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
736                                                  CmpOperand, NewOperand,
737                                                  order_succ, order_fail, position};
738
739                 CallInst *funcInst = IRB.CreateCall(CDSAtomicCAS_V1[Idx], Args);
740                 Value *Success = IRB.CreateICmpEQ(funcInst, CmpOperand);
741
742                 Value *OldVal = funcInst;
743                 Type *OrigOldValTy = CASI->getNewValOperand()->getType();
744                 if (Ty != OrigOldValTy) {
745                         // The value is a pointer, so we need to cast the return value.
746                         OldVal = IRB.CreateIntToPtr(funcInst, OrigOldValTy);
747                 }
748
749                 Value *Res =
750                   IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
751                 Res = IRB.CreateInsertValue(Res, Success, 1);
752
753                 I->replaceAllUsesWith(Res);
754                 I->eraseFromParent();
755         } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
756                 int atomic_order_index = getAtomicOrderIndex(FI->getOrdering());
757                 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
758                 Value *Args[] = {order, position};
759
760                 CallInst *funcInst = CallInst::Create(CDSAtomicThreadFence, Args);
761                 ReplaceInstWithInst(FI, funcInst);
762                 // errs() << "Thread Fences replaced\n";
763         }
764         return true;
765 }
766
767 bool CDSPass::isAtomicCall(Instruction *I) {
768         if ( auto *CI = dyn_cast<CallInst>(I) ) {
769                 Function *fun = CI->getCalledFunction();
770                 if (fun == NULL)
771                         return false;
772
773                 StringRef funName = fun->getName();
774
775                 // TODO: come up with better rules for function name checking
776                 for (StringRef name : AtomicFuncNames) {
777                         if ( funName.contains(name) ) 
778                                 return true;
779                 }
780                 
781                 for (StringRef PartialName : PartialAtomicFuncNames) {
782                         if (funName.contains(PartialName) && 
783                                         funName.contains("atomic") )
784                                 return true;
785                 }
786         }
787
788         return false;
789 }
790
791 bool CDSPass::instrumentAtomicCall(CallInst *CI, const DataLayout &DL) {
792         IRBuilder<> IRB(CI);
793         Function *fun = CI->getCalledFunction();
794         StringRef funName = fun->getName();
795         std::vector<Value *> parameters;
796
797         User::op_iterator begin = CI->arg_begin();
798         User::op_iterator end = CI->arg_end();
799         for (User::op_iterator it = begin; it != end; ++it) {
800                 Value *param = *it;
801                 parameters.push_back(param);
802         }
803
804         // obtain source line number of the CallInst
805         Value *position = getPosition(CI, IRB);
806
807         // the pointer to the address is always the first argument
808         Value *OrigPtr = parameters[0];
809
810         int Idx = getMemoryAccessFuncIndex(OrigPtr, DL);
811         if (Idx < 0)
812                 return false;
813
814         const unsigned ByteSize = 1U << Idx;
815         const unsigned BitSize = ByteSize * 8;
816         Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
817         Type *PtrTy = Ty->getPointerTo();
818
819         // atomic_init; args = {obj, order}
820         if (funName.contains("atomic_init")) {
821                 Value *OrigVal = parameters[1];
822
823                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
824                 Value *val;
825                 if (OrigVal->getType()->isPtrOrPtrVectorTy())
826                         val = IRB.CreatePointerCast(OrigVal, Ty);
827                 else
828                         val = IRB.CreateIntCast(OrigVal, Ty, true);
829
830                 Value *args[] = {ptr, val, position};
831
832                 Instruction* funcInst = CallInst::Create(CDSAtomicInit[Idx], args);
833                 ReplaceInstWithInst(CI, funcInst);
834
835                 return true;
836         }
837
838         // atomic_load; args = {obj, order}
839         if (funName.contains("atomic_load")) {
840                 bool isExplicit = funName.contains("atomic_load_explicit");
841
842                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
843                 Value *order;
844                 if (isExplicit)
845                         order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
846                 else 
847                         order = ConstantInt::get(OrdTy, 
848                                                         (int) AtomicOrderingCABI::seq_cst);
849                 Value *args[] = {ptr, order, position};
850                 
851                 Instruction* funcInst = CallInst::Create(CDSAtomicLoad[Idx], args);
852                 ReplaceInstWithInst(CI, funcInst);
853
854                 return true;
855         } else if (funName.contains("atomic") && 
856                                         funName.contains("load") ) {
857                 // does this version of call always have an atomic order as an argument?
858                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
859                 Value *order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
860                 Value *args[] = {ptr, order, position};
861
862                 if (!CI->getType()->isPointerTy()) {
863                         return false;   
864                 } 
865
866                 CallInst *funcInst = IRB.CreateCall(CDSAtomicLoad[Idx], args);
867                 Value *RetVal = IRB.CreateIntToPtr(funcInst, CI->getType());
868
869                 CI->replaceAllUsesWith(RetVal);
870                 CI->eraseFromParent();
871
872                 return true;
873         }
874
875         // atomic_store; args = {obj, val, order}
876         if (funName.contains("atomic_store")) {
877                 bool isExplicit = funName.contains("atomic_store_explicit");
878                 Value *OrigVal = parameters[1];
879
880                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
881                 Value *val = IRB.CreatePointerCast(OrigVal, Ty);
882                 Value *order;
883                 if (isExplicit)
884                         order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
885                 else 
886                         order = ConstantInt::get(OrdTy, 
887                                                         (int) AtomicOrderingCABI::seq_cst);
888                 Value *args[] = {ptr, val, order, position};
889                 
890                 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
891                 ReplaceInstWithInst(CI, funcInst);
892
893                 return true;
894         } else if (funName.contains("atomic") && 
895                                         funName.contains("store") ) {
896                 // does this version of call always have an atomic order as an argument?
897                 Value *OrigVal = parameters[1];
898
899                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
900                 Value *val;
901                 if (OrigVal->getType()->isPtrOrPtrVectorTy())
902                         val = IRB.CreatePointerCast(OrigVal, Ty);
903                 else
904                         val = IRB.CreateIntCast(OrigVal, Ty, true);
905
906                 Value *order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
907                 Value *args[] = {ptr, val, order, position};
908
909                 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
910                 ReplaceInstWithInst(CI, funcInst);
911
912                 return true;
913         }
914
915         // atomic_fetch_*; args = {obj, val, order}
916         if (funName.contains("atomic_fetch_") || 
917                 funName.contains("atomic_exchange")) {
918
919                 /* TODO: implement stricter function name checking */
920                 if (funName.contains("non"))
921                         return false;
922
923                 bool isExplicit = funName.contains("_explicit");
924                 Value *OrigVal = parameters[1];
925
926                 int op;
927                 if ( funName.contains("_fetch_add") )
928                         op = AtomicRMWInst::Add;
929                 else if ( funName.contains("_fetch_sub") )
930                         op = AtomicRMWInst::Sub;
931                 else if ( funName.contains("_fetch_and") )
932                         op = AtomicRMWInst::And;
933                 else if ( funName.contains("_fetch_or") )
934                         op = AtomicRMWInst::Or;
935                 else if ( funName.contains("_fetch_xor") )
936                         op = AtomicRMWInst::Xor;
937                 else if ( funName.contains("atomic_exchange") )
938                         op = AtomicRMWInst::Xchg;
939                 else {
940                         errs() << "Unknown atomic read-modify-write operation\n";
941                         return false;
942                 }
943
944                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
945                 Value *val;
946                 if (OrigVal->getType()->isPtrOrPtrVectorTy())
947                         val = IRB.CreatePointerCast(OrigVal, Ty);
948                 else
949                         val = IRB.CreateIntCast(OrigVal, Ty, true);
950
951                 Value *order;
952                 if (isExplicit)
953                         order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
954                 else 
955                         order = ConstantInt::get(OrdTy, 
956                                                         (int) AtomicOrderingCABI::seq_cst);
957                 Value *args[] = {ptr, val, order, position};
958                 
959                 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[op][Idx], args);
960                 ReplaceInstWithInst(CI, funcInst);
961
962                 return true;
963         } else if (funName.contains("fetch")) {
964                 errs() << "atomic fetch captured. Not implemented yet. ";
965                 errs() << "See source file :";
966                 getPosition(CI, IRB, true);
967                 return false;
968         } else if (funName.contains("exchange") &&
969                         !funName.contains("compare_exchange") ) {
970                 if (CI->getType()->isPointerTy()) {
971                         // Can not deal with this now
972                         errs() << "atomic exchange captured. Not implemented yet. ";
973                         errs() << "See source file :";
974                         getPosition(CI, IRB, true);
975
976                         return false;
977                 }
978
979                 Value *OrigVal = parameters[1];
980
981                 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
982                 Value *val;
983                 if (OrigVal->getType()->isPtrOrPtrVectorTy())
984                         val = IRB.CreatePointerCast(OrigVal, Ty);
985                 else
986                         val = IRB.CreateIntCast(OrigVal, Ty, true);
987
988                 Value *order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
989                 Value *args[] = {ptr, val, order, position};
990                 int op = AtomicRMWInst::Xchg;
991                 
992                 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[op][Idx], args);
993                 ReplaceInstWithInst(CI, funcInst);
994         }
995
996         /* atomic_compare_exchange_*; 
997            args = {obj, expected, new value, order1, order2}
998         */
999         if ( funName.contains("atomic_compare_exchange_") ) {
1000                 bool isExplicit = funName.contains("_explicit");
1001
1002                 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
1003                 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
1004                 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
1005
1006                 Value *order_succ, *order_fail;
1007                 if (isExplicit) {
1008                         order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
1009
1010                         if (parameters.size() > 4) {
1011                                 order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
1012                         } else {
1013                                 /* The failure order is not provided */
1014                                 order_fail = order_succ;
1015                                 ConstantInt * order_succ_cast = dyn_cast<ConstantInt>(order_succ);
1016                                 int index = order_succ_cast->getSExtValue();
1017
1018                                 order_fail = ConstantInt::get(OrdTy,
1019                                                                 AtomicCasFailureOrderIndex(index));
1020                         }
1021                 } else  {
1022                         order_succ = ConstantInt::get(OrdTy, 
1023                                                         (int) AtomicOrderingCABI::seq_cst);
1024                         order_fail = ConstantInt::get(OrdTy, 
1025                                                         (int) AtomicOrderingCABI::seq_cst);
1026                 }
1027
1028                 Value *args[] = {Addr, CmpOperand, NewOperand, 
1029                                                         order_succ, order_fail, position};
1030                 
1031                 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
1032                 ReplaceInstWithInst(CI, funcInst);
1033
1034                 return true;
1035         } else if ( funName.contains("compare_exchange_strong") ||
1036                                 funName.contains("compare_exchange_weak") ) {
1037                 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
1038                 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
1039                 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
1040
1041                 Value *order_succ, *order_fail;
1042                 order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
1043
1044                 if (parameters.size() > 4) {
1045                         order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
1046                 } else {
1047                         /* The failure order is not provided */
1048                         order_fail = order_succ;
1049                         ConstantInt * order_succ_cast = dyn_cast<ConstantInt>(order_succ);
1050                         int index = order_succ_cast->getSExtValue();
1051
1052                         order_fail = ConstantInt::get(OrdTy,
1053                                                         AtomicCasFailureOrderIndex(index));
1054                 }
1055
1056                 Value *args[] = {Addr, CmpOperand, NewOperand, 
1057                                                         order_succ, order_fail, position};
1058                 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
1059                 ReplaceInstWithInst(CI, funcInst);
1060
1061                 return true;
1062         }
1063
1064         return false;
1065 }
1066
1067 int CDSPass::getMemoryAccessFuncIndex(Value *Addr,
1068                                                                                 const DataLayout &DL) {
1069         Type *OrigPtrTy = Addr->getType();
1070         Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
1071         assert(OrigTy->isSized());
1072         uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
1073         if (TypeSize != 8  && TypeSize != 16 &&
1074                 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
1075                 NumAccessesWithBadSize++;
1076                 // Ignore all unusual sizes.
1077                 return -1;
1078         }
1079         size_t Idx = countTrailingZeros(TypeSize / 8);
1080         //assert(Idx < kNumberOfAccessSizes);
1081         if (Idx >= kNumberOfAccessSizes) {
1082                 return -1;
1083         }
1084         return Idx;
1085 }
1086
1087
1088 char CDSPass::ID = 0;
1089
1090 // Automatically enable the pass.
1091 static void registerCDSPass(const PassManagerBuilder &,
1092                                                         legacy::PassManagerBase &PM) {
1093         PM.add(new CDSPass());
1094 }
1095
1096 /* Enable the pass when opt level is greater than 0 */
1097 static RegisterStandardPasses 
1098         RegisterMyPass1(PassManagerBuilder::EP_OptimizerLast,
1099 registerCDSPass);
1100
1101 /* Enable the pass when opt level is 0 */
1102 static RegisterStandardPasses 
1103         RegisterMyPass2(PassManagerBuilder::EP_EnabledOnOptLevel0,
1104 registerCDSPass);