blob: 2ae3d43bca582e82719761ae6fe7d3161c8f7c0a [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- 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//
Kostya Serebryany53b34c82017-05-31 18:27:33 +000010// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000011//
12//===----------------------------------------------------------------------===//
13
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000014#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000016#include "llvm/Analysis/EHPersonalities.h"
George Karpenkov018472c2017-05-24 00:29:12 +000017#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000018#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000019#include "llvm/IR/CallSite.h"
20#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000021#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000022#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000025#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000026#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"
Mike Aizatsky5971f182016-02-26 01:17:22 +000033#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000034#include "llvm/Transforms/Scalar.h"
35#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36#include "llvm/Transforms/Utils/ModuleUtils.h"
37
38using namespace llvm;
39
40#define DEBUG_TYPE "sancov"
41
Mike Aizatsky759aca02016-03-18 23:29:29 +000042static const char *const SanCovTracePCIndirName =
43 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000044static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000045static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000049static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000052static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000055
Kostya Serebryanyda718e52016-09-14 01:39:35 +000056static const char *const SanCovTracePCGuardName =
57 "__sanitizer_cov_trace_pc_guard";
58static const char *const SanCovTracePCGuardInitName =
59 "__sanitizer_cov_trace_pc_guard_init";
60
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000061static const char *const SanCovGuardsSectionName = "sancov_guards";
62
Mike Aizatsky759aca02016-03-18 23:29:29 +000063static cl::opt<int> ClCoverageLevel(
64 "sanitizer-coverage-level",
65 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000066 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000067 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000068
Renato Golincdf840fd2017-06-05 07:35:52 +000069static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
70 cl::desc("Experimental pc tracing"),
71 cl::Hidden, cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000072
Kostya Serebryanyda718e52016-09-14 01:39:35 +000073static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
74 cl::desc("pc tracing with a guard"),
75 cl::Hidden, cl::init(false));
76
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000077static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000078 ClCMPTracing("sanitizer-coverage-trace-compares",
79 cl::desc("Tracing of CMP and similar instructions"),
80 cl::Hidden, cl::init(false));
81
82static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
83 cl::desc("Tracing of DIV instructions"),
84 cl::Hidden, cl::init(false));
85
86static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
87 cl::desc("Tracing of GEP instructions"),
88 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000089
Mike Aizatsky70ea4532016-04-06 23:24:37 +000090static cl::opt<bool>
91 ClPruneBlocks("sanitizer-coverage-prune-blocks",
92 cl::desc("Reduce the number of instrumented blocks"),
93 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +000094
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000095namespace {
96
Alexey Samsonov3514f272015-05-07 01:00:31 +000097SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
98 SanitizerCoverageOptions Res;
99 switch (LegacyCoverageLevel) {
100 case 0:
101 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
102 break;
103 case 1:
104 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
105 break;
106 case 2:
107 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
108 break;
109 case 3:
110 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
111 break;
112 case 4:
113 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
114 Res.IndirectCalls = true;
115 break;
116 }
117 return Res;
118}
119
120SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
121 // Sets CoverageType and IndirectCalls.
122 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
123 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
124 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000125 Options.TraceCmp |= ClCMPTracing;
126 Options.TraceDiv |= ClDIVTracing;
127 Options.TraceGep |= ClGEPTracing;
Renato Golincdf840fd2017-06-05 07:35:52 +0000128 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000129 Options.TracePCGuard |= ClTracePCGuard;
Renato Golincdf840fd2017-06-05 07:35:52 +0000130 if (!Options.TracePCGuard && !Options.TracePC)
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000131 Options.TracePCGuard = true; // TracePCGuard is default.
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000132 Options.NoPrune |= !ClPruneBlocks;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000133 return Options;
134}
135
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000136class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000137public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000138 SanitizerCoverageModule(
139 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000140 : ModulePass(ID), Options(OverrideFromCL(Options)) {
141 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
142 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000143 bool runOnModule(Module &M) override;
144 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000145 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000146 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000147
Chandler Carruth30061152016-03-18 22:43:42 +0000148 void getAnalysisUsage(AnalysisUsage &AU) const override {
149 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000150 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000151 }
152
153private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000154 void InjectCoverageForIndirectCalls(Function &F,
155 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000156 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000157 void InjectTraceForDiv(Function &F,
158 ArrayRef<BinaryOperator *> DivTraceTargets);
159 void InjectTraceForGep(Function &F,
160 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000161 void InjectTraceForSwitch(Function &F,
162 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000163 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000164 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
165 Function &F, Type *Ty,
166 const char *Section);
167 void CreateFunctionLocalArrays(size_t NumGuards, Function &F);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000168 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000169 void CreateInitCallForSection(Module &M, const char *InitFunctionName,
170 Type *Ty, const std::string &Section);
171
172 std::string getSectionName(const std::string &Section) const;
173 std::string getSectionStart(const std::string &Section) const;
174 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000175 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000176 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000177 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000178 Function *SanCovTraceDivFunction[2];
179 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000180 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000181 InlineAsm *EmptyAsm;
Renato Golincdf840fd2017-06-05 07:35:52 +0000182 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000183 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000184 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000185 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000186 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000188 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000189
Alexey Samsonov3514f272015-05-07 01:00:31 +0000190 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000191};
192
Mike Aizatsky759aca02016-03-18 23:29:29 +0000193} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000194
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000195void SanitizerCoverageModule::CreateInitCallForSection(
196 Module &M, const char *InitFunctionName, Type *Ty,
197 const std::string &Section) {
198 IRBuilder<> IRB(M.getContext());
199 Function *CtorFunc;
200 GlobalVariable *SecStart =
201 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
202 getSectionStart(Section));
203 SecStart->setVisibility(GlobalValue::HiddenVisibility);
204 GlobalVariable *SecEnd =
205 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
206 nullptr, getSectionEnd(Section));
207 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
208
209 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
210 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
211 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
212
213 if (TargetTriple.supportsCOMDAT()) {
214 // Use comdat to dedup CtorFunc.
215 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
216 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
217 } else {
218 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
219 }
220}
221
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000222bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000223 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
224 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000225 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000226 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000227 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000228 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000229 FunctionGuardArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000230 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000231 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000232 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000233 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000234 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000235 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000236 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000237 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000238
Mike Aizatsky759aca02016-03-18 23:29:29 +0000239 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000240 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000241 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000242 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000243 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000244 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
245 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000246 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000247 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
248 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000249 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000250 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000251 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000252 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000253
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000254 SanCovTraceDivFunction[0] =
255 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000256 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000257 SanCovTraceDivFunction[1] =
258 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000259 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000260 SanCovTraceGepFunction =
261 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000262 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000263 SanCovTraceSwitchFunction =
264 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000265 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000266
Kostya Serebryany73762942014-12-16 21:24:15 +0000267 // We insert an empty inline asm after cov callbacks to avoid callback merge.
268 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
269 StringRef(""), StringRef(""),
270 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000271
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000272 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000273 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000274 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000275 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000276
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000277 for (auto &F : M)
278 runOnFunction(F);
279
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000280 if (FunctionGuardArray)
281 CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
282 SanCovGuardsSectionName);
Justin Bogner41e632b2017-02-01 02:38:39 +0000283
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000284 return true;
285}
286
Mike Aizatsky9987f432016-03-23 23:15:03 +0000287// True if block has successors and it dominates all of them.
288static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
289 if (succ_begin(BB) == succ_end(BB))
290 return false;
291
292 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
293 if (!DT->dominates(BB, SUCC))
294 return false;
295 }
296
297 return true;
298}
299
George Karpenkov018472c2017-05-24 00:29:12 +0000300// True if block has predecessors and it postdominates all of them.
301static bool isFullPostDominator(const BasicBlock *BB,
302 const PostDominatorTree *PDT) {
303 if (pred_begin(BB) == pred_end(BB))
304 return false;
305
306 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
307 if (!PDT->dominates(BB, PRED))
308 return false;
309 }
310
311 return true;
312}
313
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000314static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
315 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000316 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000317 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000318 // Don't insert coverage for unreachable blocks: we will never call
319 // __sanitizer_cov() for them, so counting them in
320 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
321 // percentage. Also, unreachable instructions frequently have no debug
322 // locations.
323 if (isa<UnreachableInst>(BB->getTerminator()))
324 return false;
325
Reid Kleckner392f0622017-03-23 23:30:41 +0000326 // Don't insert coverage into blocks without a valid insertion point
327 // (catchswitch blocks).
328 if (BB->getFirstInsertionPt() == BB->end())
329 return false;
330
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000331 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000332 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000333
George Karpenkova1c53272017-05-25 01:41:46 +0000334 // Do not instrument full dominators, or full post-dominators with multiple
335 // predecessors.
336 return !isFullDominator(BB, DT)
337 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000338}
339
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000340bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000341 if (F.empty())
342 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000343 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000344 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000345 if (F.getName().startswith("__sanitizer_"))
346 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerec803542016-11-11 19:18:45 +0000347 // Don't instrument MSVC CRT configuration helpers. They may run before normal
348 // initialization.
349 if (F.getName() == "__local_stdio_printf_options" ||
350 F.getName() == "__local_stdio_scanf_options")
351 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000352 // Don't instrument functions using SEH for now. Splitting basic blocks like
353 // we do for coverage breaks WinEHPrepare.
354 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
355 if (F.hasPersonalityFn() &&
356 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
357 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000358 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000359 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000360 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000361 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000362 SmallVector<Instruction *, 8> CmpTraceTargets;
363 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000364 SmallVector<BinaryOperator *, 8> DivTraceTargets;
365 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000366
Mike Aizatsky602f7922016-03-21 23:08:16 +0000367 const DominatorTree *DT =
368 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000369 const PostDominatorTree *PDT =
370 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Mike Aizatsky602f7922016-03-21 23:08:16 +0000371
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000372 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000373 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000374 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000375 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000376 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000377 CallSite CS(&Inst);
378 if (CS && !CS.getCalledFunction())
379 IndirCalls.push_back(&Inst);
380 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000381 if (Options.TraceCmp) {
382 if (isa<ICmpInst>(&Inst))
383 CmpTraceTargets.push_back(&Inst);
384 if (isa<SwitchInst>(&Inst))
385 SwitchTraceTargets.push_back(&Inst);
386 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000387 if (Options.TraceDiv)
388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
389 if (BO->getOpcode() == Instruction::SDiv ||
390 BO->getOpcode() == Instruction::UDiv)
391 DivTraceTargets.push_back(BO);
392 if (Options.TraceGep)
393 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
394 GepTraceTargets.push_back(GEP);
395 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000396 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000397
398 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000399 InjectCoverageForIndirectCalls(F, IndirCalls);
400 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000401 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000402 InjectTraceForDiv(F, DivTraceTargets);
403 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000404 return true;
405}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000406
407GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
408 size_t NumElements, Function &F, Type *Ty, const char *Section) {
409 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
410 auto Array = new GlobalVariable(
411 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
412 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000413 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000414 Array->setComdat(Comdat);
415 Array->setSection(getSectionName(Section));
416 return Array;
417}
418void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
419 Function &F) {
420 if (Options.TracePCGuard)
421 FunctionGuardArray = CreateFunctionLocalArrayInSection(
422 NumGuards, F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000423}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000424
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000425bool SanitizerCoverageModule::InjectCoverage(Function &F,
426 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000427 if (AllBlocks.empty()) return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000428 switch (Options.CoverageType) {
429 case SanitizerCoverageOptions::SCK_None:
430 return false;
431 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000432 CreateFunctionLocalArrays(1, F);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000433 InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000434 return true;
435 default: {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000436 CreateFunctionLocalArrays(AllBlocks.size(), F);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000437 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000438 InjectCoverageAtBlock(F, *AllBlocks[i], i);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000439 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000440 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000441 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000442}
443
444// On every indirect call we call a run-time function
445// __sanitizer_cov_indir_call* with two parameters:
446// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000447// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000448// The cache is used to speed up recording the caller-callee pairs.
449// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000450// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000451void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
452 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000453 if (IndirCalls.empty())
454 return;
Renato Golincdf840fd2017-06-05 07:35:52 +0000455 assert(Options.TracePC || Options.TracePCGuard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000456 for (auto I : IndirCalls) {
457 IRBuilder<> IRB(I);
458 CallSite CS(I);
459 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000460 if (isa<InlineAsm>(Callee))
461 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000462 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000463 }
464}
465
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000466// For every switch statement we insert a call:
467// __sanitizer_cov_trace_switch(CondValue,
468// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
469
470void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000471 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000472 for (auto I : SwitchTraceTargets) {
473 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
474 IRBuilder<> IRB(I);
475 SmallVector<Constant *, 16> Initializers;
476 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000477 if (Cond->getType()->getScalarSizeInBits() >
478 Int64Ty->getScalarSizeInBits())
479 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000480 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
481 Initializers.push_back(
482 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
483 if (Cond->getType()->getScalarSizeInBits() <
484 Int64Ty->getScalarSizeInBits())
485 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000486 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000487 Constant *C = It.getCaseValue();
488 if (C->getType()->getScalarSizeInBits() <
489 Int64Ty->getScalarSizeInBits())
490 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
491 Initializers.push_back(C);
492 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000493 std::sort(Initializers.begin() + 2, Initializers.end(),
494 [](const Constant *A, const Constant *B) {
495 return cast<ConstantInt>(A)->getLimitedValue() <
496 cast<ConstantInt>(B)->getLimitedValue();
497 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000498 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
499 GlobalVariable *GV = new GlobalVariable(
500 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
501 ConstantArray::get(ArrayOfInt64Ty, Initializers),
502 "__sancov_gen_cov_switch_values");
503 IRB.CreateCall(SanCovTraceSwitchFunction,
504 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
505 }
506 }
507}
508
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000509void SanitizerCoverageModule::InjectTraceForDiv(
510 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
511 for (auto BO : DivTraceTargets) {
512 IRBuilder<> IRB(BO);
513 Value *A1 = BO->getOperand(1);
514 if (isa<ConstantInt>(A1)) continue;
515 if (!A1->getType()->isIntegerTy())
516 continue;
517 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
518 int CallbackIdx = TypeSize == 32 ? 0 :
519 TypeSize == 64 ? 1 : -1;
520 if (CallbackIdx < 0) continue;
521 auto Ty = Type::getIntNTy(*C, TypeSize);
522 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
523 {IRB.CreateIntCast(A1, Ty, true)});
524 }
525}
526
527void SanitizerCoverageModule::InjectTraceForGep(
528 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
529 for (auto GEP : GepTraceTargets) {
530 IRBuilder<> IRB(GEP);
531 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000532 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000533 IRB.CreateCall(SanCovTraceGepFunction,
534 {IRB.CreateIntCast(*I, IntptrTy, true)});
535 }
536}
537
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000538void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000539 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000540 for (auto I : CmpTraceTargets) {
541 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
542 IRBuilder<> IRB(ICMP);
543 Value *A0 = ICMP->getOperand(0);
544 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000545 if (!A0->getType()->isIntegerTy())
546 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000547 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000548 int CallbackIdx = TypeSize == 8 ? 0 :
549 TypeSize == 16 ? 1 :
550 TypeSize == 32 ? 2 :
551 TypeSize == 64 ? 3 : -1;
552 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000553 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000554 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000555 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000556 SanCovTraceCmpFunction[CallbackIdx],
557 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000558 }
559 }
560}
561
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000562void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000563 size_t Idx) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000564 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000565 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000566 DebugLoc EntryLoc;
567 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000568 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000569 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000570 // Keep static allocas and llvm.localescape calls in the entry block. Even
571 // if we aren't splitting the block, it's nice for allocas to be before
572 // calls.
573 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000574 } else {
575 EntryLoc = IP->getDebugLoc();
576 }
577
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000578 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000579 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000580 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000581 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
582 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Renato Golincdf840fd2017-06-05 07:35:52 +0000583 } else {
584 assert(Options.TracePCGuard);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000585 auto GuardPtr = IRB.CreateIntToPtr(
586 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
587 ConstantInt::get(IntptrTy, Idx * 4)),
588 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000589 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
590 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000591 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000592}
593
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000594std::string
595SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000596 if (TargetTriple.getObjectFormat() == Triple::COFF)
597 return ".SCOV$M";
598 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000599 return "__DATA,__" + Section;
600 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000601}
602
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000603std::string
604SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000605 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000606 return "\1section$start$__DATA$__" + Section;
607 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000608}
609
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000610std::string
611SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000612 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000613 return "\1section$end$__DATA$__" + Section;
614 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000615}
616
617
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000618char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000619INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000620 "SanitizerCoverage: TODO."
621 "ModulePass",
622 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000623INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000624INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000625INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000626 "SanitizerCoverage: TODO."
627 "ModulePass",
628 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000629ModulePass *llvm::createSanitizerCoverageModulePass(
630 const SanitizerCoverageOptions &Options) {
631 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000632}