blob: c91b89df830e8533594bb497cfc08f5a3733c0c2 [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"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000036#include "llvm/IR/DebugInfo.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000037#include "llvm/IR/Function.h"
38#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000039#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000040#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/MDBuilder.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Transforms/Scalar.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/ModuleUtils.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "sancov"
54
55static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
56static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000057static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000058static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000059static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
60static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000061static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +000062static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000063static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000064static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000065
66static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
67 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
68 "3: all blocks and critical edges, "
69 "4: above plus indirect calls"),
70 cl::Hidden, cl::init(0));
71
Kostya Serebryany77cc7292015-02-04 01:21:45 +000072static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000073 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000074 cl::desc("Use a callback with a guard check inside it if there are"
75 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000076 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000077
Kostya Serebryanycb45b122014-11-19 00:22:58 +000078static cl::opt<bool>
79 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
80 cl::desc("Experimental basic-block tracing: insert "
81 "callbacks at every basic block"),
82 cl::Hidden, cl::init(false));
83
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000084static cl::opt<bool>
85 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
86 cl::desc("Experimental tracing of CMP and similar "
87 "instructions"),
88 cl::Hidden, cl::init(false));
89
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000090// Experimental 8-bit counters used as an additional search heuristic during
91// coverage-guided fuzzing.
92// The counters are not thread-friendly:
93// - contention on these counters may cause significant slowdown;
94// - the counter updates are racy and the results may be inaccurate.
95// They are also inaccurate due to 8-bit integer overflow.
96static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
97 cl::desc("Experimental 8-bit counters"),
98 cl::Hidden, cl::init(false));
99
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000100namespace {
101
Alexey Samsonov3514f272015-05-07 01:00:31 +0000102SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
103 SanitizerCoverageOptions Res;
104 switch (LegacyCoverageLevel) {
105 case 0:
106 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
107 break;
108 case 1:
109 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
110 break;
111 case 2:
112 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
113 break;
114 case 3:
115 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
116 break;
117 case 4:
118 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
119 Res.IndirectCalls = true;
120 break;
121 }
122 return Res;
123}
124
125SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
126 // Sets CoverageType and IndirectCalls.
127 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
128 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
129 Options.IndirectCalls |= CLOpts.IndirectCalls;
130 Options.TraceBB |= ClExperimentalTracing;
131 Options.TraceCmp |= ClExperimentalCMPTracing;
132 Options.Use8bitCounters |= ClUse8bitCounters;
133 return Options;
134}
135
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000136class SanitizerCoverageModule : public ModulePass {
137 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000138 SanitizerCoverageModule(
139 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
140 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000141 bool runOnModule(Module &M) override;
142 bool runOnFunction(Function &F);
143 static char ID; // Pass identification, replacement for typeid
144 const char *getPassName() const override {
145 return "SanitizerCoverageModule";
146 }
147
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000148 private:
149 void InjectCoverageForIndirectCalls(Function &F,
150 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000151 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000152 void InjectTraceForSwitch(Function &F,
153 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000154 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000155 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000156 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000157 unsigned NumberOfInstrumentedBlocks() {
158 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses();
159 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000160 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000161 Function *SanCovWithCheckFunction;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000162 Function *SanCovIndirCallFunction;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000163 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000164 Function *SanCovTraceCmpFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000165 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000166 InlineAsm *EmptyAsm;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000167 Type *IntptrTy, *Int64Ty, *Int64PtrTy;
168 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000169 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000170 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000171
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000172 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000173 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000174
Alexey Samsonov3514f272015-05-07 01:00:31 +0000175 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000176};
177
178} // namespace
179
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000180bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000181 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
182 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000183 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000184 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000185 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000186 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000188 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000189 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000190 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000191 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000192 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000193
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000194 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000195 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000196 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000197 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000198 SanCovIndirCallFunction =
199 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
200 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
201 SanCovTraceCmpFunction =
202 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
203 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000204 SanCovTraceSwitchFunction =
205 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
206 kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000207
Kostya Serebryany73762942014-12-16 21:24:15 +0000208 // We insert an empty inline asm after cov callbacks to avoid callback merge.
209 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
210 StringRef(""), StringRef(""),
211 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000212
Alexey Samsonov3514f272015-05-07 01:00:31 +0000213 if (Options.TraceBB) {
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000214 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000215 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000216 SanCovTraceBB = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000217 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000218 }
219
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000220 // At this point we create a dummy array of guards because we don't
221 // know how many elements we will need.
222 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000223 Type *Int8Ty = IRB.getInt8Ty();
224
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000225 GuardArray =
226 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
227 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000228 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000229 EightBitCounterArray =
230 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
231 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000232
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000233 for (auto &F : M)
234 runOnFunction(F);
235
Kostya Serebryany48a40232015-03-10 01:58:27 +0000236 auto N = NumberOfInstrumentedBlocks();
237
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000238 // Now we know how many elements we need. Create an array of guards
239 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000240 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000241 GlobalVariable *RealGuardArray = new GlobalVariable(
242 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
243 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
244
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000245
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000246 // Replace the dummy array with the real one.
247 GuardArray->replaceAllUsesWith(
248 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
249 GuardArray->eraseFromParent();
250
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000251 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000252 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000253 // Make sure the array is 16-aligned.
254 static const int kCounterAlignment = 16;
255 Type *Int8ArrayNTy =
Kostya Serebryany48a40232015-03-10 01:58:27 +0000256 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000257 RealEightBitCounterArray = new GlobalVariable(
258 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
259 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
260 RealEightBitCounterArray->setAlignment(kCounterAlignment);
261 EightBitCounterArray->replaceAllUsesWith(
262 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
263 EightBitCounterArray->eraseFromParent();
264 }
265
Kostya Serebryany88599462015-02-20 00:30:44 +0000266 // Create variable for module (compilation unit) name
267 Constant *ModNameStrConst =
268 ConstantDataArray::getString(M.getContext(), M.getName(), true);
269 GlobalVariable *ModuleName =
270 new GlobalVariable(M, ModNameStrConst->getType(), true,
271 GlobalValue::PrivateLinkage, ModNameStrConst);
272
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000273 Function *CtorFunc;
274 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
275 M, kSanCovModuleCtorName, kSanCovModuleInitName,
276 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
277 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
278 ConstantInt::get(IntptrTy, N),
279 Options.Use8bitCounters
280 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
281 : Constant::getNullValue(Int8PtrTy),
282 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
283
284 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
285
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000286 return true;
287}
288
289bool SanitizerCoverageModule::runOnFunction(Function &F) {
290 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000291 if (F.getName().find(".module_ctor") != std::string::npos)
292 return false; // Should not instrument sanitizer init functions.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000293 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000294 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000295 SmallVector<Instruction*, 8> IndirCalls;
296 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000297 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000298 SmallVector<Instruction*, 8> SwitchTraceTargets;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000299 for (auto &BB : F) {
300 AllBlocks.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000301 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000302 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000303 CallSite CS(&Inst);
304 if (CS && !CS.getCalledFunction())
305 IndirCalls.push_back(&Inst);
306 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000307 if (Options.TraceCmp) {
308 if (isa<ICmpInst>(&Inst))
309 CmpTraceTargets.push_back(&Inst);
310 if (isa<SwitchInst>(&Inst))
311 SwitchTraceTargets.push_back(&Inst);
312 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000313 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000314 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000315 InjectCoverage(F, AllBlocks);
316 InjectCoverageForIndirectCalls(F, IndirCalls);
317 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000318 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000319 return true;
320}
321
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000322bool SanitizerCoverageModule::InjectCoverage(Function &F,
323 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000324 switch (Options.CoverageType) {
325 case SanitizerCoverageOptions::SCK_None:
326 return false;
327 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000328 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000329 return true;
330 default: {
331 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000332 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000333 InjectCoverageAtBlock(F, *BB, UseCalls);
334 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000335 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000336 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000337}
338
339// On every indirect call we call a run-time function
340// __sanitizer_cov_indir_call* with two parameters:
341// - callee address,
342// - global cache array that contains kCacheSize pointers (zero-initialized).
343// The cache is used to speed up recording the caller-callee pairs.
344// The address of the caller is passed implicitly via caller PC.
345// kCacheSize is encoded in the name of the run-time function.
346void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
347 Function &F, ArrayRef<Instruction *> IndirCalls) {
348 if (IndirCalls.empty()) return;
349 const int kCacheSize = 16;
350 const int kCacheAlignment = 64; // Align for better performance.
351 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
352 for (auto I : IndirCalls) {
353 IRBuilder<> IRB(I);
354 CallSite CS(I);
355 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000356 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000357 GlobalVariable *CalleeCache = new GlobalVariable(
358 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
359 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
360 CalleeCache->setAlignment(kCacheAlignment);
David Blaikieff6409d2015-05-18 22:13:54 +0000361 IRB.CreateCall(SanCovIndirCallFunction,
362 {IRB.CreatePointerCast(Callee, IntptrTy),
363 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000364 }
365}
366
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000367// For every switch statement we insert a call:
368// __sanitizer_cov_trace_switch(CondValue,
369// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
370
371void SanitizerCoverageModule::InjectTraceForSwitch(
372 Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
373 for (auto I : SwitchTraceTargets) {
374 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
375 IRBuilder<> IRB(I);
376 SmallVector<Constant *, 16> Initializers;
377 Value *Cond = SI->getCondition();
378 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
379 Initializers.push_back(
380 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
381 if (Cond->getType()->getScalarSizeInBits() <
382 Int64Ty->getScalarSizeInBits())
383 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
384 for (auto It: SI->cases()) {
385 Constant *C = It.getCaseValue();
386 if (C->getType()->getScalarSizeInBits() <
387 Int64Ty->getScalarSizeInBits())
388 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
389 Initializers.push_back(C);
390 }
391 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
392 GlobalVariable *GV = new GlobalVariable(
393 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
394 ConstantArray::get(ArrayOfInt64Ty, Initializers),
395 "__sancov_gen_cov_switch_values");
396 IRB.CreateCall(SanCovTraceSwitchFunction,
397 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
398 }
399 }
400}
401
402
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000403void SanitizerCoverageModule::InjectTraceForCmp(
404 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000405 for (auto I : CmpTraceTargets) {
406 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
407 IRBuilder<> IRB(ICMP);
408 Value *A0 = ICMP->getOperand(0);
409 Value *A1 = ICMP->getOperand(1);
410 if (!A0->getType()->isIntegerTy()) continue;
411 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000412 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000413 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000414 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000415 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
416 IRB.CreateIntCast(A0, Int64Ty, true),
417 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000418 }
419 }
420}
421
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000422void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000423 I->setMetadata(
424 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"),
425 MDNode::get(*C, None));
426}
427
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000428void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
429 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000430 // Don't insert coverage for unreachable blocks: we will never call
431 // __sanitizer_cov() for them, so counting them in
432 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
433 // percentage. Also, unreachable instructions frequently have no debug
434 // locations.
435 if (isa<UnreachableInst>(BB.getTerminator()))
436 return;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000437 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
438 // Skip static allocas at the top of the entry block so they don't become
439 // dynamic when we split the block. If we used our optimized stack layout,
440 // then there will only be one alloca and it will come first.
441 for (; IP != BE; ++IP) {
442 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
443 if (!AI || !AI->isStaticAlloca())
444 break;
445 }
446
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000447 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000448 DebugLoc EntryLoc;
449 if (IsEntryBB) {
450 if (auto SP = getDISubprogram(&F))
451 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
452 } else {
453 EntryLoc = IP->getDebugLoc();
454 }
455
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000456 IRBuilder<> IRB(IP);
457 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000458 Value *GuardP = IRB.CreateAdd(
459 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000460 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000461 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
462 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000463 if (UseCalls) {
464 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
465 } else {
466 LoadInst *Load = IRB.CreateLoad(GuardP);
467 Load->setAtomic(Monotonic);
468 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000469 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000470 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
471 Instruction *Ins = SplitBlockAndInsertIfThen(
472 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
473 IRB.SetInsertPoint(Ins);
474 IRB.SetCurrentDebugLocation(EntryLoc);
475 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
476 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000477 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000478 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000479
Alexey Samsonov3514f272015-05-07 01:00:31 +0000480 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000481 IRB.SetInsertPoint(IP);
482 Value *P = IRB.CreateAdd(
483 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000484 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000485 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000486 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000487 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000488 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000489 SetNoSanitizeMetadata(LI);
490 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000491 }
492
Alexey Samsonov3514f272015-05-07 01:00:31 +0000493 if (Options.TraceBB) {
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000494 // Experimental support for tracing.
495 // Insert a callback with the same guard variable as used for coverage.
496 IRB.SetInsertPoint(IP);
497 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
498 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000499}
500
501char SanitizerCoverageModule::ID = 0;
502INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
503 "SanitizerCoverage: TODO."
504 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000505ModulePass *llvm::createSanitizerCoverageModulePass(
506 const SanitizerCoverageOptions &Options) {
507 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000508}