f882072e6191c19feccaa10763988f6f2be20de3
[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 boolean 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) {
17 //    __sanitizer_cov();
18 //    *Guard = 1;
19 // }
20 // The accesses to Guard are atomic. The rest of the logic is
21 // in __sanitizer_cov (it's fine to call it more than once).
22 //
23 // With CoverageLevel>=3 we also split critical edges this effectively
24 // instrumenting all edges.
25 //
26 // CoverageLevel>=4 add indirect call profiling implented as a function call.
27 //
28 // This coverage implementation provides very limited data:
29 // it only tells if a given function (block) was ever executed. No counters.
30 // But for many use cases this is what we need and the added slowdown small.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #include "llvm/Transforms/Instrumentation.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/IRBuilder.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 kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
59 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
60 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
61 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
62 static const uint64_t    kSanCtorAndDtorPriority = 1;
63
64 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
65        cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
66                 "3: all blocks and critical edges, "
67                 "4: above plus indirect calls"),
68        cl::Hidden, cl::init(0));
69
70 static cl::opt<int> ClCoverageBlockThreshold(
71     "sanitizer-coverage-block-threshold",
72     cl::desc("Add coverage instrumentation only to the entry block if there "
73              "are more than this number of blocks."),
74     cl::Hidden, cl::init(1500));
75
76 static cl::opt<bool>
77     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
78                           cl::desc("Experimental basic-block tracing: insert "
79                                    "callbacks at every basic block"),
80                           cl::Hidden, cl::init(false));
81
82 namespace {
83
84 class SanitizerCoverageModule : public ModulePass {
85  public:
86    SanitizerCoverageModule(int CoverageLevel = 0)
87        : ModulePass(ID),
88          CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
89   bool runOnModule(Module &M) override;
90   bool runOnFunction(Function &F);
91   static char ID;  // Pass identification, replacement for typeid
92   const char *getPassName() const override {
93     return "SanitizerCoverageModule";
94   }
95
96   void getAnalysisUsage(AnalysisUsage &AU) const override {
97     AU.addRequired<DataLayoutPass>();
98   }
99
100  private:
101   void InjectCoverageForIndirectCalls(Function &F,
102                                       ArrayRef<Instruction *> IndirCalls);
103   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
104                       ArrayRef<Instruction *> IndirCalls);
105   bool InjectTracing(Function &F, ArrayRef<BasicBlock *> AllBlocks);
106   void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
107   Function *SanCovFunction;
108   Function *SanCovIndirCallFunction;
109   Function *SanCovModuleInit;
110   Function *SanCovTraceEnter, *SanCovTraceBB;
111   Type *IntptrTy;
112   LLVMContext *C;
113
114   int CoverageLevel;
115 };
116
117 }  // namespace
118
119 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
120   if (Function *F = dyn_cast<Function>(FuncOrBitcast))
121      return F;
122   std::string Err;
123   raw_string_ostream Stream(Err);
124   Stream << "SanitizerCoverage interface function redefined: "
125          << *FuncOrBitcast;
126   report_fatal_error(Err);
127 }
128
129 bool SanitizerCoverageModule::runOnModule(Module &M) {
130   if (!CoverageLevel) return false;
131   C = &(M.getContext());
132   DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
133   IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
134   Type *VoidTy = Type::getVoidTy(*C);
135
136   Function *CtorFunc =
137       Function::Create(FunctionType::get(VoidTy, false),
138                        GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
139   ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
140   appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
141
142   SanCovFunction =
143       checkInterfaceFunction(M.getOrInsertFunction(kSanCovName, VoidTy, nullptr));
144   SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
145       kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
146   SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
147       kSanCovModuleInitName, Type::getVoidTy(*C), IntptrTy, nullptr));
148   SanCovModuleInit->setLinkage(Function::ExternalLinkage);
149
150   if (ClExperimentalTracing) {
151     SanCovTraceEnter = checkInterfaceFunction(
152         M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, IntptrTy, nullptr));
153     SanCovTraceBB = checkInterfaceFunction(
154         M.getOrInsertFunction(kSanCovTraceBB, VoidTy, IntptrTy, nullptr));
155   }
156
157   for (auto &F : M)
158     runOnFunction(F);
159
160   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
161   IRB.CreateCall(SanCovModuleInit,
162                  ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
163   return true;
164 }
165
166 bool SanitizerCoverageModule::runOnFunction(Function &F) {
167   if (F.empty()) return false;
168   // For now instrument only functions that will also be asan-instrumented.
169   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
170     return false;
171   if (CoverageLevel >= 3)
172     SplitAllCriticalEdges(F, this);
173   SmallVector<Instruction*, 8> IndirCalls;
174   SmallVector<BasicBlock*, 16> AllBlocks;
175   for (auto &BB : F) {
176     AllBlocks.push_back(&BB);
177     if (CoverageLevel >= 4)
178       for (auto &Inst : BB) {
179         CallSite CS(&Inst);
180         if (CS && !CS.getCalledFunction())
181           IndirCalls.push_back(&Inst);
182       }
183   }
184   InjectCoverage(F, AllBlocks, IndirCalls);
185   InjectTracing(F, AllBlocks);
186   return true;
187 }
188
189 // Experimental support for tracing.
190 // Basicaly, insert a callback at the beginning of every basic block.
191 // Every callback gets a pointer to a uniqie global for internal storage.
192 bool SanitizerCoverageModule::InjectTracing(Function &F,
193                                             ArrayRef<BasicBlock *> AllBlocks) {
194   if (!ClExperimentalTracing) return false;
195   Type *Ty = ArrayType::get(IntptrTy, 1);  // May need to use more words later.
196   for (auto BB : AllBlocks) {
197     IRBuilder<> IRB(BB->getFirstInsertionPt());
198     GlobalVariable *TraceCache = new GlobalVariable(
199         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
200         Constant::getNullValue(Ty), "__sancov_gen_trace_cache");
201     IRB.CreateCall(&F.getEntryBlock() == BB ? SanCovTraceEnter : SanCovTraceBB,
202                    IRB.CreatePointerCast(TraceCache, IntptrTy));
203   }
204   return true;
205 }
206
207 bool
208 SanitizerCoverageModule::InjectCoverage(Function &F,
209                                         ArrayRef<BasicBlock *> AllBlocks,
210                                         ArrayRef<Instruction *> IndirCalls) {
211   if (!CoverageLevel) return false;
212
213   if (CoverageLevel == 1 ||
214       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
215     InjectCoverageAtBlock(F, F.getEntryBlock());
216   } else {
217     for (auto BB : AllBlocks)
218       InjectCoverageAtBlock(F, *BB);
219   }
220   InjectCoverageForIndirectCalls(F, IndirCalls);
221   return true;
222 }
223
224 // On every indirect call we call a run-time function
225 // __sanitizer_cov_indir_call* with two parameters:
226 //   - callee address,
227 //   - global cache array that contains kCacheSize pointers (zero-initialized).
228 //     The cache is used to speed up recording the caller-callee pairs.
229 // The address of the caller is passed implicitly via caller PC.
230 // kCacheSize is encoded in the name of the run-time function.
231 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
232     Function &F, ArrayRef<Instruction *> IndirCalls) {
233   if (IndirCalls.empty()) return;
234   const int kCacheSize = 16;
235   const int kCacheAlignment = 64;  // Align for better performance.
236   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
237   for (auto I : IndirCalls) {
238     IRBuilder<> IRB(I);
239     CallSite CS(I);
240     Value *Callee = CS.getCalledValue();
241     if (dyn_cast<InlineAsm>(Callee)) continue;
242     GlobalVariable *CalleeCache = new GlobalVariable(
243         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
244         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
245     CalleeCache->setAlignment(kCacheAlignment);
246     IRB.CreateCall2(SanCovIndirCallFunction,
247                     IRB.CreatePointerCast(Callee, IntptrTy),
248                     IRB.CreatePointerCast(CalleeCache, IntptrTy));
249   }
250 }
251
252 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
253                                                     BasicBlock &BB) {
254   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
255   // Skip static allocas at the top of the entry block so they don't become
256   // dynamic when we split the block.  If we used our optimized stack layout,
257   // then there will only be one alloca and it will come first.
258   for (; IP != BE; ++IP) {
259     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
260     if (!AI || !AI->isStaticAlloca())
261       break;
262   }
263
264   DebugLoc EntryLoc = &BB == &F.getEntryBlock()
265                           ? IP->getDebugLoc().getFnDebugLoc(*C)
266                           : IP->getDebugLoc();
267   IRBuilder<> IRB(IP);
268   IRB.SetCurrentDebugLocation(EntryLoc);
269   Type *Int8Ty = IRB.getInt8Ty();
270   GlobalVariable *Guard = new GlobalVariable(
271       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
272       Constant::getNullValue(Int8Ty), "__sancov_gen_cov_" + F.getName());
273   LoadInst *Load = IRB.CreateLoad(Guard);
274   Load->setAtomic(Monotonic);
275   Load->setAlignment(1);
276   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
277   Instruction *Ins = SplitBlockAndInsertIfThen(
278       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
279   IRB.SetInsertPoint(Ins);
280   IRB.SetCurrentDebugLocation(EntryLoc);
281   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
282   IRB.CreateCall(SanCovFunction);
283   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
284   Store->setAtomic(Monotonic);
285   Store->setAlignment(1);
286 }
287
288 char SanitizerCoverageModule::ID = 0;
289 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
290     "SanitizerCoverage: TODO."
291     "ModulePass", false, false)
292 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
293   return new SanitizerCoverageModule(CoverageLevel);
294 }