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