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