07223d4df5c01992c3fd6b1a2462f47afcef6f8b
[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(&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 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   InlineAsm *EmptyAsm;
112   Type *IntptrTy;
113   LLVMContext *C;
114
115   int CoverageLevel;
116 };
117
118 }  // namespace
119
120 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
121   if (Function *F = dyn_cast<Function>(FuncOrBitcast))
122      return F;
123   std::string Err;
124   raw_string_ostream Stream(Err);
125   Stream << "SanitizerCoverage interface function redefined: "
126          << *FuncOrBitcast;
127   report_fatal_error(Err);
128 }
129
130 bool SanitizerCoverageModule::runOnModule(Module &M) {
131   if (!CoverageLevel) return false;
132   C = &(M.getContext());
133   DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
134   IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
135   Type *VoidTy = Type::getVoidTy(*C);
136   IRBuilder<> IRB(*C);
137
138   Function *CtorFunc =
139       Function::Create(FunctionType::get(VoidTy, false),
140                        GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
141   ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
142   appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
143
144   SanCovFunction = checkInterfaceFunction(
145       M.getOrInsertFunction(kSanCovName, VoidTy, IRB.getInt8PtrTy(), nullptr));
146   SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
147       kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
148   SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
149       kSanCovModuleInitName, Type::getVoidTy(*C), IntptrTy, nullptr));
150   SanCovModuleInit->setLinkage(Function::ExternalLinkage);
151   // We insert an empty inline asm after cov callbacks to avoid callback merge.
152   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
153                             StringRef(""), StringRef(""),
154                             /*hasSideEffects=*/true);
155
156   if (ClExperimentalTracing) {
157     SanCovTraceEnter = checkInterfaceFunction(
158         M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, IntptrTy, nullptr));
159     SanCovTraceBB = checkInterfaceFunction(
160         M.getOrInsertFunction(kSanCovTraceBB, VoidTy, IntptrTy, nullptr));
161   }
162
163   for (auto &F : M)
164     runOnFunction(F);
165
166   IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
167   IRB.CreateCall(SanCovModuleInit,
168                  ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
169   return true;
170 }
171
172 bool SanitizerCoverageModule::runOnFunction(Function &F) {
173   if (F.empty()) return false;
174   // For now instrument only functions that will also be asan-instrumented.
175   if (!F.hasFnAttribute(Attribute::SanitizeAddress) &&
176       !F.hasFnAttribute(Attribute::SanitizeMemory))
177     return false;
178   if (CoverageLevel >= 3)
179     SplitAllCriticalEdges(F, this);
180   SmallVector<Instruction*, 8> IndirCalls;
181   SmallVector<BasicBlock*, 16> AllBlocks;
182   for (auto &BB : F) {
183     AllBlocks.push_back(&BB);
184     if (CoverageLevel >= 4)
185       for (auto &Inst : BB) {
186         CallSite CS(&Inst);
187         if (CS && !CS.getCalledFunction())
188           IndirCalls.push_back(&Inst);
189       }
190   }
191   InjectCoverage(F, AllBlocks, IndirCalls);
192   InjectTracing(F, AllBlocks);
193   return true;
194 }
195
196 // Experimental support for tracing.
197 // Basicaly, insert a callback at the beginning of every basic block.
198 // Every callback gets a pointer to a uniqie global for internal storage.
199 bool SanitizerCoverageModule::InjectTracing(Function &F,
200                                             ArrayRef<BasicBlock *> AllBlocks) {
201   if (!ClExperimentalTracing) return false;
202   Type *Ty = ArrayType::get(IntptrTy, 1);  // May need to use more words later.
203   for (auto BB : AllBlocks) {
204     IRBuilder<> IRB(BB->getFirstInsertionPt());
205     GlobalVariable *TraceCache = new GlobalVariable(
206         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
207         Constant::getNullValue(Ty), "__sancov_gen_trace_cache");
208     IRB.CreateCall(&F.getEntryBlock() == BB ? SanCovTraceEnter : SanCovTraceBB,
209                    IRB.CreatePointerCast(TraceCache, IntptrTy));
210   }
211   return true;
212 }
213
214 bool
215 SanitizerCoverageModule::InjectCoverage(Function &F,
216                                         ArrayRef<BasicBlock *> AllBlocks,
217                                         ArrayRef<Instruction *> IndirCalls) {
218   if (!CoverageLevel) return false;
219
220   if (CoverageLevel == 1 ||
221       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
222     InjectCoverageAtBlock(F, F.getEntryBlock());
223   } else {
224     for (auto BB : AllBlocks)
225       InjectCoverageAtBlock(F, *BB);
226   }
227   InjectCoverageForIndirectCalls(F, IndirCalls);
228   return true;
229 }
230
231 // On every indirect call we call a run-time function
232 // __sanitizer_cov_indir_call* with two parameters:
233 //   - callee address,
234 //   - global cache array that contains kCacheSize pointers (zero-initialized).
235 //     The cache is used to speed up recording the caller-callee pairs.
236 // The address of the caller is passed implicitly via caller PC.
237 // kCacheSize is encoded in the name of the run-time function.
238 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
239     Function &F, ArrayRef<Instruction *> IndirCalls) {
240   if (IndirCalls.empty()) return;
241   const int kCacheSize = 16;
242   const int kCacheAlignment = 64;  // Align for better performance.
243   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
244   for (auto I : IndirCalls) {
245     IRBuilder<> IRB(I);
246     CallSite CS(I);
247     Value *Callee = CS.getCalledValue();
248     if (dyn_cast<InlineAsm>(Callee)) continue;
249     GlobalVariable *CalleeCache = new GlobalVariable(
250         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
251         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
252     CalleeCache->setAlignment(kCacheAlignment);
253     IRB.CreateCall2(SanCovIndirCallFunction,
254                     IRB.CreatePointerCast(Callee, IntptrTy),
255                     IRB.CreatePointerCast(CalleeCache, IntptrTy));
256   }
257 }
258
259 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
260                                                     BasicBlock &BB) {
261   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
262   // Skip static allocas at the top of the entry block so they don't become
263   // dynamic when we split the block.  If we used our optimized stack layout,
264   // then there will only be one alloca and it will come first.
265   for (; IP != BE; ++IP) {
266     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
267     if (!AI || !AI->isStaticAlloca())
268       break;
269   }
270
271   DebugLoc EntryLoc = &BB == &F.getEntryBlock()
272                           ? IP->getDebugLoc().getFnDebugLoc(*C)
273                           : IP->getDebugLoc();
274   IRBuilder<> IRB(IP);
275   IRB.SetCurrentDebugLocation(EntryLoc);
276   Type *Int8Ty = IRB.getInt8Ty();
277   GlobalVariable *Guard = new GlobalVariable(
278       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
279       Constant::getNullValue(Int8Ty), "__sancov_gen_cov_" + F.getName());
280   LoadInst *Load = IRB.CreateLoad(Guard);
281   Load->setAtomic(Monotonic);
282   Load->setAlignment(1);
283   Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
284                     MDNode::get(*C, None));
285   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
286   Instruction *Ins = SplitBlockAndInsertIfThen(
287       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
288   IRB.SetInsertPoint(Ins);
289   IRB.SetCurrentDebugLocation(EntryLoc);
290   // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
291   IRB.CreateCall(SanCovFunction, Guard);
292   IRB.CreateCall(EmptyAsm);  // Avoids callback merge.
293 }
294
295 char SanitizerCoverageModule::ID = 0;
296 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
297     "SanitizerCoverage: TODO."
298     "ModulePass", false, false)
299 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
300   return new SanitizerCoverageModule(CoverageLevel);
301 }