blob: b021f31e6523b17a86b6dc8ad7d239bc0af32228 [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//
10// Coverage instrumentation that works with AddressSanitizer
11// and potentially with other Sanitizers.
12//
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000013// We create a Guard variable with the same linkage
Alexey Samsonov3514f272015-05-07 01:00:31 +000014// as the function and inject this code into the entry block (SCK_Function)
15// or all blocks (SCK_BB):
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000016// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000017// __sanitizer_cov(&Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018// }
19// The accesses to Guard are atomic. The rest of the logic is
20// in __sanitizer_cov (it's fine to call it more than once).
21//
Alexey Samsonov3514f272015-05-07 01:00:31 +000022// With SCK_Edge we also split critical edges this effectively
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023// instrumenting all edges.
24//
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025// This coverage implementation provides very limited data:
26// it only tells if a given function (block) was ever executed. No counters.
27// But for many use cases this is what we need and the added slowdown small.
28//
29//===----------------------------------------------------------------------===//
30
31#include "llvm/Transforms/Instrumentation.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/SmallVector.h"
Reid Klecknerdf523372015-09-03 20:18:29 +000034#include "llvm/Analysis/LibCallSemantics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000035#include "llvm/IR/CallSite.h"
36#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000037#include "llvm/IR/DebugInfo.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000038#include "llvm/IR/Function.h"
39#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000040#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000041#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/MDBuilder.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Type.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/Transforms/Scalar.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/ModuleUtils.h"
51
52using namespace llvm;
53
54#define DEBUG_TYPE "sancov"
55
56static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
57static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000058static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000059static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000060static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
61static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000062static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +000063static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000064static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000065static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000066
67static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
68 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
69 "3: all blocks and critical edges, "
70 "4: above plus indirect calls"),
71 cl::Hidden, cl::init(0));
72
Kostya Serebryany77cc7292015-02-04 01:21:45 +000073static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000074 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000075 cl::desc("Use a callback with a guard check inside it if there are"
76 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000077 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000078
Kostya Serebryanycb45b122014-11-19 00:22:58 +000079static cl::opt<bool>
80 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
81 cl::desc("Experimental basic-block tracing: insert "
82 "callbacks at every basic block"),
83 cl::Hidden, cl::init(false));
84
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000085static cl::opt<bool>
86 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
87 cl::desc("Experimental tracing of CMP and similar "
88 "instructions"),
89 cl::Hidden, cl::init(false));
90
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000091// Experimental 8-bit counters used as an additional search heuristic during
92// coverage-guided fuzzing.
93// The counters are not thread-friendly:
94// - contention on these counters may cause significant slowdown;
95// - the counter updates are racy and the results may be inaccurate.
96// They are also inaccurate due to 8-bit integer overflow.
97static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
98 cl::desc("Experimental 8-bit counters"),
99 cl::Hidden, cl::init(false));
100
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000101namespace {
102
Alexey Samsonov3514f272015-05-07 01:00:31 +0000103SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
104 SanitizerCoverageOptions Res;
105 switch (LegacyCoverageLevel) {
106 case 0:
107 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
108 break;
109 case 1:
110 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
111 break;
112 case 2:
113 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
114 break;
115 case 3:
116 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
117 break;
118 case 4:
119 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
120 Res.IndirectCalls = true;
121 break;
122 }
123 return Res;
124}
125
126SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
127 // Sets CoverageType and IndirectCalls.
128 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
129 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
130 Options.IndirectCalls |= CLOpts.IndirectCalls;
131 Options.TraceBB |= ClExperimentalTracing;
132 Options.TraceCmp |= ClExperimentalCMPTracing;
133 Options.Use8bitCounters |= ClUse8bitCounters;
134 return Options;
135}
136
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000137class SanitizerCoverageModule : public ModulePass {
138 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000139 SanitizerCoverageModule(
140 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
141 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000142 bool runOnModule(Module &M) override;
143 bool runOnFunction(Function &F);
144 static char ID; // Pass identification, replacement for typeid
145 const char *getPassName() const override {
146 return "SanitizerCoverageModule";
147 }
148
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000149 private:
150 void InjectCoverageForIndirectCalls(Function &F,
151 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000152 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000153 void InjectTraceForSwitch(Function &F,
154 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000155 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000156 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000157 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000158 unsigned NumberOfInstrumentedBlocks() {
159 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses();
160 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000161 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000162 Function *SanCovWithCheckFunction;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000163 Function *SanCovIndirCallFunction;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000164 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000165 Function *SanCovTraceCmpFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000166 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000167 InlineAsm *EmptyAsm;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000168 Type *IntptrTy, *Int64Ty, *Int64PtrTy;
169 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000170 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000171 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000172
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000173 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000174 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000175
Alexey Samsonov3514f272015-05-07 01:00:31 +0000176 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177};
178
179} // namespace
180
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000181bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000182 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
183 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000184 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000185 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000186 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000187 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000189 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000190 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000191 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000192 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000193 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000194
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000195 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000196 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000197 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000198 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000199 SanCovIndirCallFunction =
200 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
201 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
202 SanCovTraceCmpFunction =
203 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
204 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000205 SanCovTraceSwitchFunction =
206 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
207 kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000208
Kostya Serebryany73762942014-12-16 21:24:15 +0000209 // We insert an empty inline asm after cov callbacks to avoid callback merge.
210 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
211 StringRef(""), StringRef(""),
212 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000213
Alexey Samsonov3514f272015-05-07 01:00:31 +0000214 if (Options.TraceBB) {
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000215 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000216 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000217 SanCovTraceBB = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000218 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000219 }
220
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000221 // At this point we create a dummy array of guards because we don't
222 // know how many elements we will need.
223 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000224 Type *Int8Ty = IRB.getInt8Ty();
225
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000226 GuardArray =
227 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
228 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000229 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000230 EightBitCounterArray =
231 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
232 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000233
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000234 for (auto &F : M)
235 runOnFunction(F);
236
Kostya Serebryany48a40232015-03-10 01:58:27 +0000237 auto N = NumberOfInstrumentedBlocks();
238
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000239 // Now we know how many elements we need. Create an array of guards
240 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000241 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000242 GlobalVariable *RealGuardArray = new GlobalVariable(
243 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
244 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
245
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000246
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000247 // Replace the dummy array with the real one.
248 GuardArray->replaceAllUsesWith(
249 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
250 GuardArray->eraseFromParent();
251
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000252 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000253 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000254 // Make sure the array is 16-aligned.
255 static const int kCounterAlignment = 16;
256 Type *Int8ArrayNTy =
Kostya Serebryany48a40232015-03-10 01:58:27 +0000257 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000258 RealEightBitCounterArray = new GlobalVariable(
259 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
260 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
261 RealEightBitCounterArray->setAlignment(kCounterAlignment);
262 EightBitCounterArray->replaceAllUsesWith(
263 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
264 EightBitCounterArray->eraseFromParent();
265 }
266
Kostya Serebryany88599462015-02-20 00:30:44 +0000267 // Create variable for module (compilation unit) name
268 Constant *ModNameStrConst =
269 ConstantDataArray::getString(M.getContext(), M.getName(), true);
270 GlobalVariable *ModuleName =
271 new GlobalVariable(M, ModNameStrConst->getType(), true,
272 GlobalValue::PrivateLinkage, ModNameStrConst);
273
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000274 Function *CtorFunc;
275 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
276 M, kSanCovModuleCtorName, kSanCovModuleInitName,
277 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
278 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
279 ConstantInt::get(IntptrTy, N),
280 Options.Use8bitCounters
281 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
282 : Constant::getNullValue(Int8PtrTy),
283 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
284
285 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
286
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000287 return true;
288}
289
290bool SanitizerCoverageModule::runOnFunction(Function &F) {
291 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000292 if (F.getName().find(".module_ctor") != std::string::npos)
293 return false; // Should not instrument sanitizer init functions.
Reid Klecknerdf523372015-09-03 20:18:29 +0000294 // Don't instrument functions using SEH for now. Splitting basic blocks like
295 // we do for coverage breaks WinEHPrepare.
296 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
297 if (F.hasPersonalityFn() &&
298 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
299 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000300 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000301 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000302 SmallVector<Instruction*, 8> IndirCalls;
303 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000304 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000305 SmallVector<Instruction*, 8> SwitchTraceTargets;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000306 for (auto &BB : F) {
307 AllBlocks.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000308 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000309 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000310 CallSite CS(&Inst);
311 if (CS && !CS.getCalledFunction())
312 IndirCalls.push_back(&Inst);
313 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000314 if (Options.TraceCmp) {
315 if (isa<ICmpInst>(&Inst))
316 CmpTraceTargets.push_back(&Inst);
317 if (isa<SwitchInst>(&Inst))
318 SwitchTraceTargets.push_back(&Inst);
319 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000320 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000321 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000322 InjectCoverage(F, AllBlocks);
323 InjectCoverageForIndirectCalls(F, IndirCalls);
324 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000325 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000326 return true;
327}
328
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000329bool SanitizerCoverageModule::InjectCoverage(Function &F,
330 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000331 switch (Options.CoverageType) {
332 case SanitizerCoverageOptions::SCK_None:
333 return false;
334 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000335 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000336 return true;
337 default: {
338 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000339 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000340 InjectCoverageAtBlock(F, *BB, UseCalls);
341 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000342 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000343 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000344}
345
346// On every indirect call we call a run-time function
347// __sanitizer_cov_indir_call* with two parameters:
348// - callee address,
349// - global cache array that contains kCacheSize pointers (zero-initialized).
350// The cache is used to speed up recording the caller-callee pairs.
351// The address of the caller is passed implicitly via caller PC.
352// kCacheSize is encoded in the name of the run-time function.
353void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
354 Function &F, ArrayRef<Instruction *> IndirCalls) {
355 if (IndirCalls.empty()) return;
356 const int kCacheSize = 16;
357 const int kCacheAlignment = 64; // Align for better performance.
358 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
359 for (auto I : IndirCalls) {
360 IRBuilder<> IRB(I);
361 CallSite CS(I);
362 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000363 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000364 GlobalVariable *CalleeCache = new GlobalVariable(
365 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
366 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
367 CalleeCache->setAlignment(kCacheAlignment);
David Blaikieff6409d2015-05-18 22:13:54 +0000368 IRB.CreateCall(SanCovIndirCallFunction,
369 {IRB.CreatePointerCast(Callee, IntptrTy),
370 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000371 }
372}
373
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000374// For every switch statement we insert a call:
375// __sanitizer_cov_trace_switch(CondValue,
376// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
377
378void SanitizerCoverageModule::InjectTraceForSwitch(
379 Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
380 for (auto I : SwitchTraceTargets) {
381 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
382 IRBuilder<> IRB(I);
383 SmallVector<Constant *, 16> Initializers;
384 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000385 if (Cond->getType()->getScalarSizeInBits() >
386 Int64Ty->getScalarSizeInBits())
387 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000388 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
389 Initializers.push_back(
390 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
391 if (Cond->getType()->getScalarSizeInBits() <
392 Int64Ty->getScalarSizeInBits())
393 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
394 for (auto It: SI->cases()) {
395 Constant *C = It.getCaseValue();
396 if (C->getType()->getScalarSizeInBits() <
397 Int64Ty->getScalarSizeInBits())
398 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
399 Initializers.push_back(C);
400 }
401 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
402 GlobalVariable *GV = new GlobalVariable(
403 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
404 ConstantArray::get(ArrayOfInt64Ty, Initializers),
405 "__sancov_gen_cov_switch_values");
406 IRB.CreateCall(SanCovTraceSwitchFunction,
407 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
408 }
409 }
410}
411
412
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000413void SanitizerCoverageModule::InjectTraceForCmp(
414 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000415 for (auto I : CmpTraceTargets) {
416 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
417 IRBuilder<> IRB(ICMP);
418 Value *A0 = ICMP->getOperand(0);
419 Value *A1 = ICMP->getOperand(1);
420 if (!A0->getType()->isIntegerTy()) continue;
421 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000422 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000423 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000424 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000425 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
426 IRB.CreateIntCast(A0, Int64Ty, true),
427 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000428 }
429 }
430}
431
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000432void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000433 I->setMetadata(
434 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"),
435 MDNode::get(*C, None));
436}
437
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000438void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
439 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000440 // Don't insert coverage for unreachable blocks: we will never call
441 // __sanitizer_cov() for them, so counting them in
442 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
443 // percentage. Also, unreachable instructions frequently have no debug
444 // locations.
445 if (isa<UnreachableInst>(BB.getTerminator()))
446 return;
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000447 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000448
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000449 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000450 DebugLoc EntryLoc;
451 if (IsEntryBB) {
452 if (auto SP = getDISubprogram(&F))
453 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000454 // Keep static allocas and llvm.localescape calls in the entry block. Even
455 // if we aren't splitting the block, it's nice for allocas to be before
456 // calls.
457 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000458 } else {
459 EntryLoc = IP->getDebugLoc();
460 }
461
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000462 IRBuilder<> IRB(IP);
463 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000464 Value *GuardP = IRB.CreateAdd(
465 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000466 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000467 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
468 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000469 if (UseCalls) {
470 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
471 } else {
472 LoadInst *Load = IRB.CreateLoad(GuardP);
473 Load->setAtomic(Monotonic);
474 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000475 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000476 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
477 Instruction *Ins = SplitBlockAndInsertIfThen(
478 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
479 IRB.SetInsertPoint(Ins);
480 IRB.SetCurrentDebugLocation(EntryLoc);
481 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
482 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000483 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000484 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000485
Alexey Samsonov3514f272015-05-07 01:00:31 +0000486 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000487 IRB.SetInsertPoint(IP);
488 Value *P = IRB.CreateAdd(
489 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000490 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000491 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000492 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000493 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000494 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000495 SetNoSanitizeMetadata(LI);
496 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000497 }
498
Alexey Samsonov3514f272015-05-07 01:00:31 +0000499 if (Options.TraceBB) {
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000500 // Experimental support for tracing.
501 // Insert a callback with the same guard variable as used for coverage.
502 IRB.SetInsertPoint(IP);
503 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
504 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000505}
506
507char SanitizerCoverageModule::ID = 0;
508INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
509 "SanitizerCoverage: TODO."
510 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000511ModulePass *llvm::createSanitizerCoverageModulePass(
512 const SanitizerCoverageOptions &Options) {
513 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000514}