Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
Line
Count
Source (jump to first uncovered line)
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
13
#include "llvm/ADT/ArrayRef.h"
14
#include "llvm/ADT/SmallVector.h"
15
#include "llvm/Analysis/EHPersonalities.h"
16
#include "llvm/Analysis/PostDominators.h"
17
#include "llvm/IR/CFG.h"
18
#include "llvm/IR/CallSite.h"
19
#include "llvm/IR/Constant.h"
20
#include "llvm/IR/DataLayout.h"
21
#include "llvm/IR/DebugInfo.h"
22
#include "llvm/IR/Dominators.h"
23
#include "llvm/IR/Function.h"
24
#include "llvm/IR/GlobalVariable.h"
25
#include "llvm/IR/IRBuilder.h"
26
#include "llvm/IR/InlineAsm.h"
27
#include "llvm/IR/IntrinsicInst.h"
28
#include "llvm/IR/Intrinsics.h"
29
#include "llvm/IR/LLVMContext.h"
30
#include "llvm/IR/MDBuilder.h"
31
#include "llvm/IR/Mangler.h"
32
#include "llvm/IR/Module.h"
33
#include "llvm/IR/Type.h"
34
#include "llvm/Support/CommandLine.h"
35
#include "llvm/Support/Debug.h"
36
#include "llvm/Support/raw_ostream.h"
37
#include "llvm/Transforms/Instrumentation.h"
38
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39
#include "llvm/Transforms/Utils/ModuleUtils.h"
40
41
using namespace llvm;
42
43
#define DEBUG_TYPE "sancov"
44
45
static const char *const SanCovTracePCIndirName =
46
    "__sanitizer_cov_trace_pc_indir";
47
static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
48
static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49
static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50
static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51
static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
52
static const char *const SanCovTraceConstCmp1 =
53
    "__sanitizer_cov_trace_const_cmp1";
54
static const char *const SanCovTraceConstCmp2 =
55
    "__sanitizer_cov_trace_const_cmp2";
56
static const char *const SanCovTraceConstCmp4 =
57
    "__sanitizer_cov_trace_const_cmp4";
58
static const char *const SanCovTraceConstCmp8 =
59
    "__sanitizer_cov_trace_const_cmp8";
60
static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61
static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62
static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
63
static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64
static const char *const SanCovModuleCtorTracePcGuardName =
65
    "sancov.module_ctor_trace_pc_guard";
66
static const char *const SanCovModuleCtor8bitCountersName =
67
    "sancov.module_ctor_8bit_counters";
68
static const uint64_t SanCtorAndDtorPriority = 2;
69
70
static const char *const SanCovTracePCGuardName =
71
    "__sanitizer_cov_trace_pc_guard";
72
static const char *const SanCovTracePCGuardInitName =
73
    "__sanitizer_cov_trace_pc_guard_init";
74
static const char *const SanCov8bitCountersInitName =
75
    "__sanitizer_cov_8bit_counters_init";
76
static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
77
78
static const char *const SanCovGuardsSectionName = "sancov_guards";
79
static const char *const SanCovCountersSectionName = "sancov_cntrs";
80
static const char *const SanCovPCsSectionName = "sancov_pcs";
81
82
static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
83
84
static cl::opt<int> ClCoverageLevel(
85
    "sanitizer-coverage-level",
86
    cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
87
             "3: all blocks and critical edges"),
88
    cl::Hidden, cl::init(0));
89
90
static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
91
                               cl::desc("Experimental pc tracing"), cl::Hidden,
92
                               cl::init(false));
93
94
static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
95
                                    cl::desc("pc tracing with a guard"),
96
                                    cl::Hidden, cl::init(false));
97
98
// If true, we create a global variable that contains PCs of all instrumented
99
// BBs, put this global into a named section, and pass this section's bounds
100
// to __sanitizer_cov_pcs_init.
101
// This way the coverage instrumentation does not need to acquire the PCs
102
// at run-time. Works with trace-pc-guard and inline-8bit-counters.
103
static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
104
                                     cl::desc("create a static PC table"),
105
                                     cl::Hidden, cl::init(false));
106
107
static cl::opt<bool>
108
    ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
109
                         cl::desc("increments 8-bit counter for every edge"),
110
                         cl::Hidden, cl::init(false));
111
112
static cl::opt<bool>
113
    ClCMPTracing("sanitizer-coverage-trace-compares",
114
                 cl::desc("Tracing of CMP and similar instructions"),
115
                 cl::Hidden, cl::init(false));
116
117
static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
118
                                  cl::desc("Tracing of DIV instructions"),
119
                                  cl::Hidden, cl::init(false));
120
121
static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
122
                                  cl::desc("Tracing of GEP instructions"),
123
                                  cl::Hidden, cl::init(false));
124
125
static cl::opt<bool>
126
    ClPruneBlocks("sanitizer-coverage-prune-blocks",
127
                  cl::desc("Reduce the number of instrumented blocks"),
128
                  cl::Hidden, cl::init(true));
129
130
static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
131
                                  cl::desc("max stack depth tracing"),
132
                                  cl::Hidden, cl::init(false));
133
134
namespace {
135
136
42
SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
137
42
  SanitizerCoverageOptions Res;
138
42
  switch (LegacyCoverageLevel) {
139
42
  case 0:
140
1
    Res.CoverageType = SanitizerCoverageOptions::SCK_None;
141
1
    break;
142
42
  case 1:
143
18
    Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
144
18
    break;
145
42
  case 2:
146
2
    Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
147
2
    break;
148
42
  case 3:
149
15
    Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
150
15
    break;
151
42
  case 4:
152
6
    Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
153
6
    Res.IndirectCalls = true;
154
6
    break;
155
42
  }
156
42
  return Res;
157
42
}
158
159
42
SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
160
42
  // Sets CoverageType and IndirectCalls.
161
42
  SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
162
42
  Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
163
42
  Options.IndirectCalls |= CLOpts.IndirectCalls;
164
42
  Options.TraceCmp |= ClCMPTracing;
165
42
  Options.TraceDiv |= ClDIVTracing;
166
42
  Options.TraceGep |= ClGEPTracing;
167
42
  Options.TracePC |= ClTracePC;
168
42
  Options.TracePCGuard |= ClTracePCGuard;
169
42
  Options.Inline8bitCounters |= ClInline8bitCounters;
170
42
  Options.PCTable |= ClCreatePCTable;
171
42
  Options.NoPrune |= !ClPruneBlocks;
172
42
  Options.StackDepth |= ClStackDepth;
173
42
  if (!Options.TracePCGuard && 
!Options.TracePC29
&&
174
42
      
!Options.Inline8bitCounters23
&&
!Options.StackDepth18
)
175
16
    Options.TracePCGuard = true; // TracePCGuard is default.
176
42
  return Options;
177
42
}
178
179
class SanitizerCoverageModule : public ModulePass {
180
public:
181
  SanitizerCoverageModule(
182
      const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
183
42
      : ModulePass(ID), Options(OverrideFromCL(Options)) {
184
42
    initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
185
42
  }
186
  bool runOnModule(Module &M) override;
187
  bool runOnFunction(Function &F);
188
  static char ID; // Pass identification, replacement for typeid
189
0
  StringRef getPassName() const override { return "SanitizerCoverageModule"; }
190
191
42
  void getAnalysisUsage(AnalysisUsage &AU) const override {
192
42
    AU.addRequired<DominatorTreeWrapperPass>();
193
42
    AU.addRequired<PostDominatorTreeWrapperPass>();
194
42
  }
195
196
private:
197
  void InjectCoverageForIndirectCalls(Function &F,
198
                                      ArrayRef<Instruction *> IndirCalls);
199
  void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
200
  void InjectTraceForDiv(Function &F,
201
                         ArrayRef<BinaryOperator *> DivTraceTargets);
202
  void InjectTraceForGep(Function &F,
203
                         ArrayRef<GetElementPtrInst *> GepTraceTargets);
204
  void InjectTraceForSwitch(Function &F,
205
                            ArrayRef<Instruction *> SwitchTraceTargets);
206
  bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
207
                      bool IsLeafFunc = true);
208
  GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
209
                                                    Function &F, Type *Ty,
210
                                                    const char *Section);
211
  GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
212
  void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
213
  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
214
                             bool IsLeafFunc = true);
215
  Function *CreateInitCallsForSections(Module &M, const char *CtorName,
216
                                       const char *InitFunctionName, Type *Ty,
217
                                       const char *Section);
218
  std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
219
                                                Type *Ty);
220
221
22
  void SetNoSanitizeMetadata(Instruction *I) {
222
22
    I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
223
22
                   MDNode::get(*C, None));
224
22
  }
225
226
  std::string getSectionName(const std::string &Section) const;
227
  std::string getSectionStart(const std::string &Section) const;
228
  std::string getSectionEnd(const std::string &Section) const;
229
  FunctionCallee SanCovTracePCIndir;
230
  FunctionCallee SanCovTracePC, SanCovTracePCGuard;
231
  FunctionCallee SanCovTraceCmpFunction[4];
232
  FunctionCallee SanCovTraceConstCmpFunction[4];
233
  FunctionCallee SanCovTraceDivFunction[2];
234
  FunctionCallee SanCovTraceGepFunction;
235
  FunctionCallee SanCovTraceSwitchFunction;
236
  GlobalVariable *SanCovLowestStack;
237
  InlineAsm *EmptyAsm;
238
  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
239
      *Int16Ty, *Int8Ty, *Int8PtrTy;
240
  Module *CurModule;
241
  std::string CurModuleUniqueId;
242
  Triple TargetTriple;
243
  LLVMContext *C;
244
  const DataLayout *DL;
245
246
  GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
247
  GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
248
  GlobalVariable *FunctionPCsArray;  // for pc-table.
249
  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
250
  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
251
252
  SanitizerCoverageOptions Options;
253
};
254
255
} // namespace
256
257
std::pair<Value *, Value *>
258
SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
259
37
                                           Type *Ty) {
260
37
  GlobalVariable *SecStart =
261
37
      new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
262
37
                         getSectionStart(Section));
263
37
  SecStart->setVisibility(GlobalValue::HiddenVisibility);
264
37
  GlobalVariable *SecEnd =
265
37
      new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
266
37
                         nullptr, getSectionEnd(Section));
267
37
  SecEnd->setVisibility(GlobalValue::HiddenVisibility);
268
37
  IRBuilder<> IRB(M.getContext());
269
37
  Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
270
37
  if (!TargetTriple.isOSBinFormatCOFF())
271
28
    return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
272
9
273
9
  // Account for the fact that on windows-msvc __start_* symbols actually
274
9
  // point to a uint64_t before the start of the array.
275
9
  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
276
9
  auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
277
9
                           ConstantInt::get(IntptrTy, sizeof(uint64_t)));
278
9
  return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
279
9
}
280
281
Function *SanitizerCoverageModule::CreateInitCallsForSections(
282
    Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
283
32
    const char *Section) {
284
32
  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
285
32
  auto SecStart = SecStartEnd.first;
286
32
  auto SecEnd = SecStartEnd.second;
287
32
  Function *CtorFunc;
288
32
  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
289
32
      M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
290
32
  assert(CtorFunc->getName() == CtorName);
291
32
292
32
  if (TargetTriple.supportsCOMDAT()) {
293
30
    // Use comdat to dedup CtorFunc.
294
30
    CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
295
30
    appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
296
30
  } else {
297
2
    appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
298
2
  }
299
32
300
32
  if (TargetTriple.isOSBinFormatCOFF()) {
301
6
    // In COFF files, if the contructors are set as COMDAT (they are because
302
6
    // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
303
6
    // functions and data) is used, the constructors get stripped. To prevent
304
6
    // this, give the constructors weak ODR linkage and ensure the linker knows
305
6
    // to include the sancov constructor. This way the linker can deduplicate
306
6
    // the constructors but always leave one copy.
307
6
    CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
308
6
    appendToUsed(M, CtorFunc);
309
6
  }
310
32
  return CtorFunc;
311
32
}
312
313
42
bool SanitizerCoverageModule::runOnModule(Module &M) {
314
42
  if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
315
1
    return false;
316
41
  C = &(M.getContext());
317
41
  DL = &M.getDataLayout();
318
41
  CurModule = &M;
319
41
  CurModuleUniqueId = getUniqueModuleId(CurModule);
320
41
  TargetTriple = Triple(M.getTargetTriple());
321
41
  FunctionGuardArray = nullptr;
322
41
  Function8bitCounterArray = nullptr;
323
41
  FunctionPCsArray = nullptr;
324
41
  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
325
41
  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
326
41
  Type *VoidTy = Type::getVoidTy(*C);
327
41
  IRBuilder<> IRB(*C);
328
41
  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
329
41
  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
330
41
  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
331
41
  Int64Ty = IRB.getInt64Ty();
332
41
  Int32Ty = IRB.getInt32Ty();
333
41
  Int16Ty = IRB.getInt16Ty();
334
41
  Int8Ty = IRB.getInt8Ty();
335
41
336
41
  SanCovTracePCIndir =
337
41
      M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
338
41
  // Make sure smaller parameters are zero-extended to i64 as required by the
339
41
  // x86_64 ABI.
340
41
  AttributeList SanCovTraceCmpZeroExtAL;
341
41
  if (TargetTriple.getArch() == Triple::x86_64) {
342
34
    SanCovTraceCmpZeroExtAL =
343
34
        SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
344
34
    SanCovTraceCmpZeroExtAL =
345
34
        SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
346
34
  }
347
41
348
41
  SanCovTraceCmpFunction[0] =
349
41
      M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
350
41
                            IRB.getInt8Ty(), IRB.getInt8Ty());
351
41
  SanCovTraceCmpFunction[1] =
352
41
      M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
353
41
                            IRB.getInt16Ty(), IRB.getInt16Ty());
354
41
  SanCovTraceCmpFunction[2] =
355
41
      M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
356
41
                            IRB.getInt32Ty(), IRB.getInt32Ty());
357
41
  SanCovTraceCmpFunction[3] =
358
41
      M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
359
41
360
41
  SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
361
41
      SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
362
41
  SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
363
41
      SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
364
41
  SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
365
41
      SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
366
41
  SanCovTraceConstCmpFunction[3] =
367
41
      M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
368
41
369
41
  {
370
41
    AttributeList AL;
371
41
    if (TargetTriple.getArch() == Triple::x86_64)
372
34
      AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
373
41
    SanCovTraceDivFunction[0] =
374
41
        M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
375
41
  }
376
41
  SanCovTraceDivFunction[1] =
377
41
      M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
378
41
  SanCovTraceGepFunction =
379
41
      M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
380
41
  SanCovTraceSwitchFunction =
381
41
      M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
382
41
383
41
  Constant *SanCovLowestStackConstant =
384
41
      M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
385
41
  SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
386
41
  if (!SanCovLowestStack) {
387
1
    C->emitError(StringRef("'") + SanCovLowestStackName +
388
1
                 "' should not be declared by the user");
389
1
    return true;
390
1
  }
391
40
  SanCovLowestStack->setThreadLocalMode(
392
40
      GlobalValue::ThreadLocalMode::InitialExecTLSModel);
393
40
  if (Options.StackDepth && 
!SanCovLowestStack->isDeclaration()2
)
394
2
    SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
395
40
396
40
  // We insert an empty inline asm after cov callbacks to avoid callback merge.
397
40
  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
398
40
                            StringRef(""), StringRef(""),
399
40
                            /*hasSideEffects=*/true);
400
40
401
40
  SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
402
40
  SanCovTracePCGuard =
403
40
      M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
404
40
405
40
  for (auto &F : M)
406
711
    runOnFunction(F);
407
40
408
40
  Function *Ctor = nullptr;
409
40
410
40
  if (FunctionGuardArray)
411
26
    Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
412
26
                                      SanCovTracePCGuardInitName, Int32PtrTy,
413
26
                                      SanCovGuardsSectionName);
414
40
  if (Function8bitCounterArray)
415
6
    Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
416
6
                                      SanCov8bitCountersInitName, Int8PtrTy,
417
6
                                      SanCovCountersSectionName);
418
40
  if (Ctor && 
Options.PCTable31
) {
419
5
    auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
420
5
    FunctionCallee InitFunction = declareSanitizerInitFunction(
421
5
        M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
422
5
    IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
423
5
    IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
424
5
  }
425
40
  // We don't reference these arrays directly in any of our runtime functions,
426
40
  // so we need to prevent them from being dead stripped.
427
40
  if (TargetTriple.isOSBinFormatMachO())
428
2
    appendToUsed(M, GlobalsToAppendToUsed);
429
40
  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
430
40
  return true;
431
40
}
432
433
// True if block has successors and it dominates all of them.
434
63
static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
435
63
  if (succ_begin(BB) == succ_end(BB))
436
26
    return false;
437
37
438
42
  
for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB)))37
{
439
42
    if (!DT->dominates(BB, SUCC))
440
31
      return false;
441
42
  }
442
37
443
37
  
return true6
;
444
37
}
445
446
// True if block has predecessors and it postdominates all of them.
447
static bool isFullPostDominator(const BasicBlock *BB,
448
57
                                const PostDominatorTree *PDT) {
449
57
  if (pred_begin(BB) == pred_end(BB))
450
0
    return false;
451
57
452
72
  
for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB)))57
{
453
72
    if (!PDT->dominates(BB, PRED))
454
42
      return false;
455
72
  }
456
57
457
57
  
return true15
;
458
57
}
459
460
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
461
                                  const DominatorTree *DT,
462
                                  const PostDominatorTree *PDT,
463
159
                                  const SanitizerCoverageOptions &Options) {
464
159
  // Don't insert coverage for blocks containing nothing but unreachable: we
465
159
  // will never call __sanitizer_cov() for them, so counting them in
466
159
  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
467
159
  // percentage. Also, unreachable instructions frequently have no debug
468
159
  // locations.
469
159
  if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
470
1
    return false;
471
158
472
158
  // Don't insert coverage into blocks without a valid insertion point
473
158
  // (catchswitch blocks).
474
158
  if (BB->getFirstInsertionPt() == BB->end())
475
1
    return false;
476
157
477
157
  if (Options.NoPrune || 
&F.getEntryBlock() == BB144
)
478
80
    return true;
479
77
480
77
  if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
481
77
      
&F.getEntryBlock() != BB14
)
482
14
    return false;
483
63
484
63
  // Do not instrument full dominators, or full post-dominators with multiple
485
63
  // predecessors.
486
63
  return !isFullDominator(BB, DT)
487
63
    && 
!(57
isFullPostDominator(BB, PDT)57
&&
!BB->getSinglePredecessor()15
);
488
63
}
489
490
491
// Returns true iff From->To is a backedge.
492
// A twist here is that we treat From->To as a backedge if
493
//   * To dominates From or
494
//   * To->UniqueSuccessor dominates From
495
static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
496
2
                       const DominatorTree *DT) {
497
2
  if (DT->dominates(To, From))
498
1
    return true;
499
1
  if (auto Next = To->getUniqueSuccessor())
500
0
    if (DT->dominates(Next, From))
501
0
      return true;
502
1
  return false;
503
1
}
504
505
// Prunes uninteresting Cmp instrumentation:
506
//   * CMP instructions that feed into loop backedge branch.
507
//
508
// Note that Cmp pruning is controlled by the same flag as the
509
// BB pruning.
510
static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
511
13
                             const SanitizerCoverageOptions &Options) {
512
13
  if (!Options.NoPrune)
513
12
    if (CMP->hasOneUse())
514
3
      if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
515
1
        for (BasicBlock *B : BR->successors())
516
2
          if (IsBackEdge(BR->getParent(), B, DT))
517
1
            return false;
518
13
  
return true12
;
519
13
}
520
521
711
bool SanitizerCoverageModule::runOnFunction(Function &F) {
522
711
  if (F.empty())
523
634
    return false;
524
77
  if (F.getName().find(".module_ctor") != std::string::npos)
525
0
    return false; // Should not instrument sanitizer init functions.
526
77
  if (F.getName().startswith("__sanitizer_"))
527
0
    return false;  // Don't instrument __sanitizer_* callbacks.
528
77
  // Don't touch available_externally functions, their actual body is elewhere.
529
77
  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
530
3
    return false;
531
74
  // Don't instrument MSVC CRT configuration helpers. They may run before normal
532
74
  // initialization.
533
74
  if (F.getName() == "__local_stdio_printf_options" ||
534
74
      F.getName() == "__local_stdio_scanf_options")
535
0
    return false;
536
74
  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
537
3
    return false;
538
71
  // Don't instrument functions using SEH for now. Splitting basic blocks like
539
71
  // we do for coverage breaks WinEHPrepare.
540
71
  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
541
71
  if (F.hasPersonalityFn() &&
542
71
      
isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))3
)
543
2
    return false;
544
69
  if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
545
38
    SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
546
69
  SmallVector<Instruction *, 8> IndirCalls;
547
69
  SmallVector<BasicBlock *, 16> BlocksToInstrument;
548
69
  SmallVector<Instruction *, 8> CmpTraceTargets;
549
69
  SmallVector<Instruction *, 8> SwitchTraceTargets;
550
69
  SmallVector<BinaryOperator *, 8> DivTraceTargets;
551
69
  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
552
69
553
69
  const DominatorTree *DT =
554
69
      &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
555
69
  const PostDominatorTree *PDT =
556
69
      &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
557
69
  bool IsLeafFunc = true;
558
69
559
159
  for (auto &BB : F) {
560
159
    if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
561
123
      BlocksToInstrument.push_back(&BB);
562
307
    for (auto &Inst : BB) {
563
307
      if (Options.IndirectCalls) {
564
72
        CallSite CS(&Inst);
565
72
        if (CS && 
!CS.getCalledFunction()9
)
566
9
          IndirCalls.push_back(&Inst);
567
72
      }
568
307
      if (Options.TraceCmp) {
569
50
        if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
570
13
          if (IsInterestingCmp(CMP, DT, Options))
571
12
            CmpTraceTargets.push_back(&Inst);
572
50
        if (isa<SwitchInst>(&Inst))
573
2
          SwitchTraceTargets.push_back(&Inst);
574
50
      }
575
307
      if (Options.TraceDiv)
576
6
        if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
577
3
          if (BO->getOpcode() == Instruction::SDiv ||
578
3
              
BO->getOpcode() == Instruction::UDiv1
)
579
3
            DivTraceTargets.push_back(BO);
580
307
      if (Options.TraceGep)
581
11
        if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
582
3
          GepTraceTargets.push_back(GEP);
583
307
      if (Options.StackDepth)
584
8
        if (isa<InvokeInst>(Inst) ||
585
8
            (isa<CallInst>(Inst) && 
!isa<IntrinsicInst>(Inst)2
))
586
2
          IsLeafFunc = false;
587
307
    }
588
159
  }
589
69
590
69
  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
591
69
  InjectCoverageForIndirectCalls(F, IndirCalls);
592
69
  InjectTraceForCmp(F, CmpTraceTargets);
593
69
  InjectTraceForSwitch(F, SwitchTraceTargets);
594
69
  InjectTraceForDiv(F, DivTraceTargets);
595
69
  InjectTraceForGep(F, GepTraceTargets);
596
69
  return true;
597
69
}
598
599
GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
600
65
    size_t NumElements, Function &F, Type *Ty, const char *Section) {
601
65
  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
602
65
  auto Array = new GlobalVariable(
603
65
      *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
604
65
      Constant::getNullValue(ArrayTy), "__sancov_gen_");
605
65
606
65
  if (TargetTriple.supportsCOMDAT() && 
!F.isInterposable()61
)
607
57
    if (auto Comdat =
608
57
            GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
609
57
      Array->setComdat(Comdat);
610
65
  Array->setSection(getSectionName(Section));
611
65
  Array->setAlignment(Ty->isPointerTy() ? 
DL->getPointerSize()6
612
65
                                        : 
Ty->getPrimitiveSizeInBits() / 859
);
613
65
  GlobalsToAppendToUsed.push_back(Array);
614
65
  GlobalsToAppendToCompilerUsed.push_back(Array);
615
65
  MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
616
65
  Array->addMetadata(LLVMContext::MD_associated, *MD);
617
65
618
65
  return Array;
619
65
}
620
621
GlobalVariable *
622
SanitizerCoverageModule::CreatePCArray(Function &F,
623
6
                                       ArrayRef<BasicBlock *> AllBlocks) {
624
6
  size_t N = AllBlocks.size();
625
6
  assert(N);
626
6
  SmallVector<Constant *, 32> PCs;
627
6
  IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
628
16
  for (size_t i = 0; i < N; 
i++10
) {
629
10
    if (&F.getEntryBlock() == AllBlocks[i]) {
630
6
      PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
631
6
      PCs.push_back((Constant *)IRB.CreateIntToPtr(
632
6
          ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
633
6
    } else {
634
4
      PCs.push_back((Constant *)IRB.CreatePointerCast(
635
4
          BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
636
4
      PCs.push_back((Constant *)IRB.CreateIntToPtr(
637
4
          ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
638
4
    }
639
10
  }
640
6
  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
641
6
                                                    SanCovPCsSectionName);
642
6
  PCArray->setInitializer(
643
6
      ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
644
6
  PCArray->setConstant(true);
645
6
646
6
  return PCArray;
647
6
}
648
649
void SanitizerCoverageModule::CreateFunctionLocalArrays(
650
69
    Function &F, ArrayRef<BasicBlock *> AllBlocks) {
651
69
  if (Options.TracePCGuard)
652
52
    FunctionGuardArray = CreateFunctionLocalArrayInSection(
653
52
        AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
654
69
655
69
  if (Options.Inline8bitCounters)
656
7
    Function8bitCounterArray = CreateFunctionLocalArrayInSection(
657
7
        AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
658
69
659
69
  if (Options.PCTable)
660
6
    FunctionPCsArray = CreatePCArray(F, AllBlocks);
661
69
}
662
663
bool SanitizerCoverageModule::InjectCoverage(Function &F,
664
                                             ArrayRef<BasicBlock *> AllBlocks,
665
69
                                             bool IsLeafFunc) {
666
69
  if (AllBlocks.empty()) 
return false0
;
667
69
  CreateFunctionLocalArrays(F, AllBlocks);
668
192
  for (size_t i = 0, N = AllBlocks.size(); i < N; 
i++123
)
669
123
    InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
670
69
  return true;
671
69
}
672
673
// On every indirect call we call a run-time function
674
// __sanitizer_cov_indir_call* with two parameters:
675
//   - callee address,
676
//   - global cache array that contains CacheSize pointers (zero-initialized).
677
//     The cache is used to speed up recording the caller-callee pairs.
678
// The address of the caller is passed implicitly via caller PC.
679
// CacheSize is encoded in the name of the run-time function.
680
void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
681
69
    Function &F, ArrayRef<Instruction *> IndirCalls) {
682
69
  if (IndirCalls.empty())
683
66
    return;
684
3
  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
685
9
  for (auto I : IndirCalls) {
686
9
    IRBuilder<> IRB(I);
687
9
    CallSite CS(I);
688
9
    Value *Callee = CS.getCalledValue();
689
9
    if (isa<InlineAsm>(Callee))
690
3
      continue;
691
6
    IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
692
6
  }
693
3
}
694
695
// For every switch statement we insert a call:
696
// __sanitizer_cov_trace_switch(CondValue,
697
//      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
698
699
void SanitizerCoverageModule::InjectTraceForSwitch(
700
69
    Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
701
69
  for (auto I : SwitchTraceTargets) {
702
2
    if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
703
2
      IRBuilder<> IRB(I);
704
2
      SmallVector<Constant *, 16> Initializers;
705
2
      Value *Cond = SI->getCondition();
706
2
      if (Cond->getType()->getScalarSizeInBits() >
707
2
          Int64Ty->getScalarSizeInBits())
708
1
        continue;
709
1
      Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
710
1
      Initializers.push_back(
711
1
          ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
712
1
      if (Cond->getType()->getScalarSizeInBits() <
713
1
          Int64Ty->getScalarSizeInBits())
714
1
        Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
715
3
      for (auto It : SI->cases()) {
716
3
        Constant *C = It.getCaseValue();
717
3
        if (C->getType()->getScalarSizeInBits() <
718
3
            Int64Ty->getScalarSizeInBits())
719
3
          C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
720
3
        Initializers.push_back(C);
721
3
      }
722
1
      llvm::sort(Initializers.begin() + 2, Initializers.end(),
723
3
                 [](const Constant *A, const Constant *B) {
724
3
                   return cast<ConstantInt>(A)->getLimitedValue() <
725
3
                          cast<ConstantInt>(B)->getLimitedValue();
726
3
                 });
727
1
      ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
728
1
      GlobalVariable *GV = new GlobalVariable(
729
1
          *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
730
1
          ConstantArray::get(ArrayOfInt64Ty, Initializers),
731
1
          "__sancov_gen_cov_switch_values");
732
1
      IRB.CreateCall(SanCovTraceSwitchFunction,
733
1
                     {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
734
1
    }
735
2
  }
736
69
}
737
738
void SanitizerCoverageModule::InjectTraceForDiv(
739
69
    Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
740
69
  for (auto BO : DivTraceTargets) {
741
3
    IRBuilder<> IRB(BO);
742
3
    Value *A1 = BO->getOperand(1);
743
3
    if (isa<ConstantInt>(A1)) 
continue1
;
744
2
    if (!A1->getType()->isIntegerTy())
745
0
      continue;
746
2
    uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
747
2
    int CallbackIdx = TypeSize == 32 ? 
01
:
748
2
        
TypeSize == 64 1
?
11
:
-10
;
749
2
    if (CallbackIdx < 0) 
continue0
;
750
2
    auto Ty = Type::getIntNTy(*C, TypeSize);
751
2
    IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
752
2
                   {IRB.CreateIntCast(A1, Ty, true)});
753
2
  }
754
69
}
755
756
void SanitizerCoverageModule::InjectTraceForGep(
757
69
    Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
758
69
  for (auto GEP : GepTraceTargets) {
759
3
    IRBuilder<> IRB(GEP);
760
7
    for (auto I = GEP->idx_begin(); I != GEP->idx_end(); 
++I4
)
761
4
      if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
762
3
        IRB.CreateCall(SanCovTraceGepFunction,
763
3
                       {IRB.CreateIntCast(*I, IntptrTy, true)});
764
3
  }
765
69
}
766
767
void SanitizerCoverageModule::InjectTraceForCmp(
768
69
    Function &, ArrayRef<Instruction *> CmpTraceTargets) {
769
69
  for (auto I : CmpTraceTargets) {
770
12
    if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
771
12
      IRBuilder<> IRB(ICMP);
772
12
      Value *A0 = ICMP->getOperand(0);
773
12
      Value *A1 = ICMP->getOperand(1);
774
12
      if (!A0->getType()->isIntegerTy())
775
0
        continue;
776
12
      uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
777
12
      int CallbackIdx = TypeSize == 8 ? 
02
:
778
12
                        
TypeSize == 16 10
?
12
:
779
10
                        
TypeSize == 32 8
?
26
:
780
8
                        
TypeSize == 64 2
?
32
:
-10
;
781
12
      if (CallbackIdx < 0) 
continue0
;
782
12
      // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
783
12
      auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
784
12
      bool FirstIsConst = isa<ConstantInt>(A0);
785
12
      bool SecondIsConst = isa<ConstantInt>(A1);
786
12
      // If both are const, then we don't need such a comparison.
787
12
      if (FirstIsConst && 
SecondIsConst5
)
continue1
;
788
11
      // If only one is const, then make it the first callback argument.
789
11
      if (FirstIsConst || 
SecondIsConst7
) {
790
8
        CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
791
8
        if (SecondIsConst)
792
4
          std::swap(A0, A1);
793
8
      }
794
11
795
11
      auto Ty = Type::getIntNTy(*C, TypeSize);
796
11
      IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
797
11
              IRB.CreateIntCast(A1, Ty, true)});
798
11
    }
799
12
  }
800
69
}
801
802
void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
803
                                                    size_t Idx,
804
123
                                                    bool IsLeafFunc) {
805
123
  BasicBlock::iterator IP = BB.getFirstInsertionPt();
806
123
  bool IsEntryBB = &BB == &F.getEntryBlock();
807
123
  DebugLoc EntryLoc;
808
123
  if (IsEntryBB) {
809
69
    if (auto SP = F.getSubprogram())
810
2
      EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
811
69
    // Keep static allocas and llvm.localescape calls in the entry block.  Even
812
69
    // if we aren't splitting the block, it's nice for allocas to be before
813
69
    // calls.
814
69
    IP = PrepareToSplitEntryBlock(BB, IP);
815
69
  } else {
816
54
    EntryLoc = IP->getDebugLoc();
817
54
  }
818
123
819
123
  IRBuilder<> IRB(&*IP);
820
123
  IRB.SetCurrentDebugLocation(EntryLoc);
821
123
  if (Options.TracePC) {
822
35
    IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
823
35
    IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
824
35
  }
825
123
  if (Options.TracePCGuard) {
826
77
    auto GuardPtr = IRB.CreateIntToPtr(
827
77
        IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
828
77
                      ConstantInt::get(IntptrTy, Idx * 4)),
829
77
        Int32PtrTy);
830
77
    IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
831
77
    IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
832
77
  }
833
123
  if (Options.Inline8bitCounters) {
834
9
    auto CounterPtr = IRB.CreateGEP(
835
9
        Function8bitCounterArray->getValueType(), Function8bitCounterArray,
836
9
        {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
837
9
    auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
838
9
    auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
839
9
    auto Store = IRB.CreateStore(Inc, CounterPtr);
840
9
    SetNoSanitizeMetadata(Load);
841
9
    SetNoSanitizeMetadata(Store);
842
9
  }
843
123
  if (Options.StackDepth && 
IsEntryBB6
&&
!IsLeafFunc6
) {
844
2
    // Check stack depth.  If it's the deepest so far, record it.
845
2
    Module *M = F.getParent();
846
2
    Function *GetFrameAddr = Intrinsic::getDeclaration(
847
2
        M, Intrinsic::frameaddress,
848
2
        IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
849
2
    auto FrameAddrPtr =
850
2
        IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
851
2
    auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
852
2
    auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
853
2
    auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
854
2
    auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
855
2
    IRBuilder<> ThenIRB(ThenTerm);
856
2
    auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
857
2
    SetNoSanitizeMetadata(LowestStack);
858
2
    SetNoSanitizeMetadata(Store);
859
2
  }
860
123
}
861
862
std::string
863
65
SanitizerCoverageModule::getSectionName(const std::string &Section) const {
864
65
  if (TargetTriple.isOSBinFormatCOFF()) {
865
19
    if (Section == SanCovCountersSectionName)
866
4
      return ".SCOV$CM";
867
15
    if (Section == SanCovPCsSectionName)
868
4
      return ".SCOVP$M";
869
11
    return ".SCOV$GM"; // For SanCovGuardsSectionName.
870
11
  }
871
46
  if (TargetTriple.isOSBinFormatMachO())
872
4
    return "__DATA,__" + Section;
873
42
  return "__" + Section;
874
42
}
875
876
std::string
877
37
SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
878
37
  if (TargetTriple.isOSBinFormatMachO())
879
2
    return "\1section$start$__DATA$__" + Section;
880
35
  return "__start___" + Section;
881
35
}
882
883
std::string
884
37
SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
885
37
  if (TargetTriple.isOSBinFormatMachO())
886
2
    return "\1section$end$__DATA$__" + Section;
887
35
  return "__stop___" + Section;
888
35
}
889
890
891
char SanitizerCoverageModule::ID = 0;
892
11.0k
INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
893
11.0k
                      "SanitizerCoverage: TODO."
894
11.0k
                      "ModulePass",
895
11.0k
                      false, false)
896
11.0k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
897
11.0k
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
898
11.0k
INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
899
                    "SanitizerCoverage: TODO."
900
                    "ModulePass",
901
                    false, false)
902
ModulePass *llvm::createSanitizerCoverageModulePass(
903
0
    const SanitizerCoverageOptions &Options) {
904
0
  return new SanitizerCoverageModule(Options);
905
0
}