Remove subtarget dependence in pass pipeline setup for AArch64.
[oota-llvm.git] / lib / Transforms / Instrumentation / SanitizerCoverage.cpp
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
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 // Coverage instrumentation that works with AddressSanitizer
11 // and potentially with other Sanitizers.
12 //
13 // We create a Guard variable with the same linkage
14 // as the function and inject this code into the entry block (CoverageLevel=1)
15 // or all blocks (CoverageLevel>=2):
16 // if (Guard < 0) {
17 //    __sanitizer_cov(&Guard);
18 // }
19 // The accesses to Guard are atomic. The rest of the logic is
20 // in __sanitizer_cov (it's fine to call it more than once).
21 //
22 // With CoverageLevel>=3 we also split critical edges this effectively
23 // instrumenting all edges.
24 //
25 // CoverageLevel>=4 add indirect call profiling implented as a function call.
26 //
27 // This coverage implementation provides very limited data:
28 // it only tells if a given function (block) was ever executed. No counters.
29 // But for many use cases this is what we need and the added slowdown small.
30 //
31 //===----------------------------------------------------------------------===//
32
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "sancov"
55
56 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
57 static const char *const kSanCovName = "__sanitizer_cov";
58 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
59 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
60 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
61 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
62 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
63 static const uint64_t    kSanCtorAndDtorPriority = 2;
64
65 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
66        cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
67                 "3: all blocks and critical edges, "
68                 "4: above plus indirect calls"),
69        cl::Hidden, cl::init(0));
70
71 static cl::opt<unsigned> ClCoverageBlockThreshold(
72     "sanitizer-coverage-block-threshold",
73     cl::desc("Use a callback with a guard check inside it if there are"
74              " more than this number of blocks."),
75     cl::Hidden, cl::init(1000));
76
77 static cl::opt<bool>
78     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
79                           cl::desc("Experimental basic-block tracing: insert "
80                                    "callbacks at every basic block"),
81                           cl::Hidden, cl::init(false));
82
83 namespace {
84
85 class SanitizerCoverageModule : public ModulePass {
86  public:
87    SanitizerCoverageModule(int CoverageLevel = 0)
88        : ModulePass(ID),
89          CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
90   bool runOnModule(Module &M) override;
91   bool runOnFunction(Function &F);
92   static char ID;  // Pass identification, replacement for typeid
93   const char *getPassName() const override {
94     return "SanitizerCoverageModule";
95   }
96
97   void getAnalysisUsage(AnalysisUsage &AU) const override {
98     AU.addRequired<DataLayoutPass>();
99   }
100
101  private:
102   void InjectCoverageForIndirectCalls(Function &F,
103                                       ArrayRef<Instruction *> IndirCalls);
104   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
105                       ArrayRef<Instruction *> IndirCalls);
106   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
107   Function *SanCovFunction;
108   Function *SanCovWithCheckFunction;
109   Function *SanCovIndirCallFunction;
110   Function *SanCovModuleInit;
111   Function *SanCovTraceEnter, *SanCovTraceBB;
112   InlineAsm *EmptyAsm;
113   Type *IntptrTy;
114   LLVMContext *C;
115
116   GlobalVariable *GuardArray;
117
118   int CoverageLevel;
119 };
120
121 }  // namespace
122
123 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
124   if (Function *F = dyn_cast<Function>(FuncOrBitcast))
125      return F;
126   std::string Err;
127   raw_string_ostream Stream(Err);
128   Stream << "SanitizerCoverage interface function redefined: "
129          << *FuncOrBitcast;
130   report_fatal_error(Err);
131 }
132
133 bool SanitizerCoverageModule::runOnModule(Module &M) {
134   if (!CoverageLevel) return false;
135   C = &(M.getContext());
136   DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
137   IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
138   Type *VoidTy = Type::getVoidTy(*C);
139   IRBuilder<> IRB(*C);
140   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
141   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
142
143   Function *CtorFunc =
144       Function::Create(FunctionType::get(VoidTy, false),
145                        GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
146   ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
147   appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
148
149   SanCovFunction = checkInterfaceFunction(
150       M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
151   SanCovWithCheckFunction = checkInterfaceFunction(
152       M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
153   SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
154       kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
155   SanCovModuleInit = checkInterfaceFunction(
156       M.getOrInsertFunction(kSanCovModuleInitName, Type::getVoidTy(*C),
157                             Int32PtrTy, IntptrTy, Int8PtrTy, nullptr));
158   SanCovModuleInit->setLinkage(Function::ExternalLinkage);
159   // We insert an empty inline asm after cov callbacks to avoid callback merge.
160   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
161                             StringRef(""), StringRef(""),
162                             /*hasSideEffects=*/true);
163
164   if (ClExperimentalTracing) {
165     SanCovTraceEnter = checkInterfaceFunction(
166         M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
167     SanCovTraceBB = checkInterfaceFunction(
168         M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
169   }
170
171   // At this point we create a dummy array of guards because we don't
172   // know how many elements we will need.
173   Type *Int32Ty = IRB.getInt32Ty();
174   GuardArray =
175       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
176                          nullptr, "__sancov_gen_cov_tmp");
177
178   for (auto &F : M)
179     runOnFunction(F);
180
181   // Now we know how many elements we need. Create an array of guards
182   // with one extra element at the beginning for the size.
183   Type *Int32ArrayNTy =
184       ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
185   GlobalVariable *RealGuardArray = new GlobalVariable(
186       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
187       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
188
189   // Replace the dummy array with the real one.
190   GuardArray->replaceAllUsesWith(
191       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
192   GuardArray->eraseFromParent();
193
194   // Create variable for module (compilation unit) name
195   Constant *ModNameStrConst =
196       ConstantDataArray::getString(M.getContext(), M.getName(), true);
197   GlobalVariable *ModuleName =
198       new GlobalVariable(M, ModNameStrConst->getType(), true,
199                          GlobalValue::PrivateLinkage, ModNameStrConst);
200
201   // Call __sanitizer_cov_module_init
202   IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
203   IRB.CreateCall3(SanCovModuleInit,
204                   IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
205                   ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()),
206                   IRB.CreatePointerCast(ModuleName, Int8PtrTy));
207   return true;
208 }
209
210 bool SanitizerCoverageModule::runOnFunction(Function &F) {
211   if (F.empty()) return false;
212   if (F.getName().find(".module_ctor") != std::string::npos)
213     return false;  // Should not instrument sanitizer init functions.
214   if (CoverageLevel >= 3)
215     SplitAllCriticalEdges(F);
216   SmallVector<Instruction*, 8> IndirCalls;
217   SmallVector<BasicBlock*, 16> AllBlocks;
218   for (auto &BB : F) {
219     AllBlocks.push_back(&BB);
220     if (CoverageLevel >= 4)
221       for (auto &Inst : BB) {
222         CallSite CS(&Inst);
223         if (CS && !CS.getCalledFunction())
224           IndirCalls.push_back(&Inst);
225       }
226   }
227   InjectCoverage(F, AllBlocks, IndirCalls);
228   return true;
229 }
230
231 bool
232 SanitizerCoverageModule::InjectCoverage(Function &F,
233                                         ArrayRef<BasicBlock *> AllBlocks,
234                                         ArrayRef<Instruction *> IndirCalls) {
235   if (!CoverageLevel) return false;
236
237   if (CoverageLevel == 1) {
238     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
239   } else {
240     for (auto BB : AllBlocks)
241       InjectCoverageAtBlock(F, *BB,
242                             ClCoverageBlockThreshold < AllBlocks.size());
243   }
244   InjectCoverageForIndirectCalls(F, IndirCalls);
245   return true;
246 }
247
248 // On every indirect call we call a run-time function
249 // __sanitizer_cov_indir_call* with two parameters:
250 //   - callee address,
251 //   - global cache array that contains kCacheSize pointers (zero-initialized).
252 //     The cache is used to speed up recording the caller-callee pairs.
253 // The address of the caller is passed implicitly via caller PC.
254 // kCacheSize is encoded in the name of the run-time function.
255 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
256     Function &F, ArrayRef<Instruction *> IndirCalls) {
257   if (IndirCalls.empty()) return;
258   const int kCacheSize = 16;
259   const int kCacheAlignment = 64;  // Align for better performance.
260   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
261   for (auto I : IndirCalls) {
262     IRBuilder<> IRB(I);
263     CallSite CS(I);
264     Value *Callee = CS.getCalledValue();
265     if (dyn_cast<InlineAsm>(Callee)) continue;
266     GlobalVariable *CalleeCache = new GlobalVariable(
267         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
268         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
269     CalleeCache->setAlignment(kCacheAlignment);
270     IRB.CreateCall2(SanCovIndirCallFunction,
271                     IRB.CreatePointerCast(Callee, IntptrTy),
272                     IRB.CreatePointerCast(CalleeCache, IntptrTy));
273   }
274 }
275
276 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
277                                                     bool UseCalls) {
278   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
279   // Skip static allocas at the top of the entry block so they don't become
280   // dynamic when we split the block.  If we used our optimized stack layout,
281   // then there will only be one alloca and it will come first.
282   for (; IP != BE; ++IP) {
283     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
284     if (!AI || !AI->isStaticAlloca())
285       break;
286   }
287
288   bool IsEntryBB = &BB == &F.getEntryBlock();
289   DebugLoc EntryLoc =
290       IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
291   IRBuilder<> IRB(IP);
292   IRB.SetCurrentDebugLocation(EntryLoc);
293   SmallVector<Value *, 1> Indices;
294   Value *GuardP = IRB.CreateAdd(
295       IRB.CreatePointerCast(GuardArray, IntptrTy),
296       ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
297   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
298   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
299   if (UseCalls) {
300     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
301   } else {
302     LoadInst *Load = IRB.CreateLoad(GuardP);
303     Load->setAtomic(Monotonic);
304     Load->setAlignment(4);
305     Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
306                       MDNode::get(*C, None));
307     Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
308     Instruction *Ins = SplitBlockAndInsertIfThen(
309         Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
310     IRB.SetInsertPoint(Ins);
311     IRB.SetCurrentDebugLocation(EntryLoc);
312     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
313     IRB.CreateCall(SanCovFunction, GuardP);
314     IRB.CreateCall(EmptyAsm);  // Avoids callback merge.
315   }
316
317   if (ClExperimentalTracing) {
318     // Experimental support for tracing.
319     // Insert a callback with the same guard variable as used for coverage.
320     IRB.SetInsertPoint(IP);
321     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
322   }
323 }
324
325 char SanitizerCoverageModule::ID = 0;
326 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
327     "SanitizerCoverage: TODO."
328     "ModulePass", false, false)
329 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
330   return new SanitizerCoverageModule(CoverageLevel);
331 }