xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision a1f12ba17e94aad4ddb904385aeae124f4586a26)
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 done on LLVM IR level, works with Sanitizers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/EHPersonalities.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/ModuleUtils.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "sancov"
41 
42 static const char *const SanCovTracePCIndirName =
43     "__sanitizer_cov_trace_pc_indir";
44 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
45 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
49 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
52 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54 static const uint64_t SanCtorAndDtorPriority = 2;
55 
56 static const char *const SanCovTracePCGuardName =
57     "__sanitizer_cov_trace_pc_guard";
58 static const char *const SanCovTracePCGuardInitName =
59     "__sanitizer_cov_trace_pc_guard_init";
60 static const char *const SanCov8bitCountersInitName =
61     "__sanitizer_cov_8bit_counters_init";
62 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
63 
64 static const char *const SanCovGuardsSectionName = "sancov_guards";
65 static const char *const SanCovCountersSectionName = "sancov_cntrs";
66 static const char *const SanCovPCsSectionName = "sancov_pcs";
67 
68 static cl::opt<int> ClCoverageLevel(
69     "sanitizer-coverage-level",
70     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
71              "3: all blocks and critical edges"),
72     cl::Hidden, cl::init(0));
73 
74 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
75                                cl::desc("Experimental pc tracing"), cl::Hidden,
76                                cl::init(false));
77 
78 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
79                                     cl::desc("pc tracing with a guard"),
80                                     cl::Hidden, cl::init(false));
81 
82 // If true, we create a global variable that contains PCs of all instrumented
83 // BBs, put this global into a named section, and pass this section's bounds
84 // to __sanitizer_cov_pcs_init.
85 // This way the coverage instrumentation does not need to acquire the PCs
86 // at run-time. Works with trace-pc-guard and inline-8bit-counters.
87 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
88                                      cl::desc("create a static PC table"),
89                                      cl::Hidden, cl::init(false));
90 
91 static cl::opt<bool>
92     ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
93                          cl::desc("increments 8-bit counter for every edge"),
94                          cl::Hidden, cl::init(false));
95 
96 static cl::opt<bool>
97     ClCMPTracing("sanitizer-coverage-trace-compares",
98                  cl::desc("Tracing of CMP and similar instructions"),
99                  cl::Hidden, cl::init(false));
100 
101 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
102                                   cl::desc("Tracing of DIV instructions"),
103                                   cl::Hidden, cl::init(false));
104 
105 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
106                                   cl::desc("Tracing of GEP instructions"),
107                                   cl::Hidden, cl::init(false));
108 
109 static cl::opt<bool>
110     ClPruneBlocks("sanitizer-coverage-prune-blocks",
111                   cl::desc("Reduce the number of instrumented blocks"),
112                   cl::Hidden, cl::init(true));
113 
114 namespace {
115 
116 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
117   SanitizerCoverageOptions Res;
118   switch (LegacyCoverageLevel) {
119   case 0:
120     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
121     break;
122   case 1:
123     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
124     break;
125   case 2:
126     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
127     break;
128   case 3:
129     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
130     break;
131   case 4:
132     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
133     Res.IndirectCalls = true;
134     break;
135   }
136   return Res;
137 }
138 
139 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
140   // Sets CoverageType and IndirectCalls.
141   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
142   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
143   Options.IndirectCalls |= CLOpts.IndirectCalls;
144   Options.TraceCmp |= ClCMPTracing;
145   Options.TraceDiv |= ClDIVTracing;
146   Options.TraceGep |= ClGEPTracing;
147   Options.TracePC |= ClTracePC;
148   Options.TracePCGuard |= ClTracePCGuard;
149   Options.Inline8bitCounters |= ClInline8bitCounters;
150   Options.PCTable |= ClCreatePCTable;
151   if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters)
152     Options.TracePCGuard = true; // TracePCGuard is default.
153   Options.NoPrune |= !ClPruneBlocks;
154   return Options;
155 }
156 
157 class SanitizerCoverageModule : public ModulePass {
158 public:
159   SanitizerCoverageModule(
160       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
161       : ModulePass(ID), Options(OverrideFromCL(Options)) {
162     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
163   }
164   bool runOnModule(Module &M) override;
165   bool runOnFunction(Function &F);
166   static char ID; // Pass identification, replacement for typeid
167   StringRef getPassName() const override { return "SanitizerCoverageModule"; }
168 
169   void getAnalysisUsage(AnalysisUsage &AU) const override {
170     AU.addRequired<DominatorTreeWrapperPass>();
171     AU.addRequired<PostDominatorTreeWrapperPass>();
172   }
173 
174 private:
175   void InjectCoverageForIndirectCalls(Function &F,
176                                       ArrayRef<Instruction *> IndirCalls);
177   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
178   void InjectTraceForDiv(Function &F,
179                          ArrayRef<BinaryOperator *> DivTraceTargets);
180   void InjectTraceForGep(Function &F,
181                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
182   void InjectTraceForSwitch(Function &F,
183                             ArrayRef<Instruction *> SwitchTraceTargets);
184   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
185   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
186                                                     Function &F, Type *Ty,
187                                                     const char *Section);
188   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
189   void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
190   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
191   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
192                                        Type *Ty, const char *Section);
193   std::pair<GlobalVariable *, GlobalVariable *>
194   CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
195 
196   void SetNoSanitizeMetadata(Instruction *I) {
197     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
198                    MDNode::get(*C, None));
199   }
200 
201   std::string getSectionName(const std::string &Section) const;
202   std::string getSectionStart(const std::string &Section) const;
203   std::string getSectionEnd(const std::string &Section) const;
204   Function *SanCovTracePCIndir;
205   Function *SanCovTracePC, *SanCovTracePCGuard;
206   Function *SanCovTraceCmpFunction[4];
207   Function *SanCovTraceDivFunction[2];
208   Function *SanCovTraceGepFunction;
209   Function *SanCovTraceSwitchFunction;
210   InlineAsm *EmptyAsm;
211   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
212       *Int8Ty, *Int8PtrTy;
213   Module *CurModule;
214   Triple TargetTriple;
215   LLVMContext *C;
216   const DataLayout *DL;
217 
218   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
219   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
220   GlobalVariable *FunctionPCsArray;  // for pc-table.
221 
222   SanitizerCoverageOptions Options;
223 };
224 
225 } // namespace
226 
227 std::pair<GlobalVariable *, GlobalVariable *>
228 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
229                                            Type *Ty) {
230   GlobalVariable *SecStart =
231       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
232                          getSectionStart(Section));
233   SecStart->setVisibility(GlobalValue::HiddenVisibility);
234   GlobalVariable *SecEnd =
235       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
236                          nullptr, getSectionEnd(Section));
237   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
238 
239   return std::make_pair(SecStart, SecEnd);
240 }
241 
242 
243 Function *SanitizerCoverageModule::CreateInitCallsForSections(
244     Module &M, const char *InitFunctionName, Type *Ty,
245     const char *Section) {
246   IRBuilder<> IRB(M.getContext());
247   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
248   auto SecStart = SecStartEnd.first;
249   auto SecEnd = SecStartEnd.second;
250   Function *CtorFunc;
251   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
252       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
253       {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
254 
255   if (TargetTriple.supportsCOMDAT()) {
256     // Use comdat to dedup CtorFunc.
257     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
258     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
259   } else {
260     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
261   }
262   return CtorFunc;
263 }
264 
265 bool SanitizerCoverageModule::runOnModule(Module &M) {
266   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
267     return false;
268   C = &(M.getContext());
269   DL = &M.getDataLayout();
270   CurModule = &M;
271   TargetTriple = Triple(M.getTargetTriple());
272   FunctionGuardArray = nullptr;
273   Function8bitCounterArray = nullptr;
274   FunctionPCsArray = nullptr;
275   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
276   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
277   Type *VoidTy = Type::getVoidTy(*C);
278   IRBuilder<> IRB(*C);
279   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
280   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
281   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
282   Int64Ty = IRB.getInt64Ty();
283   Int32Ty = IRB.getInt32Ty();
284   Int8Ty = IRB.getInt8Ty();
285 
286   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
287       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
288   SanCovTraceCmpFunction[0] =
289       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
290           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
291   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
292       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
293                             IRB.getInt16Ty()));
294   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
295       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
296                             IRB.getInt32Ty()));
297   SanCovTraceCmpFunction[3] =
298       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
299           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
300 
301   SanCovTraceDivFunction[0] =
302       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
303           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
304   SanCovTraceDivFunction[1] =
305       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
306           SanCovTraceDiv8, VoidTy, Int64Ty));
307   SanCovTraceGepFunction =
308       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
309           SanCovTraceGep, VoidTy, IntptrTy));
310   SanCovTraceSwitchFunction =
311       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
312           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
313   // Make sure smaller parameters are zero-extended to i64 as required by the
314   // x86_64 ABI.
315   if (TargetTriple.getArch() == Triple::x86_64) {
316     for (int i = 0; i < 3; i++) {
317       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
318       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
319     }
320     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
321   }
322 
323 
324   // We insert an empty inline asm after cov callbacks to avoid callback merge.
325   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
326                             StringRef(""), StringRef(""),
327                             /*hasSideEffects=*/true);
328 
329   SanCovTracePC = checkSanitizerInterfaceFunction(
330       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
331   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
332       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
333 
334   for (auto &F : M)
335     runOnFunction(F);
336 
337   Function *Ctor = nullptr;
338 
339   if (FunctionGuardArray)
340     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
341                                       SanCovGuardsSectionName);
342   if (Function8bitCounterArray)
343     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
344                                       SanCovCountersSectionName);
345   if (Ctor && Options.PCTable) {
346     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, Int8PtrTy);
347     Function *InitFunction = declareSanitizerInitFunction(
348         M, SanCovPCsInitName, {Int8PtrTy, Int8PtrTy});
349     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
350     IRBCtor.CreateCall(InitFunction,
351                        {IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy),
352                         IRB.CreatePointerCast(SecStartEnd.second, Int8PtrTy)});
353   }
354   return true;
355 }
356 
357 // True if block has successors and it dominates all of them.
358 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
359   if (succ_begin(BB) == succ_end(BB))
360     return false;
361 
362   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
363     if (!DT->dominates(BB, SUCC))
364       return false;
365   }
366 
367   return true;
368 }
369 
370 // True if block has predecessors and it postdominates all of them.
371 static bool isFullPostDominator(const BasicBlock *BB,
372                                 const PostDominatorTree *PDT) {
373   if (pred_begin(BB) == pred_end(BB))
374     return false;
375 
376   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
377     if (!PDT->dominates(BB, PRED))
378       return false;
379   }
380 
381   return true;
382 }
383 
384 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
385                                   const DominatorTree *DT,
386                                   const PostDominatorTree *PDT,
387                                   const SanitizerCoverageOptions &Options) {
388   // Don't insert coverage for unreachable blocks: we will never call
389   // __sanitizer_cov() for them, so counting them in
390   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
391   // percentage. Also, unreachable instructions frequently have no debug
392   // locations.
393   if (isa<UnreachableInst>(BB->getTerminator()))
394     return false;
395 
396   // Don't insert coverage into blocks without a valid insertion point
397   // (catchswitch blocks).
398   if (BB->getFirstInsertionPt() == BB->end())
399     return false;
400 
401   if (Options.NoPrune || &F.getEntryBlock() == BB)
402     return true;
403 
404   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
405       &F.getEntryBlock() != BB)
406     return false;
407 
408   // Do not instrument full dominators, or full post-dominators with multiple
409   // predecessors.
410   return !isFullDominator(BB, DT)
411     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
412 }
413 
414 bool SanitizerCoverageModule::runOnFunction(Function &F) {
415   if (F.empty())
416     return false;
417   if (F.getName().find(".module_ctor") != std::string::npos)
418     return false; // Should not instrument sanitizer init functions.
419   if (F.getName().startswith("__sanitizer_"))
420     return false;  // Don't instrument __sanitizer_* callbacks.
421   // Don't touch available_externally functions, their actual body is elewhere.
422   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
423     return false;
424   // Don't instrument MSVC CRT configuration helpers. They may run before normal
425   // initialization.
426   if (F.getName() == "__local_stdio_printf_options" ||
427       F.getName() == "__local_stdio_scanf_options")
428     return false;
429   // Don't instrument functions using SEH for now. Splitting basic blocks like
430   // we do for coverage breaks WinEHPrepare.
431   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
432   if (F.hasPersonalityFn() &&
433       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
434     return false;
435   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
436     SplitAllCriticalEdges(F);
437   SmallVector<Instruction *, 8> IndirCalls;
438   SmallVector<BasicBlock *, 16> BlocksToInstrument;
439   SmallVector<Instruction *, 8> CmpTraceTargets;
440   SmallVector<Instruction *, 8> SwitchTraceTargets;
441   SmallVector<BinaryOperator *, 8> DivTraceTargets;
442   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
443 
444   const DominatorTree *DT =
445       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
446   const PostDominatorTree *PDT =
447       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
448 
449   for (auto &BB : F) {
450     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
451       BlocksToInstrument.push_back(&BB);
452     for (auto &Inst : BB) {
453       if (Options.IndirectCalls) {
454         CallSite CS(&Inst);
455         if (CS && !CS.getCalledFunction())
456           IndirCalls.push_back(&Inst);
457       }
458       if (Options.TraceCmp) {
459         if (isa<ICmpInst>(&Inst))
460           CmpTraceTargets.push_back(&Inst);
461         if (isa<SwitchInst>(&Inst))
462           SwitchTraceTargets.push_back(&Inst);
463       }
464       if (Options.TraceDiv)
465         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
466           if (BO->getOpcode() == Instruction::SDiv ||
467               BO->getOpcode() == Instruction::UDiv)
468             DivTraceTargets.push_back(BO);
469       if (Options.TraceGep)
470         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
471           GepTraceTargets.push_back(GEP);
472    }
473   }
474 
475   InjectCoverage(F, BlocksToInstrument);
476   InjectCoverageForIndirectCalls(F, IndirCalls);
477   InjectTraceForCmp(F, CmpTraceTargets);
478   InjectTraceForSwitch(F, SwitchTraceTargets);
479   InjectTraceForDiv(F, DivTraceTargets);
480   InjectTraceForGep(F, GepTraceTargets);
481   return true;
482 }
483 
484 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
485     size_t NumElements, Function &F, Type *Ty, const char *Section) {
486   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
487   auto Array = new GlobalVariable(
488       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
489       Constant::getNullValue(ArrayTy), "__sancov_gen_");
490   if (auto Comdat = F.getComdat())
491     Array->setComdat(Comdat);
492   Array->setSection(getSectionName(Section));
493   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
494                                         : Ty->getPrimitiveSizeInBits() / 8);
495   return Array;
496 }
497 
498 void SanitizerCoverageModule::CreatePCArray(Function &F,
499                                             ArrayRef<BasicBlock *> AllBlocks) {
500   size_t N = AllBlocks.size();
501   assert(N);
502   SmallVector<Constant *, 16> PCs;
503   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
504   for (size_t i = 0; i < N; i++)
505     if (&F.getEntryBlock() == AllBlocks[i])
506       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, Int8PtrTy));
507     else
508       PCs.push_back(BlockAddress::get(AllBlocks[i]));
509   FunctionPCsArray =
510       CreateFunctionLocalArrayInSection(N, F, Int8PtrTy, SanCovPCsSectionName);
511   FunctionPCsArray->setInitializer(
512       ConstantArray::get(ArrayType::get(Int8PtrTy, N), PCs));
513   FunctionPCsArray->setConstant(true);
514 }
515 
516 void SanitizerCoverageModule::CreateFunctionLocalArrays(
517     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
518   if (Options.TracePCGuard)
519     FunctionGuardArray = CreateFunctionLocalArrayInSection(
520         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
521   if (Options.Inline8bitCounters)
522     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
523         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
524   if (Options.PCTable)
525     CreatePCArray(F, AllBlocks);
526 }
527 
528 bool SanitizerCoverageModule::InjectCoverage(Function &F,
529                                              ArrayRef<BasicBlock *> AllBlocks) {
530   if (AllBlocks.empty()) return false;
531   CreateFunctionLocalArrays(F, AllBlocks);
532   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
533     InjectCoverageAtBlock(F, *AllBlocks[i], i);
534   return true;
535 }
536 
537 // On every indirect call we call a run-time function
538 // __sanitizer_cov_indir_call* with two parameters:
539 //   - callee address,
540 //   - global cache array that contains CacheSize pointers (zero-initialized).
541 //     The cache is used to speed up recording the caller-callee pairs.
542 // The address of the caller is passed implicitly via caller PC.
543 // CacheSize is encoded in the name of the run-time function.
544 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
545     Function &F, ArrayRef<Instruction *> IndirCalls) {
546   if (IndirCalls.empty())
547     return;
548   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
549   for (auto I : IndirCalls) {
550     IRBuilder<> IRB(I);
551     CallSite CS(I);
552     Value *Callee = CS.getCalledValue();
553     if (isa<InlineAsm>(Callee))
554       continue;
555     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
556   }
557 }
558 
559 // For every switch statement we insert a call:
560 // __sanitizer_cov_trace_switch(CondValue,
561 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
562 
563 void SanitizerCoverageModule::InjectTraceForSwitch(
564     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
565   for (auto I : SwitchTraceTargets) {
566     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
567       IRBuilder<> IRB(I);
568       SmallVector<Constant *, 16> Initializers;
569       Value *Cond = SI->getCondition();
570       if (Cond->getType()->getScalarSizeInBits() >
571           Int64Ty->getScalarSizeInBits())
572         continue;
573       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
574       Initializers.push_back(
575           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
576       if (Cond->getType()->getScalarSizeInBits() <
577           Int64Ty->getScalarSizeInBits())
578         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
579       for (auto It : SI->cases()) {
580         Constant *C = It.getCaseValue();
581         if (C->getType()->getScalarSizeInBits() <
582             Int64Ty->getScalarSizeInBits())
583           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
584         Initializers.push_back(C);
585       }
586       std::sort(Initializers.begin() + 2, Initializers.end(),
587                 [](const Constant *A, const Constant *B) {
588                   return cast<ConstantInt>(A)->getLimitedValue() <
589                          cast<ConstantInt>(B)->getLimitedValue();
590                 });
591       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
592       GlobalVariable *GV = new GlobalVariable(
593           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
594           ConstantArray::get(ArrayOfInt64Ty, Initializers),
595           "__sancov_gen_cov_switch_values");
596       IRB.CreateCall(SanCovTraceSwitchFunction,
597                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
598     }
599   }
600 }
601 
602 void SanitizerCoverageModule::InjectTraceForDiv(
603     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
604   for (auto BO : DivTraceTargets) {
605     IRBuilder<> IRB(BO);
606     Value *A1 = BO->getOperand(1);
607     if (isa<ConstantInt>(A1)) continue;
608     if (!A1->getType()->isIntegerTy())
609       continue;
610     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
611     int CallbackIdx = TypeSize == 32 ? 0 :
612         TypeSize == 64 ? 1 : -1;
613     if (CallbackIdx < 0) continue;
614     auto Ty = Type::getIntNTy(*C, TypeSize);
615     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
616                    {IRB.CreateIntCast(A1, Ty, true)});
617   }
618 }
619 
620 void SanitizerCoverageModule::InjectTraceForGep(
621     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
622   for (auto GEP : GepTraceTargets) {
623     IRBuilder<> IRB(GEP);
624     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
625       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
626         IRB.CreateCall(SanCovTraceGepFunction,
627                        {IRB.CreateIntCast(*I, IntptrTy, true)});
628   }
629 }
630 
631 void SanitizerCoverageModule::InjectTraceForCmp(
632     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
633   for (auto I : CmpTraceTargets) {
634     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
635       IRBuilder<> IRB(ICMP);
636       Value *A0 = ICMP->getOperand(0);
637       Value *A1 = ICMP->getOperand(1);
638       if (!A0->getType()->isIntegerTy())
639         continue;
640       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
641       int CallbackIdx = TypeSize == 8 ? 0 :
642                         TypeSize == 16 ? 1 :
643                         TypeSize == 32 ? 2 :
644                         TypeSize == 64 ? 3 : -1;
645       if (CallbackIdx < 0) continue;
646       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
647       auto Ty = Type::getIntNTy(*C, TypeSize);
648       IRB.CreateCall(
649           SanCovTraceCmpFunction[CallbackIdx],
650           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
651     }
652   }
653 }
654 
655 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
656                                                     size_t Idx) {
657   BasicBlock::iterator IP = BB.getFirstInsertionPt();
658   bool IsEntryBB = &BB == &F.getEntryBlock();
659   DebugLoc EntryLoc;
660   if (IsEntryBB) {
661     if (auto SP = F.getSubprogram())
662       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
663     // Keep static allocas and llvm.localescape calls in the entry block.  Even
664     // if we aren't splitting the block, it's nice for allocas to be before
665     // calls.
666     IP = PrepareToSplitEntryBlock(BB, IP);
667   } else {
668     EntryLoc = IP->getDebugLoc();
669   }
670 
671   IRBuilder<> IRB(&*IP);
672   IRB.SetCurrentDebugLocation(EntryLoc);
673   if (Options.TracePC) {
674     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
675     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
676   }
677   if (Options.TracePCGuard) {
678     auto GuardPtr = IRB.CreateIntToPtr(
679         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
680                       ConstantInt::get(IntptrTy, Idx * 4)),
681         Int32PtrTy);
682     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
683     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
684   }
685   if (Options.Inline8bitCounters) {
686     auto CounterPtr = IRB.CreateGEP(
687         Function8bitCounterArray,
688         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
689     auto Load = IRB.CreateLoad(CounterPtr);
690     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
691     auto Store = IRB.CreateStore(Inc, CounterPtr);
692     SetNoSanitizeMetadata(Load);
693     SetNoSanitizeMetadata(Store);
694   }
695 }
696 
697 std::string
698 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
699   if (TargetTriple.getObjectFormat() == Triple::COFF)
700     return ".SCOV$M";
701   if (TargetTriple.isOSBinFormatMachO())
702     return "__DATA,__" + Section;
703   return "__" + Section;
704 }
705 
706 std::string
707 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
708   if (TargetTriple.isOSBinFormatMachO())
709     return "\1section$start$__DATA$__" + Section;
710   return "__start___" + Section;
711 }
712 
713 std::string
714 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
715   if (TargetTriple.isOSBinFormatMachO())
716     return "\1section$end$__DATA$__" + Section;
717   return "__stop___" + Section;
718 }
719 
720 
721 char SanitizerCoverageModule::ID = 0;
722 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
723                       "SanitizerCoverage: TODO."
724                       "ModulePass",
725                       false, false)
726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
727 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
728 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
729                     "SanitizerCoverage: TODO."
730                     "ModulePass",
731                     false, false)
732 ModulePass *llvm::createSanitizerCoverageModulePass(
733     const SanitizerCoverageOptions &Options) {
734   return new SanitizerCoverageModule(Options);
735 }
736