blob: 325b64cd8b436ec80a9d0008491cb8b841b91240 [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
Mike Aizatsky759aca02016-03-18 23:29:29 +000061static cl::opt<int> ClCoverageLevel(
62 "sanitizer-coverage-level",
63 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000064 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000065 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000066
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000067static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
68 cl::desc("Experimental pc tracing"),
69 cl::Hidden, cl::init(false));
70
Kostya Serebryanyda718e52016-09-14 01:39:35 +000071static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
72 cl::desc("pc tracing with a guard"),
73 cl::Hidden, cl::init(false));
74
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000075static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000076 ClCMPTracing("sanitizer-coverage-trace-compares",
77 cl::desc("Tracing of CMP and similar instructions"),
78 cl::Hidden, cl::init(false));
79
80static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
81 cl::desc("Tracing of DIV instructions"),
82 cl::Hidden, cl::init(false));
83
84static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
85 cl::desc("Tracing of GEP instructions"),
86 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000087
Mike Aizatsky70ea4532016-04-06 23:24:37 +000088static cl::opt<bool>
89 ClPruneBlocks("sanitizer-coverage-prune-blocks",
90 cl::desc("Reduce the number of instrumented blocks"),
91 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +000092
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000093namespace {
94
Alexey Samsonov3514f272015-05-07 01:00:31 +000095SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
96 SanitizerCoverageOptions Res;
97 switch (LegacyCoverageLevel) {
98 case 0:
99 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
100 break;
101 case 1:
102 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
103 break;
104 case 2:
105 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
106 break;
107 case 3:
108 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
109 break;
110 case 4:
111 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
112 Res.IndirectCalls = true;
113 break;
114 }
115 return Res;
116}
117
118SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
119 // Sets CoverageType and IndirectCalls.
120 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
121 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
122 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000123 Options.TraceCmp |= ClCMPTracing;
124 Options.TraceDiv |= ClDIVTracing;
125 Options.TraceGep |= ClGEPTracing;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000126 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000127 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000128 if (!Options.TracePCGuard && !Options.TracePC)
129 Options.TracePCGuard = true; // TracePCGuard is default.
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000130 Options.NoPrune |= !ClPruneBlocks;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000131 return Options;
132}
133
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000134class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000135public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000136 SanitizerCoverageModule(
137 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000138 : ModulePass(ID), Options(OverrideFromCL(Options)) {
139 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
140 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000141 bool runOnModule(Module &M) override;
142 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000143 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000144 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000145
Chandler Carruth30061152016-03-18 22:43:42 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
147 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000148 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000149 }
150
151private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000152 void InjectCoverageForIndirectCalls(Function &F,
153 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000154 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000155 void InjectTraceForDiv(Function &F,
156 ArrayRef<BinaryOperator *> DivTraceTargets);
157 void InjectTraceForGep(Function &F,
158 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000159 void InjectTraceForSwitch(Function &F,
160 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000161 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000162 void CreateFunctionGuardArray(size_t NumGuards, Function &F);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000163 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000164 StringRef getSanCovTracePCGuardSection() const;
165 StringRef getSanCovTracePCGuardSectionStart() const;
166 StringRef getSanCovTracePCGuardSectionEnd() const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000167 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000168 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000169 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000170 Function *SanCovTraceDivFunction[2];
171 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000172 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000173 InlineAsm *EmptyAsm;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000174 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000175 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000176 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000178 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000179
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000180 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany186d6182016-09-27 01:08:33 +0000181 bool HasSancovGuardsSection;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000182
Alexey Samsonov3514f272015-05-07 01:00:31 +0000183 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000184};
185
Mike Aizatsky759aca02016-03-18 23:29:29 +0000186} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000189 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
190 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000191 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000192 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000193 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000194 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany186d6182016-09-27 01:08:33 +0000195 HasSancovGuardsSection = false;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000196 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000197 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000198 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000199 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000200 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000201 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000202 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000203 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000204
Mike Aizatsky759aca02016-03-18 23:29:29 +0000205 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000206 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000207 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000208 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000209 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000210 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
211 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000212 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000213 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
214 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000215 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000216 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000217 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000218 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000219
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000220 SanCovTraceDivFunction[0] =
221 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000222 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000223 SanCovTraceDivFunction[1] =
224 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000225 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000226 SanCovTraceGepFunction =
227 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000228 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000229 SanCovTraceSwitchFunction =
230 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000231 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000232
Kostya Serebryany73762942014-12-16 21:24:15 +0000233 // We insert an empty inline asm after cov callbacks to avoid callback merge.
234 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
235 StringRef(""), StringRef(""),
236 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000237
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000238 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000239 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000240 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000241 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000242
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000243 for (auto &F : M)
244 runOnFunction(F);
245
Kostya Serebryany88599462015-02-20 00:30:44 +0000246 // Create variable for module (compilation unit) name
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000247 if (Options.TracePCGuard) {
Kostya Serebryany186d6182016-09-27 01:08:33 +0000248 if (HasSancovGuardsSection) {
249 Function *CtorFunc;
Justin Bogner41e632b2017-02-01 02:38:39 +0000250 GlobalVariable *SecStart = new GlobalVariable(
251 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000252 getSanCovTracePCGuardSectionStart());
Justin Bogner41e632b2017-02-01 02:38:39 +0000253 SecStart->setVisibility(GlobalValue::HiddenVisibility);
254 GlobalVariable *SecEnd = new GlobalVariable(
255 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000256 getSanCovTracePCGuardSectionEnd());
Justin Bogner41e632b2017-02-01 02:38:39 +0000257 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
258
Kostya Serebryany186d6182016-09-27 01:08:33 +0000259 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
260 M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000261 {Int32PtrTy, Int32PtrTy},
Justin Bogner41e632b2017-02-01 02:38:39 +0000262 {IRB.CreatePointerCast(SecStart, Int32PtrTy),
263 IRB.CreatePointerCast(SecEnd, Int32PtrTy)});
Kostya Serebryany186d6182016-09-27 01:08:33 +0000264
Mike Aizatsky4705ae92017-02-08 23:12:46 +0000265 if (TargetTriple.supportsCOMDAT()) {
266 // Use comdat to dedup CtorFunc.
267 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
268 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
269 } else {
270 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
271 }
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000272 }
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000273 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000274 return true;
275}
276
Mike Aizatsky9987f432016-03-23 23:15:03 +0000277// True if block has successors and it dominates all of them.
278static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
279 if (succ_begin(BB) == succ_end(BB))
280 return false;
281
282 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
283 if (!DT->dominates(BB, SUCC))
284 return false;
285 }
286
287 return true;
288}
289
George Karpenkov018472c2017-05-24 00:29:12 +0000290// True if block has predecessors and it postdominates all of them.
291static bool isFullPostDominator(const BasicBlock *BB,
292 const PostDominatorTree *PDT) {
293 if (pred_begin(BB) == pred_end(BB))
294 return false;
295
296 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
297 if (!PDT->dominates(BB, PRED))
298 return false;
299 }
300
301 return true;
302}
303
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000304static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
305 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000306 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000307 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000308 // Don't insert coverage for unreachable blocks: we will never call
309 // __sanitizer_cov() for them, so counting them in
310 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
311 // percentage. Also, unreachable instructions frequently have no debug
312 // locations.
313 if (isa<UnreachableInst>(BB->getTerminator()))
314 return false;
315
Reid Kleckner392f0622017-03-23 23:30:41 +0000316 // Don't insert coverage into blocks without a valid insertion point
317 // (catchswitch blocks).
318 if (BB->getFirstInsertionPt() == BB->end())
319 return false;
320
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000321 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000322 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000323
George Karpenkova1c53272017-05-25 01:41:46 +0000324 // Do not instrument full dominators, or full post-dominators with multiple
325 // predecessors.
326 return !isFullDominator(BB, DT)
327 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000328}
329
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000330bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000331 if (F.empty())
332 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000333 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000334 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000335 if (F.getName().startswith("__sanitizer_"))
336 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerec803542016-11-11 19:18:45 +0000337 // Don't instrument MSVC CRT configuration helpers. They may run before normal
338 // initialization.
339 if (F.getName() == "__local_stdio_printf_options" ||
340 F.getName() == "__local_stdio_scanf_options")
341 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000342 // Don't instrument functions using SEH for now. Splitting basic blocks like
343 // we do for coverage breaks WinEHPrepare.
344 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
345 if (F.hasPersonalityFn() &&
346 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
347 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000348 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000349 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000350 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000351 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000352 SmallVector<Instruction *, 8> CmpTraceTargets;
353 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000354 SmallVector<BinaryOperator *, 8> DivTraceTargets;
355 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000356
Mike Aizatsky602f7922016-03-21 23:08:16 +0000357 const DominatorTree *DT =
358 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000359 const PostDominatorTree *PDT =
360 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Mike Aizatsky602f7922016-03-21 23:08:16 +0000361
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000362 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000363 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000364 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000365 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000366 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000367 CallSite CS(&Inst);
368 if (CS && !CS.getCalledFunction())
369 IndirCalls.push_back(&Inst);
370 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000371 if (Options.TraceCmp) {
372 if (isa<ICmpInst>(&Inst))
373 CmpTraceTargets.push_back(&Inst);
374 if (isa<SwitchInst>(&Inst))
375 SwitchTraceTargets.push_back(&Inst);
376 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000377 if (Options.TraceDiv)
378 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
379 if (BO->getOpcode() == Instruction::SDiv ||
380 BO->getOpcode() == Instruction::UDiv)
381 DivTraceTargets.push_back(BO);
382 if (Options.TraceGep)
383 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
384 GepTraceTargets.push_back(GEP);
385 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000386 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000387
388 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000389 InjectCoverageForIndirectCalls(F, IndirCalls);
390 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000391 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000392 InjectTraceForDiv(F, DivTraceTargets);
393 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000394 return true;
395}
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000396void SanitizerCoverageModule::CreateFunctionGuardArray(size_t NumGuards,
397 Function &F) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000398 if (!Options.TracePCGuard) return;
399 HasSancovGuardsSection = true;
400 ArrayType *ArrayOfInt32Ty = ArrayType::get(Int32Ty, NumGuards);
401 FunctionGuardArray = new GlobalVariable(
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000402 *CurModule, ArrayOfInt32Ty, false, GlobalVariable::PrivateLinkage,
Kostya Serebryany9d6dc7b2016-11-15 21:12:50 +0000403 Constant::getNullValue(ArrayOfInt32Ty), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000404 if (auto Comdat = F.getComdat())
405 FunctionGuardArray->setComdat(Comdat);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000406 FunctionGuardArray->setSection(getSanCovTracePCGuardSection());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000407}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000408
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000409bool SanitizerCoverageModule::InjectCoverage(Function &F,
410 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000411 if (AllBlocks.empty()) return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000412 switch (Options.CoverageType) {
413 case SanitizerCoverageOptions::SCK_None:
414 return false;
415 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000416 CreateFunctionGuardArray(1, F);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000417 InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000418 return true;
419 default: {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000420 CreateFunctionGuardArray(AllBlocks.size(), F);
421 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000422 InjectCoverageAtBlock(F, *AllBlocks[i], i);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000423 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000424 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000425 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000426}
427
428// On every indirect call we call a run-time function
429// __sanitizer_cov_indir_call* with two parameters:
430// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000431// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000432// The cache is used to speed up recording the caller-callee pairs.
433// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000434// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000435void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
436 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000437 if (IndirCalls.empty())
438 return;
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000439 assert(Options.TracePC || Options.TracePCGuard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000440 for (auto I : IndirCalls) {
441 IRBuilder<> IRB(I);
442 CallSite CS(I);
443 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000444 if (isa<InlineAsm>(Callee))
445 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000446 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000447 }
448}
449
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000450// For every switch statement we insert a call:
451// __sanitizer_cov_trace_switch(CondValue,
452// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
453
454void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000455 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000456 for (auto I : SwitchTraceTargets) {
457 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
458 IRBuilder<> IRB(I);
459 SmallVector<Constant *, 16> Initializers;
460 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000461 if (Cond->getType()->getScalarSizeInBits() >
462 Int64Ty->getScalarSizeInBits())
463 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000464 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
465 Initializers.push_back(
466 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
467 if (Cond->getType()->getScalarSizeInBits() <
468 Int64Ty->getScalarSizeInBits())
469 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000470 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000471 Constant *C = It.getCaseValue();
472 if (C->getType()->getScalarSizeInBits() <
473 Int64Ty->getScalarSizeInBits())
474 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
475 Initializers.push_back(C);
476 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000477 std::sort(Initializers.begin() + 2, Initializers.end(),
478 [](const Constant *A, const Constant *B) {
479 return cast<ConstantInt>(A)->getLimitedValue() <
480 cast<ConstantInt>(B)->getLimitedValue();
481 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000482 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
483 GlobalVariable *GV = new GlobalVariable(
484 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
485 ConstantArray::get(ArrayOfInt64Ty, Initializers),
486 "__sancov_gen_cov_switch_values");
487 IRB.CreateCall(SanCovTraceSwitchFunction,
488 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
489 }
490 }
491}
492
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000493void SanitizerCoverageModule::InjectTraceForDiv(
494 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
495 for (auto BO : DivTraceTargets) {
496 IRBuilder<> IRB(BO);
497 Value *A1 = BO->getOperand(1);
498 if (isa<ConstantInt>(A1)) continue;
499 if (!A1->getType()->isIntegerTy())
500 continue;
501 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
502 int CallbackIdx = TypeSize == 32 ? 0 :
503 TypeSize == 64 ? 1 : -1;
504 if (CallbackIdx < 0) continue;
505 auto Ty = Type::getIntNTy(*C, TypeSize);
506 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
507 {IRB.CreateIntCast(A1, Ty, true)});
508 }
509}
510
511void SanitizerCoverageModule::InjectTraceForGep(
512 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
513 for (auto GEP : GepTraceTargets) {
514 IRBuilder<> IRB(GEP);
515 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000516 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000517 IRB.CreateCall(SanCovTraceGepFunction,
518 {IRB.CreateIntCast(*I, IntptrTy, true)});
519 }
520}
521
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000522void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000523 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000524 for (auto I : CmpTraceTargets) {
525 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
526 IRBuilder<> IRB(ICMP);
527 Value *A0 = ICMP->getOperand(0);
528 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000529 if (!A0->getType()->isIntegerTy())
530 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000531 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000532 int CallbackIdx = TypeSize == 8 ? 0 :
533 TypeSize == 16 ? 1 :
534 TypeSize == 32 ? 2 :
535 TypeSize == 64 ? 3 : -1;
536 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000537 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000538 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000539 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000540 SanCovTraceCmpFunction[CallbackIdx],
541 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000542 }
543 }
544}
545
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000546void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000547 size_t Idx) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000548 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000549 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000550 DebugLoc EntryLoc;
551 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000552 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000553 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000554 // Keep static allocas and llvm.localescape calls in the entry block. Even
555 // if we aren't splitting the block, it's nice for allocas to be before
556 // calls.
557 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000558 } else {
559 EntryLoc = IP->getDebugLoc();
560 }
561
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000562 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000563 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000564 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000565 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
566 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000567 } else {
568 assert(Options.TracePCGuard);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000569 auto GuardPtr = IRB.CreateIntToPtr(
570 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
571 ConstantInt::get(IntptrTy, Idx * 4)),
572 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000573 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
574 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000575 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000576}
577
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000578StringRef SanitizerCoverageModule::getSanCovTracePCGuardSection() const {
579 if (TargetTriple.getObjectFormat() == Triple::COFF)
580 return ".SCOV$M";
581 if (TargetTriple.isOSBinFormatMachO())
582 return "__DATA,__sancov_guards";
583 return "__sancov_guards";
584}
585
586StringRef SanitizerCoverageModule::getSanCovTracePCGuardSectionStart() const {
587 if (TargetTriple.isOSBinFormatMachO())
588 return "\1section$start$__DATA$__sancov_guards";
589 return "__start___sancov_guards";
590}
591
592StringRef SanitizerCoverageModule::getSanCovTracePCGuardSectionEnd() const {
593 if (TargetTriple.isOSBinFormatMachO())
594 return "\1section$end$__DATA$__sancov_guards";
595 return "__stop___sancov_guards";
596}
597
598
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000599char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000600INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000601 "SanitizerCoverage: TODO."
602 "ModulePass",
603 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000604INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000605INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000606INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000607 "SanitizerCoverage: TODO."
608 "ModulePass",
609 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000610ModulePass *llvm::createSanitizerCoverageModulePass(
611 const SanitizerCoverageOptions &Options) {
612 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000613}