LLVM 24.0.0git
InstrProfiling.cpp
Go to the documentation of this file.
1//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
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// This pass lowers instrprof_* intrinsics emitted by an instrumentor.
10// It also builds the data structures and initialization code needed for
11// updating execution counts and emitting the profile at runtime.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
23#include "llvm/Analysis/CFG.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CFG.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/CycleInfo.h"
33#include "llvm/IR/DIBuilder.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalAlias.h"
39#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/MDBuilder.h"
48#include "llvm/IR/Module.h"
50#include "llvm/IR/Type.h"
51#include "llvm/Pass.h"
57#include "llvm/Support/Error.h"
65#include <algorithm>
66#include <cassert>
67#include <cstdint>
68#include <string>
69
70using namespace llvm;
71
72#define DEBUG_TYPE "instrprof"
73
74namespace llvm {
75// Command line option to enable vtable value profiling. Defined in
76// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
79 "profile-correlate",
80 cl::desc("Use debug info or binary file to correlate profiles."),
83 "No profile correlation"),
85 "Use debug info to correlate"),
87 "Use binary to correlate")));
88} // namespace llvm
89
90namespace {
91
92cl::opt<bool> DoHashBasedCounterSplit(
93 "hash-based-counter-split",
94 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
95 cl::init(true));
96
98 RuntimeCounterRelocation("runtime-counter-relocation",
99 cl::desc("Enable relocating counters at runtime."),
100 cl::init(false));
101
102cl::opt<bool> ValueProfileStaticAlloc(
103 "vp-static-alloc",
104 cl::desc("Do static counter allocation for value profiler"),
105 cl::init(true));
106
107cl::opt<double> NumCountersPerValueSite(
108 "vp-counters-per-site",
109 cl::desc("The average number of profile counters allocated "
110 "per value profiling site."),
111 // This is set to a very small value because in real programs, only
112 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
113 // For those sites with non-zero profile, the average number of targets
114 // is usually smaller than 2.
115 cl::init(1.0));
116
117cl::opt<bool> AtomicCounterUpdateAll(
118 "instrprof-atomic-counter-update-all",
119 cl::desc("Make all profile counter updates atomic (for testing only)"),
120 cl::init(false));
121
122cl::opt<bool> VerifyAtomicPromotion(
123 "verify-atomic-counter-promoted",
124 cl::desc("Check that all profile counter updates were made atomic; no-op "
125 "if atomic updates are not requested (-fprofile-update=atomic)"),
126 cl::init(false));
127
128cl::opt<bool> AtomicCounterUpdatePromoted(
129 "atomic-counter-update-promoted",
130 cl::desc("Do counter update using atomic fetch add "
131 " for promoted counters only"),
132 cl::init(false));
133
134cl::opt<bool> AtomicFirstCounter(
135 "atomic-first-counter",
136 cl::desc("Use atomic fetch add for first counter in a function (usually "
137 "the entry counter)"),
138 cl::init(false));
139
140cl::opt<bool> ConditionalCounterUpdate(
141 "conditional-counter-update",
142 cl::desc("Do conditional counter updates in single byte counters mode)"),
143 cl::init(false));
144
145// If the option is not specified, the default behavior about whether
146// counter promotion is done depends on how instrumentation lowering
147// pipeline is setup, i.e., the default value of true of this option
148// does not mean the promotion will be done by default. Explicitly
149// setting this option can override the default behavior.
150cl::opt<bool> DoCounterPromotion("do-counter-promotion",
151 cl::desc("Do counter register promotion"),
152 cl::init(false));
153cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
154 "max-counter-promotions-per-loop", cl::init(20),
155 cl::desc("Max number counter promotions per loop to avoid"
156 " increasing register pressure too much"));
157
158// A debug option
160 MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
161 cl::desc("Max number of allowed counter promotions"));
162
163cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
164 "speculative-counter-promotion-max-exiting", cl::init(3),
165 cl::desc("The max number of exiting blocks of a loop to allow "
166 " speculative counter promotion"));
167
168cl::opt<bool> SpeculativeCounterPromotionToLoop(
169 "speculative-counter-promotion-to-loop",
170 cl::desc("When the option is false, if the target block is in a loop, "
171 "the promotion will be disallowed unless the promoted counter "
172 " update can be further/iteratively promoted into an acyclic "
173 " region."));
174
175static cl::opt<unsigned> OffloadPGOSampling(
176 "offload-pgo-sampling",
177 cl::desc("Log2 of the sampling period for offload PGO instrumentation. "
178 "Only 1 in every 2^N blocks is instrumented. "
179 "0 = all blocks, 1 = 50%, 2 = 25%, 3 = 12.5% (default). "
180 "Higher values reduce overhead at the cost of sparser profiles."),
181 cl::init(3));
182
183cl::opt<bool> IterativeCounterPromotion(
184 "iterative-counter-promotion", cl::init(true),
185 cl::desc("Allow counter promotion across the whole loop nest."));
186
187cl::opt<bool> SkipRetExitBlock(
188 "skip-ret-exit-block", cl::init(true),
189 cl::desc("Suppress counter promotion if exit blocks contain ret."));
190
191static cl::opt<bool> SampledInstr("sampled-instrumentation",
192 cl::desc("Do PGO instrumentation sampling"));
193
194static cl::opt<unsigned> SampledInstrPeriod(
195 "sampled-instr-period",
196 cl::desc("Set the profile instrumentation sample period. A sample period "
197 "of 0 is invalid. For each sample period, a fixed number of "
198 "consecutive samples will be recorded. The number is controlled "
199 "by 'sampled-instr-burst-duration' flag. The default sample "
200 "period of 65536 is optimized for generating efficient code that "
201 "leverages unsigned short integer wrapping in overflow, but this "
202 "is disabled under simple sampling (burst duration = 1)."),
203 cl::init(USHRT_MAX + 1));
204
205static cl::opt<unsigned> SampledInstrBurstDuration(
206 "sampled-instr-burst-duration",
207 cl::desc("Set the profile instrumentation burst duration, which can range "
208 "from 1 to the value of 'sampled-instr-period' (0 is invalid). "
209 "This number of samples will be recorded for each "
210 "'sampled-instr-period' count update. Setting to 1 enables simple "
211 "sampling, in which case it is recommended to set "
212 "'sampled-instr-period' to a prime number."),
213 cl::init(200));
214
215struct SampledInstrumentationConfig {
216 unsigned BurstDuration;
217 unsigned Period;
218 bool UseShort;
219 bool IsSimpleSampling;
220 bool IsFastSampling;
221};
222
223static SampledInstrumentationConfig getSampledInstrumentationConfig() {
224 SampledInstrumentationConfig config;
225 config.BurstDuration = SampledInstrBurstDuration.getValue();
226 config.Period = SampledInstrPeriod.getValue();
227 if (config.BurstDuration > config.Period)
229 "SampledBurstDuration must be less than or equal to SampledPeriod");
230 if (config.Period == 0 || config.BurstDuration == 0)
232 "SampledPeriod and SampledBurstDuration must be greater than 0");
233 config.IsSimpleSampling = (config.BurstDuration == 1);
234 // If (BurstDuration == 1 && Period == 65536), generate the simple sampling
235 // style code.
236 config.IsFastSampling =
237 (!config.IsSimpleSampling && config.Period == USHRT_MAX + 1);
238 config.UseShort = (config.Period <= USHRT_MAX) || config.IsFastSampling;
239 return config;
240}
241
242using LoadStorePair = std::pair<Instruction *, Instruction *>;
243
244static void makeAtomic(Instruction *Load, Instruction *Store) {
245 auto *Addition = dyn_cast<BinaryOperator>(Store->getOperand(0));
246 assert(Addition && Addition->getOpcode() == Instruction::BinaryOps::Add);
247 auto *Addend = Addition->getOperand(1);
248
249 IRBuilder<> Builder(Load);
250 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Store->getOperand(1), Addend,
252 Store->eraseFromParent();
253 Addition->eraseFromParent();
254 Load->eraseFromParent();
255}
256
257static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
258 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
259 if (!MD)
260 return 0;
261
262 // If the flag is a ConstantAsMetadata, it should be an integer representable
263 // in 64-bits.
264 return cast<ConstantInt>(MD->getValue())->getZExtValue();
265}
266
267static bool enablesValueProfiling(const Module &M) {
268 return isIRPGOFlagSet(&M) ||
269 getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
270}
271
272// Conservatively returns true if value profiling is enabled.
273static bool profDataReferencedByCode(const Module &M) {
274 return enablesValueProfiling(M);
275}
276
277class InstrLowerer final {
278public:
279 InstrLowerer(Module &M, const InstrProfOptions &Options,
280 std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
281 bool IsCS)
282 : M(M), Options(Options), TT(M.getTargetTriple()), IsCS(IsCS),
283 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
284
285 bool lower();
286
287private:
288 Module &M;
289 const InstrProfOptions Options;
290 const Triple TT;
291 // Is this lowering for the context-sensitive instrumentation.
292 const bool IsCS;
293
294 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
295
296 const bool DataReferencedByCode;
297
298 struct PerFunctionProfileData {
299 uint32_t NumValueSites[IPVK_Last + 1] = {};
300 GlobalVariable *RegionCounters = nullptr;
301 GlobalVariable *UniformCounters =
302 nullptr; // Per-block uniform-entry counters
303 GlobalVariable *DataVar = nullptr;
304 GlobalVariable *RegionBitmaps = nullptr;
305 uint32_t NumBitmapBytes = 0;
306
307 PerFunctionProfileData() = default;
308 };
309 DenseMap<GlobalVariable *, PerFunctionProfileData> ProfileDataMap;
310 // Key is virtual table variable, value is 'VTableProfData' in the form of
311 // GlobalVariable.
312 DenseMap<GlobalVariable *, GlobalVariable *> VTableDataMap;
313 /// If runtime relocation is enabled, this maps functions to the load
314 /// instruction that produces the profile relocation bias.
315 DenseMap<const Function *, LoadInst *> FunctionToProfileBiasMap;
316 std::vector<GlobalValue *> CompilerUsedVars;
317 std::vector<GlobalValue *> UsedVars;
318 std::vector<GlobalVariable *> ReferencedNames;
319 // The list of virtual table variables of which the VTableProfData is
320 // collected.
321 std::vector<GlobalVariable *> ReferencedVTables;
322 GlobalVariable *NamesVar = nullptr;
323 size_t NamesSize = 0;
324
325 StructType *ProfileDataTy = nullptr;
326
327 // vector of counter load/store pairs to be register promoted.
328 std::vector<LoadStorePair> PromotionCandidates;
329
330 int64_t TotalCountersPromoted = 0;
331
332 // Per-function cache of invariant values for GPU PGO instrumentation.
333 // Computed once at the function entry and reused across all instrumentation
334 // points to avoid redundant IR and help the optimizer.
335 struct GPUPGOInvariants {
336 Value *Matched = nullptr;
337 bool WaveSizeStored = false;
338 };
339 DenseMap<Function *, GPUPGOInvariants> GPUInvariantsCache;
340
341 /// Emit invariant PGO values at the function entry block and cache them.
342 GPUPGOInvariants &getOrCreateGPUInvariants(Function *F);
343
344 /// Lower instrumentation intrinsics in the function. Returns true if there
345 /// any lowering.
346 bool lowerIntrinsics(Function *F);
347
348 /// Register-promote counter loads and stores in loops.
349 void promoteCounterLoadStores(Function *F);
350
351 /// Returns true if relocating counters at runtime is enabled.
352 bool isRuntimeCounterRelocationEnabled() const;
353
354 /// Returns true if profile counter update register promotion is enabled.
355 bool isCounterPromotionEnabled() const;
356
357 /// Returns true if profile counter updates should be atomic.
358 bool isAtomic() const;
359
360 /// Return true if profile sampling is enabled.
361 bool isSamplingEnabled() const;
362
363 /// Count the number of instrumented value sites for the function.
364 void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
365
366 /// Replace instrprof.value.profile with a call to runtime library.
367 void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
368
369 /// Replace instrprof.cover with a store instruction to the coverage byte.
370 void lowerCover(InstrProfCoverInst *Inc);
371
372 /// Replace instrprof.timestamp with a call to
373 /// INSTR_PROF_PROFILE_SET_TIMESTAMP.
374 void lowerTimestamp(InstrProfTimestampInst *TimestampInstruction);
375
376 /// Replace instrprof.increment with an increment of the appropriate value.
377 void lowerIncrement(InstrProfIncrementInst *Inc);
378
379 /// Force emitting of name vars for unused functions.
380 void lowerCoverageData(GlobalVariable *CoverageNamesVar);
381
382 /// Replace instrprof.mcdc.tvbitmask.update with a shift and or instruction
383 /// using the index represented by the a temp value into a bitmap.
384 void lowerMCDCTestVectorBitmapUpdate(InstrProfMCDCTVBitmapUpdate *Ins);
385
386 /// Get the Bias value for data to access mmap-ed area.
387 /// Create it if it hasn't been seen.
388 GlobalVariable *getOrCreateBiasVar(StringRef VarName);
389
390 /// Compute the address of the counter value that this profiling instruction
391 /// acts on.
392 Value *getCounterAddress(InstrProfCntrInstBase *I);
393
394 /// Lower the incremental instructions under profile sampling predicates.
395 void doSampling(Instruction *I);
396
397 /// Get the region counters for an increment, creating them if necessary.
398 ///
399 /// If the counter array doesn't yet exist, the profile data variables
400 /// referring to them will also be created.
401 GlobalVariable *getOrCreateRegionCounters(InstrProfCntrInstBase *Inc);
402
403 /// Get the uniform entry counters for GPU divergence tracking.
404 /// These counters track how often blocks are entered with all lanes active.
405 GlobalVariable *getOrCreateUniformCounters(InstrProfCntrInstBase *Inc);
406
407 /// Create the region counters.
408 GlobalVariable *createRegionCounters(InstrProfCntrInstBase *Inc,
409 StringRef Name,
411
412 /// Compute the address of the test vector bitmap that this profiling
413 /// instruction acts on.
414 Value *getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I);
415
416 /// Get the region bitmaps for an increment, creating them if necessary.
417 ///
418 /// If the bitmap array doesn't yet exist, the profile data variables
419 /// referring to them will also be created.
420 GlobalVariable *getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc);
421
422 /// Create the MC/DC bitmap as a byte-aligned array of bytes associated with
423 /// an MC/DC Decision region. The number of bytes required is indicated by
424 /// the intrinsic used (type InstrProfMCDCBitmapInstBase). This is called
425 /// as part of setupProfileSection() and is conceptually very similar to
426 /// what is done for profile data counters in createRegionCounters().
427 GlobalVariable *createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
428 StringRef Name,
430
431 /// Set Comdat property of GV, if required.
432 void maybeSetComdat(GlobalVariable *GV, GlobalObject *GO, StringRef VarName);
433
434 /// Setup the sections into which counters and bitmaps are allocated.
435 GlobalVariable *setupProfileSection(InstrProfInstBase *Inc,
436 InstrProfSectKind IPSK);
437
438 /// Create INSTR_PROF_DATA variable for counters and bitmaps.
439 void createDataVariable(InstrProfCntrInstBase *Inc);
440
441 /// Get the counters for virtual table values, creating them if necessary.
442 void getOrCreateVTableProfData(GlobalVariable *GV);
443
444 /// Emit the section with compressed function names.
445 void emitNameData();
446
447 /// Emit the section with compressed vtable names.
448 void emitVTableNames();
449
450 /// Emit value nodes section for value profiling.
451 void emitVNodes();
452
453 /// Emit runtime registration functions for each profile data variable.
454 void emitRegistration();
455
456 /// Emit the necessary plumbing to pull in the runtime initialization.
457 /// Returns true if a change was made.
458 bool emitRuntimeHook();
459
460 /// Add uses of our data variables and runtime hook.
461 void emitUses();
462
463 /// Create a static initializer for our data, on platforms that need it,
464 /// and for any profile output file that was specified.
465 void emitInitialization();
466
467 /// Return the __llvm_profile_data struct type.
468 StructType *getProfileDataTy();
469};
470
471///
472/// A helper class to promote one counter RMW operation in the loop
473/// into register update.
474///
475/// RWM update for the counter will be sinked out of the loop after
476/// the transformation.
477///
478class PGOCounterPromoterHelper : public LoadAndStorePromoter {
479public:
480 PGOCounterPromoterHelper(
481 Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
482 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
483 ArrayRef<Instruction *> InsertPts,
484 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
485 LoopInfo &LI, bool IsAtomic)
486 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
487 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI),
488 IsAtomic(IsAtomic) {
491 SSA.AddAvailableValue(PH, Init);
492 }
493
494 void doExtraRewritesBeforeFinalDeletion() override {
495 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
496 BasicBlock *ExitBlock = ExitBlocks[i];
497 Instruction *InsertPos = InsertPts[i];
498 // Get LiveIn value into the ExitBlock. If there are multiple
499 // predecessors, the value is defined by a PHI node in this
500 // block.
501 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
502 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
503 Type *Ty = LiveInValue->getType();
504 IRBuilder<> Builder(InsertPos);
505 if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
506 // If isRuntimeCounterRelocationEnabled() is true then the address of
507 // the store instruction is computed with two instructions in
508 // InstrProfiling::getCounterAddress(). We need to copy those
509 // instructions to this block to compute Addr correctly.
510 // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
511 // %Addr = inttoptr i64 %BiasAdd to i64*
512 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
513 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
514 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
515 Addr = Builder.CreateIntToPtr(BiasInst,
516 PointerType::getUnqual(Ty->getContext()));
517 }
518 auto *TargetLoop =
519 IterativeCounterPromotion ? LI.getLoopFor(ExitBlock) : nullptr;
520 // Generate the relaxed atomic RMW if we've asked for it and no more
521 // promotion is possible.
522 if ((IsAtomic && !TargetLoop) || AtomicCounterUpdatePromoted)
523 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
524 MaybeAlign(), AtomicOrdering::Monotonic);
525 else {
526 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
527 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
528 auto *NewStore = Builder.CreateStore(NewVal, Addr);
529
530 // Now update the parent loop's candidate list:
531 if (TargetLoop)
532 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
533 }
534 }
535 }
536
537private:
538 Instruction *Store;
539 ArrayRef<BasicBlock *> ExitBlocks;
540 ArrayRef<Instruction *> InsertPts;
541 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
542 LoopInfo &LI;
543 const bool IsAtomic;
544};
545
546/// A helper class to do register promotion for all profile counter
547/// updates in a loop.
548///
549class PGOCounterPromoter {
550public:
551 PGOCounterPromoter(
552 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
553 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI, bool IsAtomic)
554 : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI),
555 IsAtomic(IsAtomic) {
556
557 // Skip collection of ExitBlocks and InsertPts for loops that will not be
558 // able to have counters promoted.
559 SmallVector<BasicBlock *, 8> LoopExitBlocks;
560 SmallPtrSet<BasicBlock *, 8> BlockSet;
561
562 L.getExitBlocks(LoopExitBlocks);
563 if (!isPromotionPossible(&L, LoopExitBlocks))
564 return;
565
566 for (BasicBlock *ExitBlock : LoopExitBlocks) {
567 if (BlockSet.insert(ExitBlock).second &&
568 llvm::none_of(predecessors(ExitBlock), [&](const BasicBlock *Pred) {
569 return llvm::isPresplitCoroSuspendExitEdge(*Pred, *ExitBlock);
570 })) {
571 ExitBlocks.push_back(ExitBlock);
572 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
573 }
574 }
575 }
576
577 bool run(int64_t *NumPromoted) {
578 bool RC = promoteCandidates(NumPromoted);
579 // In certain case, e.g. with -fprofile-update=atomic, we want to generate
580 // atomic updates of the PGO counters, but also perform promotion of these
581 // updates out of loops to reduce train time. The strategy is:
582 // 1) generate non-atomic load-increment-store sequence of instructions
583 // during lowerIntrinsics phase,
584 // 2) perform the promotion (in promoteCandidates function), then
585 // 3) convert all (promoted and unpromotable) updates to atomicRMW.
586 // This requires that promoted candidates are set to nullptr in the
587 // LoopToCandidates[&L] array by the promoteCandidates() function.
588 if (IsAtomic)
589 for (auto &Cand : LoopToCandidates[&L])
590 if (Cand.first != nullptr && Cand.second != nullptr)
591 makeAtomic(Cand.first, Cand.second);
592 return RC;
593 }
594
595private:
596 bool promoteCandidates(int64_t *NumPromoted) {
597 // Skip 'infinite' loops:
598 if (ExitBlocks.size() == 0)
599 return false;
600
601 // Skip if any of the ExitBlocks contains a ret instruction.
602 // This is to prevent dumping of incomplete profile -- if the
603 // the loop is a long running loop and dump is called in the middle
604 // of the loop, the result profile is incomplete.
605 // FIXME: add other heuristics to detect long running loops.
606 if (SkipRetExitBlock) {
607 for (auto *BB : ExitBlocks)
608 if (isa<ReturnInst>(BB->getTerminator()))
609 return false;
610 }
611
612 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
613 if (MaxProm == 0)
614 return false;
615
616 [[maybe_unused]] auto *Ptr = LoopToCandidates.getPointerIntoBucketsArray();
617 unsigned Promoted = 0;
618 for (auto &Cand : LoopToCandidates[&L]) {
620 SSAUpdater SSA(&NewPHIs);
621 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
622
623 // If BFI is set, we will use it to guide the promotions.
624 if (BFI) {
625 auto *BB = Cand.first->getParent();
626 auto InstrCount = BFI->getBlockProfileCount(BB);
627 if (!InstrCount)
628 continue;
629 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
630 // If the average loop trip count is not greater than 1.5, we skip
631 // promotion.
632 if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
633 continue;
634 }
635
636 PGOCounterPromoterHelper Promoter(
637 Cand.first, Cand.second, SSA, InitVal, L.getLoopPreheader(),
638 ExitBlocks, InsertPts, LoopToCandidates, LI, IsAtomic);
639 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
640
641 assert(LoopToCandidates.isPointerIntoBucketsArray(Ptr) &&
642 "References into LoopToCandidates might be invalid");
643 Cand = {nullptr, nullptr};
644
645 Promoted++;
646 if (Promoted >= MaxProm)
647 break;
648
649 (*NumPromoted)++;
650 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
651 break;
652 }
653
654 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
655 << L.getLoopDepth() << ")\n");
656 return Promoted != 0;
657 }
658
659private:
660 bool allowSpeculativeCounterPromotion(Loop *LP) {
661 SmallVector<BasicBlock *, 8> ExitingBlocks;
662 L.getExitingBlocks(ExitingBlocks);
663 // Not considierered speculative.
664 if (ExitingBlocks.size() == 1)
665 return true;
666 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
667 return false;
668 return true;
669 }
670
671 // Check whether the loop satisfies the basic conditions needed to perform
672 // Counter Promotions.
673 bool
674 isPromotionPossible(Loop *LP,
675 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
676 // We can't insert into a catchswitch.
677 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
678 return isa<CatchSwitchInst>(Exit->getTerminator());
679 }))
680 return false;
681
682 if (!LP->hasDedicatedExits())
683 return false;
684
685 BasicBlock *PH = LP->getLoopPreheader();
686 if (!PH)
687 return false;
688
689 return true;
690 }
691
692 // Returns the max number of Counter Promotions for LP.
693 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
694 SmallVector<BasicBlock *, 8> LoopExitBlocks;
695 LP->getExitBlocks(LoopExitBlocks);
696 if (!isPromotionPossible(LP, LoopExitBlocks))
697 return 0;
698
699 SmallVector<BasicBlock *, 8> ExitingBlocks;
700 LP->getExitingBlocks(ExitingBlocks);
701
702 // If BFI is set, we do more aggressive promotions based on BFI.
703 if (BFI)
704 return (unsigned)-1;
705
706 // Not considierered speculative.
707 if (ExitingBlocks.size() == 1)
708 return MaxNumOfPromotionsPerLoop;
709
710 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
711 return 0;
712
713 // Whether the target block is in a loop does not matter:
714 if (SpeculativeCounterPromotionToLoop)
715 return MaxNumOfPromotionsPerLoop;
716
717 // Now check the target block:
718 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
719 for (auto *TargetBlock : LoopExitBlocks) {
720 auto *TargetLoop = LI.getLoopFor(TargetBlock);
721 if (!TargetLoop)
722 continue;
723 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
724 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
725 MaxProm =
726 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
727 PendingCandsInTarget);
728 }
729 return MaxProm;
730 }
731
732 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
733 SmallVector<BasicBlock *, 8> ExitBlocks;
734 SmallVector<Instruction *, 8> InsertPts;
735 Loop &L;
736 LoopInfo &LI;
737 BlockFrequencyInfo *BFI;
738 const bool IsAtomic; // Whether to convert counter updates to atomics.
739};
740
741enum class ValueProfilingCallType {
742 // Individual values are tracked. Currently used for indiret call target
743 // profiling.
744 Default,
745
746 // MemOp: the memop size value profiling.
747 MemOp
748};
749
750} // end anonymous namespace
751
756 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
757 return FAM.getResult<TargetLibraryAnalysis>(F);
758 };
759 InstrLowerer Lowerer(M, Options, GetTLI, IsCS);
760 if (!Lowerer.lower())
761 return PreservedAnalyses::all();
762
764}
765
766//
767// Perform instrumentation sampling.
768//
769// There are 3 favors of sampling:
770// (1) Full burst sampling: We transform:
771// Increment_Instruction;
772// to:
773// if (__llvm_profile_sampling__ <= SampledInstrBurstDuration - 1) {
774// Increment_Instruction;
775// }
776// __llvm_profile_sampling__ += 1;
777// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
778// __llvm_profile_sampling__ = 0;
779// }
780//
781// "__llvm_profile_sampling__" is a thread-local global shared by all PGO
782// counters (value-instrumentation and edge instrumentation).
783//
784// (2) Fast burst sampling:
785// "__llvm_profile_sampling__" variable is an unsigned type, meaning it will
786// wrap around to zero when overflows. In this case, the second check is
787// unnecessary, so we won't generate check2 when the SampledInstrPeriod is
788// set to 65536 (64K). The code after:
789// if (__llvm_profile_sampling__ <= SampledInstrBurstDuration - 1) {
790// Increment_Instruction;
791// }
792// __llvm_profile_sampling__ += 1;
793//
794// (3) Simple sampling:
795// When SampledInstrBurstDuration is set to 1, we do a simple sampling:
796// __llvm_profile_sampling__ += 1;
797// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
798// __llvm_profile_sampling__ = 0;
799// Increment_Instruction;
800// }
801//
802// Note that, the code snippet after the transformation can still be counter
803// promoted. However, with sampling enabled, counter updates are expected to
804// be infrequent, making the benefits of counter promotion negligible.
805// Moreover, counter promotion can potentially cause issues in server
806// applications, particularly when the counters are dumped without a clean
807// exit. To mitigate this risk, counter promotion is disabled by default when
808// sampling is enabled. This behavior can be overridden using the internal
809// option.
810void InstrLowerer::doSampling(Instruction *I) {
811 if (!isSamplingEnabled())
812 return;
813
814 SampledInstrumentationConfig config = getSampledInstrumentationConfig();
815 auto GetConstant = [&config](IRBuilder<> &Builder, uint32_t C) {
816 if (config.UseShort)
817 return Builder.getInt16(C);
818 else
819 return Builder.getInt32(C);
820 };
821
822 IntegerType *SamplingVarTy;
823 if (config.UseShort)
824 SamplingVarTy = Type::getInt16Ty(M.getContext());
825 else
826 SamplingVarTy = Type::getInt32Ty(M.getContext());
827 auto *SamplingVar =
829 assert(SamplingVar && "SamplingVar not set properly");
830
831 // Create the condition for checking the burst duration.
832 Instruction *SamplingVarIncr;
833 Value *NewSamplingVarVal;
834 MDBuilder MDB(I->getContext());
835 MDNode *BranchWeight;
836 IRBuilder<> CondBuilder(I);
837 auto *LoadSamplingVar = CondBuilder.CreateLoad(SamplingVarTy, SamplingVar);
838 if (config.IsSimpleSampling) {
839 // For the simple sampling, just create the load and increments.
840 IRBuilder<> IncBuilder(I);
841 NewSamplingVarVal =
842 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
843 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
844 } else {
845 // For the burst-sampling, create the conditional update.
846 auto *DurationCond = CondBuilder.CreateICmpULE(
847 LoadSamplingVar, GetConstant(CondBuilder, config.BurstDuration - 1));
848 BranchWeight = MDB.createBranchWeights(
849 config.BurstDuration, config.Period - config.BurstDuration);
851 DurationCond, I, /* Unreachable */ false, BranchWeight);
852 IRBuilder<> IncBuilder(I);
853 NewSamplingVarVal =
854 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
855 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
856 I->moveBefore(ThenTerm->getIterator());
857 }
858
859 if (config.IsFastSampling)
860 return;
861
862 // Create the condition for checking the period.
863 Instruction *ThenTerm, *ElseTerm;
864 IRBuilder<> PeriodCondBuilder(SamplingVarIncr);
865 auto *PeriodCond = PeriodCondBuilder.CreateICmpUGE(
866 NewSamplingVarVal, GetConstant(PeriodCondBuilder, config.Period));
867 BranchWeight = MDB.createBranchWeights(1, config.Period - 1);
868 SplitBlockAndInsertIfThenElse(PeriodCond, SamplingVarIncr, &ThenTerm,
869 &ElseTerm, BranchWeight);
870
871 // For the simple sampling, the counter update happens in sampling var reset.
872 if (config.IsSimpleSampling)
873 I->moveBefore(ThenTerm->getIterator());
874
875 IRBuilder<> ResetBuilder(ThenTerm);
876 ResetBuilder.CreateStore(GetConstant(ResetBuilder, 0), SamplingVar);
877 SamplingVarIncr->moveBefore(ElseTerm->getIterator());
878}
879
880bool InstrLowerer::lowerIntrinsics(Function *F) {
881 bool MadeChange = false;
882 PromotionCandidates.clear();
884
885 // To ensure compatibility with sampling, we save the intrinsics into
886 // a buffer to prevent potential breakage of the iterator (as the
887 // intrinsics will be moved to a different BB).
888 for (BasicBlock &BB : *F) {
889 for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
890 if (auto *IP = dyn_cast<InstrProfInstBase>(&Instr))
891 InstrProfInsts.push_back(IP);
892 }
893 }
894
895 for (auto *Instr : InstrProfInsts) {
896 doSampling(Instr);
897 if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(Instr)) {
898 lowerIncrement(IPIS);
899 MadeChange = true;
900 } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(Instr)) {
901 lowerIncrement(IPI);
902 MadeChange = true;
903 } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(Instr)) {
904 lowerTimestamp(IPC);
905 MadeChange = true;
906 } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(Instr)) {
907 lowerCover(IPC);
908 MadeChange = true;
909 } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(Instr)) {
910 lowerValueProfileInst(IPVP);
911 MadeChange = true;
912 } else if (auto *IPMP = dyn_cast<InstrProfMCDCBitmapParameters>(Instr)) {
913 IPMP->eraseFromParent();
914 MadeChange = true;
915 } else if (auto *IPBU = dyn_cast<InstrProfMCDCTVBitmapUpdate>(Instr)) {
916 lowerMCDCTestVectorBitmapUpdate(IPBU);
917 MadeChange = true;
918 }
919 }
920
921 if (!MadeChange)
922 return false;
923
924 promoteCounterLoadStores(F);
925 return true;
926}
927
928bool InstrLowerer::isRuntimeCounterRelocationEnabled() const {
929 // Mach-O don't support weak external references.
930 if (TT.isOSBinFormatMachO())
931 return false;
932
933 if (RuntimeCounterRelocation.getNumOccurrences() > 0)
934 return RuntimeCounterRelocation;
935
936 // Fuchsia uses runtime counter relocation by default.
937 return TT.isOSFuchsia();
938}
939
940bool InstrLowerer::isSamplingEnabled() const {
941 if (SampledInstr.getNumOccurrences() > 0)
942 return SampledInstr;
943 return Options.Sampling;
944}
945
946bool InstrLowerer::isCounterPromotionEnabled() const {
947 if (DoCounterPromotion.getNumOccurrences() > 0)
948 return DoCounterPromotion;
949 return Options.DoCounterPromotion;
950}
951
952bool InstrLowerer::isAtomic() const {
953 return Options.Atomic || AtomicCounterUpdateAll;
954}
955
956static void doAtomicCheck(Function *F) {
957 for (const llvm::Instruction &I : llvm::instructions(F)) {
958 const Value *Addr = nullptr;
959 if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
960 Addr = LI->getOperand(0);
961 else if (const StoreInst *LI = dyn_cast<StoreInst>(&I))
962 Addr = LI->getOperand(1);
963
964 if (Addr && Addr->stripInBoundsOffsets()->getName().starts_with(
966 LLVM_DEBUG(dbgs() << "Missed candidate: "; I.dump());
967 report_fatal_error("Candidate load/store not converted to atomic");
968 }
969 }
970}
971
972void InstrLowerer::promoteCounterLoadStores(Function *F) {
973 if (!isCounterPromotionEnabled())
974 return;
975
976 DominatorTree DT(*F);
977 CycleInfo CI;
978 CI.compute(*F);
979 LoopInfo LI(DT);
980 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
981
982 std::unique_ptr<BlockFrequencyInfo> BFI;
983 if (Options.UseBFIInPromotion) {
984 std::unique_ptr<BranchProbabilityInfo> BPI;
985 BPI.reset(new BranchProbabilityInfo(*F, CI, &GetTLI(*F)));
986 BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
987 }
988
989 for (const auto &LoadStore : PromotionCandidates) {
990 auto *CounterLoad = LoadStore.first;
991 auto *CounterStore = LoadStore.second;
992 BasicBlock *BB = CounterLoad->getParent();
993 Loop *ParentLoop = LI.getLoopFor(BB);
994 if (!ParentLoop) {
995 if (isAtomic())
996 makeAtomic(CounterLoad, CounterStore);
997 continue;
998 }
999 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
1000 }
1001
1003
1004 // Do a post-order traversal of the loops so that counter updates can be
1005 // iteratively hoisted outside the loop nest.
1006 for (auto *Loop : llvm::reverse(Loops)) {
1007 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get(),
1008 isAtomic());
1009 Promoter.run(&TotalCountersPromoted);
1010 }
1011
1012 if (isAtomic() && VerifyAtomicPromotion)
1014}
1015
1017 // On Fuchsia, we only need runtime hook if any counters are present.
1018 if (TT.isOSFuchsia())
1019 return false;
1020
1021 return true;
1022}
1023
1024/// Check if the module contains uses of any profiling intrinsics.
1026 auto containsIntrinsic = [&](int ID) {
1027 if (auto *F = Intrinsic::getDeclarationIfExists(&M, ID))
1028 return !F->use_empty();
1029 return false;
1030 };
1031 return containsIntrinsic(Intrinsic::instrprof_cover) ||
1032 containsIntrinsic(Intrinsic::instrprof_increment) ||
1033 containsIntrinsic(Intrinsic::instrprof_increment_step) ||
1034 containsIntrinsic(Intrinsic::instrprof_timestamp) ||
1035 containsIntrinsic(Intrinsic::instrprof_value_profile);
1036}
1037
1038bool InstrLowerer::lower() {
1039 bool MadeChange = false;
1040 bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
1041 if (NeedsRuntimeHook)
1042 MadeChange = emitRuntimeHook();
1043
1044 if (!IsCS && isSamplingEnabled())
1046
1047 bool ContainsProfiling = containsProfilingIntrinsics(M);
1048 GlobalVariable *CoverageNamesVar =
1049 M.getNamedGlobal(getCoverageUnusedNamesVarName());
1050 // Improve compile time by avoiding linear scans when there is no work.
1051 if (!ContainsProfiling && !CoverageNamesVar)
1052 return MadeChange;
1053
1054 // We did not know how many value sites there would be inside
1055 // the instrumented function. This is counting the number of instrumented
1056 // target value sites to enter it as field in the profile data variable.
1057 for (Function &F : M) {
1058 InstrProfCntrInstBase *FirstProfInst = nullptr;
1059 for (BasicBlock &BB : F) {
1060 for (auto I = BB.begin(), E = BB.end(); I != E; I++) {
1061 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
1062 computeNumValueSiteCounts(Ind);
1063 else {
1064 if (FirstProfInst == nullptr &&
1066 FirstProfInst = dyn_cast<InstrProfCntrInstBase>(I);
1067 // If the MCDCBitmapParameters intrinsic seen, create the bitmaps.
1068 if (const auto &Params = dyn_cast<InstrProfMCDCBitmapParameters>(I))
1069 static_cast<void>(getOrCreateRegionBitmaps(Params));
1070 }
1071 }
1072 }
1073
1074 // Use a profile intrinsic to create the region counters and data variable.
1075 // Also create the data variable based on the MCDCParams.
1076 if (FirstProfInst != nullptr) {
1077 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
1078 }
1079 }
1080
1082 for (GlobalVariable &GV : M.globals())
1083 // Global variables with type metadata are virtual table variables.
1084 if (GV.hasMetadata(LLVMContext::MD_type))
1085 getOrCreateVTableProfData(&GV);
1086
1087 for (Function &F : M)
1088 MadeChange |= lowerIntrinsics(&F);
1089
1090 if (CoverageNamesVar) {
1091 lowerCoverageData(CoverageNamesVar);
1092 MadeChange = true;
1093 }
1094
1095 if (!MadeChange)
1096 return false;
1097
1098 emitVNodes();
1099 emitNameData();
1100 emitVTableNames();
1101
1102 // Emit runtime hook for the cases where the target does not unconditionally
1103 // require pulling in profile runtime, and coverage is enabled on code that is
1104 // not eliminated by the front-end, e.g. unused functions with internal
1105 // linkage.
1106 if (!NeedsRuntimeHook && ContainsProfiling)
1107 emitRuntimeHook();
1108
1109 emitRegistration();
1110 emitUses();
1111 emitInitialization();
1112 return true;
1113}
1114
1116 Module &M, const TargetLibraryInfo &TLI,
1117 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
1118 LLVMContext &Ctx = M.getContext();
1119 auto *ReturnTy = Type::getVoidTy(M.getContext());
1120
1121 AttributeList AL;
1122 if (auto AK = TLI.getExtAttrForI32Param(false))
1123 AL = AL.addParamAttribute(M.getContext(), 2, AK);
1124
1125 assert((CallType == ValueProfilingCallType::Default ||
1126 CallType == ValueProfilingCallType::MemOp) &&
1127 "Must be Default or MemOp");
1128 Type *ParamTypes[] = {
1129#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
1131 };
1132 auto *ValueProfilingCallTy =
1133 FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
1134 StringRef FuncName = CallType == ValueProfilingCallType::Default
1137 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
1138}
1139
1140void InstrLowerer::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
1141 GlobalVariable *Name = Ind->getName();
1142 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
1143 uint64_t Index = Ind->getIndex()->getZExtValue();
1144 auto &PD = ProfileDataMap[Name];
1145 PD.NumValueSites[ValueKind] =
1146 std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
1147}
1148
1149void InstrLowerer::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
1150 // TODO: Value profiling heavily depends on the data section which is omitted
1151 // in lightweight mode. We need to move the value profile pointer to the
1152 // Counter struct to get this working.
1153 assert(
1155 "Value profiling is not yet supported with lightweight instrumentation");
1156 GlobalVariable *Name = Ind->getName();
1157 auto It = ProfileDataMap.find(Name);
1158 assert(It != ProfileDataMap.end() && It->second.DataVar &&
1159 "value profiling detected in function with no counter increment");
1160
1161 GlobalVariable *DataVar = It->second.DataVar;
1162 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
1163 uint64_t Index = Ind->getIndex()->getZExtValue();
1164 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
1165 Index += It->second.NumValueSites[Kind];
1166
1167 IRBuilder<> Builder(Ind);
1168 bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
1169 llvm::InstrProfValueKind::IPVK_MemOPSize);
1170 CallInst *Call = nullptr;
1171 auto *TLI = &GetTLI(*Ind->getFunction());
1172 auto *NormalizedDataVarPtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1173 DataVar, PointerType::get(M.getContext(), 0));
1174
1175 // To support value profiling calls within Windows exception handlers, funclet
1176 // information contained within operand bundles needs to be copied over to
1177 // the library call. This is required for the IR to be processed by the
1178 // WinEHPrepare pass.
1180 Ind->getOperandBundlesAsDefs(OpBundles);
1181 if (!IsMemOpSize) {
1182 Value *Args[3] = {Ind->getTargetValue(), NormalizedDataVarPtr,
1183 Builder.getInt32(Index)};
1184 Call = Builder.CreateCall(getOrInsertValueProfilingCall(M, *TLI), Args,
1185 OpBundles);
1186 } else {
1187 Value *Args[3] = {Ind->getTargetValue(), NormalizedDataVarPtr,
1188 Builder.getInt32(Index)};
1189 Call = Builder.CreateCall(
1190 getOrInsertValueProfilingCall(M, *TLI, ValueProfilingCallType::MemOp),
1191 Args, OpBundles);
1192 }
1193 if (auto AK = TLI->getExtAttrForI32Param(false))
1194 Call->addParamAttr(2, AK);
1196 Ind->eraseFromParent();
1197}
1198
1199GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
1200 GlobalVariable *Bias = M.getGlobalVariable(VarName);
1201 if (Bias)
1202 return Bias;
1203
1204 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1205
1206 // Compiler must define this variable when runtime counter relocation
1207 // is being used. Runtime has a weak external reference that is used
1208 // to check whether that's the case or not.
1209 Bias = new GlobalVariable(M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
1210 Constant::getNullValue(Int64Ty), VarName);
1212 // A definition that's weak (linkonce_odr) without being in a COMDAT
1213 // section wouldn't lead to link errors, but it would lead to a dead
1214 // data word from every TU but one. Putting it in COMDAT ensures there
1215 // will be exactly one data slot in the link.
1216 if (TT.supportsCOMDAT())
1217 Bias->setComdat(M.getOrInsertComdat(VarName));
1218
1219 return Bias;
1220}
1221
1222Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
1223 auto *Counters = getOrCreateRegionCounters(I);
1224 IRBuilder<> Builder(I);
1225
1227 Counters->setAlignment(Align(8));
1228
1229 auto *Addr = Builder.CreateConstInBoundsGEP2_32(
1230 Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
1231
1232 if (!isRuntimeCounterRelocationEnabled())
1233 return Addr;
1234
1235 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1236 Function *Fn = I->getParent()->getParent();
1237 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
1238 if (!BiasLI) {
1239 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1240 auto *Bias = getOrCreateBiasVar(getInstrProfCounterBiasVarName());
1241 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profc_bias");
1242 // Bias doesn't change after startup.
1243 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1244 MDNode::get(M.getContext(), {}));
1245 }
1246 auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
1247 return Builder.CreateIntToPtr(Add, Addr->getType());
1248}
1249
1250Value *InstrLowerer::getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I) {
1251 auto *Bitmaps = getOrCreateRegionBitmaps(I);
1252 if (!isRuntimeCounterRelocationEnabled())
1253 return Bitmaps;
1254
1255 // Put BiasLI onto the entry block.
1256 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1257 Function *Fn = I->getFunction();
1258 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1259 auto *Bias = getOrCreateBiasVar(getInstrProfBitmapBiasVarName());
1260 auto *BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profbm_bias");
1261 // Assume BiasLI invariant (in the function at least)
1262 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1263 MDNode::get(M.getContext(), {}));
1264
1265 // Add Bias to Bitmaps and put it before the intrinsic.
1266 IRBuilder<> Builder(I);
1267 return Builder.CreatePtrAdd(Bitmaps, BiasLI, "profbm_addr");
1268}
1269
1270void InstrLowerer::lowerCover(InstrProfCoverInst *CoverInstruction) {
1271 auto *Addr = getCounterAddress(CoverInstruction);
1272 IRBuilder<> Builder(CoverInstruction);
1273 if (ConditionalCounterUpdate) {
1274 Instruction *SplitBefore = CoverInstruction->getNextNode();
1275 auto &Ctx = CoverInstruction->getParent()->getContext();
1276 auto *Int8Ty = llvm::Type::getInt8Ty(Ctx);
1277 Value *Load = Builder.CreateLoad(Int8Ty, Addr, "pgocount");
1278 Value *Cmp = Builder.CreateIsNotNull(Load, "pgocount.ifnonzero");
1279 Instruction *ThenBranch =
1280 SplitBlockAndInsertIfThen(Cmp, SplitBefore, false);
1281 Builder.SetInsertPoint(ThenBranch);
1282 }
1283
1284 // We store zero to represent that this block is covered.
1285 Builder.CreateStore(Builder.getInt8(0), Addr);
1286 CoverInstruction->eraseFromParent();
1287}
1288
1289void InstrLowerer::lowerTimestamp(
1290 InstrProfTimestampInst *TimestampInstruction) {
1291 assert(TimestampInstruction->getIndex()->isNullValue() &&
1292 "timestamp probes are always the first probe for a function");
1293 auto &Ctx = M.getContext();
1294 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1295 IRBuilder<> Builder(TimestampInstruction);
1296 auto *CalleeTy =
1297 FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
1298 auto Callee = M.getOrInsertFunction(
1300 Builder.CreateCall(Callee, {TimestampAddr});
1301 TimestampInstruction->eraseFromParent();
1302}
1303
1304InstrLowerer::GPUPGOInvariants &
1305InstrLowerer::getOrCreateGPUInvariants(Function *F) {
1306 auto It = GPUInvariantsCache.find(F);
1307 if (It != GPUInvariantsCache.end())
1308 return It->second;
1309
1310 LLVMContext &Context = M.getContext();
1311 auto *Int32Ty = Type::getInt32Ty(Context);
1312
1313 BasicBlock &EntryBB = F->getEntryBlock();
1314 IRBuilder<> Builder(&*EntryBB.getFirstInsertionPt());
1315
1317 if (OffloadPGOSampling > 0) {
1318 FunctionCallee IsSampledFn =
1320 RTLIB::impl___llvm_profile_sampling_gpu),
1321 Int32Ty, Int32Ty);
1322 Value *SampledInt = Builder.CreateCall(
1323 IsSampledFn, {ConstantInt::get(Int32Ty, OffloadPGOSampling)},
1324 "pgo.sampled");
1325 Matched = Builder.CreateICmpNE(SampledInt, ConstantInt::get(Int32Ty, 0),
1326 "pgo.matched");
1327 }
1328
1329 auto &Inv = GPUInvariantsCache[F];
1330 Inv.Matched = Matched;
1331 return Inv;
1332}
1333
1334void InstrLowerer::lowerIncrement(InstrProfIncrementInst *Inc) {
1335 IRBuilder<> Builder(Inc);
1336 if (isGPUProfTarget(M)) {
1337 Function *F = Inc->getFunction();
1338 auto &Inv = getOrCreateGPUInvariants(F);
1339
1340 LLVMContext &Context = M.getContext();
1341 auto *Int64Ty = Type::getInt64Ty(Context);
1342 auto *PtrTy = PointerType::getUnqual(Context);
1343
1344 auto *Addr = getCounterAddress(Inc);
1345
1346 // Store the device wave/warp size into the profile data struct once per
1347 // function. AMDGPU folds llvm.amdgcn.wavefrontsize to the subtarget's
1348 // constant; other GPUs use their fixed warp size.
1349 if (!Inv.WaveSizeStored) {
1350 Inv.WaveSizeStored = true;
1351 GlobalVariable *NamePtr = Inc->getName();
1352 auto &PD = ProfileDataMap[NamePtr];
1353 if (PD.DataVar) {
1354 IRBuilder<> EntryBuilder(&*F->getEntryBlock().getFirstInsertionPt());
1355 Value *WaveSize16 = nullptr;
1356 // Look the intrinsic up by name so this target-agnostic pass does not
1357 // pull in IntrinsicsAMDGPU.h. AMDGPU folds the intrinsic to the
1358 // subtarget's wavefront size; other GPUs fall back to a 32-lane warp.
1359 if (TT.isAMDGPU()) {
1360 Intrinsic::ID WaveSizeID =
1361 Intrinsic::lookupIntrinsicID("llvm.amdgcn.wavefrontsize");
1362 if (WaveSizeID != Intrinsic::not_intrinsic) {
1363 Function *WaveSizeFn =
1364 Intrinsic::getOrInsertDeclaration(&M, WaveSizeID);
1365 Value *WaveSize = EntryBuilder.CreateCall(WaveSizeFn);
1366 WaveSize16 = EntryBuilder.CreateTrunc(
1367 WaveSize, Type::getInt16Ty(Context), "wavesize.i16");
1368 }
1369 }
1370 if (!WaveSize16)
1371 WaveSize16 = ConstantInt::get(Type::getInt16Ty(Context), 32);
1372 Value *WaveSizeAddr = EntryBuilder.CreateStructGEP(
1373 PD.DataVar->getValueType(), PD.DataVar, 9, "profd.wavesize");
1374 EntryBuilder.CreateStore(WaveSize16, WaveSizeAddr);
1375 }
1376 }
1377
1378 GlobalVariable *UniformCounters = getOrCreateUniformCounters(Inc);
1379 Value *UniformAddrArg = ConstantPointerNull::get(PtrTy);
1380 if (UniformCounters) {
1381 Value *UniformIndices[] = {Builder.getInt32(0), Inc->getIndex()};
1382 Value *UniformAddr = Builder.CreateInBoundsGEP(
1383 UniformCounters->getValueType(), UniformCounters, UniformIndices,
1384 "unifctr.addr");
1385 UniformAddrArg =
1386 Builder.CreatePointerBitCastOrAddrSpaceCast(UniformAddr, PtrTy);
1387 }
1388 Value *CastAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PtrTy);
1389 Value *StepI64 =
1390 Builder.CreateZExtOrTrunc(Inc->getStep(), Int64Ty, "step.i64");
1391
1392 auto *CalleeTy = FunctionType::get(Type::getVoidTy(Context),
1393 {PtrTy, PtrTy, Int64Ty}, false);
1396 RTLIB::impl___llvm_profile_instrument_gpu),
1397 CalleeTy);
1398
1399 if (OffloadPGOSampling > 0) {
1400 BasicBlock *CurBB = Builder.GetInsertBlock();
1401 BasicBlock *ContBB =
1402 CurBB->splitBasicBlock(BasicBlock::iterator(Inc), "po_cont");
1403 BasicBlock *ThenBB = BasicBlock::Create(Context, "po_then", F);
1404
1405 CurBB->getTerminator()->eraseFromParent();
1406 IRBuilder<> HeadBuilder(CurBB);
1407 HeadBuilder.CreateCondBr(Inv.Matched, ThenBB, ContBB);
1408
1409 IRBuilder<> ThenBuilder(ThenBB);
1410 ThenBuilder.CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1411 ThenBuilder.CreateBr(ContBB);
1412 } else {
1413 Builder.CreateCall(Callee, {CastAddr, UniformAddrArg, StepI64});
1414 }
1415 Inc->eraseFromParent();
1416 return;
1417 }
1418
1419 auto *Addr = getCounterAddress(Inc);
1420 // If promotion is enabled then delay generating atomic updates until
1421 // after promotion is done.
1422 if ((!isCounterPromotionEnabled() && isAtomic()) ||
1423 (Inc->getIndex()->isNullValue() && AtomicFirstCounter)) {
1424 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
1426 } else {
1427 Value *IncStep = Inc->getStep();
1428 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
1429 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
1430 auto *Store = Builder.CreateStore(Count, Addr);
1431 if (isCounterPromotionEnabled())
1432 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
1433 }
1434 Inc->eraseFromParent();
1435}
1436
1437void InstrLowerer::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
1438 ConstantArray *Names =
1439 cast<ConstantArray>(CoverageNamesVar->getInitializer());
1440 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
1441 Constant *NC = Names->getOperand(I);
1442 Value *V = NC->stripPointerCasts();
1443 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
1445
1446 Name->setLinkage(GlobalValue::PrivateLinkage);
1447 ReferencedNames.push_back(Name);
1448 if (isa<ConstantExpr>(NC))
1449 NC->dropAllReferences();
1450 }
1451 CoverageNamesVar->eraseFromParent();
1452}
1453
1454void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1456 auto &Ctx = M.getContext();
1457 IRBuilder<> Builder(Update);
1458 auto *Int8Ty = Type::getInt8Ty(Ctx);
1459 auto *Int32Ty = Type::getInt32Ty(Ctx);
1460 auto *MCDCCondBitmapAddr = Update->getMCDCCondBitmapAddr();
1461 auto *BitmapAddr = getBitmapAddress(Update);
1462
1463 // Load Temp Val + BitmapIdx.
1464 // %mcdc.temp = load i32, ptr %mcdc.addr, align 4
1465 auto *Temp = Builder.CreateAdd(
1466 Builder.CreateLoad(Int32Ty, MCDCCondBitmapAddr, "mcdc.temp"),
1467 Update->getBitmapIndex());
1468
1469 // Calculate byte offset using div8.
1470 // %1 = lshr i32 %mcdc.temp, 3
1471 auto *BitmapByteOffset = Builder.CreateLShr(Temp, 0x3);
1472
1473 // Add byte offset to section base byte address.
1474 // %4 = getelementptr inbounds i8, ptr @__profbm_test, i32 %1
1475 auto *BitmapByteAddr =
1476 Builder.CreateInBoundsPtrAdd(BitmapAddr, BitmapByteOffset);
1477
1478 // Calculate bit offset into bitmap byte by using div8 remainder (AND ~8)
1479 // %5 = and i32 %mcdc.temp, 7
1480 // %6 = trunc i32 %5 to i8
1481 auto *BitToSet = Builder.CreateTrunc(Builder.CreateAnd(Temp, 0x7), Int8Ty);
1482
1483 // Shift bit offset left to form a bitmap.
1484 // %7 = shl i8 1, %6
1485 auto *ShiftedVal = Builder.CreateShl(Builder.getInt8(0x1), BitToSet);
1486
1487 // Load profile bitmap byte.
1488 // %mcdc.bits = load i8, ptr %4, align 1
1489 auto *Bitmap = Builder.CreateLoad(Int8Ty, BitmapByteAddr, "mcdc.bits");
1490
1491 if (isAtomic()) {
1492 // If ((Bitmap & Val) != Val), then execute atomic (Bitmap |= Val).
1493 // Note, just-loaded Bitmap might not be up-to-date. Use it just for
1494 // early testing.
1495 auto *Masked = Builder.CreateAnd(Bitmap, ShiftedVal);
1496 auto *ShouldStore = Builder.CreateICmpNE(Masked, ShiftedVal);
1497
1498 // Assume updating will be rare.
1499 auto *Unlikely = MDBuilder(Ctx).createUnlikelyBranchWeights();
1500 Instruction *ThenBranch =
1501 SplitBlockAndInsertIfThen(ShouldStore, Update, false, Unlikely);
1502
1503 // Execute if (unlikely(ShouldStore)).
1504 Builder.SetInsertPoint(ThenBranch);
1505 Builder.CreateAtomicRMW(AtomicRMWInst::Or, BitmapByteAddr, ShiftedVal,
1507 } else {
1508 // Perform logical OR of profile bitmap byte and shifted bit offset.
1509 // %8 = or i8 %mcdc.bits, %7
1510 auto *Result = Builder.CreateOr(Bitmap, ShiftedVal);
1511
1512 // Store the updated profile bitmap byte.
1513 // store i8 %8, ptr %3, align 1
1514 Builder.CreateStore(Result, BitmapByteAddr);
1515 }
1516
1517 Update->eraseFromParent();
1518}
1519
1520/// Get the name of a profiling variable for a particular function.
1521static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
1522 bool &Renamed) {
1523 StringRef NamePrefix = getInstrProfNameVarPrefix();
1524 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
1525 Function *F = Inc->getParent()->getParent();
1526 Module *M = F->getParent();
1527 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
1529 Renamed = false;
1530 return (Prefix + Name).str();
1531 }
1532 Renamed = true;
1534 SmallVector<char, 24> HashPostfix;
1535 if (Name.ends_with((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
1536 return (Prefix + Name).str();
1537 return (Prefix + Name + "." + Twine(FuncHash)).str();
1538}
1539
1541 // Only record function addresses if IR PGO is enabled or if clang value
1542 // profiling is enabled. Recording function addresses greatly increases object
1543 // file size, because it prevents the inliner from deleting functions that
1544 // have been inlined everywhere.
1545 if (!profDataReferencedByCode(*F->getParent()))
1546 return false;
1547
1548 // Check the linkage
1549 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
1550 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
1551 !HasAvailableExternallyLinkage)
1552 return true;
1553
1554 // A function marked 'alwaysinline' with available_externally linkage can't
1555 // have its address taken. Doing so would create an undefined external ref to
1556 // the function, which would fail to link.
1557 if (HasAvailableExternallyLinkage &&
1558 F->hasFnAttribute(Attribute::AlwaysInline))
1559 return false;
1560
1561 // Prohibit function address recording if the function is both internal and
1562 // COMDAT. This avoids the profile data variable referencing internal symbols
1563 // in COMDAT.
1564 if (F->hasLocalLinkage() && F->hasComdat())
1565 return false;
1566
1567 // Check uses of this function for other than direct calls or invokes to it.
1568 // Inline virtual functions have linkeOnceODR linkage. When a key method
1569 // exists, the vtable will only be emitted in the TU where the key method
1570 // is defined. In a TU where vtable is not available, the function won't
1571 // be 'addresstaken'. If its address is not recorded here, the profile data
1572 // with missing address may be picked by the linker leading to missing
1573 // indirect call target info.
1574 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
1575}
1576
1577static inline bool shouldUsePublicSymbol(Function *Fn) {
1578 // It isn't legal to make an alias of this function at all
1579 if (Fn->isDeclarationForLinker())
1580 return true;
1581
1582 // Symbols with local linkage can just use the symbol directly without
1583 // introducing relocations
1584 if (Fn->hasLocalLinkage())
1585 return true;
1586
1587 // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
1588 // unfavorable interaction between the new alias and the alias renaming done
1589 // in LowerTypeTests under ThinLTO. For comdat functions that would normally
1590 // be deduplicated, but the renaming scheme ends up preventing renaming, since
1591 // it creates unique names for each alias, resulting in duplicated symbols. In
1592 // the future, we should update the CFI related passes to migrate these
1593 // aliases to the same module as the jump-table they refer to will be defined.
1594 if (Fn->hasMetadata(LLVMContext::MD_type))
1595 return true;
1596
1597 // For comdat functions, an alias would need the same linkage as the original
1598 // function and hidden visibility. There is no point in adding an alias with
1599 // identical linkage an visibility to avoid introducing symbolic relocations.
1600 if (Fn->hasComdat() &&
1602 return true;
1603
1604 // its OK to use an alias
1605 return false;
1606}
1607
1609 auto *Int8PtrTy = PointerType::getUnqual(Fn->getContext());
1610 // Store a nullptr in __llvm_profd, if we shouldn't use a real address
1611 if (!shouldRecordFunctionAddr(Fn))
1612 return ConstantPointerNull::get(Int8PtrTy);
1613
1614 // If we can't use an alias, we must use the public symbol, even though this
1615 // may require a symbolic relocation.
1616 if (shouldUsePublicSymbol(Fn))
1617 return Fn;
1618
1619 // For GPU targets, weak functions cannot use private aliases because
1620 // LTO may pick a different TU's copy, leaving the alias undefined
1621 if (isGPUProfTarget(*Fn->getParent()) &&
1623 return Fn;
1624
1625 // When possible use a private alias to avoid symbolic relocations.
1627 Fn->getName() + ".local", Fn);
1628
1629 // When the instrumented function is a COMDAT function, we cannot use a
1630 // private alias. If we did, we would create reference to a local label in
1631 // this function's section. If this version of the function isn't selected by
1632 // the linker, then the metadata would introduce a reference to a discarded
1633 // section. So, for COMDAT functions, we need to adjust the linkage of the
1634 // alias. Using hidden visibility avoids a dynamic relocation and an entry in
1635 // the dynamic symbol table.
1636 //
1637 // Note that this handles COMDAT functions with visibility other than Hidden,
1638 // since that case is covered in shouldUsePublicSymbol()
1639 if (Fn->hasComdat()) {
1640 GA->setLinkage(Fn->getLinkage());
1642 }
1643
1644 // appendToCompilerUsed(*Fn->getParent(), {GA});
1645
1646 return GA;
1647}
1648
1650 // NVPTX is an ELF target but PTX does not expose sections or linker symbols.
1651 if (TT.isNVPTX())
1652 return true;
1653
1654 // compiler-rt uses linker support to get data/counters/name start/end for
1655 // ELF, COFF, Mach-O, XCOFF, and Wasm.
1656 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1657 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF() ||
1658 TT.isOSBinFormatWasm())
1659 return false;
1660
1661 return true;
1662}
1663
1664void InstrLowerer::maybeSetComdat(GlobalVariable *GV, GlobalObject *GO,
1665 StringRef CounterGroupName) {
1666 // Place lowered global variables in a comdat group if the associated function
1667 // or global variable is a COMDAT. This will make sure that only one copy of
1668 // global variable (e.g. function counters) of the COMDAT function will be
1669 // emitted after linking.
1670 bool NeedComdat = needsComdatForCounter(*GO, M);
1671 bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1672
1673 if (!UseComdat)
1674 return;
1675
1676 // Keep in mind that this pass may run before the inliner, so we need to
1677 // create a new comdat group (for counters, profiling data, etc). If we use
1678 // the comdat of the parent function, that will result in relocations against
1679 // discarded sections.
1680 //
1681 // If the data variable is referenced by code, non-counter variables (notably
1682 // profiling data) and counters have to be in different comdats for COFF
1683 // because the Visual C++ linker will report duplicate symbol errors if there
1684 // are multiple external symbols with the same name marked
1685 // IMAGE_COMDAT_SELECT_ASSOCIATIVE.
1686 StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1687 ? GV->getName()
1688 : CounterGroupName;
1689 Comdat *C = M.getOrInsertComdat(GroupName);
1690
1691 if (!NeedComdat) {
1692 // Object file format must be ELF since `UseComdat && !NeedComdat` is true.
1693 //
1694 // For ELF, when not using COMDAT, put counters, data and values into a
1695 // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
1696 // allows -z start-stop-gc to discard the entire group when the function is
1697 // discarded.
1698 C->setSelectionKind(Comdat::NoDeduplicate);
1699 }
1700 GV->setComdat(C);
1701 // COFF doesn't allow the comdat group leader to have private linkage, so
1702 // upgrade private linkage to internal linkage to produce a symbol table
1703 // entry.
1704 if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1706}
1707
1709 if (!profDataReferencedByCode(*GV->getParent()))
1710 return false;
1711
1712 if (!GV->hasLinkOnceLinkage() && !GV->hasLocalLinkage() &&
1714 return true;
1715
1716 // This avoids the profile data from referencing internal symbols in
1717 // COMDAT.
1718 if (GV->hasLocalLinkage() && GV->hasComdat())
1719 return false;
1720
1721 return true;
1722}
1723
1724// FIXME: Introduce an internal alias like what's done for functions to reduce
1725// the number of relocation entries.
1727 // Store a nullptr in __profvt_ if a real address shouldn't be used.
1728 if (!shouldRecordVTableAddr(GV))
1730
1731 return GV;
1732}
1733
1734void InstrLowerer::getOrCreateVTableProfData(GlobalVariable *GV) {
1736 "Value profiling is not supported with lightweight instrumentation");
1738 return;
1739
1740 // Skip llvm internal global variable or __prof variables.
1741 if (GV->getName().starts_with("llvm.") ||
1742 GV->getName().starts_with("__llvm") ||
1743 GV->getName().starts_with("__prof"))
1744 return;
1745
1746 // VTableProfData already created
1747 auto It = VTableDataMap.find(GV);
1748 if (It != VTableDataMap.end() && It->second)
1749 return;
1750
1753
1754 // This is to keep consistent with per-function profile data
1755 // for correctness.
1756 if (TT.isOSBinFormatXCOFF()) {
1758 Visibility = GlobalValue::DefaultVisibility;
1759 }
1760
1761 LLVMContext &Ctx = M.getContext();
1762 Type *DataTypes[] = {
1763#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1765#undef INSTR_PROF_VTABLE_DATA
1766 };
1767
1768 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1769
1770 // Used by INSTR_PROF_VTABLE_DATA MACRO
1771 Constant *VTableAddr = getVTableAddrForProfData(GV);
1772 const std::string PGOVTableName = getPGOName(*GV);
1773 // Record the length of the vtable. This is needed since vtable pointers
1774 // loaded from C++ objects might be from the middle of a vtable definition.
1775 uint32_t VTableSizeVal = GV->getGlobalSize(M.getDataLayout());
1776
1777 Constant *DataVals[] = {
1778#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1780#undef INSTR_PROF_VTABLE_DATA
1781 };
1782
1783 auto *Data =
1784 new GlobalVariable(M, DataTy, /*constant=*/false, Linkage,
1785 ConstantStruct::get(DataTy, DataVals),
1786 getInstrProfVTableVarPrefix() + PGOVTableName);
1787
1788 Data->setVisibility(Visibility);
1789 Data->setSection(getInstrProfSectionName(IPSK_vtab, TT.getObjectFormat()));
1790 Data->setAlignment(Align(8));
1791
1792 maybeSetComdat(Data, GV, Data->getName());
1793
1794 VTableDataMap[GV] = Data;
1795
1796 ReferencedVTables.push_back(GV);
1797
1798 // VTable <Hash, Addr> is used by runtime but not referenced by other
1799 // sections. Conservatively mark it linker retained.
1800 UsedVars.push_back(Data);
1801}
1802
1803GlobalVariable *InstrLowerer::setupProfileSection(InstrProfInstBase *Inc,
1804 InstrProfSectKind IPSK) {
1805 GlobalVariable *NamePtr = Inc->getName();
1806
1807 // Match the linkage and visibility of the name global.
1808 Function *Fn = Inc->getParent()->getParent();
1810 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1811
1812 // Use internal rather than private linkage so the counter variable shows up
1813 // in the symbol table when using debug info for correlation.
1815 TT.isOSBinFormatMachO() && Linkage == GlobalValue::PrivateLinkage)
1817
1818 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1819 // symbols in the same csect won't be discarded. When there are duplicate weak
1820 // symbols, we can NOT guarantee that the relocations get resolved to the
1821 // intended weak symbol, so we can not ensure the correctness of the relative
1822 // CounterPtr, so we have to use private linkage for counter and data symbols.
1823 if (TT.isOSBinFormatXCOFF()) {
1825 Visibility = GlobalValue::DefaultVisibility;
1826 }
1827 // Move the name variable to the right section.
1828 bool Renamed;
1829 GlobalVariable *Ptr;
1830 StringRef VarPrefix;
1831 std::string VarName;
1832 if (IPSK == IPSK_cnts) {
1833 VarPrefix = getInstrProfCountersVarPrefix();
1834 VarName = getVarName(Inc, VarPrefix, Renamed);
1836 Ptr = createRegionCounters(CntrIncrement, VarName, Linkage);
1837 } else if (IPSK == IPSK_bitmap) {
1838 VarPrefix = getInstrProfBitmapVarPrefix();
1839 VarName = getVarName(Inc, VarPrefix, Renamed);
1840 InstrProfMCDCBitmapInstBase *BitmapUpdate =
1842 Ptr = createRegionBitmaps(BitmapUpdate, VarName, Linkage);
1843 } else {
1844 llvm_unreachable("Profile Section must be for Counters or Bitmaps");
1845 }
1846
1847 Ptr->setVisibility(Visibility);
1848 Ptr->setSection(getInstrProfSectionName(IPSK, TT.getObjectFormat()));
1849 Ptr->setLinkage(Linkage);
1850 if (isGPUProfTarget(M) && !Ptr->hasComdat()) {
1851 Ptr->setComdat(M.getOrInsertComdat(VarName));
1854 } else {
1855 maybeSetComdat(Ptr, Fn, VarName);
1856 }
1857 return Ptr;
1858}
1859
1861InstrLowerer::createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
1862 StringRef Name,
1864 uint64_t NumBytes = Inc->getNumBitmapBytes();
1865 auto *BitmapTy = ArrayType::get(Type::getInt8Ty(M.getContext()), NumBytes);
1866 auto GV = new GlobalVariable(M, BitmapTy, false, Linkage,
1867 Constant::getNullValue(BitmapTy), Name);
1868 GV->setAlignment(Align(1));
1869 return GV;
1870}
1871
1873InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
1874 GlobalVariable *NamePtr = Inc->getName();
1875 auto &PD = ProfileDataMap[NamePtr];
1876 if (PD.RegionBitmaps)
1877 return PD.RegionBitmaps;
1878
1879 // If RegionBitmaps doesn't already exist, create it by first setting up
1880 // the corresponding profile section.
1881 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1882 PD.RegionBitmaps = BitmapPtr;
1883 PD.NumBitmapBytes = Inc->getNumBitmapBytes();
1884
1885 if (PD.NumBitmapBytes &&
1887 LLVMContext &Ctx = M.getContext();
1888 Function *Fn = Inc->getParent()->getParent();
1889 if (auto *SP = Fn->getSubprogram()) {
1890 DIBuilder DB(M, true, SP->getUnit());
1891 Metadata *FunctionNameAnnotation[] = {
1894 };
1895 Metadata *NumBitmapBitsAnnotation[] = {
1898 };
1899 auto Annotations = DB.getOrCreateArray({
1900 MDNode::get(Ctx, FunctionNameAnnotation),
1901 MDNode::get(Ctx, NumBitmapBitsAnnotation),
1902 });
1903 auto *DICounter = DB.createGlobalVariableExpression(
1904 SP, BitmapPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1905 /*LineNo=*/0, DB.createUnspecifiedType("Profile Bitmap Type"),
1906 BitmapPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1907 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1908 Annotations);
1909 BitmapPtr->addDebugInfo(DICounter);
1910 DB.finalizeSubprogram(SP);
1911 DB.finalize();
1912 }
1913
1914 // Mark the bitmap variable as used so that it isn't optimized out.
1915 CompilerUsedVars.push_back(PD.RegionBitmaps);
1916 }
1917
1918 return PD.RegionBitmaps;
1919}
1920
1922InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
1924 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1925 auto &Ctx = M.getContext();
1926 GlobalVariable *GV;
1927 if (isa<InstrProfCoverInst>(Inc)) {
1928 auto *CounterTy = Type::getInt8Ty(Ctx);
1929 auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
1930 // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
1931 std::vector<Constant *> InitialValues(NumCounters,
1932 Constant::getAllOnesValue(CounterTy));
1933 GV = new GlobalVariable(M, CounterArrTy, false, Linkage,
1934 ConstantArray::get(CounterArrTy, InitialValues),
1935 Name);
1936 GV->setAlignment(Align(1));
1937 } else {
1938 auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
1939 GV = new GlobalVariable(M, CounterTy, false, Linkage,
1940 Constant::getNullValue(CounterTy), Name);
1941 GV->setAlignment(Align(8));
1942 }
1943 return GV;
1944}
1945
1947InstrLowerer::getOrCreateRegionCounters(InstrProfCntrInstBase *Inc) {
1948 GlobalVariable *NamePtr = Inc->getName();
1949 auto &PD = ProfileDataMap[NamePtr];
1950 if (PD.RegionCounters)
1951 return PD.RegionCounters;
1952
1953 // If RegionCounters doesn't already exist, create it by first setting up
1954 // the corresponding profile section.
1955 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1956 PD.RegionCounters = CounterPtr;
1957
1959 LLVMContext &Ctx = M.getContext();
1960 Function *Fn = Inc->getParent()->getParent();
1961 if (auto *SP = Fn->getSubprogram()) {
1962 DIBuilder DB(M, true, SP->getUnit());
1963 Metadata *FunctionNameAnnotation[] = {
1966 };
1967 Metadata *CFGHashAnnotation[] = {
1970 };
1971 Metadata *NumCountersAnnotation[] = {
1974 };
1975 auto Annotations = DB.getOrCreateArray({
1976 MDNode::get(Ctx, FunctionNameAnnotation),
1977 MDNode::get(Ctx, CFGHashAnnotation),
1978 MDNode::get(Ctx, NumCountersAnnotation),
1979 });
1980 auto *DICounter = DB.createGlobalVariableExpression(
1981 SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1982 /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
1983 CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1984 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1985 Annotations);
1986 CounterPtr->addDebugInfo(DICounter);
1987 DB.finalizeSubprogram(SP);
1988 DB.finalize();
1989 }
1990
1991 // Mark the counter variable as used so that it isn't optimized out.
1992 CompilerUsedVars.push_back(PD.RegionCounters);
1993 }
1994
1995 // Create uniform counters before the data variable so that
1996 // UniformCounterPtr can reference them in createDataVariable().
1997 getOrCreateUniformCounters(Inc);
1998
1999 // Create the data variable (if it doesn't already exist).
2000 createDataVariable(Inc);
2001
2002 return PD.RegionCounters;
2003}
2004
2006InstrLowerer::getOrCreateUniformCounters(InstrProfCntrInstBase *Inc) {
2007 // Uniform counters are only meaningful for GPU profile targets.
2008 if (!isGPUProfTarget(M))
2009 return nullptr;
2010
2011 GlobalVariable *NamePtr = Inc->getName();
2012 auto &PD = ProfileDataMap[NamePtr];
2013 if (PD.UniformCounters)
2014 return PD.UniformCounters;
2015
2016 assert(PD.RegionCounters && "region counters must be created first");
2017
2018 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
2019
2020 LLVMContext &Ctx = M.getContext();
2021 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
2022
2023 bool Renamed;
2024 std::string VarName = getVarName(Inc, "__llvm_prf_unifcnt_", Renamed);
2025
2026 auto *GV = new GlobalVariable(M, CounterTy, false, NamePtr->getLinkage(),
2027 Constant::getNullValue(CounterTy), VarName);
2028 GV->setAlignment(Align(8));
2029
2030 GV->setSection(getInstrProfSectionName(IPSK_ucnts, TT.getObjectFormat()));
2031
2032 GV->setComdat(M.getOrInsertComdat(VarName));
2035
2036 PD.UniformCounters = GV;
2037 CompilerUsedVars.push_back(GV);
2038
2039 return PD.UniformCounters;
2040}
2041
2042void InstrLowerer::createDataVariable(InstrProfCntrInstBase *Inc) {
2043 // When debug information is correlated to profile data, a data variable
2044 // is not needed.
2046 return;
2047
2048 GlobalVariable *NamePtr = Inc->getName();
2049 auto &PD = ProfileDataMap[NamePtr];
2050
2051 // Return if data variable was already created.
2052 if (PD.DataVar)
2053 return;
2054
2055 LLVMContext &Ctx = M.getContext();
2056
2057 Function *Fn = Inc->getParent()->getParent();
2059 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
2060
2061 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
2062 // symbols in the same csect won't be discarded. When there are duplicate weak
2063 // symbols, we can NOT guarantee that the relocations get resolved to the
2064 // intended weak symbol, so we can not ensure the correctness of the relative
2065 // CounterPtr, so we have to use private linkage for counter and data symbols.
2066 if (TT.isOSBinFormatXCOFF()) {
2068 Visibility = GlobalValue::DefaultVisibility;
2069 }
2070
2071 bool NeedComdat = needsComdatForCounter(*Fn, M);
2072 bool Renamed;
2073
2074 // The Data Variable section is anchored to profile counters.
2075 std::string CntsVarName =
2077 std::string DataVarName =
2078 getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
2079
2080 auto *Int8PtrTy = PointerType::getUnqual(Ctx);
2081 // Allocate statically the array of pointers to value profile nodes for
2082 // the current function.
2083 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
2084 uint64_t NS = 0;
2085 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
2086 NS += PD.NumValueSites[Kind];
2087 if (NS > 0 && ValueProfileStaticAlloc &&
2089 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
2090 auto *ValuesVar = new GlobalVariable(
2091 M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
2092 getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
2093 ValuesVar->setVisibility(Visibility);
2094 setGlobalVariableLargeSection(TT, *ValuesVar);
2095 ValuesVar->setSection(
2096 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
2097 ValuesVar->setAlignment(Align(8));
2098 maybeSetComdat(ValuesVar, Fn, CntsVarName);
2100 ValuesVar, PointerType::get(Fn->getContext(), 0));
2101 }
2102
2103 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
2104
2105 Constant *CounterPtr = PD.RegionCounters;
2106 Constant *UniformCounterPtr = PD.UniformCounters;
2107
2108 uint64_t NumBitmapBytes = PD.NumBitmapBytes;
2109
2110 // Create data variable.
2111 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
2112 auto *Int16Ty = Type::getInt16Ty(Ctx);
2113 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
2114 auto *DataTy = getProfileDataTy();
2115
2116 Constant *FunctionAddr = getFuncAddrForProfData(Fn);
2117
2118 Constant *Int16ArrayVals[IPVK_Last + 1];
2119 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
2120 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
2121
2122 uint16_t OffloadDeviceWaveSizeVal = 0;
2123
2124 if (isGPUProfTarget(M)) {
2125 // For GPU targets, weak functions need weak linkage for their profile data
2126 // aliases to allow linker deduplication across TUs
2128 Linkage = Fn->getLinkage();
2129 else
2132 }
2133 // If the data variable is not referenced by code (if we don't emit
2134 // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
2135 // data variable live under linker GC, the data variable can be private. This
2136 // optimization applies to ELF.
2137 //
2138 // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
2139 // to be false.
2140 //
2141 // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
2142 // that other copies must have the same CFG and cannot have value profiling.
2143 // If no hash suffix, other profd copies may be referenced by code.
2144 if (!isGPUProfTarget(M) && NS == 0 &&
2145 !(DataReferencedByCode && NeedComdat && !Renamed) &&
2146 (TT.isOSBinFormatELF() ||
2147 (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
2149 Visibility = GlobalValue::DefaultVisibility;
2150 }
2151 // GPU-target ELF objects are always ET_DYN, so non-local symbols with
2152 // default visibility are preemptible. The CounterPtr label difference
2153 // emits a REL32 relocation that lld rejects against preemptible targets.
2154 if (TT.isGPU() && TT.isOSBinFormatELF() &&
2157 auto *Data =
2158 new GlobalVariable(M, DataTy, false, Linkage, nullptr, DataVarName);
2159
2160 Constant *RelativeCounterPtr;
2161 Constant *RelativeUniformCounterPtr = ConstantInt::get(IntPtrTy, 0);
2162 GlobalVariable *BitmapPtr = PD.RegionBitmaps;
2163 Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
2164 InstrProfSectKind DataSectionKind;
2165 // With binary profile correlation, profile data is not loaded into memory.
2166 // profile data must reference profile counter with an absolute relocation.
2168 DataSectionKind = IPSK_covdata;
2169 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
2170 if (BitmapPtr != nullptr)
2171 RelativeBitmapPtr = ConstantExpr::getPtrToInt(BitmapPtr, IntPtrTy);
2172 if (UniformCounterPtr != nullptr)
2173 RelativeUniformCounterPtr =
2175 } else if (TT.isNVPTX()) {
2176 // The NVPTX target cannot handle self-referencing constant expressions in
2177 // global initializers at all. Use absolute pointers and have the runtime
2178 // registration convert them to relative offsets.
2179 DataSectionKind = IPSK_data;
2180 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
2181 } else {
2182 // Reference the counter variable with a label difference (link-time
2183 // constant).
2184 DataSectionKind = IPSK_data;
2185 RelativeCounterPtr =
2188 if (BitmapPtr != nullptr)
2189 RelativeBitmapPtr =
2192 if (UniformCounterPtr != nullptr)
2193 RelativeUniformCounterPtr = ConstantExpr::getSub(
2196 }
2197
2198 Constant *DataVals[] = {
2199#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
2201 };
2202 Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
2203
2204 Data->setVisibility(Visibility);
2205 Data->setSection(
2206 getInstrProfSectionName(DataSectionKind, TT.getObjectFormat()));
2207 Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
2208 if (isGPUProfTarget(M) && !Data->hasComdat()) {
2209 Data->setComdat(M.getOrInsertComdat(CntsVarName));
2211 } else {
2212 maybeSetComdat(Data, Fn, CntsVarName);
2213 }
2214
2215 PD.DataVar = Data;
2216
2217 // Mark the data variable as used so that it isn't stripped out.
2218 CompilerUsedVars.push_back(Data);
2219 // Now that the linkage set by the FE has been passed to the data and counter
2220 // variables, reset Name variable's linkage and visibility to private so that
2221 // it can be removed later by the compiler.
2223 // Collect the referenced names to be used by emitNameData.
2224 ReferencedNames.push_back(NamePtr);
2225}
2226
2227void InstrLowerer::emitVNodes() {
2228 if (!ValueProfileStaticAlloc)
2229 return;
2230
2231 // For now only support this on platforms that do
2232 // not require runtime registration to discover
2233 // named section start/end.
2235 return;
2236
2237 size_t TotalNS = 0;
2238 for (auto &PD : ProfileDataMap) {
2239 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
2240 TotalNS += PD.second.NumValueSites[Kind];
2241 }
2242
2243 if (!TotalNS)
2244 return;
2245
2246 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
2247// Heuristic for small programs with very few total value sites.
2248// The default value of vp-counters-per-site is chosen based on
2249// the observation that large apps usually have a low percentage
2250// of value sites that actually have any profile data, and thus
2251// the average number of counters per site is low. For small
2252// apps with very few sites, this may not be true. Bump up the
2253// number of counters in this case.
2254#define INSTR_PROF_MIN_VAL_COUNTS 10
2255 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
2256 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
2257
2258 auto &Ctx = M.getContext();
2259 Type *VNodeTypes[] = {
2260#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
2262 };
2263 auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
2264
2265 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
2266 auto *VNodesVar = new GlobalVariable(
2267 M, VNodesTy, false, GlobalValue::PrivateLinkage,
2269 setGlobalVariableLargeSection(TT, *VNodesVar);
2270 VNodesVar->setSection(
2271 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
2272 VNodesVar->setAlignment(M.getDataLayout().getABITypeAlign(VNodesTy));
2273 // VNodesVar is used by runtime but not referenced via relocation by other
2274 // sections. Conservatively make it linker retained.
2275 UsedVars.push_back(VNodesVar);
2276}
2277
2278// Build the per-TU device-PGO sections struct: section start/stop bounds for
2279// names/counters/data/uniform-counters plus the raw version. Returns null if it
2280// already exists.
2282 StringRef CUIDPostfix) {
2283 std::string Name = ("__llvm_profile_sections" + CUIDPostfix).str();
2284 if (M.getNamedValue(Name))
2285 return nullptr;
2286
2287 LLVMContext &Ctx = M.getContext();
2288 unsigned AS = M.getDataLayout().getDefaultGlobalsAddressSpace();
2289 auto Extern = [&](StringRef Sym, Type *Ty, bool IsConst,
2291 GlobalVariable *GV = M.getNamedGlobal(Sym);
2292 if (!GV) {
2293 GV = new GlobalVariable(M, Ty, IsConst, GlobalValue::ExternalLinkage,
2294 nullptr, Sym, nullptr,
2296 GV->setVisibility(Vis);
2297 }
2298 return GV;
2299 };
2300 // Section bounds are hidden i8 markers; raw_version is an i64 constant.
2301 auto *I8 = Type::getInt8Ty(Ctx);
2302 auto Hidden = GlobalValue::HiddenVisibility;
2303 Constant *Fields[] = {Extern("__start___llvm_prf_names", I8, false, Hidden),
2304 Extern("__stop___llvm_prf_names", I8, false, Hidden),
2305 Extern("__start___llvm_prf_cnts", I8, false, Hidden),
2306 Extern("__stop___llvm_prf_cnts", I8, false, Hidden),
2307 Extern("__start___llvm_prf_data", I8, false, Hidden),
2308 Extern("__stop___llvm_prf_data", I8, false, Hidden),
2309 Extern("__start___llvm_prf_ucnts", I8, false, Hidden),
2310 Extern("__stop___llvm_prf_ucnts", I8, false, Hidden),
2311 Extern("__llvm_profile_raw_version",
2312 Type::getInt64Ty(Ctx), true,
2314 auto *PtrTy = PointerType::get(Ctx, AS);
2315 auto *STy = StructType::get(
2316 Ctx, {PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy, PtrTy});
2317 auto *GV = new GlobalVariable(M, STy, /*isConstant=*/true,
2319 ConstantStruct::get(STy, Fields), Name, nullptr,
2321 GV->setVisibility(GlobalValue::ProtectedVisibility);
2322 return GV;
2323}
2324
2325void InstrLowerer::emitNameData() {
2326 if (ReferencedNames.empty())
2327 return;
2328
2329 std::string CompressedNameStr;
2330 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
2332 report_fatal_error(Twine(toString(std::move(E))), false);
2333 }
2334
2335 auto &Ctx = M.getContext();
2336 auto *NamesVal =
2337 ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
2338 std::string NamesVarName = std::string(getInstrProfNamesVarName());
2341 std::string GPUCUIDPostfix;
2342 if (isGPUProfTarget(M)) {
2343 if (auto *GV = M.getNamedGlobal(getInstrProfNamesVarPostfixVarName())) {
2344 if (auto *Init =
2346 if (Init->isCString()) {
2347 GPUCUIDPostfix = Init->getAsCString().str();
2348 NamesVarName += GPUCUIDPostfix;
2349 NamesLinkage = GlobalValue::ExternalLinkage;
2350 NamesVisibility = GlobalValue::ProtectedVisibility;
2352 M, [GV](Constant *C) { return C->stripPointerCasts() == GV; });
2353 GV->eraseFromParent();
2354 }
2355 }
2356 }
2357 }
2358 NamesVar = new GlobalVariable(M, NamesVal->getType(), true, NamesLinkage,
2359 NamesVal, NamesVarName);
2360 NamesVar->setVisibility(NamesVisibility);
2361
2362 NamesSize = CompressedNameStr.size();
2363 setGlobalVariableLargeSection(TT, *NamesVar);
2364 std::string NamesSectionName =
2366 ? getInstrProfSectionName(IPSK_covname, TT.getObjectFormat())
2367 : getInstrProfSectionName(IPSK_name, TT.getObjectFormat());
2368 NamesVar->setSection(NamesSectionName);
2369 // On COFF, it's important to reduce the alignment down to 1 to prevent the
2370 // linker from inserting padding before the start of the names section or
2371 // between names entries.
2372 NamesVar->setAlignment(Align(1));
2373 // NamesVar is used by runtime but not referenced via relocation by other
2374 // sections. Conservatively make it linker retained.
2375 UsedVars.push_back(NamesVar);
2376
2377 for (auto *NamePtr : ReferencedNames)
2378 NamePtr->eraseFromParent();
2379
2380 // Emit the device sections struct only when this TU produced profile data, so
2381 // its section start/stop references are backed by a real section.
2382 bool HasData = llvm::any_of(ProfileDataMap,
2383 [](const auto &KV) { return KV.second.DataVar; });
2384 if (!GPUCUIDPostfix.empty() && HasData)
2385 if (GlobalVariable *GV = emitGPUOffloadSectionsStruct(M, GPUCUIDPostfix))
2386 CompilerUsedVars.push_back(GV);
2387}
2388
2389void InstrLowerer::emitVTableNames() {
2390 if (!EnableVTableValueProfiling || ReferencedVTables.empty())
2391 return;
2392
2393 // Collect the PGO names of referenced vtables and compress them.
2394 std::string CompressedVTableNames;
2395 if (Error E = collectVTableStrings(ReferencedVTables, CompressedVTableNames,
2397 report_fatal_error(Twine(toString(std::move(E))), false);
2398 }
2399
2400 auto &Ctx = M.getContext();
2401 auto *VTableNamesVal = ConstantDataArray::getString(
2402 Ctx, StringRef(CompressedVTableNames), false /* AddNull */);
2403 GlobalVariable *VTableNamesVar =
2404 new GlobalVariable(M, VTableNamesVal->getType(), true /* constant */,
2405 GlobalValue::PrivateLinkage, VTableNamesVal,
2407 VTableNamesVar->setSection(
2408 getInstrProfSectionName(IPSK_vname, TT.getObjectFormat()));
2409 VTableNamesVar->setAlignment(Align(1));
2410 // Make VTableNames linker retained.
2411 UsedVars.push_back(VTableNamesVar);
2412}
2413
2414void InstrLowerer::emitRegistration() {
2416 return;
2417
2418 // Construct the function.
2419 auto *VoidTy = Type::getVoidTy(M.getContext());
2420 auto *VoidPtrTy = PointerType::getUnqual(M.getContext());
2421 auto *Int64Ty = Type::getInt64Ty(M.getContext());
2422 auto *RegisterFTy = FunctionType::get(VoidTy, false);
2423 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
2425 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2426 if (Options.NoRedZone)
2427 RegisterF->addFnAttr(Attribute::NoRedZone);
2428
2429 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
2430 auto *RuntimeRegisterF =
2433
2434 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", RegisterF));
2435 for (Value *Data : CompilerUsedVars)
2436 if (!isa<Function>(Data))
2437 // Check for addrspace cast when profiling GPU
2438 IRB.CreateCall(RuntimeRegisterF,
2439 IRB.CreatePointerBitCastOrAddrSpaceCast(Data, VoidPtrTy));
2440 for (Value *Data : UsedVars)
2441 if (Data != NamesVar && !isa<Function>(Data))
2442 IRB.CreateCall(RuntimeRegisterF,
2443 IRB.CreatePointerBitCastOrAddrSpaceCast(Data, VoidPtrTy));
2444
2445 if (NamesVar) {
2446 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
2447 auto *NamesRegisterTy =
2448 FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
2449 auto *NamesRegisterF =
2452 IRB.CreateCall(NamesRegisterF, {IRB.CreatePointerBitCastOrAddrSpaceCast(
2453 NamesVar, VoidPtrTy),
2454 IRB.getInt64(NamesSize)});
2455 }
2456
2457 IRB.CreateRetVoid();
2458}
2459
2460bool InstrLowerer::emitRuntimeHook() {
2461 // GPU profiling data is read directly by the host offload runtime. We do not
2462 // need the standard runtime hook.
2463 if (TT.isGPU())
2464 return false;
2465
2466 // We expect the linker to be invoked with -u<hook_var> flag for Linux
2467 // in which case there is no need to emit the external variable.
2468 if (TT.isOSLinux() || TT.isOSAIX())
2469 return false;
2470
2471 // If the module's provided its own runtime, we don't need to do anything.
2472 if (M.getGlobalVariable(getInstrProfRuntimeHookVarName()))
2473 return false;
2474
2475 // Declare an external variable that will pull in the runtime initialization.
2476 auto *Int32Ty = Type::getInt32Ty(M.getContext());
2477 auto *Var =
2478 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
2480 Var->setVisibility(GlobalValue::HiddenVisibility);
2481
2482 if (TT.isOSBinFormatELF() && !TT.isPS()) {
2483 // Mark the user variable as used so that it isn't stripped out.
2484 CompilerUsedVars.push_back(Var);
2485 } else {
2486 // Make a function that uses it.
2487 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
2490 User->addFnAttr(Attribute::NoInline);
2491 if (Options.NoRedZone)
2492 User->addFnAttr(Attribute::NoRedZone);
2493 User->setVisibility(GlobalValue::HiddenVisibility);
2494 if (TT.supportsCOMDAT())
2495 User->setComdat(M.getOrInsertComdat(User->getName()));
2496 // Explicitly mark this function as cold since it is never called.
2497 User->setEntryCount(0);
2498
2499 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", User));
2500 auto *Load = IRB.CreateLoad(Int32Ty, Var);
2501 IRB.CreateRet(Load);
2502
2503 // Mark the function as used so that it isn't stripped out.
2504 CompilerUsedVars.push_back(User);
2505 }
2506 return true;
2507}
2508
2509void InstrLowerer::emitUses() {
2510 // The metadata sections are parallel arrays. Optimizers (e.g.
2511 // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
2512 // we conservatively retain all unconditionally in the compiler.
2513 //
2514 // On ELF and Mach-O, the linker can guarantee the associated sections will be
2515 // retained or discarded as a unit, so llvm.compiler.used is sufficient.
2516 // Similarly on COFF, if prof data is not referenced by code we use one comdat
2517 // and ensure this GC property as well. Otherwise, we have to conservatively
2518 // make all of the sections retained by the linker.
2519 if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
2520 (TT.isOSBinFormatCOFF() && !DataReferencedByCode))
2521 appendToCompilerUsed(M, CompilerUsedVars);
2522 else
2523 appendToUsed(M, CompilerUsedVars);
2524
2525 // We do not add proper references from used metadata sections to NamesVar and
2526 // VNodesVar, so we have to be conservative and place them in llvm.used
2527 // regardless of the target,
2528 appendToUsed(M, UsedVars);
2529}
2530
2531void InstrLowerer::emitInitialization() {
2532 // Create ProfileFileName variable. Don't don't this for the
2533 // context-sensitive instrumentation lowering: This lowering is after
2534 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
2535 // have already create the variable before LTO/ThinLTO linking.
2536 if (!IsCS)
2537 createProfileFileNameVar(M, Options.InstrProfileOutput);
2538 Function *RegisterF = M.getFunction(getInstrProfRegFuncsName());
2539 if (!RegisterF)
2540 return;
2541
2542 // Create the initialization function.
2543 auto *VoidTy = Type::getVoidTy(M.getContext());
2544 auto *F = Function::Create(FunctionType::get(VoidTy, false),
2547 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2548 F->addFnAttr(Attribute::NoInline);
2549 if (Options.NoRedZone)
2550 F->addFnAttr(Attribute::NoRedZone);
2551
2552 // Add the basic block and the necessary calls.
2553 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", F));
2554 IRB.CreateCall(RegisterF, {});
2555 IRB.CreateRetVoid();
2556
2557 appendToGlobalCtors(M, F, 0);
2558}
2559
2560namespace llvm {
2561// Create the variable for profile sampling.
2564 IntegerType *SamplingVarTy;
2565 Constant *ValueZero;
2566 if (getSampledInstrumentationConfig().UseShort) {
2567 SamplingVarTy = Type::getInt16Ty(M.getContext());
2568 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(16, 0));
2569 } else {
2570 SamplingVarTy = Type::getInt32Ty(M.getContext());
2571 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(32, 0));
2572 }
2573 auto SamplingVar = new GlobalVariable(
2574 M, SamplingVarTy, false, GlobalValue::WeakAnyLinkage, ValueZero, VarName);
2575 SamplingVar->setVisibility(GlobalValue::DefaultVisibility);
2576 SamplingVar->setThreadLocal(true);
2577 Triple TT(M.getTargetTriple());
2578 if (TT.supportsCOMDAT()) {
2579 SamplingVar->setLinkage(GlobalValue::ExternalLinkage);
2580 SamplingVar->setComdat(M.getOrInsertComdat(VarName));
2581 }
2582 appendToCompilerUsed(M, SamplingVar);
2583}
2584} // namespace llvm
2585
2586// For GPU targets: Allocate contiguous arrays for all profile data.
2587// This solves the linker reordering problem by using ONE symbol per section
2588// type, so there's nothing for the linker to reorder.
2589StructType *InstrLowerer::getProfileDataTy() {
2590 if (ProfileDataTy)
2591 return ProfileDataTy;
2592
2593 auto &Ctx = M.getContext();
2594 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
2595 auto *Int16Ty = Type::getInt16Ty(Ctx);
2596 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
2597 Type *DataTypes[] = {
2598#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
2600 };
2601 ProfileDataTy = StructType::get(Ctx, ArrayRef(DataTypes));
2602 return ProfileDataTy;
2603}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
static unsigned InstrCount
DXIL Finalize Linkage
@ Default
Hexagon Hardware Loops
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define INSTR_PROF_QUOTE(x)
#define INSTR_PROF_DATA_ALIGNMENT
#define INSTR_PROF_PROFILE_SET_TIMESTAMP
#define INSTR_PROF_PROFILE_SAMPLING_VAR
static bool shouldRecordVTableAddr(GlobalVariable *GV)
static bool shouldRecordFunctionAddr(Function *F)
static bool needsRuntimeHookUnconditionally(const Triple &TT)
static bool containsProfilingIntrinsics(Module &M)
Check if the module contains uses of any profiling intrinsics.
static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix, bool &Renamed)
Get the name of a profiling variable for a particular function.
#define INSTR_PROF_MIN_VAL_COUNTS
static Constant * getFuncAddrForProfData(Function *Fn)
static bool shouldUsePublicSymbol(Function *Fn)
static FunctionCallee getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI, ValueProfilingCallType CallType=ValueProfilingCallType::Default)
static Constant * getVTableAddrForProfData(GlobalVariable *GV)
static void doAtomicCheck(Function *F)
static GlobalVariable * emitGPUOffloadSectionsStruct(Module &M, StringRef CUIDPostfix)
static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT)
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
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
Machine Check Debug Module
Memory SSA
Definition MemorySSA.cpp:73
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Class for arbitrary precision integers.
Definition APInt.h:78
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:67
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.
@ Add
*p = old + v
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
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 BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:484
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
const BasicBlock & getEntryBlock() const
Definition Function.h:786
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
Definition Function.h:166
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
void compute(FunctionT &F)
Compute the cycle info for a function.
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
bool hasComdat() const
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
bool hasLinkOnceLinkage() const
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
void setLinkage(LinkageTypes LT)
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
void setVisibility(VisibilityTypes V)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
bool hasAvailableExternallyLinkage() const
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
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2238
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1532
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:467
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2092
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:175
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2302
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2379
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:477
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:1906
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1511
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1570
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition IRBuilder.h:2046
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1422
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2742
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2554
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2107
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2097
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
AtomicRMWInst * CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, bool Elementwise=false)
Definition IRBuilder.h:1981
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
A base class for all instrprof counter intrinsics.
LLVM_ABI ConstantInt * getIndex() const
LLVM_ABI ConstantInt * getNumCounters() const
static LLVM_ABI const char * FunctionNameAttributeName
static LLVM_ABI const char * CFGHashAttributeName
static LLVM_ABI const char * NumCountersAttributeName
static LLVM_ABI const char * NumBitmapBitsAttributeName
This represents the llvm.instrprof.cover intrinsic.
This represents the llvm.instrprof.increment intrinsic.
LLVM_ABI Value * getStep() const
A base class for all instrprof intrinsics.
GlobalVariable * getName() const
ConstantInt * getHash() const
A base class for instrprof mcdc intrinsics that require global bitmap bytes.
ConstantInt * getNumBitmapBits() const
This represents the llvm.instrprof.mcdc.tvbitmap.update intrinsic.
ConstantInt * getBitmapIndex() const
This represents the llvm.instrprof.timestamp intrinsic.
This represents the llvm.instrprof.value.profile intrinsic.
ConstantInt * getIndex() const
ConstantInt * getValueKind() const
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition SSAUpdater.h:149
An instruction for reading from memory.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition MDBuilder.cpp:48
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
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
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:308
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:828
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:389
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:131
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
Definition InstrProf.h:101
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition InstrProf.h:206
UniformCounterPtr
Definition InstrProf.h:82
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void createProfileSamplingVar(Module &M)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition InstrProf.h:143
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
StringRef getInstrProfVTableNamesVarName()
Definition InstrProf.h:159
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition InstrProf.h:137
RelativeUniformCounterPtr ValuesPtrExpr Int16ArrayTy
Definition InstrProf.h:95
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition InstrProf.h:172
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FuncHash
Definition InstrProf.h:78
LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition InstrProf.h:201
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition InstrProf.h:146
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
StringRef getInstrProfCounterBiasVarName()
Definition InstrProf.h:216
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition InstrProf.h:212
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition InstrProf.h:181
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
InstrProfSectKind
Definition InstrProf.h:91
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition InstrProf.h:140
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
inst_range instructions(Function *F)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
Definition InstrProf.h:220
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition InstrProf.h:118
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
LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition InstrProf.h:193
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
@ Add
Sum of integers.
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
LLVM_ABI void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
StringRef getInstrProfNamesVarPostfixVarName()
Definition InstrProf.h:155
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.
LLVM_ABI bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
Definition CFG.cpp:424
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)
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition InstrProf.h:112
llvm::cl::opt< llvm::InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition InstrProf.h:187
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 ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
Definition InstrProf.h:153
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition InstrProf.h:149
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
@ Extern
Replace returns with jump to thunk, don't emit thunk.
Definition CodeGen.h:163
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition InstrProf.h:134
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.