LLVM 24.0.0git
SanitizerCoverage.cpp
Go to the documentation of this file.
1//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ArrayRef.h"
18#include "llvm/IR/Constant.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/Dominators.h"
23#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
45const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
46const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
47const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
48const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
49const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
50const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
51const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
52const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
53const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
54const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
55const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
56const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
57const char SanCovLoad1[] = "__sanitizer_cov_load1";
58const char SanCovLoad2[] = "__sanitizer_cov_load2";
59const char SanCovLoad4[] = "__sanitizer_cov_load4";
60const char SanCovLoad8[] = "__sanitizer_cov_load8";
61const char SanCovLoad16[] = "__sanitizer_cov_load16";
62const char SanCovStore1[] = "__sanitizer_cov_store1";
63const char SanCovStore2[] = "__sanitizer_cov_store2";
64const char SanCovStore4[] = "__sanitizer_cov_store4";
65const char SanCovStore8[] = "__sanitizer_cov_store8";
66const char SanCovStore16[] = "__sanitizer_cov_store16";
67const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
68const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
69const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
70const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
72 "sancov.module_ctor_trace_pc_guard";
74 "sancov.module_ctor_8bit_counters";
75const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
77
78const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
79const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
80const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
81const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
82const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
83const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
84
85const char SanCovGuardsSectionName[] = "sancov_guards";
86const char SanCovCountersSectionName[] = "sancov_cntrs";
87const char SanCovBoolFlagSectionName[] = "sancov_bools";
88const char SanCovPCsSectionName[] = "sancov_pcs";
89const char SanCovCFsSectionName[] = "sancov_cfs";
90const char SanCovCallbackGateSectionName[] = "sancov_gate";
91
92const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
93const char SanCovLowestStackName[] = "__sancov_lowest_stack";
94const char SanCovCallbackGateName[] = "__sancov_should_track";
95
97 "sanitizer-coverage-level",
98 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
99 "3: all blocks and critical edges"),
100 cl::Hidden);
101
102static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
103 cl::desc("Experimental pc tracing"), cl::Hidden);
104
106 "sanitizer-coverage-trace-pc-entry-exit",
107 cl::desc("pc tracing with separate entry/exit callbacks"), cl::Hidden);
108
109static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
110 cl::desc("pc tracing with a guard"),
111 cl::Hidden);
112
113// If true, we create a global variable that contains PCs of all instrumented
114// BBs, put this global into a named section, and pass this section's bounds
115// to __sanitizer_cov_pcs_init.
116// This way the coverage instrumentation does not need to acquire the PCs
117// at run-time. Works with trace-pc-guard, inline-8bit-counters, and
118// inline-bool-flag.
119static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
120 cl::desc("create a static PC table"),
121 cl::Hidden);
122
123static cl::opt<bool>
124 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
125 cl::desc("increments 8-bit counter for every edge"),
126 cl::Hidden);
127
128static cl::opt<bool>
129 ClSancovDropCtors("sanitizer-coverage-drop-ctors",
130 cl::desc("do not emit module ctors for global counters"),
131 cl::Hidden);
132
133static cl::opt<bool>
134 ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
135 cl::desc("sets a boolean flag for every edge"),
136 cl::Hidden);
137
138static cl::opt<bool>
139 ClCMPTracing("sanitizer-coverage-trace-compares",
140 cl::desc("Tracing of CMP and similar instructions"),
141 cl::Hidden);
142
143static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
144 cl::desc("Tracing of DIV instructions"),
145 cl::Hidden);
146
147static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
148 cl::desc("Tracing of load instructions"),
149 cl::Hidden);
150
151static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
152 cl::desc("Tracing of store instructions"),
153 cl::Hidden);
154
155static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
156 cl::desc("Tracing of GEP instructions"),
157 cl::Hidden);
158
159static cl::opt<bool>
160 ClPruneBlocks("sanitizer-coverage-prune-blocks",
161 cl::desc("Reduce the number of instrumented blocks"),
162 cl::Hidden, cl::init(true));
163
164static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
165 cl::desc("max stack depth tracing"),
166 cl::Hidden);
167
169 "sanitizer-coverage-stack-depth-callback-min",
170 cl::desc("max stack depth tracing should use callback and only when "
171 "stack depth more than specified"),
172 cl::Hidden);
173
174static cl::opt<bool>
175 ClCollectCF("sanitizer-coverage-control-flow",
176 cl::desc("collect control flow for each function"), cl::Hidden);
177
179 "sanitizer-coverage-gated-trace-callbacks",
180 cl::desc("Gate the invocation of the tracing callbacks on a global variable"
181 ". Currently only supported for trace-pc-guard and trace-cmp."),
182 cl::Hidden, cl::init(false));
183
184namespace {
185
186SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
188 switch (LegacyCoverageLevel) {
189 case 0:
191 break;
192 case 1:
194 break;
195 case 2:
197 break;
198 case 3:
200 break;
201 case 4:
203 Res.IndirectCalls = true;
204 break;
205 }
206 return Res;
207}
208
210 // Sets CoverageType and IndirectCalls.
211 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
212 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
213 Options.IndirectCalls |= CLOpts.IndirectCalls;
214 Options.TraceCmp |= ClCMPTracing;
215 Options.TraceDiv |= ClDIVTracing;
216 Options.TraceGep |= ClGEPTracing;
217 Options.TracePC |= ClTracePC;
218 Options.TracePCEntryExit |= ClTracePCEntryExit;
219 Options.TracePCGuard |= ClTracePCGuard;
220 Options.Inline8bitCounters |= ClInline8bitCounters;
221 Options.InlineBoolFlag |= ClInlineBoolFlag;
222 Options.PCTable |= ClCreatePCTable;
223 Options.NoPrune |= !ClPruneBlocks;
224 Options.StackDepth |= ClStackDepth;
225 Options.StackDepthCallbackMin = std::max(Options.StackDepthCallbackMin,
226 ClStackDepthCallbackMin.getValue());
227 Options.TraceLoads |= ClLoadTracing;
228 Options.TraceStores |= ClStoreTracing;
229 Options.GatedCallbacks |= ClGatedCallbacks;
230 if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
231 !Options.Inline8bitCounters && !Options.StackDepth &&
232 !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
233 Options.TracePCGuard = true; // TracePCGuard is default.
234 Options.CollectControlFlow |= ClCollectCF;
235 return Options;
236}
237
238class ModuleSanitizerCoverage {
239public:
240 using DomTreeCallback = function_ref<const DominatorTree &(Function &F)>;
241 using PostDomTreeCallback =
242 function_ref<const PostDominatorTree &(Function &F)>;
243
244 ModuleSanitizerCoverage(Module &M, DomTreeCallback DTCallback,
245 PostDomTreeCallback PDTCallback,
246 const SanitizerCoverageOptions &Options,
247 const SpecialCaseList *Allowlist,
248 const SpecialCaseList *Blocklist)
249 : M(M), DTCallback(DTCallback), PDTCallback(PDTCallback),
250 Options(Options), Allowlist(Allowlist), Blocklist(Blocklist) {}
251
252 bool instrumentModule();
253
254private:
255 void createFunctionControlFlow(Function &F);
256 void instrumentFunction(Function &F);
257 void InjectCoverageForIndirectCalls(Function &F,
258 ArrayRef<Instruction *> IndirCalls);
259 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets,
260 Value *&FunctionGateCmp);
261 void InjectTraceForDiv(Function &F,
262 ArrayRef<BinaryOperator *> DivTraceTargets);
263 void InjectTraceForGep(Function &F,
264 ArrayRef<GetElementPtrInst *> GepTraceTargets);
265 void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
266 ArrayRef<StoreInst *> Stores);
267 void InjectTraceForExits(Function &F);
268 void InjectTraceForSwitch(Function &F,
269 ArrayRef<Instruction *> SwitchTraceTargets,
270 Value *&FunctionGateCmp);
271 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
272 Value *&FunctionGateCmp, bool IsLeafFunc);
273 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
274 Function &F, Type *Ty,
275 const char *Section);
276 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
277 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
278 Instruction *CreateGateBranch(Function &F, Value *&FunctionGateCmp,
279 Instruction *I);
280 Value *CreateFunctionLocalGateCmp(IRBuilder<> &IRB);
281 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
282 Value *&FunctionGateCmp, bool IsLeafFunc);
283 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
284 const char *InitFunctionName, Type *Ty,
285 const char *Section);
286 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
287 Type *Ty);
288
289 std::string getSectionName(const std::string &Section) const;
290 std::string getSectionStart(const std::string &Section) const;
291 std::string getSectionEnd(const std::string &Section) const;
292
293 Module &M;
294 DomTreeCallback DTCallback;
295 PostDomTreeCallback PDTCallback;
296
297 FunctionCallee SanCovStackDepthCallback;
298 FunctionCallee SanCovTracePCIndir;
299 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
300 FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
301 std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
302 std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
303 std::array<FunctionCallee, 5> SanCovLoadFunction;
304 std::array<FunctionCallee, 5> SanCovStoreFunction;
305 std::array<FunctionCallee, 2> SanCovTraceDivFunction;
306 FunctionCallee SanCovTraceGepFunction;
307 FunctionCallee SanCovTraceSwitchFunction;
308 GlobalVariable *SanCovLowestStack;
309 GlobalVariable *SanCovCallbackGate;
310 Type *PtrTy, *IntptrTy, *Int64Ty, *Int32Ty, *Int16Ty, *Int8Ty, *Int1Ty;
311 Module *CurModule;
312 Triple TargetTriple;
313 LLVMContext *C;
314 const DataLayout *DL;
315
316 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
317 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
318 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
319 GlobalVariable *FunctionPCsArray; // for pc-table.
320 GlobalVariable *FunctionCFsArray; // for control flow table
321 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
322 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
323
324 SanitizerCoverageOptions Options;
325
326 const SpecialCaseList *Allowlist;
327 const SpecialCaseList *Blocklist;
328};
329} // namespace
330
333 const std::vector<std::string> &AllowlistFiles,
334 const std::vector<std::string> &BlocklistFiles)
335 : Options(std::move(Options)),
336 VFS(VFS ? std::move(VFS) : vfs::getRealFileSystem()) {
337 if (AllowlistFiles.size() > 0)
338 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, *this->VFS);
339 if (BlocklistFiles.size() > 0)
340 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, *this->VFS);
341}
342
345 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
346 auto DTCallback = [&FAM](Function &F) -> const DominatorTree & {
347 return FAM.getResult<DominatorTreeAnalysis>(F);
348 };
349 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree & {
350 return FAM.getResult<PostDominatorTreeAnalysis>(F);
351 };
352 ModuleSanitizerCoverage ModuleSancov(M, DTCallback, PDTCallback,
353 OverrideFromCL(Options), Allowlist.get(),
354 Blocklist.get());
355 if (!ModuleSancov.instrumentModule())
356 return PreservedAnalyses::all();
357
359 // GlobalsAA is considered stateless and does not get invalidated unless
360 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
361 // make changes that require GlobalsAA to be invalidated.
362 PA.abandon<GlobalsAA>();
363 return PA;
364}
365
366std::pair<Value *, Value *>
367ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
368 Type *Ty) {
369 // Use ExternalWeak so that if all sections are discarded due to section
370 // garbage collection, the linker will not report undefined symbol errors.
371 // Windows defines the start/stop symbols in compiler-rt so no need for
372 // ExternalWeak.
373 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
376 GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, Linkage, nullptr,
377 getSectionStart(Section));
379 GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, Linkage, nullptr,
380 getSectionEnd(Section));
382 if (!TargetTriple.isOSBinFormatCOFF())
383 return std::make_pair(SecStart, SecEnd);
384
385 // Account for the fact that on windows-msvc __start_* symbols actually
386 // point to a uint64_t before the start of the array.
388 SecStart, ConstantInt::get(IntptrTy, sizeof(uint64_t)));
389 return std::make_pair(GEP, SecEnd);
390}
391
392Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
393 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
394 const char *Section) {
396 return nullptr;
397 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
398 auto SecStart = SecStartEnd.first;
399 auto SecEnd = SecStartEnd.second;
400 Function *CtorFunc;
401 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
402 M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
403 assert(CtorFunc->getName() == CtorName);
404
405 if (TargetTriple.supportsCOMDAT()) {
406 // Use comdat to dedup CtorFunc.
407 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
408 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
409 } else {
411 }
412
413 if (TargetTriple.isOSBinFormatCOFF()) {
414 // In COFF files, if the contructors are set as COMDAT (they are because
415 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
416 // functions and data) is used, the constructors get stripped. To prevent
417 // this, give the constructors weak ODR linkage and ensure the linker knows
418 // to include the sancov constructor. This way the linker can deduplicate
419 // the constructors but always leave one copy.
421 }
422 return CtorFunc;
423}
424
425bool ModuleSanitizerCoverage::instrumentModule() {
427 return false;
428 if (Allowlist &&
429 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
430 return false;
431 if (Blocklist &&
432 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
433 return false;
434 C = &(M.getContext());
435 DL = &M.getDataLayout();
436 CurModule = &M;
437 TargetTriple = M.getTargetTriple();
438 FunctionGuardArray = nullptr;
439 Function8bitCounterArray = nullptr;
440 FunctionBoolArray = nullptr;
441 FunctionPCsArray = nullptr;
442 FunctionCFsArray = nullptr;
443 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
444 PtrTy = PointerType::getUnqual(*C);
445 Type *VoidTy = Type::getVoidTy(*C);
446 IRBuilder<> IRB(*C);
447 Int64Ty = IRB.getInt64Ty();
448 Int32Ty = IRB.getInt32Ty();
449 Int16Ty = IRB.getInt16Ty();
450 Int8Ty = IRB.getInt8Ty();
451 Int1Ty = IRB.getInt1Ty();
452
453 SanCovTracePCIndir =
454 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
455 // Make sure smaller parameters are zero-extended to i64 if required by the
456 // target ABI.
457 AttributeList SanCovTraceCmpZeroExtAL;
458 SanCovTraceCmpZeroExtAL =
459 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
460 SanCovTraceCmpZeroExtAL =
461 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
462
463 SanCovTraceCmpFunction[0] =
464 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
465 IRB.getInt8Ty(), IRB.getInt8Ty());
466 SanCovTraceCmpFunction[1] =
467 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
468 IRB.getInt16Ty(), IRB.getInt16Ty());
469 SanCovTraceCmpFunction[2] =
470 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
471 IRB.getInt32Ty(), IRB.getInt32Ty());
472 SanCovTraceCmpFunction[3] =
473 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
474
475 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
476 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
477 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
478 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
479 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
480 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
481 SanCovTraceConstCmpFunction[3] =
482 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
483
484 // Loads.
485 SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, PtrTy);
486 SanCovLoadFunction[1] = M.getOrInsertFunction(SanCovLoad2, VoidTy, PtrTy);
487 SanCovLoadFunction[2] = M.getOrInsertFunction(SanCovLoad4, VoidTy, PtrTy);
488 SanCovLoadFunction[3] = M.getOrInsertFunction(SanCovLoad8, VoidTy, PtrTy);
489 SanCovLoadFunction[4] = M.getOrInsertFunction(SanCovLoad16, VoidTy, PtrTy);
490 // Stores.
491 SanCovStoreFunction[0] = M.getOrInsertFunction(SanCovStore1, VoidTy, PtrTy);
492 SanCovStoreFunction[1] = M.getOrInsertFunction(SanCovStore2, VoidTy, PtrTy);
493 SanCovStoreFunction[2] = M.getOrInsertFunction(SanCovStore4, VoidTy, PtrTy);
494 SanCovStoreFunction[3] = M.getOrInsertFunction(SanCovStore8, VoidTy, PtrTy);
495 SanCovStoreFunction[4] = M.getOrInsertFunction(SanCovStore16, VoidTy, PtrTy);
496
497 {
498 AttributeList AL;
499 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
500 SanCovTraceDivFunction[0] =
501 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
502 }
503 SanCovTraceDivFunction[1] =
504 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
505 SanCovTraceGepFunction =
506 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
507 SanCovTraceSwitchFunction =
508 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, PtrTy);
509
510 SanCovLowestStack = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
511 if (SanCovLowestStack->getValueType() != IntptrTy) {
512 C->emitError(StringRef("'") + SanCovLowestStackName +
513 "' should not be declared by the user");
514 return true;
515 }
516 SanCovLowestStack->setThreadLocalMode(
518 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
519 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
520
521 if (Options.GatedCallbacks) {
522 if (!Options.TracePCGuard && !Options.TraceCmp) {
523 C->emitError(StringRef("'") + ClGatedCallbacks.ArgStr +
524 "' is only supported with trace-pc-guard or trace-cmp");
525 return true;
526 }
527
528 SanCovCallbackGate = cast<GlobalVariable>(
529 M.getOrInsertGlobal(SanCovCallbackGateName, Int64Ty));
530 SanCovCallbackGate->setSection(
532 SanCovCallbackGate->setInitializer(Constant::getNullValue(Int64Ty));
533 SanCovCallbackGate->setLinkage(GlobalVariable::LinkOnceAnyLinkage);
534 SanCovCallbackGate->setVisibility(GlobalVariable::HiddenVisibility);
535 appendToCompilerUsed(M, SanCovCallbackGate);
536 }
537
538 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
539 SanCovTracePCEntry = M.getOrInsertFunction(SanCovTracePCEntryName, VoidTy);
540 SanCovTracePCExit = M.getOrInsertFunction(SanCovTracePCExitName, VoidTy);
541 SanCovTracePCGuard =
542 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
543
544 SanCovStackDepthCallback =
545 M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
546
547 for (auto &F : M)
548 instrumentFunction(F);
549
550 Function *Ctor = nullptr;
551
552 if (FunctionGuardArray)
553 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
556 if (Function8bitCounterArray)
557 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
560 if (FunctionBoolArray) {
561 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
564 }
565 if (Ctor && Options.PCTable) {
566 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
567 FunctionCallee InitFunction =
569 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
570 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
571 }
572
573 if (Ctor && Options.CollectControlFlow) {
574 auto SecStartEnd = CreateSecStartEnd(M, SanCovCFsSectionName, IntptrTy);
575 FunctionCallee InitFunction =
577 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
578 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
579 }
580
581 appendToUsed(M, GlobalsToAppendToUsed);
582 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
583 return true;
584}
585
586// True if block has successors and it dominates all of them.
587static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT) {
588 if (succ_empty(BB))
589 return false;
590
591 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
592 return DT.dominates(BB, SUCC);
593 });
594}
595
596// True if block has predecessors and it postdominates all of them.
597static bool isFullPostDominator(const BasicBlock *BB,
598 const PostDominatorTree &PDT) {
599 if (pred_empty(BB))
600 return false;
601
602 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
603 return PDT.dominates(BB, PRED);
604 });
605}
606
607static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
608 const DominatorTree &DT,
609 const PostDominatorTree &PDT,
611 // Don't insert coverage for blocks containing nothing but unreachable: we
612 // will never call __sanitizer_cov() for them, so counting them in
613 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
614 // percentage. Also, unreachable instructions frequently have no debug
615 // locations.
617 return false;
618
619 // Don't insert coverage into blocks without a valid insertion point
620 // (catchswitch blocks).
621 if (BB->getFirstInsertionPt() == BB->end())
622 return false;
623
624 if (Options.NoPrune || &F.getEntryBlock() == BB)
625 return true;
626
628 &F.getEntryBlock() != BB)
629 return false;
630
631 // Do not instrument full dominators, or full post-dominators with multiple
632 // predecessors.
633 return !isFullDominator(BB, DT) &&
634 !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
635}
636
637// Returns true iff From->To is a backedge.
638// A twist here is that we treat From->To as a backedge if
639// * To dominates From or
640// * To->UniqueSuccessor dominates From
641static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
642 const DominatorTree &DT) {
643 if (DT.dominates(To, From))
644 return true;
645 if (auto Next = To->getUniqueSuccessor())
646 if (DT.dominates(Next, From))
647 return true;
648 return false;
649}
650
651// Prunes uninteresting Cmp instrumentation:
652// * CMP instructions that feed into loop backedge branch.
653//
654// Note that Cmp pruning is controlled by the same flag as the
655// BB pruning.
656static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT,
658 if (!Options.NoPrune)
659 if (CMP->hasOneUse())
660 if (auto BR = dyn_cast<CondBrInst>(CMP->user_back()))
661 for (BasicBlock *B : BR->successors())
662 if (IsBackEdge(BR->getParent(), B, DT))
663 return false;
664 return true;
665}
666
667void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
668 if (F.empty())
669 return;
670 if (F.getName().contains(".module_ctor"))
671 return; // Should not instrument sanitizer init functions.
672 if (F.getName().starts_with("__sanitizer_"))
673 return; // Don't instrument __sanitizer_* callbacks.
674 // Don't touch available_externally functions, their actual body is elewhere.
675 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
676 return;
677 // Don't instrument MSVC CRT configuration helpers. They may run before normal
678 // initialization.
679 if (F.getName() == "__local_stdio_printf_options" ||
680 F.getName() == "__local_stdio_scanf_options")
681 return;
682 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
683 return;
684 // Don't instrument functions using SEH for now. Splitting basic blocks like
685 // we do for coverage breaks WinEHPrepare.
686 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
687 if (F.hasPersonalityFn() &&
689 return;
690 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
691 return;
692 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
693 return;
694 // Do not apply any instrumentation for naked functions.
695 if (F.hasFnAttribute(Attribute::Naked))
696 return;
697 if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
698 return;
699 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
700 return;
701 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) {
703 F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
704 }
706 SmallVector<BasicBlock *, 16> BlocksToInstrument;
707 SmallVector<Instruction *, 8> CmpTraceTargets;
708 SmallVector<Instruction *, 8> SwitchTraceTargets;
709 SmallVector<BinaryOperator *, 8> DivTraceTargets;
713
714 const DominatorTree &DT = DTCallback(F);
715 const PostDominatorTree &PDT = PDTCallback(F);
716 bool IsLeafFunc = true;
717
718 for (auto &BB : F) {
719 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
720 BlocksToInstrument.push_back(&BB);
721 for (auto &Inst : BB) {
722 if (Options.IndirectCalls) {
723 CallBase *CB = dyn_cast<CallBase>(&Inst);
724 if (CB && CB->isIndirectCall())
725 IndirCalls.push_back(&Inst);
726 }
727 if (Options.TraceCmp) {
728 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
729 if (IsInterestingCmp(CMP, DT, Options))
730 CmpTraceTargets.push_back(&Inst);
731 if (isa<SwitchInst>(&Inst))
732 SwitchTraceTargets.push_back(&Inst);
733 }
734 if (Options.TraceDiv)
736 if (BO->getOpcode() == Instruction::SDiv ||
737 BO->getOpcode() == Instruction::UDiv)
738 DivTraceTargets.push_back(BO);
739 if (Options.TraceGep)
741 GepTraceTargets.push_back(GEP);
742 if (Options.TraceLoads)
743 if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
744 Loads.push_back(LI);
745 if (Options.TraceStores)
746 if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
747 Stores.push_back(SI);
748 if (Options.StackDepth)
749 if (isa<InvokeInst>(Inst) ||
750 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
751 IsLeafFunc = false;
752 }
753 }
754
755 if (Options.CollectControlFlow)
756 createFunctionControlFlow(F);
757
758 Value *FunctionGateCmp = nullptr;
759 InjectCoverage(F, BlocksToInstrument, FunctionGateCmp, IsLeafFunc);
760 InjectCoverageForIndirectCalls(F, IndirCalls);
761 InjectTraceForCmp(F, CmpTraceTargets, FunctionGateCmp);
762 InjectTraceForSwitch(F, SwitchTraceTargets, FunctionGateCmp);
763 InjectTraceForDiv(F, DivTraceTargets);
764 InjectTraceForGep(F, GepTraceTargets);
765 InjectTraceForLoadsAndStores(F, Loads, Stores);
766
767 if (Options.TracePCEntryExit)
768 InjectTraceForExits(F);
769}
770
771GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
772 size_t NumElements, Function &F, Type *Ty, const char *Section) {
773 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
774 auto Array = new GlobalVariable(
775 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
776 Constant::getNullValue(ArrayTy), "__sancov_gen_");
777
778 if (TargetTriple.supportsCOMDAT() &&
779 (F.hasComdat() || TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
780 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
781 Array->setComdat(Comdat);
782 Array->setSection(getSectionName(Section));
783 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedValue()));
784
785 // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
786 // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
787 // section(s) as a unit, so we conservatively retain all unconditionally in
788 // the compiler.
789 //
790 // With comdat (COFF/ELF), the linker can guarantee the associated sections
791 // will be retained or discarded as a unit, so llvm.compiler.used is
792 // sufficient. Otherwise, conservatively make all of them retained by the
793 // linker.
794 if (Array->hasComdat())
795 GlobalsToAppendToCompilerUsed.push_back(Array);
796 else
797 GlobalsToAppendToUsed.push_back(Array);
798
799 return Array;
800}
801
803ModuleSanitizerCoverage::CreatePCArray(Function &F,
804 ArrayRef<BasicBlock *> AllBlocks) {
805 size_t N = AllBlocks.size();
806 assert(N);
808 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
809 for (size_t i = 0; i < N; i++) {
810 if (&F.getEntryBlock() == AllBlocks[i]) {
811 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
812 PCs.push_back(
813 (Constant *)IRB.CreateIntToPtr(ConstantInt::get(IntptrTy, 1), PtrTy));
814 } else {
815 PCs.push_back((Constant *)IRB.CreatePointerCast(
816 BlockAddress::get(AllBlocks[i]), PtrTy));
818 }
819 }
820 auto *PCArray =
821 CreateFunctionLocalArrayInSection(N * 2, F, PtrTy, SanCovPCsSectionName);
822 PCArray->setInitializer(
823 ConstantArray::get(ArrayType::get(PtrTy, N * 2), PCs));
824 PCArray->setConstant(true);
825
826 return PCArray;
827}
828
829void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
830 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
831 if (Options.TracePCGuard)
832 FunctionGuardArray = CreateFunctionLocalArrayInSection(
833 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
834
835 if (Options.Inline8bitCounters)
836 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
837 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
838 if (Options.InlineBoolFlag)
839 FunctionBoolArray = CreateFunctionLocalArrayInSection(
840 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
841
842 if (Options.PCTable)
843 FunctionPCsArray = CreatePCArray(F, AllBlocks);
844}
845
846Value *ModuleSanitizerCoverage::CreateFunctionLocalGateCmp(IRBuilder<> &IRB) {
847 auto Load = IRB.CreateLoad(Int64Ty, SanCovCallbackGate);
848 Load->setNoSanitizeMetadata();
849 auto Cmp = IRB.CreateIsNotNull(Load);
850 Cmp->setName("sancov gate cmp");
851 return Cmp;
852}
853
854Instruction *ModuleSanitizerCoverage::CreateGateBranch(Function &F,
855 Value *&FunctionGateCmp,
856 Instruction *IP) {
857 if (!FunctionGateCmp) {
858 // Create this in the entry block
859 BasicBlock &BB = F.getEntryBlock();
861 IP = PrepareToSplitEntryBlock(BB, IP);
862 IRBuilder<> EntryIRB(&*IP);
863 FunctionGateCmp = CreateFunctionLocalGateCmp(EntryIRB);
864 }
865 // Set the branch weights in order to minimize the price paid when the
866 // gate is turned off, allowing the default enablement of this
867 // instrumentation with as little of a performance cost as possible
868 auto Weights = MDBuilder(*C).createBranchWeights(1, 100000);
869 return SplitBlockAndInsertIfThen(FunctionGateCmp, IP, false, Weights);
870}
871
872bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
873 ArrayRef<BasicBlock *> AllBlocks,
874 Value *&FunctionGateCmp,
875 bool IsLeafFunc) {
876 if (AllBlocks.empty())
877 return false;
878 CreateFunctionLocalArrays(F, AllBlocks);
879 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
880 InjectCoverageAtBlock(F, *AllBlocks[i], i, FunctionGateCmp, IsLeafFunc);
881
882 return true;
883}
884
885// On every indirect call we call a run-time function
886// __sanitizer_cov_indir_call* with two parameters:
887// - callee address,
888// - global cache array that contains CacheSize pointers (zero-initialized).
889// The cache is used to speed up recording the caller-callee pairs.
890// The address of the caller is passed implicitly via caller PC.
891// CacheSize is encoded in the name of the run-time function.
892void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
893 Function &F, ArrayRef<Instruction *> IndirCalls) {
894 if (IndirCalls.empty())
895 return;
896 assert(Options.TracePC || Options.TracePCEntryExit || Options.TracePCGuard ||
897 Options.Inline8bitCounters || Options.InlineBoolFlag);
898 for (auto *I : IndirCalls) {
900 CallBase &CB = cast<CallBase>(*I);
902 if (isa<InlineAsm>(Callee))
903 continue;
904 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
905 }
906}
907
908// For every switch statement we insert a call:
909// __sanitizer_cov_trace_switch(CondValue,
910// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
911
912void ModuleSanitizerCoverage::InjectTraceForSwitch(
913 Function &F, ArrayRef<Instruction *> SwitchTraceTargets,
914 Value *&FunctionGateCmp) {
915 for (auto *I : SwitchTraceTargets) {
918 SmallVector<Constant *, 16> Initializers;
919 Value *Cond = SI->getCondition();
920 if (Cond->getType()->getScalarSizeInBits() >
921 Int64Ty->getScalarSizeInBits())
922 continue;
923 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
924 Initializers.push_back(
925 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
926 if (Cond->getType()->getScalarSizeInBits() <
927 Int64Ty->getScalarSizeInBits())
928 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
929 for (auto It : SI->cases()) {
930 ConstantInt *C = It.getCaseValue();
931 if (C->getType()->getScalarSizeInBits() < 64)
932 C = ConstantInt::get(C->getContext(), C->getValue().zext(64));
933 Initializers.push_back(C);
934 }
935 llvm::sort(drop_begin(Initializers, 2),
936 [](const Constant *A, const Constant *B) {
937 return cast<ConstantInt>(A)->getLimitedValue() <
938 cast<ConstantInt>(B)->getLimitedValue();
939 });
940 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
942 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
943 ConstantArray::get(ArrayOfInt64Ty, Initializers),
944 "__sancov_gen_cov_switch_values");
945 if (Options.GatedCallbacks) {
946 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
947 IRBuilder<> GateIRB(GateBranch);
948 GateIRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
949 } else {
950 IRB.CreateCall(SanCovTraceSwitchFunction, {Cond, GV});
951 }
952 }
953 }
954}
955
956void ModuleSanitizerCoverage::InjectTraceForDiv(
957 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
958 for (auto *BO : DivTraceTargets) {
960 Value *A1 = BO->getOperand(1);
961 if (isa<ConstantInt>(A1))
962 continue;
963 if (!A1->getType()->isIntegerTy())
964 continue;
965 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
966 int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
967 if (CallbackIdx < 0)
968 continue;
969 auto Ty = Type::getIntNTy(*C, TypeSize);
970 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
971 {IRB.CreateIntCast(A1, Ty, true)});
972 }
973}
974
975void ModuleSanitizerCoverage::InjectTraceForGep(
976 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
977 for (auto *GEP : GepTraceTargets) {
979 for (Use &Idx : GEP->indices())
980 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
981 IRB.CreateCall(SanCovTraceGepFunction,
982 {IRB.CreateIntCast(Idx, IntptrTy, true)});
983 }
984}
985
986void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
988 auto CallbackIdx = [&](Type *ElementTy) -> int {
989 uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
990 return TypeSize == 8 ? 0
991 : TypeSize == 16 ? 1
992 : TypeSize == 32 ? 2
993 : TypeSize == 64 ? 3
994 : TypeSize == 128 ? 4
995 : -1;
996 };
997 for (auto *LI : Loads) {
999 auto Ptr = LI->getPointerOperand();
1000 int Idx = CallbackIdx(LI->getType());
1001 if (Idx < 0)
1002 continue;
1003 IRB.CreateCall(SanCovLoadFunction[Idx], Ptr);
1004 }
1005 for (auto *SI : Stores) {
1007 auto Ptr = SI->getPointerOperand();
1008 int Idx = CallbackIdx(SI->getValueOperand()->getType());
1009 if (Idx < 0)
1010 continue;
1011 IRB.CreateCall(SanCovStoreFunction[Idx], Ptr);
1012 }
1013}
1014
1015void ModuleSanitizerCoverage::InjectTraceForExits(Function &F) {
1016 EscapeEnumerator EE(F, "sancov_exit");
1017 while (IRBuilder<> *AtExit = EE.Next()) {
1019 AtExit->CreateCall(SanCovTracePCExit, {})
1020 ->setTailCallKind(CallInst::TCK_NoTail);
1021 }
1022}
1023
1024void ModuleSanitizerCoverage::InjectTraceForCmp(
1025 Function &F, ArrayRef<Instruction *> CmpTraceTargets,
1026 Value *&FunctionGateCmp) {
1027 for (auto *I : CmpTraceTargets) {
1028 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
1029 InstrumentationIRBuilder IRB(ICMP);
1030 Value *A0 = ICMP->getOperand(0);
1031 Value *A1 = ICMP->getOperand(1);
1032 if (!A0->getType()->isIntegerTy())
1033 continue;
1034 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1035 int CallbackIdx = TypeSize == 8 ? 0
1036 : TypeSize == 16 ? 1
1037 : TypeSize == 32 ? 2
1038 : TypeSize == 64 ? 3
1039 : -1;
1040 if (CallbackIdx < 0)
1041 continue;
1042 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1043 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1044 bool FirstIsConst = isa<ConstantInt>(A0);
1045 bool SecondIsConst = isa<ConstantInt>(A1);
1046 // If both are const, then we don't need such a comparison.
1047 if (FirstIsConst && SecondIsConst)
1048 continue;
1049 // If only one is const, then make it the first callback argument.
1050 if (FirstIsConst || SecondIsConst) {
1051 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1052 if (SecondIsConst)
1053 std::swap(A0, A1);
1054 }
1055
1056 auto Ty = Type::getIntNTy(*C, TypeSize);
1057 if (Options.GatedCallbacks) {
1058 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1059 IRBuilder<> GateIRB(GateBranch);
1060 GateIRB.CreateCall(CallbackFunc, {GateIRB.CreateIntCast(A0, Ty, true),
1061 GateIRB.CreateIntCast(A1, Ty, true)});
1062 } else {
1063 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
1064 IRB.CreateIntCast(A1, Ty, true)});
1065 }
1066 }
1067 }
1068}
1069
1070void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
1071 size_t Idx,
1072 Value *&FunctionGateCmp,
1073 bool IsLeafFunc) {
1075 bool IsEntryBB = &BB == &F.getEntryBlock();
1076 DebugLoc EntryLoc;
1077 if (IsEntryBB) {
1078 if (auto SP = F.getSubprogram())
1079 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1080 // Keep static allocas and llvm.localescape calls in the entry block. Even
1081 // if we aren't splitting the block, it's nice for allocas to be before
1082 // calls.
1083 IP = PrepareToSplitEntryBlock(BB, IP);
1084 }
1085
1086 InstrumentationIRBuilder IRB(&*IP);
1087 if (EntryLoc)
1088 IRB.SetCurrentDebugLocation(EntryLoc);
1089 if (Options.TracePC || (IsEntryBB && Options.TracePCEntryExit)) {
1090 FunctionCallee Callee = IsEntryBB && Options.TracePCEntryExit
1091 ? SanCovTracePCEntry
1092 : SanCovTracePC;
1093 IRB.CreateCall(Callee)
1094 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
1095 }
1096 if (Options.TracePCGuard) {
1097 auto GuardPtr = IRB.CreateConstInBoundsGEP2_64(
1098 FunctionGuardArray->getValueType(), FunctionGuardArray, 0, Idx);
1099 if (Options.GatedCallbacks) {
1100 Instruction *I = &*IP;
1101 auto GateBranch = CreateGateBranch(F, FunctionGateCmp, I);
1102 IRBuilder<> GateIRB(GateBranch);
1103 GateIRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1104 } else {
1105 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1106 }
1107 }
1108 if (Options.Inline8bitCounters) {
1109 auto CounterPtr = IRB.CreateGEP(
1110 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1111 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1112 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1113 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1114 auto Store = IRB.CreateStore(Inc, CounterPtr);
1115 Load->setNoSanitizeMetadata();
1116 Store->setNoSanitizeMetadata();
1117 }
1118 if (Options.InlineBoolFlag) {
1119 auto FlagPtr = IRB.CreateGEP(
1120 FunctionBoolArray->getValueType(), FunctionBoolArray,
1121 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1122 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1123 auto ThenTerm = SplitBlockAndInsertIfThen(
1124 IRB.CreateIsNull(Load), &*IP, false,
1126 InstrumentationIRBuilder ThenIRB(ThenTerm);
1127 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1128 if (EntryLoc)
1129 Store->setDebugLoc(EntryLoc);
1130 Load->setNoSanitizeMetadata();
1131 Store->setNoSanitizeMetadata();
1132 }
1133 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1134 Module *M = F.getParent();
1135 const DataLayout &DL = M->getDataLayout();
1136
1137 if (Options.StackDepthCallbackMin) {
1138 // In callback mode, only add call when stack depth reaches minimum.
1139 int EstimatedStackSize = 0;
1140 // If dynamic alloca found, always add call.
1141 bool HasDynamicAlloc = false;
1142 // Find an insertion point after last "alloca".
1143 llvm::Instruction *InsertBefore = nullptr;
1144
1145 // Examine all allocas in the basic block. since we're too early
1146 // to have results from Intrinsic::frameaddress, we have to manually
1147 // estimate the stack size.
1148 for (auto &I : BB) {
1149 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1150 // Move potential insertion point past the "alloca".
1151 InsertBefore = AI->getNextNode();
1152
1153 // Make an estimate on the stack usage.
1154 if (auto AllocaSize = AI->getAllocationSize(DL)) {
1155 if (AllocaSize->isFixed())
1156 EstimatedStackSize += AllocaSize->getFixedValue();
1157 else
1158 HasDynamicAlloc = true;
1159 } else {
1160 HasDynamicAlloc = true;
1161 }
1162 }
1163 }
1164
1165 if (HasDynamicAlloc ||
1166 EstimatedStackSize >= Options.StackDepthCallbackMin) {
1167 if (InsertBefore)
1168 IRB.SetInsertPoint(InsertBefore);
1169 auto Call = IRB.CreateCall(SanCovStackDepthCallback);
1170 if (EntryLoc)
1171 Call->setDebugLoc(EntryLoc);
1173 }
1174 } else {
1175 // Check stack depth. If it's the deepest so far, record it.
1176 auto FrameAddrPtr = IRB.CreateIntrinsic(
1177 Intrinsic::frameaddress, IRB.getPtrTy(DL.getAllocaAddrSpace()),
1178 {Constant::getNullValue(Int32Ty)});
1179 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1180 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1181 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1182 auto ThenTerm = SplitBlockAndInsertIfThen(
1183 IsStackLower, &*IP, false,
1185 InstrumentationIRBuilder ThenIRB(ThenTerm);
1186 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1187 if (EntryLoc)
1188 Store->setDebugLoc(EntryLoc);
1189 LowestStack->setNoSanitizeMetadata();
1190 Store->setNoSanitizeMetadata();
1191 }
1192 }
1193}
1194
1195std::string
1196ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1197 if (TargetTriple.isOSBinFormatCOFF()) {
1198 if (Section == SanCovCountersSectionName)
1199 return ".SCOV$CM";
1200 if (Section == SanCovBoolFlagSectionName)
1201 return ".SCOV$BM";
1202 if (Section == SanCovPCsSectionName)
1203 return ".SCOVP$M";
1204 return ".SCOV$GM"; // For SanCovGuardsSectionName.
1205 }
1206 if (TargetTriple.isOSBinFormatMachO())
1207 return "__DATA,__" + Section;
1208 return "__" + Section;
1209}
1210
1211std::string
1212ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1213 if (TargetTriple.isOSBinFormatMachO())
1214 return "\1section$start$__DATA$__" + Section;
1215 return "__start___" + Section;
1216}
1217
1218std::string
1219ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1220 if (TargetTriple.isOSBinFormatMachO())
1221 return "\1section$end$__DATA$__" + Section;
1222 return "__stop___" + Section;
1223}
1224
1225void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
1227 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
1228
1229 for (auto &BB : F) {
1230 // blockaddress can not be used on function's entry block.
1231 if (&BB == &F.getEntryBlock())
1232 CFs.push_back((Constant *)IRB.CreatePointerCast(&F, PtrTy));
1233 else
1234 CFs.push_back(
1235 (Constant *)IRB.CreatePointerCast(BlockAddress::get(&BB), PtrTy));
1236
1237 for (auto SuccBB : successors(&BB)) {
1238 assert(SuccBB != &F.getEntryBlock());
1239 CFs.push_back(
1240 (Constant *)IRB.CreatePointerCast(BlockAddress::get(SuccBB), PtrTy));
1241 }
1242
1244
1245 for (auto &Inst : BB) {
1246 if (CallBase *CB = dyn_cast<CallBase>(&Inst)) {
1247 if (CB->isIndirectCall()) {
1248 // TODO(navidem): handle indirect calls, for now mark its existence.
1250 ConstantInt::getAllOnesValue(IntptrTy), PtrTy));
1251 } else {
1252 auto CalledF = CB->getCalledFunction();
1253 if (CalledF && !CalledF->isIntrinsic())
1254 CFs.push_back((Constant *)IRB.CreatePointerCast(CalledF, PtrTy));
1255 }
1256 }
1257 }
1258
1260 }
1261
1262 FunctionCFsArray = CreateFunctionLocalArrayInSection(CFs.size(), F, PtrTy,
1264 FunctionCFsArray->setInitializer(
1265 ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
1266 FunctionCFsArray->setConstant(true);
1267}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< bool > ClLoadTracing("sanitizer-coverage-trace-loads", cl::desc("Tracing of load instructions"), cl::Hidden)
const char SanCovCFsSectionName[]
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree &PDT)
static cl::opt< int > ClCoverageLevel("sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, " "3: all blocks and critical edges"), cl::Hidden)
static cl::opt< bool > ClSancovDropCtors("sanitizer-coverage-drop-ctors", cl::desc("do not emit module ctors for global counters"), cl::Hidden)
static cl::opt< bool > ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), cl::Hidden)
static cl::opt< bool > ClTracePCEntryExit("sanitizer-coverage-trace-pc-entry-exit", cl::desc("pc tracing with separate entry/exit callbacks"), cl::Hidden)
static cl::opt< bool > ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag", cl::desc("sets a boolean flag for every edge"), cl::Hidden)
const char SanCovTraceConstCmp4[]
const char SanCovBoolFlagSectionName[]
const char SanCov8bitCountersInitName[]
const char SanCovTracePCEntryName[]
const char SanCovLoad8[]
const char SanCovTraceSwitchName[]
const char SanCovTraceCmp1[]
const char SanCovModuleCtorTracePcGuardName[]
const char SanCovCountersSectionName[]
static cl::opt< bool > ClCreatePCTable("sanitizer-coverage-pc-table", cl::desc("create a static PC table"), cl::Hidden)
const char SanCovPCsInitName[]
const char SanCovTracePCGuardName[]
static cl::opt< int > ClStackDepthCallbackMin("sanitizer-coverage-stack-depth-callback-min", cl::desc("max stack depth tracing should use callback and only when " "stack depth more than specified"), cl::Hidden)
const char SanCovModuleCtor8bitCountersName[]
const char SanCovTracePCGuardInitName[]
static cl::opt< bool > ClCollectCF("sanitizer-coverage-control-flow", cl::desc("collect control flow for each function"), cl::Hidden)
const char SanCovTraceDiv4[]
static const uint64_t SanCtorAndDtorPriority
const char SanCovBoolFlagInitName[]
static cl::opt< bool > ClGatedCallbacks("sanitizer-coverage-gated-trace-callbacks", cl::desc("Gate the invocation of the tracing callbacks on a global variable" ". Currently only supported for trace-pc-guard and trace-cmp."), cl::Hidden, cl::init(false))
const char SanCovTraceGep[]
const char SanCovLoad16[]
const char SanCovTraceConstCmp8[]
const char SanCovGuardsSectionName[]
const char SanCovStore1[]
const char SanCovTraceConstCmp2[]
const char SanCovTraceConstCmp1[]
static bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree &DT)
static cl::opt< bool > ClStoreTracing("sanitizer-coverage-trace-stores", cl::desc("Tracing of store instructions"), cl::Hidden)
const char SanCovCallbackGateName[]
static cl::opt< bool > ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden)
const char SanCovTraceDiv8[]
const char SanCovLoad4[]
static cl::opt< bool > ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden)
const char SanCovStackDepthCallbackName[]
const char SanCovCFsInitName[]
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden)
const char SanCovStore2[]
static cl::opt< bool > ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true))
const char SanCovPCsSectionName[]
const char SanCovLoad1[]
const char SanCovTracePCExitName[]
static bool isFullDominator(const BasicBlock *BB, const DominatorTree &DT)
static cl::opt< bool > ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden)
const char SanCovTraceCmp8[]
const char SanCovCallbackGateSectionName[]
const char SanCovStore16[]
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree &DT, const SanitizerCoverageOptions &Options)
static cl::opt< bool > ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden)
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden)
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree &DT, const PostDominatorTree &PDT, const SanitizerCoverageOptions &Options)
const char SanCovModuleCtorBoolFlagName[]
const char SanCovTraceCmp2[]
const char SanCovStore8[]
const char SanCovTracePCName[]
const char SanCovStore4[]
const char SanCovLoad2[]
const char SanCovTraceCmp4[]
const char SanCovLowestStackName[]
const char SanCovTracePCIndirName[]
This file defines the SmallVector class.
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
void setCannotMerge()
Value * getCalledOperand() const
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1513
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
void setLinkage(LinkageTypes LT)
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2406
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2305
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2246
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:221
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2019
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1914
LLVMContext & getContext() const
Definition IRBuilder.h:177
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition IRBuilder.h:2084
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1933
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1430
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2241
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2757
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2569
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:577
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2331
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2752
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
Instruction * user_back()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
An instruction for reading from memory.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SanitizerCoveragePass(SanitizerCoverageOptions Options=SanitizerCoverageOptions(), IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr, const std::vector< std::string > &AllowlistFiles={}, const std::vector< std::string > &BlocklistFiles={})
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static LLVM_ABI std::unique_ptr< SpecialCaseList > createOrDie(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS)
Parses the special case list entries from files.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
initializer< Ty > init(const Ty &Val)
static constexpr const StringLiteral & getSectionName(DebugSectionKind SectionKind)
Return the name of the section.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool succ_empty(const Instruction *I)
Definition CFG.h:141
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI Comdat * getOrCreateFunctionComdat(Function &F, Triple &T)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Option class for critical edge splitting.
static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F)
enum llvm::SanitizerCoverageOptions::Type CoverageType