LLVM 20.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"
25#include "llvm/IR/Attributes.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/Constant.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/DIBuilder.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalValue.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/Instruction.h"
41#include "llvm/IR/MDBuilder.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
45#include "llvm/Pass.h"
50#include "llvm/Support/Error.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <string>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "instrprof"
66
67namespace llvm {
68// Command line option to enable vtable value profiling. Defined in
69// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
71// TODO: Remove -debug-info-correlate in next LLVM release, in favor of
72// -profile-correlate=debug-info.
74 "debug-info-correlate",
75 cl::desc("Use debug info to correlate profiles. (Deprecated, use "
76 "-profile-correlate=debug-info)"),
77 cl::init(false));
78
80 "profile-correlate",
81 cl::desc("Use debug info or binary file to correlate profiles."),
84 "No profile correlation"),
86 "Use debug info to correlate"),
88 "Use binary to correlate")));
89} // namespace llvm
90
91namespace {
92
93cl::opt<bool> DoHashBasedCounterSplit(
94 "hash-based-counter-split",
95 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
96 cl::init(true));
97
99 RuntimeCounterRelocation("runtime-counter-relocation",
100 cl::desc("Enable relocating counters at runtime."),
101 cl::init(false));
102
103cl::opt<bool> ValueProfileStaticAlloc(
104 "vp-static-alloc",
105 cl::desc("Do static counter allocation for value profiler"),
106 cl::init(true));
107
108cl::opt<double> NumCountersPerValueSite(
109 "vp-counters-per-site",
110 cl::desc("The average number of profile counters allocated "
111 "per value profiling site."),
112 // This is set to a very small value because in real programs, only
113 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
114 // For those sites with non-zero profile, the average number of targets
115 // is usually smaller than 2.
116 cl::init(1.0));
117
118cl::opt<bool> AtomicCounterUpdateAll(
119 "instrprof-atomic-counter-update-all",
120 cl::desc("Make all profile counter updates atomic (for testing only)"),
121 cl::init(false));
122
123cl::opt<bool> AtomicCounterUpdatePromoted(
124 "atomic-counter-update-promoted",
125 cl::desc("Do counter update using atomic fetch add "
126 " for promoted counters only"),
127 cl::init(false));
128
129cl::opt<bool> AtomicFirstCounter(
130 "atomic-first-counter",
131 cl::desc("Use atomic fetch add for first counter in a function (usually "
132 "the entry counter)"),
133 cl::init(false));
134
135cl::opt<bool> ConditionalCounterUpdate(
136 "conditional-counter-update",
137 cl::desc("Do conditional counter updates in single byte counters mode)"),
138 cl::init(false));
139
140// If the option is not specified, the default behavior about whether
141// counter promotion is done depends on how instrumentaiton lowering
142// pipeline is setup, i.e., the default value of true of this option
143// does not mean the promotion will be done by default. Explicitly
144// setting this option can override the default behavior.
145cl::opt<bool> DoCounterPromotion("do-counter-promotion",
146 cl::desc("Do counter register promotion"),
147 cl::init(false));
148cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
149 "max-counter-promotions-per-loop", cl::init(20),
150 cl::desc("Max number counter promotions per loop to avoid"
151 " increasing register pressure too much"));
152
153// A debug option
155 MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
156 cl::desc("Max number of allowed counter promotions"));
157
158cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
159 "speculative-counter-promotion-max-exiting", cl::init(3),
160 cl::desc("The max number of exiting blocks of a loop to allow "
161 " speculative counter promotion"));
162
163cl::opt<bool> SpeculativeCounterPromotionToLoop(
164 "speculative-counter-promotion-to-loop",
165 cl::desc("When the option is false, if the target block is in a loop, "
166 "the promotion will be disallowed unless the promoted counter "
167 " update can be further/iteratively promoted into an acyclic "
168 " region."));
169
170cl::opt<bool> IterativeCounterPromotion(
171 "iterative-counter-promotion", cl::init(true),
172 cl::desc("Allow counter promotion across the whole loop nest."));
173
174cl::opt<bool> SkipRetExitBlock(
175 "skip-ret-exit-block", cl::init(true),
176 cl::desc("Suppress counter promotion if exit blocks contain ret."));
177
178static cl::opt<bool> SampledInstr("sampled-instrumentation", cl::ZeroOrMore,
179 cl::init(false),
180 cl::desc("Do PGO instrumentation sampling"));
181
182static cl::opt<unsigned> SampledInstrPeriod(
183 "sampled-instr-period",
184 cl::desc("Set the profile instrumentation sample period. For each sample "
185 "period, a fixed number of consecutive samples will be recorded. "
186 "The number is controlled by 'sampled-instr-burst-duration' flag. "
187 "The default sample period of 65535 is optimized for generating "
188 "efficient code that leverages unsigned integer wrapping in "
189 "overflow."),
190 cl::init(65535));
191
192static cl::opt<unsigned> SampledInstrBurstDuration(
193 "sampled-instr-burst-duration",
194 cl::desc("Set the profile instrumentation burst duration, which can range "
195 "from 0 to one less than the value of 'sampled-instr-period'. "
196 "This number of samples will be recorded for each "
197 "'sampled-instr-period' count update. Setting to 1 enables "
198 "simple sampling, in which case it is recommended to set "
199 "'sampled-instr-period' to a prime number."),
200 cl::init(200));
201
202using LoadStorePair = std::pair<Instruction *, Instruction *>;
203
204static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
205 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
206 if (!MD)
207 return 0;
208
209 // If the flag is a ConstantAsMetadata, it should be an integer representable
210 // in 64-bits.
211 return cast<ConstantInt>(MD->getValue())->getZExtValue();
212}
213
214static bool enablesValueProfiling(const Module &M) {
215 return isIRPGOFlagSet(&M) ||
216 getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
217}
218
219// Conservatively returns true if value profiling is enabled.
220static bool profDataReferencedByCode(const Module &M) {
221 return enablesValueProfiling(M);
222}
223
224class InstrLowerer final {
225public:
226 InstrLowerer(Module &M, const InstrProfOptions &Options,
227 std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
228 bool IsCS)
229 : M(M), Options(Options), TT(Triple(M.getTargetTriple())), IsCS(IsCS),
230 GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
231
232 bool lower();
233
234private:
235 Module &M;
236 const InstrProfOptions Options;
237 const Triple TT;
238 // Is this lowering for the context-sensitive instrumentation.
239 const bool IsCS;
240
241 std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
242
243 const bool DataReferencedByCode;
244
245 struct PerFunctionProfileData {
246 uint32_t NumValueSites[IPVK_Last + 1] = {};
247 GlobalVariable *RegionCounters = nullptr;
248 GlobalVariable *DataVar = nullptr;
249 GlobalVariable *RegionBitmaps = nullptr;
250 uint32_t NumBitmapBytes = 0;
251
252 PerFunctionProfileData() = default;
253 };
255 // Key is virtual table variable, value is 'VTableProfData' in the form of
256 // GlobalVariable.
258 /// If runtime relocation is enabled, this maps functions to the load
259 /// instruction that produces the profile relocation bias.
260 DenseMap<const Function *, LoadInst *> FunctionToProfileBiasMap;
261 std::vector<GlobalValue *> CompilerUsedVars;
262 std::vector<GlobalValue *> UsedVars;
263 std::vector<GlobalVariable *> ReferencedNames;
264 // The list of virtual table variables of which the VTableProfData is
265 // collected.
266 std::vector<GlobalVariable *> ReferencedVTables;
267 GlobalVariable *NamesVar = nullptr;
268 size_t NamesSize = 0;
269
270 /// The instance of [[alwaysinline]] rmw_or(ptr, i8).
271 /// This is name-insensitive.
272 Function *RMWOrFunc = nullptr;
273
274 // vector of counter load/store pairs to be register promoted.
275 std::vector<LoadStorePair> PromotionCandidates;
276
277 int64_t TotalCountersPromoted = 0;
278
279 /// Lower instrumentation intrinsics in the function. Returns true if there
280 /// any lowering.
281 bool lowerIntrinsics(Function *F);
282
283 /// Register-promote counter loads and stores in loops.
284 void promoteCounterLoadStores(Function *F);
285
286 /// Returns true if relocating counters at runtime is enabled.
287 bool isRuntimeCounterRelocationEnabled() const;
288
289 /// Returns true if profile counter update register promotion is enabled.
290 bool isCounterPromotionEnabled() const;
291
292 /// Return true if profile sampling is enabled.
293 bool isSamplingEnabled() const;
294
295 /// Count the number of instrumented value sites for the function.
296 void computeNumValueSiteCounts(InstrProfValueProfileInst *Ins);
297
298 /// Replace instrprof.value.profile with a call to runtime library.
299 void lowerValueProfileInst(InstrProfValueProfileInst *Ins);
300
301 /// Replace instrprof.cover with a store instruction to the coverage byte.
302 void lowerCover(InstrProfCoverInst *Inc);
303
304 /// Replace instrprof.timestamp with a call to
305 /// INSTR_PROF_PROFILE_SET_TIMESTAMP.
306 void lowerTimestamp(InstrProfTimestampInst *TimestampInstruction);
307
308 /// Replace instrprof.increment with an increment of the appropriate value.
309 void lowerIncrement(InstrProfIncrementInst *Inc);
310
311 /// Force emitting of name vars for unused functions.
312 void lowerCoverageData(GlobalVariable *CoverageNamesVar);
313
314 /// Replace instrprof.mcdc.tvbitmask.update with a shift and or instruction
315 /// using the index represented by the a temp value into a bitmap.
316 void lowerMCDCTestVectorBitmapUpdate(InstrProfMCDCTVBitmapUpdate *Ins);
317
318 /// Get the Bias value for data to access mmap-ed area.
319 /// Create it if it hasn't been seen.
320 GlobalVariable *getOrCreateBiasVar(StringRef VarName);
321
322 /// Compute the address of the counter value that this profiling instruction
323 /// acts on.
324 Value *getCounterAddress(InstrProfCntrInstBase *I);
325
326 /// Lower the incremental instructions under profile sampling predicates.
327 void doSampling(Instruction *I);
328
329 /// Get the region counters for an increment, creating them if necessary.
330 ///
331 /// If the counter array doesn't yet exist, the profile data variables
332 /// referring to them will also be created.
333 GlobalVariable *getOrCreateRegionCounters(InstrProfCntrInstBase *Inc);
334
335 /// Create the region counters.
336 GlobalVariable *createRegionCounters(InstrProfCntrInstBase *Inc,
339
340 /// Create [[alwaysinline]] rmw_or(ptr, i8).
341 /// This doesn't update `RMWOrFunc`.
342 Function *createRMWOrFunc();
343
344 /// Get the call to `rmw_or`.
345 /// Create the instance if it is unknown.
346 CallInst *getRMWOrCall(Value *Addr, Value *Val);
347
348 /// Compute the address of the test vector bitmap that this profiling
349 /// instruction acts on.
350 Value *getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I);
351
352 /// Get the region bitmaps for an increment, creating them if necessary.
353 ///
354 /// If the bitmap array doesn't yet exist, the profile data variables
355 /// referring to them will also be created.
356 GlobalVariable *getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc);
357
358 /// Create the MC/DC bitmap as a byte-aligned array of bytes associated with
359 /// an MC/DC Decision region. The number of bytes required is indicated by
360 /// the intrinsic used (type InstrProfMCDCBitmapInstBase). This is called
361 /// as part of setupProfileSection() and is conceptually very similar to
362 /// what is done for profile data counters in createRegionCounters().
363 GlobalVariable *createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
366
367 /// Set Comdat property of GV, if required.
368 void maybeSetComdat(GlobalVariable *GV, GlobalObject *GO, StringRef VarName);
369
370 /// Setup the sections into which counters and bitmaps are allocated.
371 GlobalVariable *setupProfileSection(InstrProfInstBase *Inc,
372 InstrProfSectKind IPSK);
373
374 /// Create INSTR_PROF_DATA variable for counters and bitmaps.
375 void createDataVariable(InstrProfCntrInstBase *Inc);
376
377 /// Get the counters for virtual table values, creating them if necessary.
378 void getOrCreateVTableProfData(GlobalVariable *GV);
379
380 /// Emit the section with compressed function names.
381 void emitNameData();
382
383 /// Emit the section with compressed vtable names.
384 void emitVTableNames();
385
386 /// Emit value nodes section for value profiling.
387 void emitVNodes();
388
389 /// Emit runtime registration functions for each profile data variable.
390 void emitRegistration();
391
392 /// Emit the necessary plumbing to pull in the runtime initialization.
393 /// Returns true if a change was made.
394 bool emitRuntimeHook();
395
396 /// Add uses of our data variables and runtime hook.
397 void emitUses();
398
399 /// Create a static initializer for our data, on platforms that need it,
400 /// and for any profile output file that was specified.
401 void emitInitialization();
402};
403
404///
405/// A helper class to promote one counter RMW operation in the loop
406/// into register update.
407///
408/// RWM update for the counter will be sinked out of the loop after
409/// the transformation.
410///
411class PGOCounterPromoterHelper : public LoadAndStorePromoter {
412public:
413 PGOCounterPromoterHelper(
415 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
416 ArrayRef<Instruction *> InsertPts,
418 LoopInfo &LI)
419 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
420 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
421 assert(isa<LoadInst>(L));
422 assert(isa<StoreInst>(S));
423 SSA.AddAvailableValue(PH, Init);
424 }
425
426 void doExtraRewritesBeforeFinalDeletion() override {
427 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
428 BasicBlock *ExitBlock = ExitBlocks[i];
429 Instruction *InsertPos = InsertPts[i];
430 // Get LiveIn value into the ExitBlock. If there are multiple
431 // predecessors, the value is defined by a PHI node in this
432 // block.
433 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
434 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
435 Type *Ty = LiveInValue->getType();
436 IRBuilder<> Builder(InsertPos);
437 if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
438 // If isRuntimeCounterRelocationEnabled() is true then the address of
439 // the store instruction is computed with two instructions in
440 // InstrProfiling::getCounterAddress(). We need to copy those
441 // instructions to this block to compute Addr correctly.
442 // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
443 // %Addr = inttoptr i64 %BiasAdd to i64*
444 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
445 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
446 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
447 Addr = Builder.CreateIntToPtr(BiasInst,
448 PointerType::getUnqual(Ty->getContext()));
449 }
450 if (AtomicCounterUpdatePromoted)
451 // automic update currently can only be promoted across the current
452 // loop, not the whole loop nest.
453 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
454 MaybeAlign(),
455 AtomicOrdering::SequentiallyConsistent);
456 else {
457 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
458 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
459 auto *NewStore = Builder.CreateStore(NewVal, Addr);
460
461 // Now update the parent loop's candidate list:
462 if (IterativeCounterPromotion) {
463 auto *TargetLoop = LI.getLoopFor(ExitBlock);
464 if (TargetLoop)
465 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
466 }
467 }
468 }
469 }
470
471private:
473 ArrayRef<BasicBlock *> ExitBlocks;
474 ArrayRef<Instruction *> InsertPts;
476 LoopInfo &LI;
477};
478
479/// A helper class to do register promotion for all profile counter
480/// updates in a loop.
481///
482class PGOCounterPromoter {
483public:
484 PGOCounterPromoter(
486 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
487 : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
488
489 // Skip collection of ExitBlocks and InsertPts for loops that will not be
490 // able to have counters promoted.
491 SmallVector<BasicBlock *, 8> LoopExitBlocks;
493
494 L.getExitBlocks(LoopExitBlocks);
495 if (!isPromotionPossible(&L, LoopExitBlocks))
496 return;
497
498 for (BasicBlock *ExitBlock : LoopExitBlocks) {
499 if (BlockSet.insert(ExitBlock).second &&
500 llvm::none_of(predecessors(ExitBlock), [&](const BasicBlock *Pred) {
501 return llvm::isPresplitCoroSuspendExitEdge(*Pred, *ExitBlock);
502 })) {
503 ExitBlocks.push_back(ExitBlock);
504 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
505 }
506 }
507 }
508
509 bool run(int64_t *NumPromoted) {
510 // Skip 'infinite' loops:
511 if (ExitBlocks.size() == 0)
512 return false;
513
514 // Skip if any of the ExitBlocks contains a ret instruction.
515 // This is to prevent dumping of incomplete profile -- if the
516 // the loop is a long running loop and dump is called in the middle
517 // of the loop, the result profile is incomplete.
518 // FIXME: add other heuristics to detect long running loops.
519 if (SkipRetExitBlock) {
520 for (auto *BB : ExitBlocks)
521 if (isa<ReturnInst>(BB->getTerminator()))
522 return false;
523 }
524
525 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
526 if (MaxProm == 0)
527 return false;
528
529 unsigned Promoted = 0;
530 for (auto &Cand : LoopToCandidates[&L]) {
531
533 SSAUpdater SSA(&NewPHIs);
534 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
535
536 // If BFI is set, we will use it to guide the promotions.
537 if (BFI) {
538 auto *BB = Cand.first->getParent();
539 auto InstrCount = BFI->getBlockProfileCount(BB);
540 if (!InstrCount)
541 continue;
542 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
543 // If the average loop trip count is not greater than 1.5, we skip
544 // promotion.
545 if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
546 continue;
547 }
548
549 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
550 L.getLoopPreheader(), ExitBlocks,
551 InsertPts, LoopToCandidates, LI);
552 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
553 Promoted++;
554 if (Promoted >= MaxProm)
555 break;
556
557 (*NumPromoted)++;
558 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
559 break;
560 }
561
562 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
563 << L.getLoopDepth() << ")\n");
564 return Promoted != 0;
565 }
566
567private:
568 bool allowSpeculativeCounterPromotion(Loop *LP) {
569 SmallVector<BasicBlock *, 8> ExitingBlocks;
570 L.getExitingBlocks(ExitingBlocks);
571 // Not considierered speculative.
572 if (ExitingBlocks.size() == 1)
573 return true;
574 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
575 return false;
576 return true;
577 }
578
579 // Check whether the loop satisfies the basic conditions needed to perform
580 // Counter Promotions.
581 bool
582 isPromotionPossible(Loop *LP,
583 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
584 // We can't insert into a catchswitch.
585 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
586 return isa<CatchSwitchInst>(Exit->getTerminator());
587 }))
588 return false;
589
590 if (!LP->hasDedicatedExits())
591 return false;
592
593 BasicBlock *PH = LP->getLoopPreheader();
594 if (!PH)
595 return false;
596
597 return true;
598 }
599
600 // Returns the max number of Counter Promotions for LP.
601 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
602 SmallVector<BasicBlock *, 8> LoopExitBlocks;
603 LP->getExitBlocks(LoopExitBlocks);
604 if (!isPromotionPossible(LP, LoopExitBlocks))
605 return 0;
606
607 SmallVector<BasicBlock *, 8> ExitingBlocks;
608 LP->getExitingBlocks(ExitingBlocks);
609
610 // If BFI is set, we do more aggressive promotions based on BFI.
611 if (BFI)
612 return (unsigned)-1;
613
614 // Not considierered speculative.
615 if (ExitingBlocks.size() == 1)
616 return MaxNumOfPromotionsPerLoop;
617
618 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
619 return 0;
620
621 // Whether the target block is in a loop does not matter:
622 if (SpeculativeCounterPromotionToLoop)
623 return MaxNumOfPromotionsPerLoop;
624
625 // Now check the target block:
626 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
627 for (auto *TargetBlock : LoopExitBlocks) {
628 auto *TargetLoop = LI.getLoopFor(TargetBlock);
629 if (!TargetLoop)
630 continue;
631 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
632 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
633 MaxProm =
634 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
635 PendingCandsInTarget);
636 }
637 return MaxProm;
638 }
639
643 Loop &L;
644 LoopInfo &LI;
646};
647
648enum class ValueProfilingCallType {
649 // Individual values are tracked. Currently used for indiret call target
650 // profiling.
651 Default,
652
653 // MemOp: the memop size value profiling.
654 MemOp
655};
656
657} // end anonymous namespace
658
663 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
665 };
666 InstrLowerer Lowerer(M, Options, GetTLI, IsCS);
667 if (!Lowerer.lower())
668 return PreservedAnalyses::all();
669
671}
672
673//
674// Perform instrumentation sampling.
675//
676// There are 3 favors of sampling:
677// (1) Full burst sampling: We transform:
678// Increment_Instruction;
679// to:
680// if (__llvm_profile_sampling__ < SampledInstrBurstDuration) {
681// Increment_Instruction;
682// }
683// __llvm_profile_sampling__ += 1;
684// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
685// __llvm_profile_sampling__ = 0;
686// }
687//
688// "__llvm_profile_sampling__" is a thread-local global shared by all PGO
689// counters (value-instrumentation and edge instrumentation).
690//
691// (2) Fast burst sampling:
692// "__llvm_profile_sampling__" variable is an unsigned type, meaning it will
693// wrap around to zero when overflows. In this case, the second check is
694// unnecessary, so we won't generate check2 when the SampledInstrPeriod is
695// set to 65535 (64K - 1). The code after:
696// if (__llvm_profile_sampling__ < SampledInstrBurstDuration) {
697// Increment_Instruction;
698// }
699// __llvm_profile_sampling__ += 1;
700//
701// (3) Simple sampling:
702// When SampledInstrBurstDuration sets to 1, we do a simple sampling:
703// __llvm_profile_sampling__ += 1;
704// if (__llvm_profile_sampling__ >= SampledInstrPeriod) {
705// __llvm_profile_sampling__ = 0;
706// Increment_Instruction;
707// }
708//
709// Note that, the code snippet after the transformation can still be counter
710// promoted. However, with sampling enabled, counter updates are expected to
711// be infrequent, making the benefits of counter promotion negligible.
712// Moreover, counter promotion can potentially cause issues in server
713// applications, particularly when the counters are dumped without a clean
714// exit. To mitigate this risk, counter promotion is disabled by default when
715// sampling is enabled. This behavior can be overridden using the internal
716// option.
717void InstrLowerer::doSampling(Instruction *I) {
718 if (!isSamplingEnabled())
719 return;
720
721 unsigned SampledBurstDuration = SampledInstrBurstDuration.getValue();
722 unsigned SampledPeriod = SampledInstrPeriod.getValue();
723 if (SampledBurstDuration >= SampledPeriod) {
725 "SampledPeriod needs to be greater than SampledBurstDuration");
726 }
727 bool UseShort = (SampledPeriod <= USHRT_MAX);
728 bool IsSimpleSampling = (SampledBurstDuration == 1);
729 // If (SampledBurstDuration == 1 && SampledPeriod == 65535), generate
730 // the simple sampling style code.
731 bool IsFastSampling = (!IsSimpleSampling && SampledPeriod == 65535);
732
733 auto GetConstant = [UseShort](IRBuilder<> &Builder, uint32_t C) {
734 if (UseShort)
735 return Builder.getInt16(C);
736 else
737 return Builder.getInt32(C);
738 };
739
740 IntegerType *SamplingVarTy;
741 if (UseShort)
742 SamplingVarTy = Type::getInt16Ty(M.getContext());
743 else
744 SamplingVarTy = Type::getInt32Ty(M.getContext());
745 auto *SamplingVar =
746 M.getGlobalVariable(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SAMPLING_VAR));
747 assert(SamplingVar && "SamplingVar not set properly");
748
749 // Create the condition for checking the burst duration.
750 Instruction *SamplingVarIncr;
751 Value *NewSamplingVarVal;
752 MDBuilder MDB(I->getContext());
753 MDNode *BranchWeight;
754 IRBuilder<> CondBuilder(I);
755 auto *LoadSamplingVar = CondBuilder.CreateLoad(SamplingVarTy, SamplingVar);
756 if (IsSimpleSampling) {
757 // For the simple sampling, just create the load and increments.
758 IRBuilder<> IncBuilder(I);
759 NewSamplingVarVal =
760 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
761 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
762 } else {
763 // For the bust-sampling, create the conditonal update.
764 auto *DurationCond = CondBuilder.CreateICmpULE(
765 LoadSamplingVar, GetConstant(CondBuilder, SampledBurstDuration));
766 BranchWeight = MDB.createBranchWeights(
767 SampledBurstDuration, SampledPeriod + 1 - SampledBurstDuration);
769 DurationCond, I, /* Unreachable */ false, BranchWeight);
770 IRBuilder<> IncBuilder(I);
771 NewSamplingVarVal =
772 IncBuilder.CreateAdd(LoadSamplingVar, GetConstant(IncBuilder, 1));
773 SamplingVarIncr = IncBuilder.CreateStore(NewSamplingVarVal, SamplingVar);
774 I->moveBefore(ThenTerm);
775 }
776
777 if (IsFastSampling)
778 return;
779
780 // Create the condtion for checking the period.
781 Instruction *ThenTerm, *ElseTerm;
782 IRBuilder<> PeriodCondBuilder(SamplingVarIncr);
783 auto *PeriodCond = PeriodCondBuilder.CreateICmpUGE(
784 NewSamplingVarVal, GetConstant(PeriodCondBuilder, SampledPeriod));
785 BranchWeight = MDB.createBranchWeights(1, SampledPeriod);
786 SplitBlockAndInsertIfThenElse(PeriodCond, SamplingVarIncr, &ThenTerm,
787 &ElseTerm, BranchWeight);
788
789 // For the simple sampling, the counter update happens in sampling var reset.
790 if (IsSimpleSampling)
791 I->moveBefore(ThenTerm);
792
793 IRBuilder<> ResetBuilder(ThenTerm);
794 ResetBuilder.CreateStore(GetConstant(ResetBuilder, 0), SamplingVar);
795 SamplingVarIncr->moveBefore(ElseTerm);
796}
797
798bool InstrLowerer::lowerIntrinsics(Function *F) {
799 bool MadeChange = false;
800 PromotionCandidates.clear();
802
803 // To ensure compatibility with sampling, we save the intrinsics into
804 // a buffer to prevent potential breakage of the iterator (as the
805 // intrinsics will be moved to a different BB).
806 for (BasicBlock &BB : *F) {
807 for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
808 if (auto *IP = dyn_cast<InstrProfInstBase>(&Instr))
809 InstrProfInsts.push_back(IP);
810 }
811 }
812
813 for (auto *Instr : InstrProfInsts) {
814 doSampling(Instr);
815 if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(Instr)) {
816 lowerIncrement(IPIS);
817 MadeChange = true;
818 } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(Instr)) {
819 lowerIncrement(IPI);
820 MadeChange = true;
821 } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(Instr)) {
822 lowerTimestamp(IPC);
823 MadeChange = true;
824 } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(Instr)) {
825 lowerCover(IPC);
826 MadeChange = true;
827 } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(Instr)) {
828 lowerValueProfileInst(IPVP);
829 MadeChange = true;
830 } else if (auto *IPMP = dyn_cast<InstrProfMCDCBitmapParameters>(Instr)) {
831 IPMP->eraseFromParent();
832 MadeChange = true;
833 } else if (auto *IPBU = dyn_cast<InstrProfMCDCTVBitmapUpdate>(Instr)) {
834 lowerMCDCTestVectorBitmapUpdate(IPBU);
835 MadeChange = true;
836 }
837 }
838
839 if (!MadeChange)
840 return false;
841
842 promoteCounterLoadStores(F);
843 return true;
844}
845
846bool InstrLowerer::isRuntimeCounterRelocationEnabled() const {
847 // Mach-O don't support weak external references.
848 if (TT.isOSBinFormatMachO())
849 return false;
850
851 if (RuntimeCounterRelocation.getNumOccurrences() > 0)
852 return RuntimeCounterRelocation;
853
854 // Fuchsia uses runtime counter relocation by default.
855 return TT.isOSFuchsia();
856}
857
858bool InstrLowerer::isSamplingEnabled() const {
859 if (SampledInstr.getNumOccurrences() > 0)
860 return SampledInstr;
861 return Options.Sampling;
862}
863
864bool InstrLowerer::isCounterPromotionEnabled() const {
865 if (DoCounterPromotion.getNumOccurrences() > 0)
866 return DoCounterPromotion;
867
868 return Options.DoCounterPromotion;
869}
870
871void InstrLowerer::promoteCounterLoadStores(Function *F) {
872 if (!isCounterPromotionEnabled())
873 return;
874
875 DominatorTree DT(*F);
876 LoopInfo LI(DT);
877 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
878
879 std::unique_ptr<BlockFrequencyInfo> BFI;
880 if (Options.UseBFIInPromotion) {
881 std::unique_ptr<BranchProbabilityInfo> BPI;
882 BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
883 BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
884 }
885
886 for (const auto &LoadStore : PromotionCandidates) {
887 auto *CounterLoad = LoadStore.first;
888 auto *CounterStore = LoadStore.second;
889 BasicBlock *BB = CounterLoad->getParent();
890 Loop *ParentLoop = LI.getLoopFor(BB);
891 if (!ParentLoop)
892 continue;
893 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
894 }
895
897
898 // Do a post-order traversal of the loops so that counter updates can be
899 // iteratively hoisted outside the loop nest.
900 for (auto *Loop : llvm::reverse(Loops)) {
901 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
902 Promoter.run(&TotalCountersPromoted);
903 }
904}
905
907 // On Fuchsia, we only need runtime hook if any counters are present.
908 if (TT.isOSFuchsia())
909 return false;
910
911 return true;
912}
913
914/// Check if the module contains uses of any profiling intrinsics.
916 auto containsIntrinsic = [&](int ID) {
917 if (auto *F = M.getFunction(Intrinsic::getName(ID)))
918 return !F->use_empty();
919 return false;
920 };
921 return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
922 containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
923 containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
924 containsIntrinsic(llvm::Intrinsic::instrprof_timestamp) ||
925 containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
926}
927
928bool InstrLowerer::lower() {
929 bool MadeChange = false;
930 bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
931 if (NeedsRuntimeHook)
932 MadeChange = emitRuntimeHook();
933
934 if (!IsCS && isSamplingEnabled())
936
937 bool ContainsProfiling = containsProfilingIntrinsics(M);
938 GlobalVariable *CoverageNamesVar =
939 M.getNamedGlobal(getCoverageUnusedNamesVarName());
940 // Improve compile time by avoiding linear scans when there is no work.
941 if (!ContainsProfiling && !CoverageNamesVar)
942 return MadeChange;
943
944 // We did not know how many value sites there would be inside
945 // the instrumented function. This is counting the number of instrumented
946 // target value sites to enter it as field in the profile data variable.
947 for (Function &F : M) {
948 InstrProfCntrInstBase *FirstProfInst = nullptr;
949 for (BasicBlock &BB : F) {
950 for (auto I = BB.begin(), E = BB.end(); I != E; I++) {
951 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
952 computeNumValueSiteCounts(Ind);
953 else {
954 if (FirstProfInst == nullptr &&
955 (isa<InstrProfIncrementInst>(I) || isa<InstrProfCoverInst>(I)))
956 FirstProfInst = dyn_cast<InstrProfCntrInstBase>(I);
957 // If the MCDCBitmapParameters intrinsic seen, create the bitmaps.
958 if (const auto &Params = dyn_cast<InstrProfMCDCBitmapParameters>(I))
959 static_cast<void>(getOrCreateRegionBitmaps(Params));
960 }
961 }
962 }
963
964 // Use a profile intrinsic to create the region counters and data variable.
965 // Also create the data variable based on the MCDCParams.
966 if (FirstProfInst != nullptr) {
967 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
968 }
969 }
970
972 for (GlobalVariable &GV : M.globals())
973 // Global variables with type metadata are virtual table variables.
974 if (GV.hasMetadata(LLVMContext::MD_type))
975 getOrCreateVTableProfData(&GV);
976
977 for (Function &F : M)
978 MadeChange |= lowerIntrinsics(&F);
979
980 if (CoverageNamesVar) {
981 lowerCoverageData(CoverageNamesVar);
982 MadeChange = true;
983 }
984
985 if (!MadeChange)
986 return false;
987
988 emitVNodes();
989 emitNameData();
990 emitVTableNames();
991
992 // Emit runtime hook for the cases where the target does not unconditionally
993 // require pulling in profile runtime, and coverage is enabled on code that is
994 // not eliminated by the front-end, e.g. unused functions with internal
995 // linkage.
996 if (!NeedsRuntimeHook && ContainsProfiling)
997 emitRuntimeHook();
998
999 emitRegistration();
1000 emitUses();
1001 emitInitialization();
1002 return true;
1003}
1004
1006 Module &M, const TargetLibraryInfo &TLI,
1007 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
1008 LLVMContext &Ctx = M.getContext();
1009 auto *ReturnTy = Type::getVoidTy(M.getContext());
1010
1011 AttributeList AL;
1012 if (auto AK = TLI.getExtAttrForI32Param(false))
1013 AL = AL.addParamAttribute(M.getContext(), 2, AK);
1014
1015 assert((CallType == ValueProfilingCallType::Default ||
1016 CallType == ValueProfilingCallType::MemOp) &&
1017 "Must be Default or MemOp");
1018 Type *ParamTypes[] = {
1019#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
1021 };
1022 auto *ValueProfilingCallTy =
1023 FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
1024 StringRef FuncName = CallType == ValueProfilingCallType::Default
1027 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
1028}
1029
1030void InstrLowerer::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
1031 GlobalVariable *Name = Ind->getName();
1033 uint64_t Index = Ind->getIndex()->getZExtValue();
1034 auto &PD = ProfileDataMap[Name];
1035 PD.NumValueSites[ValueKind] =
1036 std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
1037}
1038
1039void InstrLowerer::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
1040 // TODO: Value profiling heavily depends on the data section which is omitted
1041 // in lightweight mode. We need to move the value profile pointer to the
1042 // Counter struct to get this working.
1043 assert(
1045 "Value profiling is not yet supported with lightweight instrumentation");
1046 GlobalVariable *Name = Ind->getName();
1047 auto It = ProfileDataMap.find(Name);
1048 assert(It != ProfileDataMap.end() && It->second.DataVar &&
1049 "value profiling detected in function with no counter incerement");
1050
1051 GlobalVariable *DataVar = It->second.DataVar;
1053 uint64_t Index = Ind->getIndex()->getZExtValue();
1054 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
1055 Index += It->second.NumValueSites[Kind];
1056
1057 IRBuilder<> Builder(Ind);
1058 bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
1059 llvm::InstrProfValueKind::IPVK_MemOPSize);
1060 CallInst *Call = nullptr;
1061 auto *TLI = &GetTLI(*Ind->getFunction());
1062
1063 // To support value profiling calls within Windows exception handlers, funclet
1064 // information contained within operand bundles needs to be copied over to
1065 // the library call. This is required for the IR to be processed by the
1066 // WinEHPrepare pass.
1068 Ind->getOperandBundlesAsDefs(OpBundles);
1069 if (!IsMemOpSize) {
1070 Value *Args[3] = {Ind->getTargetValue(), DataVar, Builder.getInt32(Index)};
1071 Call = Builder.CreateCall(getOrInsertValueProfilingCall(M, *TLI), Args,
1072 OpBundles);
1073 } else {
1074 Value *Args[3] = {Ind->getTargetValue(), DataVar, Builder.getInt32(Index)};
1075 Call = Builder.CreateCall(
1076 getOrInsertValueProfilingCall(M, *TLI, ValueProfilingCallType::MemOp),
1077 Args, OpBundles);
1078 }
1079 if (auto AK = TLI->getExtAttrForI32Param(false))
1080 Call->addParamAttr(2, AK);
1081 Ind->replaceAllUsesWith(Call);
1082 Ind->eraseFromParent();
1083}
1084
1085GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
1086 GlobalVariable *Bias = M.getGlobalVariable(VarName);
1087 if (Bias)
1088 return Bias;
1089
1090 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1091
1092 // Compiler must define this variable when runtime counter relocation
1093 // is being used. Runtime has a weak external reference that is used
1094 // to check whether that's the case or not.
1095 Bias = new GlobalVariable(M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
1096 Constant::getNullValue(Int64Ty), VarName);
1098 // A definition that's weak (linkonce_odr) without being in a COMDAT
1099 // section wouldn't lead to link errors, but it would lead to a dead
1100 // data word from every TU but one. Putting it in COMDAT ensures there
1101 // will be exactly one data slot in the link.
1102 if (TT.supportsCOMDAT())
1103 Bias->setComdat(M.getOrInsertComdat(VarName));
1104
1105 return Bias;
1106}
1107
1108Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
1109 auto *Counters = getOrCreateRegionCounters(I);
1110 IRBuilder<> Builder(I);
1111
1112 if (isa<InstrProfTimestampInst>(I))
1113 Counters->setAlignment(Align(8));
1114
1115 auto *Addr = Builder.CreateConstInBoundsGEP2_32(
1116 Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
1117
1118 if (!isRuntimeCounterRelocationEnabled())
1119 return Addr;
1120
1121 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1122 Function *Fn = I->getParent()->getParent();
1123 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
1124 if (!BiasLI) {
1125 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1126 auto *Bias = getOrCreateBiasVar(getInstrProfCounterBiasVarName());
1127 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profc_bias");
1128 // Bias doesn't change after startup.
1129 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1130 MDNode::get(M.getContext(), std::nullopt));
1131 }
1132 auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
1133 return Builder.CreateIntToPtr(Add, Addr->getType());
1134}
1135
1136/// Create `void [[alwaysinline]] rmw_or(uint8_t *ArgAddr, uint8_t ArgVal)`
1137/// "Basic" sequence is `*ArgAddr |= ArgVal`
1138Function *InstrLowerer::createRMWOrFunc() {
1139 auto &Ctx = M.getContext();
1140 auto *Int8Ty = Type::getInt8Ty(Ctx);
1143 {PointerType::getUnqual(Ctx), Int8Ty}, false),
1145 Fn->addFnAttr(Attribute::AlwaysInline);
1146 auto *ArgAddr = Fn->getArg(0);
1147 auto *ArgVal = Fn->getArg(1);
1148 IRBuilder<> Builder(BasicBlock::Create(Ctx, "", Fn));
1149
1150 // Load profile bitmap byte.
1151 // %mcdc.bits = load i8, ptr %4, align 1
1152 auto *Bitmap = Builder.CreateLoad(Int8Ty, ArgAddr, "mcdc.bits");
1153
1154 if (Options.Atomic || AtomicCounterUpdateAll) {
1155 // If ((Bitmap & Val) != Val), then execute atomic (Bitmap |= Val).
1156 // Note, just-loaded Bitmap might not be up-to-date. Use it just for
1157 // early testing.
1158 auto *Masked = Builder.CreateAnd(Bitmap, ArgVal);
1159 auto *ShouldStore = Builder.CreateICmpNE(Masked, ArgVal);
1160 auto *ThenTerm = BasicBlock::Create(Ctx, "", Fn);
1161 auto *ElseTerm = BasicBlock::Create(Ctx, "", Fn);
1162 // Assume updating will be rare.
1163 auto *Unlikely = MDBuilder(Ctx).createUnlikelyBranchWeights();
1164 Builder.CreateCondBr(ShouldStore, ThenTerm, ElseTerm, Unlikely);
1165
1166 IRBuilder<> ThenBuilder(ThenTerm);
1167 ThenBuilder.CreateAtomicRMW(AtomicRMWInst::Or, ArgAddr, ArgVal,
1169 ThenBuilder.CreateRetVoid();
1170
1171 IRBuilder<> ElseBuilder(ElseTerm);
1172 ElseBuilder.CreateRetVoid();
1173
1174 return Fn;
1175 }
1176
1177 // Perform logical OR of profile bitmap byte and shifted bit offset.
1178 // %8 = or i8 %mcdc.bits, %7
1179 auto *Result = Builder.CreateOr(Bitmap, ArgVal);
1180
1181 // Store the updated profile bitmap byte.
1182 // store i8 %8, ptr %3, align 1
1183 Builder.CreateStore(Result, ArgAddr);
1184
1185 // Terminator
1186 Builder.CreateRetVoid();
1187
1188 return Fn;
1189}
1190
1191CallInst *InstrLowerer::getRMWOrCall(Value *Addr, Value *Val) {
1192 if (!RMWOrFunc)
1193 RMWOrFunc = createRMWOrFunc();
1194
1195 return CallInst::Create(RMWOrFunc, {Addr, Val});
1196}
1197
1198Value *InstrLowerer::getBitmapAddress(InstrProfMCDCTVBitmapUpdate *I) {
1199 auto *Bitmaps = getOrCreateRegionBitmaps(I);
1200 if (!isRuntimeCounterRelocationEnabled())
1201 return Bitmaps;
1202
1203 // Put BiasLI onto the entry block.
1204 Type *Int64Ty = Type::getInt64Ty(M.getContext());
1205 Function *Fn = I->getFunction();
1206 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
1207 auto *Bias = getOrCreateBiasVar(getInstrProfBitmapBiasVarName());
1208 auto *BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias, "profbm_bias");
1209 // Assume BiasLI invariant (in the function at least)
1210 BiasLI->setMetadata(LLVMContext::MD_invariant_load,
1211 MDNode::get(M.getContext(), std::nullopt));
1212
1213 // Add Bias to Bitmaps and put it before the intrinsic.
1214 IRBuilder<> Builder(I);
1215 return Builder.CreatePtrAdd(Bitmaps, BiasLI, "profbm_addr");
1216}
1217
1218void InstrLowerer::lowerCover(InstrProfCoverInst *CoverInstruction) {
1219 auto *Addr = getCounterAddress(CoverInstruction);
1220 IRBuilder<> Builder(CoverInstruction);
1221 if (ConditionalCounterUpdate) {
1222 Instruction *SplitBefore = CoverInstruction->getNextNode();
1223 auto &Ctx = CoverInstruction->getParent()->getContext();
1224 auto *Int8Ty = llvm::Type::getInt8Ty(Ctx);
1225 Value *Load = Builder.CreateLoad(Int8Ty, Addr, "pgocount");
1226 Value *Cmp = Builder.CreateIsNotNull(Load, "pgocount.ifnonzero");
1227 Instruction *ThenBranch =
1228 SplitBlockAndInsertIfThen(Cmp, SplitBefore, false);
1229 Builder.SetInsertPoint(ThenBranch);
1230 }
1231
1232 // We store zero to represent that this block is covered.
1233 Builder.CreateStore(Builder.getInt8(0), Addr);
1234 CoverInstruction->eraseFromParent();
1235}
1236
1237void InstrLowerer::lowerTimestamp(
1238 InstrProfTimestampInst *TimestampInstruction) {
1239 assert(TimestampInstruction->getIndex()->isZeroValue() &&
1240 "timestamp probes are always the first probe for a function");
1241 auto &Ctx = M.getContext();
1242 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
1243 IRBuilder<> Builder(TimestampInstruction);
1244 auto *CalleeTy =
1245 FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
1246 auto Callee = M.getOrInsertFunction(
1247 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SET_TIMESTAMP), CalleeTy);
1248 Builder.CreateCall(Callee, {TimestampAddr});
1249 TimestampInstruction->eraseFromParent();
1250}
1251
1252void InstrLowerer::lowerIncrement(InstrProfIncrementInst *Inc) {
1253 auto *Addr = getCounterAddress(Inc);
1254
1255 IRBuilder<> Builder(Inc);
1256 if (Options.Atomic || AtomicCounterUpdateAll ||
1257 (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
1260 } else {
1261 Value *IncStep = Inc->getStep();
1262 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
1263 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
1264 auto *Store = Builder.CreateStore(Count, Addr);
1265 if (isCounterPromotionEnabled())
1266 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
1267 }
1268 Inc->eraseFromParent();
1269}
1270
1271void InstrLowerer::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
1272 ConstantArray *Names =
1273 cast<ConstantArray>(CoverageNamesVar->getInitializer());
1274 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
1275 Constant *NC = Names->getOperand(I);
1276 Value *V = NC->stripPointerCasts();
1277 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
1278 GlobalVariable *Name = cast<GlobalVariable>(V);
1279
1280 Name->setLinkage(GlobalValue::PrivateLinkage);
1281 ReferencedNames.push_back(Name);
1282 if (isa<ConstantExpr>(NC))
1283 NC->dropAllReferences();
1284 }
1285 CoverageNamesVar->eraseFromParent();
1286}
1287
1288void InstrLowerer::lowerMCDCTestVectorBitmapUpdate(
1290 IRBuilder<> Builder(Update);
1291 auto *Int8Ty = Type::getInt8Ty(M.getContext());
1292 auto *Int32Ty = Type::getInt32Ty(M.getContext());
1293 auto *MCDCCondBitmapAddr = Update->getMCDCCondBitmapAddr();
1294 auto *BitmapAddr = getBitmapAddress(Update);
1295
1296 // Load Temp Val + BitmapIdx.
1297 // %mcdc.temp = load i32, ptr %mcdc.addr, align 4
1298 auto *Temp = Builder.CreateAdd(
1299 Builder.CreateLoad(Int32Ty, MCDCCondBitmapAddr, "mcdc.temp"),
1300 Update->getBitmapIndex());
1301
1302 // Calculate byte offset using div8.
1303 // %1 = lshr i32 %mcdc.temp, 3
1304 auto *BitmapByteOffset = Builder.CreateLShr(Temp, 0x3);
1305
1306 // Add byte offset to section base byte address.
1307 // %4 = getelementptr inbounds i8, ptr @__profbm_test, i32 %1
1308 auto *BitmapByteAddr =
1309 Builder.CreateInBoundsPtrAdd(BitmapAddr, BitmapByteOffset);
1310
1311 // Calculate bit offset into bitmap byte by using div8 remainder (AND ~8)
1312 // %5 = and i32 %mcdc.temp, 7
1313 // %6 = trunc i32 %5 to i8
1314 auto *BitToSet = Builder.CreateTrunc(Builder.CreateAnd(Temp, 0x7), Int8Ty);
1315
1316 // Shift bit offset left to form a bitmap.
1317 // %7 = shl i8 1, %6
1318 auto *ShiftedVal = Builder.CreateShl(Builder.getInt8(0x1), BitToSet);
1319
1320 Builder.Insert(getRMWOrCall(BitmapByteAddr, ShiftedVal));
1321 Update->eraseFromParent();
1322}
1323
1324/// Get the name of a profiling variable for a particular function.
1325static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
1326 bool &Renamed) {
1327 StringRef NamePrefix = getInstrProfNameVarPrefix();
1328 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
1329 Function *F = Inc->getParent()->getParent();
1330 Module *M = F->getParent();
1331 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
1333 Renamed = false;
1334 return (Prefix + Name).str();
1335 }
1336 Renamed = true;
1337 uint64_t FuncHash = Inc->getHash()->getZExtValue();
1338 SmallVector<char, 24> HashPostfix;
1339 if (Name.ends_with((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
1340 return (Prefix + Name).str();
1341 return (Prefix + Name + "." + Twine(FuncHash)).str();
1342}
1343
1345 // Only record function addresses if IR PGO is enabled or if clang value
1346 // profiling is enabled. Recording function addresses greatly increases object
1347 // file size, because it prevents the inliner from deleting functions that
1348 // have been inlined everywhere.
1349 if (!profDataReferencedByCode(*F->getParent()))
1350 return false;
1351
1352 // Check the linkage
1353 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
1354 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
1355 !HasAvailableExternallyLinkage)
1356 return true;
1357
1358 // A function marked 'alwaysinline' with available_externally linkage can't
1359 // have its address taken. Doing so would create an undefined external ref to
1360 // the function, which would fail to link.
1361 if (HasAvailableExternallyLinkage &&
1362 F->hasFnAttribute(Attribute::AlwaysInline))
1363 return false;
1364
1365 // Prohibit function address recording if the function is both internal and
1366 // COMDAT. This avoids the profile data variable referencing internal symbols
1367 // in COMDAT.
1368 if (F->hasLocalLinkage() && F->hasComdat())
1369 return false;
1370
1371 // Check uses of this function for other than direct calls or invokes to it.
1372 // Inline virtual functions have linkeOnceODR linkage. When a key method
1373 // exists, the vtable will only be emitted in the TU where the key method
1374 // is defined. In a TU where vtable is not available, the function won't
1375 // be 'addresstaken'. If its address is not recorded here, the profile data
1376 // with missing address may be picked by the linker leading to missing
1377 // indirect call target info.
1378 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
1379}
1380
1381static inline bool shouldUsePublicSymbol(Function *Fn) {
1382 // It isn't legal to make an alias of this function at all
1383 if (Fn->isDeclarationForLinker())
1384 return true;
1385
1386 // Symbols with local linkage can just use the symbol directly without
1387 // introducing relocations
1388 if (Fn->hasLocalLinkage())
1389 return true;
1390
1391 // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
1392 // unfavorable interaction between the new alias and the alias renaming done
1393 // in LowerTypeTests under ThinLTO. For comdat functions that would normally
1394 // be deduplicated, but the renaming scheme ends up preventing renaming, since
1395 // it creates unique names for each alias, resulting in duplicated symbols. In
1396 // the future, we should update the CFI related passes to migrate these
1397 // aliases to the same module as the jump-table they refer to will be defined.
1398 if (Fn->hasMetadata(LLVMContext::MD_type))
1399 return true;
1400
1401 // For comdat functions, an alias would need the same linkage as the original
1402 // function and hidden visibility. There is no point in adding an alias with
1403 // identical linkage an visibility to avoid introducing symbolic relocations.
1404 if (Fn->hasComdat() &&
1406 return true;
1407
1408 // its OK to use an alias
1409 return false;
1410}
1411
1413 auto *Int8PtrTy = PointerType::getUnqual(Fn->getContext());
1414 // Store a nullptr in __llvm_profd, if we shouldn't use a real address
1415 if (!shouldRecordFunctionAddr(Fn))
1416 return ConstantPointerNull::get(Int8PtrTy);
1417
1418 // If we can't use an alias, we must use the public symbol, even though this
1419 // may require a symbolic relocation.
1420 if (shouldUsePublicSymbol(Fn))
1421 return Fn;
1422
1423 // When possible use a private alias to avoid symbolic relocations.
1425 Fn->getName() + ".local", Fn);
1426
1427 // When the instrumented function is a COMDAT function, we cannot use a
1428 // private alias. If we did, we would create reference to a local label in
1429 // this function's section. If this version of the function isn't selected by
1430 // the linker, then the metadata would introduce a reference to a discarded
1431 // section. So, for COMDAT functions, we need to adjust the linkage of the
1432 // alias. Using hidden visibility avoids a dynamic relocation and an entry in
1433 // the dynamic symbol table.
1434 //
1435 // Note that this handles COMDAT functions with visibility other than Hidden,
1436 // since that case is covered in shouldUsePublicSymbol()
1437 if (Fn->hasComdat()) {
1438 GA->setLinkage(Fn->getLinkage());
1440 }
1441
1442 // appendToCompilerUsed(*Fn->getParent(), {GA});
1443
1444 return GA;
1445}
1446
1448 // compiler-rt uses linker support to get data/counters/name start/end for
1449 // ELF, COFF, Mach-O and XCOFF.
1450 if (TT.isOSBinFormatELF() || TT.isOSBinFormatCOFF() ||
1451 TT.isOSBinFormatMachO() || TT.isOSBinFormatXCOFF())
1452 return false;
1453
1454 return true;
1455}
1456
1457void InstrLowerer::maybeSetComdat(GlobalVariable *GV, GlobalObject *GO,
1458 StringRef CounterGroupName) {
1459 // Place lowered global variables in a comdat group if the associated function
1460 // or global variable is a COMDAT. This will make sure that only one copy of
1461 // global variable (e.g. function counters) of the COMDAT function will be
1462 // emitted after linking.
1463 bool NeedComdat = needsComdatForCounter(*GO, M);
1464 bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1465
1466 if (!UseComdat)
1467 return;
1468
1469 // Keep in mind that this pass may run before the inliner, so we need to
1470 // create a new comdat group (for counters, profiling data, etc). If we use
1471 // the comdat of the parent function, that will result in relocations against
1472 // discarded sections.
1473 //
1474 // If the data variable is referenced by code, non-counter variables (notably
1475 // profiling data) and counters have to be in different comdats for COFF
1476 // because the Visual C++ linker will report duplicate symbol errors if there
1477 // are multiple external symbols with the same name marked
1478 // IMAGE_COMDAT_SELECT_ASSOCIATIVE.
1479 StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1480 ? GV->getName()
1481 : CounterGroupName;
1482 Comdat *C = M.getOrInsertComdat(GroupName);
1483
1484 if (!NeedComdat) {
1485 // Object file format must be ELF since `UseComdat && !NeedComdat` is true.
1486 //
1487 // For ELF, when not using COMDAT, put counters, data and values into a
1488 // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
1489 // allows -z start-stop-gc to discard the entire group when the function is
1490 // discarded.
1491 C->setSelectionKind(Comdat::NoDeduplicate);
1492 }
1493 GV->setComdat(C);
1494 // COFF doesn't allow the comdat group leader to have private linkage, so
1495 // upgrade private linkage to internal linkage to produce a symbol table
1496 // entry.
1497 if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1499}
1500
1502 if (!profDataReferencedByCode(*GV->getParent()))
1503 return false;
1504
1505 if (!GV->hasLinkOnceLinkage() && !GV->hasLocalLinkage() &&
1507 return true;
1508
1509 // This avoids the profile data from referencing internal symbols in
1510 // COMDAT.
1511 if (GV->hasLocalLinkage() && GV->hasComdat())
1512 return false;
1513
1514 return true;
1515}
1516
1517// FIXME: Introduce an internal alias like what's done for functions to reduce
1518// the number of relocation entries.
1520 auto *Int8PtrTy = PointerType::getUnqual(GV->getContext());
1521
1522 // Store a nullptr in __profvt_ if a real address shouldn't be used.
1523 if (!shouldRecordVTableAddr(GV))
1524 return ConstantPointerNull::get(Int8PtrTy);
1525
1526 return ConstantExpr::getBitCast(GV, Int8PtrTy);
1527}
1528
1529void InstrLowerer::getOrCreateVTableProfData(GlobalVariable *GV) {
1531 "Value profiling is not supported with lightweight instrumentation");
1533 return;
1534
1535 // Skip llvm internal global variable or __prof variables.
1536 if (GV->getName().starts_with("llvm.") ||
1537 GV->getName().starts_with("__llvm") ||
1538 GV->getName().starts_with("__prof"))
1539 return;
1540
1541 // VTableProfData already created
1542 auto It = VTableDataMap.find(GV);
1543 if (It != VTableDataMap.end() && It->second)
1544 return;
1545
1548
1549 // This is to keep consistent with per-function profile data
1550 // for correctness.
1551 if (TT.isOSBinFormatXCOFF()) {
1553 Visibility = GlobalValue::DefaultVisibility;
1554 }
1555
1556 LLVMContext &Ctx = M.getContext();
1557 Type *DataTypes[] = {
1558#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) LLVMType,
1560#undef INSTR_PROF_VTABLE_DATA
1561 };
1562
1563 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1564
1565 // Used by INSTR_PROF_VTABLE_DATA MACRO
1566 Constant *VTableAddr = getVTableAddrForProfData(GV);
1567 const std::string PGOVTableName = getPGOName(*GV);
1568 // Record the length of the vtable. This is needed since vtable pointers
1569 // loaded from C++ objects might be from the middle of a vtable definition.
1570 uint32_t VTableSizeVal =
1571 M.getDataLayout().getTypeAllocSize(GV->getValueType());
1572
1573 Constant *DataVals[] = {
1574#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Init,
1576#undef INSTR_PROF_VTABLE_DATA
1577 };
1578
1579 auto *Data =
1580 new GlobalVariable(M, DataTy, /*constant=*/false, Linkage,
1581 ConstantStruct::get(DataTy, DataVals),
1582 getInstrProfVTableVarPrefix() + PGOVTableName);
1583
1584 Data->setVisibility(Visibility);
1585 Data->setSection(getInstrProfSectionName(IPSK_vtab, TT.getObjectFormat()));
1586 Data->setAlignment(Align(8));
1587
1588 maybeSetComdat(Data, GV, Data->getName());
1589
1590 VTableDataMap[GV] = Data;
1591
1592 ReferencedVTables.push_back(GV);
1593
1594 // VTable <Hash, Addr> is used by runtime but not referenced by other
1595 // sections. Conservatively mark it linker retained.
1596 UsedVars.push_back(Data);
1597}
1598
1599GlobalVariable *InstrLowerer::setupProfileSection(InstrProfInstBase *Inc,
1600 InstrProfSectKind IPSK) {
1601 GlobalVariable *NamePtr = Inc->getName();
1602
1603 // Match the linkage and visibility of the name global.
1604 Function *Fn = Inc->getParent()->getParent();
1606 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1607
1608 // Use internal rather than private linkage so the counter variable shows up
1609 // in the symbol table when using debug info for correlation.
1610 if ((DebugInfoCorrelate ||
1612 TT.isOSBinFormatMachO() && Linkage == GlobalValue::PrivateLinkage)
1614
1615 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1616 // symbols in the same csect won't be discarded. When there are duplicate weak
1617 // symbols, we can NOT guarantee that the relocations get resolved to the
1618 // intended weak symbol, so we can not ensure the correctness of the relative
1619 // CounterPtr, so we have to use private linkage for counter and data symbols.
1620 if (TT.isOSBinFormatXCOFF()) {
1622 Visibility = GlobalValue::DefaultVisibility;
1623 }
1624 // Move the name variable to the right section.
1625 bool Renamed;
1627 StringRef VarPrefix;
1628 std::string VarName;
1629 if (IPSK == IPSK_cnts) {
1630 VarPrefix = getInstrProfCountersVarPrefix();
1631 VarName = getVarName(Inc, VarPrefix, Renamed);
1632 InstrProfCntrInstBase *CntrIncrement = dyn_cast<InstrProfCntrInstBase>(Inc);
1633 Ptr = createRegionCounters(CntrIncrement, VarName, Linkage);
1634 } else if (IPSK == IPSK_bitmap) {
1635 VarPrefix = getInstrProfBitmapVarPrefix();
1636 VarName = getVarName(Inc, VarPrefix, Renamed);
1637 InstrProfMCDCBitmapInstBase *BitmapUpdate =
1638 dyn_cast<InstrProfMCDCBitmapInstBase>(Inc);
1639 Ptr = createRegionBitmaps(BitmapUpdate, VarName, Linkage);
1640 } else {
1641 llvm_unreachable("Profile Section must be for Counters or Bitmaps");
1642 }
1643
1644 Ptr->setVisibility(Visibility);
1645 // Put the counters and bitmaps in their own sections so linkers can
1646 // remove unneeded sections.
1647 Ptr->setSection(getInstrProfSectionName(IPSK, TT.getObjectFormat()));
1648 Ptr->setLinkage(Linkage);
1649 maybeSetComdat(Ptr, Fn, VarName);
1650 return Ptr;
1651}
1652
1654InstrLowerer::createRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc,
1656 GlobalValue::LinkageTypes Linkage) {
1657 uint64_t NumBytes = Inc->getNumBitmapBytes();
1658 auto *BitmapTy = ArrayType::get(Type::getInt8Ty(M.getContext()), NumBytes);
1659 auto GV = new GlobalVariable(M, BitmapTy, false, Linkage,
1660 Constant::getNullValue(BitmapTy), Name);
1661 GV->setAlignment(Align(1));
1662 return GV;
1663}
1664
1666InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
1667 GlobalVariable *NamePtr = Inc->getName();
1668 auto &PD = ProfileDataMap[NamePtr];
1669 if (PD.RegionBitmaps)
1670 return PD.RegionBitmaps;
1671
1672 // If RegionBitmaps doesn't already exist, create it by first setting up
1673 // the corresponding profile section.
1674 auto *BitmapPtr = setupProfileSection(Inc, IPSK_bitmap);
1675 PD.RegionBitmaps = BitmapPtr;
1676 PD.NumBitmapBytes = Inc->getNumBitmapBytes();
1677 return PD.RegionBitmaps;
1678}
1679
1681InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
1682 GlobalValue::LinkageTypes Linkage) {
1683 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1684 auto &Ctx = M.getContext();
1685 GlobalVariable *GV;
1686 if (isa<InstrProfCoverInst>(Inc)) {
1687 auto *CounterTy = Type::getInt8Ty(Ctx);
1688 auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
1689 // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
1690 std::vector<Constant *> InitialValues(NumCounters,
1691 Constant::getAllOnesValue(CounterTy));
1692 GV = new GlobalVariable(M, CounterArrTy, false, Linkage,
1693 ConstantArray::get(CounterArrTy, InitialValues),
1694 Name);
1695 GV->setAlignment(Align(1));
1696 } else {
1697 auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
1698 GV = new GlobalVariable(M, CounterTy, false, Linkage,
1699 Constant::getNullValue(CounterTy), Name);
1700 GV->setAlignment(Align(8));
1701 }
1702 return GV;
1703}
1704
1706InstrLowerer::getOrCreateRegionCounters(InstrProfCntrInstBase *Inc) {
1707 GlobalVariable *NamePtr = Inc->getName();
1708 auto &PD = ProfileDataMap[NamePtr];
1709 if (PD.RegionCounters)
1710 return PD.RegionCounters;
1711
1712 // If RegionCounters doesn't already exist, create it by first setting up
1713 // the corresponding profile section.
1714 auto *CounterPtr = setupProfileSection(Inc, IPSK_cnts);
1715 PD.RegionCounters = CounterPtr;
1716
1717 if (DebugInfoCorrelate ||
1719 LLVMContext &Ctx = M.getContext();
1720 Function *Fn = Inc->getParent()->getParent();
1721 if (auto *SP = Fn->getSubprogram()) {
1722 DIBuilder DB(M, true, SP->getUnit());
1723 Metadata *FunctionNameAnnotation[] = {
1726 };
1727 Metadata *CFGHashAnnotation[] = {
1730 };
1731 Metadata *NumCountersAnnotation[] = {
1734 };
1735 auto Annotations = DB.getOrCreateArray({
1736 MDNode::get(Ctx, FunctionNameAnnotation),
1737 MDNode::get(Ctx, CFGHashAnnotation),
1738 MDNode::get(Ctx, NumCountersAnnotation),
1739 });
1740 auto *DICounter = DB.createGlobalVariableExpression(
1741 SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1742 /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
1743 CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1744 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1745 Annotations);
1746 CounterPtr->addDebugInfo(DICounter);
1747 DB.finalize();
1748 }
1749
1750 // Mark the counter variable as used so that it isn't optimized out.
1751 CompilerUsedVars.push_back(PD.RegionCounters);
1752 }
1753
1754 // Create the data variable (if it doesn't already exist).
1755 createDataVariable(Inc);
1756
1757 return PD.RegionCounters;
1758}
1759
1760void InstrLowerer::createDataVariable(InstrProfCntrInstBase *Inc) {
1761 // When debug information is correlated to profile data, a data variable
1762 // is not needed.
1764 return;
1765
1766 GlobalVariable *NamePtr = Inc->getName();
1767 auto &PD = ProfileDataMap[NamePtr];
1768
1769 // Return if data variable was already created.
1770 if (PD.DataVar)
1771 return;
1772
1773 LLVMContext &Ctx = M.getContext();
1774
1775 Function *Fn = Inc->getParent()->getParent();
1777 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
1778
1779 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1780 // symbols in the same csect won't be discarded. When there are duplicate weak
1781 // symbols, we can NOT guarantee that the relocations get resolved to the
1782 // intended weak symbol, so we can not ensure the correctness of the relative
1783 // CounterPtr, so we have to use private linkage for counter and data symbols.
1784 if (TT.isOSBinFormatXCOFF()) {
1786 Visibility = GlobalValue::DefaultVisibility;
1787 }
1788
1789 bool NeedComdat = needsComdatForCounter(*Fn, M);
1790 bool Renamed;
1791
1792 // The Data Variable section is anchored to profile counters.
1793 std::string CntsVarName =
1795 std::string DataVarName =
1796 getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
1797
1798 auto *Int8PtrTy = PointerType::getUnqual(Ctx);
1799 // Allocate statically the array of pointers to value profile nodes for
1800 // the current function.
1801 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1802 uint64_t NS = 0;
1803 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1804 NS += PD.NumValueSites[Kind];
1805 if (NS > 0 && ValueProfileStaticAlloc &&
1807 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1808 auto *ValuesVar = new GlobalVariable(
1809 M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1810 getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
1811 ValuesVar->setVisibility(Visibility);
1812 setGlobalVariableLargeSection(TT, *ValuesVar);
1813 ValuesVar->setSection(
1814 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1815 ValuesVar->setAlignment(Align(8));
1816 maybeSetComdat(ValuesVar, Fn, CntsVarName);
1817 ValuesPtrExpr = ValuesVar;
1818 }
1819
1820 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1821 auto *CounterPtr = PD.RegionCounters;
1822
1823 uint64_t NumBitmapBytes = PD.NumBitmapBytes;
1824
1825 // Create data variable.
1826 auto *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
1827 auto *Int16Ty = Type::getInt16Ty(Ctx);
1828 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1829 Type *DataTypes[] = {
1830#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1832 };
1833 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1834
1835 Constant *FunctionAddr = getFuncAddrForProfData(Fn);
1836
1837 Constant *Int16ArrayVals[IPVK_Last + 1];
1838 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1839 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1840
1841 // If the data variable is not referenced by code (if we don't emit
1842 // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1843 // data variable live under linker GC, the data variable can be private. This
1844 // optimization applies to ELF.
1845 //
1846 // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1847 // to be false.
1848 //
1849 // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1850 // that other copies must have the same CFG and cannot have value profiling.
1851 // If no hash suffix, other profd copies may be referenced by code.
1852 if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1853 (TT.isOSBinFormatELF() ||
1854 (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1856 Visibility = GlobalValue::DefaultVisibility;
1857 }
1858 auto *Data =
1859 new GlobalVariable(M, DataTy, false, Linkage, nullptr, DataVarName);
1860 Constant *RelativeCounterPtr;
1861 GlobalVariable *BitmapPtr = PD.RegionBitmaps;
1862 Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
1863 InstrProfSectKind DataSectionKind;
1864 // With binary profile correlation, profile data is not loaded into memory.
1865 // profile data must reference profile counter with an absolute relocation.
1867 DataSectionKind = IPSK_covdata;
1868 RelativeCounterPtr = ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy);
1869 if (BitmapPtr != nullptr)
1870 RelativeBitmapPtr = ConstantExpr::getPtrToInt(BitmapPtr, IntPtrTy);
1871 } else {
1872 // Reference the counter variable with a label difference (link-time
1873 // constant).
1874 DataSectionKind = IPSK_data;
1875 RelativeCounterPtr =
1876 ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1877 ConstantExpr::getPtrToInt(Data, IntPtrTy));
1878 if (BitmapPtr != nullptr)
1879 RelativeBitmapPtr =
1881 ConstantExpr::getPtrToInt(Data, IntPtrTy));
1882 }
1883
1884 Constant *DataVals[] = {
1885#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1887 };
1888 Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1889
1890 Data->setVisibility(Visibility);
1891 Data->setSection(
1892 getInstrProfSectionName(DataSectionKind, TT.getObjectFormat()));
1893 Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1894 maybeSetComdat(Data, Fn, CntsVarName);
1895
1896 PD.DataVar = Data;
1897
1898 // Mark the data variable as used so that it isn't stripped out.
1899 CompilerUsedVars.push_back(Data);
1900 // Now that the linkage set by the FE has been passed to the data and counter
1901 // variables, reset Name variable's linkage and visibility to private so that
1902 // it can be removed later by the compiler.
1904 // Collect the referenced names to be used by emitNameData.
1905 ReferencedNames.push_back(NamePtr);
1906}
1907
1908void InstrLowerer::emitVNodes() {
1909 if (!ValueProfileStaticAlloc)
1910 return;
1911
1912 // For now only support this on platforms that do
1913 // not require runtime registration to discover
1914 // named section start/end.
1916 return;
1917
1918 size_t TotalNS = 0;
1919 for (auto &PD : ProfileDataMap) {
1920 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1921 TotalNS += PD.second.NumValueSites[Kind];
1922 }
1923
1924 if (!TotalNS)
1925 return;
1926
1927 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1928// Heuristic for small programs with very few total value sites.
1929// The default value of vp-counters-per-site is chosen based on
1930// the observation that large apps usually have a low percentage
1931// of value sites that actually have any profile data, and thus
1932// the average number of counters per site is low. For small
1933// apps with very few sites, this may not be true. Bump up the
1934// number of counters in this case.
1935#define INSTR_PROF_MIN_VAL_COUNTS 10
1936 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1937 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1938
1939 auto &Ctx = M.getContext();
1940 Type *VNodeTypes[] = {
1941#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1943 };
1944 auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
1945
1946 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1947 auto *VNodesVar = new GlobalVariable(
1948 M, VNodesTy, false, GlobalValue::PrivateLinkage,
1950 setGlobalVariableLargeSection(TT, *VNodesVar);
1951 VNodesVar->setSection(
1952 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1953 VNodesVar->setAlignment(M.getDataLayout().getABITypeAlign(VNodesTy));
1954 // VNodesVar is used by runtime but not referenced via relocation by other
1955 // sections. Conservatively make it linker retained.
1956 UsedVars.push_back(VNodesVar);
1957}
1958
1959void InstrLowerer::emitNameData() {
1960 std::string UncompressedData;
1961
1962 if (ReferencedNames.empty())
1963 return;
1964
1965 std::string CompressedNameStr;
1966 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
1968 report_fatal_error(Twine(toString(std::move(E))), false);
1969 }
1970
1971 auto &Ctx = M.getContext();
1972 auto *NamesVal =
1973 ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1974 NamesVar = new GlobalVariable(M, NamesVal->getType(), true,
1977 NamesSize = CompressedNameStr.size();
1978 setGlobalVariableLargeSection(TT, *NamesVar);
1979 NamesVar->setSection(
1981 ? getInstrProfSectionName(IPSK_covname, TT.getObjectFormat())
1982 : getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1983 // On COFF, it's important to reduce the alignment down to 1 to prevent the
1984 // linker from inserting padding before the start of the names section or
1985 // between names entries.
1986 NamesVar->setAlignment(Align(1));
1987 // NamesVar is used by runtime but not referenced via relocation by other
1988 // sections. Conservatively make it linker retained.
1989 UsedVars.push_back(NamesVar);
1990
1991 for (auto *NamePtr : ReferencedNames)
1992 NamePtr->eraseFromParent();
1993}
1994
1995void InstrLowerer::emitVTableNames() {
1996 if (!EnableVTableValueProfiling || ReferencedVTables.empty())
1997 return;
1998
1999 // Collect the PGO names of referenced vtables and compress them.
2000 std::string CompressedVTableNames;
2001 if (Error E = collectVTableStrings(ReferencedVTables, CompressedVTableNames,
2003 report_fatal_error(Twine(toString(std::move(E))), false);
2004 }
2005
2006 auto &Ctx = M.getContext();
2007 auto *VTableNamesVal = ConstantDataArray::getString(
2008 Ctx, StringRef(CompressedVTableNames), false /* AddNull */);
2009 GlobalVariable *VTableNamesVar =
2010 new GlobalVariable(M, VTableNamesVal->getType(), true /* constant */,
2011 GlobalValue::PrivateLinkage, VTableNamesVal,
2013 VTableNamesVar->setSection(
2014 getInstrProfSectionName(IPSK_vname, TT.getObjectFormat()));
2015 VTableNamesVar->setAlignment(Align(1));
2016 // Make VTableNames linker retained.
2017 UsedVars.push_back(VTableNamesVar);
2018}
2019
2020void InstrLowerer::emitRegistration() {
2022 return;
2023
2024 // Construct the function.
2025 auto *VoidTy = Type::getVoidTy(M.getContext());
2026 auto *VoidPtrTy = PointerType::getUnqual(M.getContext());
2027 auto *Int64Ty = Type::getInt64Ty(M.getContext());
2028 auto *RegisterFTy = FunctionType::get(VoidTy, false);
2029 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
2031 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2032 if (Options.NoRedZone)
2033 RegisterF->addFnAttr(Attribute::NoRedZone);
2034
2035 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
2036 auto *RuntimeRegisterF =
2039
2040 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", RegisterF));
2041 for (Value *Data : CompilerUsedVars)
2042 if (!isa<Function>(Data))
2043 IRB.CreateCall(RuntimeRegisterF, Data);
2044 for (Value *Data : UsedVars)
2045 if (Data != NamesVar && !isa<Function>(Data))
2046 IRB.CreateCall(RuntimeRegisterF, Data);
2047
2048 if (NamesVar) {
2049 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
2050 auto *NamesRegisterTy =
2051 FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
2052 auto *NamesRegisterF =
2055 IRB.CreateCall(NamesRegisterF, {NamesVar, IRB.getInt64(NamesSize)});
2056 }
2057
2058 IRB.CreateRetVoid();
2059}
2060
2061bool InstrLowerer::emitRuntimeHook() {
2062 // We expect the linker to be invoked with -u<hook_var> flag for Linux
2063 // in which case there is no need to emit the external variable.
2064 if (TT.isOSLinux() || TT.isOSAIX())
2065 return false;
2066
2067 // If the module's provided its own runtime, we don't need to do anything.
2068 if (M.getGlobalVariable(getInstrProfRuntimeHookVarName()))
2069 return false;
2070
2071 // Declare an external variable that will pull in the runtime initialization.
2072 auto *Int32Ty = Type::getInt32Ty(M.getContext());
2073 auto *Var =
2074 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
2076 Var->setVisibility(GlobalValue::HiddenVisibility);
2077
2078 if (TT.isOSBinFormatELF() && !TT.isPS()) {
2079 // Mark the user variable as used so that it isn't stripped out.
2080 CompilerUsedVars.push_back(Var);
2081 } else {
2082 // Make a function that uses it.
2083 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
2086 User->addFnAttr(Attribute::NoInline);
2087 if (Options.NoRedZone)
2088 User->addFnAttr(Attribute::NoRedZone);
2089 User->setVisibility(GlobalValue::HiddenVisibility);
2090 if (TT.supportsCOMDAT())
2091 User->setComdat(M.getOrInsertComdat(User->getName()));
2092
2093 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", User));
2094 auto *Load = IRB.CreateLoad(Int32Ty, Var);
2095 IRB.CreateRet(Load);
2096
2097 // Mark the function as used so that it isn't stripped out.
2098 CompilerUsedVars.push_back(User);
2099 }
2100 return true;
2101}
2102
2103void InstrLowerer::emitUses() {
2104 // The metadata sections are parallel arrays. Optimizers (e.g.
2105 // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
2106 // we conservatively retain all unconditionally in the compiler.
2107 //
2108 // On ELF and Mach-O, the linker can guarantee the associated sections will be
2109 // retained or discarded as a unit, so llvm.compiler.used is sufficient.
2110 // Similarly on COFF, if prof data is not referenced by code we use one comdat
2111 // and ensure this GC property as well. Otherwise, we have to conservatively
2112 // make all of the sections retained by the linker.
2113 if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
2114 (TT.isOSBinFormatCOFF() && !DataReferencedByCode))
2115 appendToCompilerUsed(M, CompilerUsedVars);
2116 else
2117 appendToUsed(M, CompilerUsedVars);
2118
2119 // We do not add proper references from used metadata sections to NamesVar and
2120 // VNodesVar, so we have to be conservative and place them in llvm.used
2121 // regardless of the target,
2122 appendToUsed(M, UsedVars);
2123}
2124
2125void InstrLowerer::emitInitialization() {
2126 // Create ProfileFileName variable. Don't don't this for the
2127 // context-sensitive instrumentation lowering: This lowering is after
2128 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
2129 // have already create the variable before LTO/ThinLTO linking.
2130 if (!IsCS)
2131 createProfileFileNameVar(M, Options.InstrProfileOutput);
2132 Function *RegisterF = M.getFunction(getInstrProfRegFuncsName());
2133 if (!RegisterF)
2134 return;
2135
2136 // Create the initialization function.
2137 auto *VoidTy = Type::getVoidTy(M.getContext());
2138 auto *F = Function::Create(FunctionType::get(VoidTy, false),
2141 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
2142 F->addFnAttr(Attribute::NoInline);
2143 if (Options.NoRedZone)
2144 F->addFnAttr(Attribute::NoRedZone);
2145
2146 // Add the basic block and the necessary calls.
2147 IRBuilder<> IRB(BasicBlock::Create(M.getContext(), "", F));
2148 IRB.CreateCall(RegisterF, {});
2149 IRB.CreateRetVoid();
2150
2151 appendToGlobalCtors(M, F, 0);
2152}
2153
2154namespace llvm {
2155// Create the variable for profile sampling.
2157 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SAMPLING_VAR));
2158 IntegerType *SamplingVarTy;
2159 Constant *ValueZero;
2160 if (SampledInstrPeriod.getValue() <= USHRT_MAX) {
2161 SamplingVarTy = Type::getInt16Ty(M.getContext());
2162 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(16, 0));
2163 } else {
2164 SamplingVarTy = Type::getInt32Ty(M.getContext());
2165 ValueZero = Constant::getIntegerValue(SamplingVarTy, APInt(32, 0));
2166 }
2167 auto SamplingVar = new GlobalVariable(
2168 M, SamplingVarTy, false, GlobalValue::WeakAnyLinkage, ValueZero, VarName);
2169 SamplingVar->setVisibility(GlobalValue::DefaultVisibility);
2170 SamplingVar->setThreadLocal(true);
2171 Triple TT(M.getTargetTriple());
2172 if (TT.supportsCOMDAT()) {
2173 SamplingVar->setLinkage(GlobalValue::ExternalLinkage);
2174 SamplingVar->setComdat(M.getOrInsertComdat(VarName));
2175 }
2176 appendToCompilerUsed(M, SamplingVar);
2177}
2178} // namespace llvm
This file contains the simple types necessary to represent the attributes associated with functions a...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:686
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static unsigned InstrCount
#define LLVM_DEBUG(X)
Definition: Debug.h:101
@ Default
Definition: DwarfDebug.cpp:87
uint64_t Addr
std::string Name
Hexagon Hardware Loops
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
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 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:55
#define I(x, y, z)
Definition: MD5.cpp:58
Memory SSA
Definition: MemorySSA.cpp:72
Module.h This file contains the declarations for the Module class.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition: APInt.h:78
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:635
@ Add
*p = old + v
Definition: Instructions.h:712
@ Or
*p = old | v
Definition: Instructions.h:720
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:461
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:416
const Instruction & front() const
Definition: BasicBlock.h:471
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis providing branch probability information.
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1292
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2950
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2618
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2267
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2295
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:155
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1800
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1357
This is an important base class in LLVM.
Definition: Constant.h:42
static 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...
Definition: Constants.cpp:400
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:76
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:653
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:172
const BasicBlock & getEntryBlock() const
Definition: Function.h:807
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1837
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:380
Argument * getArg(unsigned i) const
Definition: Function.h:884
static 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:550
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:589
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:137
void setComdat(Comdat *C)
Definition: Globals.cpp:206
bool hasComdat() const
Definition: GlobalObject.h:128
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:267
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:515
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:66
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:512
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:481
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2142
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1454
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:473
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1996
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2265
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:483
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:142
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition: IRBuilder.h:1137
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:1807
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1433
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1492
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1107
Value * CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1, const Twine &Name="")
Definition: IRBuilder.h:1930
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1820
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1344
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2137
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2569
AtomicRMWInst * CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val, MaybeAlign Align, AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Definition: IRBuilder.h:1871
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2027
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1514
ConstantInt * getInt16(uint16_t C)
Get a constant 16-bit value.
Definition: IRBuilder.h:478
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2432
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition: IRBuilder.h:2001
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
A base class for all instrprof counter intrinsics.
ConstantInt * getIndex() const
ConstantInt * getNumCounters() const
static const char * FunctionNameAttributeName
static const char * CFGHashAttributeName
static const char * NumCountersAttributeName
This represents the llvm.instrprof.cover intrinsic.
This represents the llvm.instrprof.increment intrinsic.
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.
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:92
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:70
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1642
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Class to represent integer types.
Definition: DerivedTypes.h:40
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition: SSAUpdater.h:151
virtual void doExtraRewritesBeforeFinalDeletion()
This hook is invoked after all the stores are found and inserted as available values.
Definition: SSAUpdater.h:176
An instruction for reading from memory.
Definition: Instructions.h:174
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Definition: MDBuilder.cpp:47
Metadata node.
Definition: Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:606
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:40
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:556
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
static 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:361
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:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
const ParentTy * getParent() const
Definition: ilist_node.h:32
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:353
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
ValueKind
Value kinds.
@ Exit
Definition: COFF.h:827
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:1096
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
Definition: X86BaseInfo.h:721
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:92
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition: InstrProf.h:163
void createProfileSamplingVar(Module &M)
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition: InstrProf.h:104
cl::opt< bool > DoInstrProfNameCompression
cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate("profile-correlate", cl::desc("Use debug info or binary file to correlate profiles."), cl::init(InstrProfCorrelator::NONE), cl::values(clEnumValN(InstrProfCorrelator::NONE, "", "No profile correlation"), clEnumValN(InstrProfCorrelator::DEBUG_INFO, "debug-info", "Use debug info to correlate"), clEnumValN(InstrProfCorrelator::BINARY, "binary", "Use binary to correlate")))
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:656
StringRef getInstrProfVTableNamesVarName()
Definition: InstrProf.h:116
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition: InstrProf.h:98
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition: InstrProf.h:129
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:236
cl::opt< bool > DebugInfoCorrelate
bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1416
std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
Definition: InstrProf.cpp:395
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition: InstrProf.h:158
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition: InstrProf.h:107
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:1729
StringRef getInstrProfCounterBiasVarName()
Definition: InstrProf.h:173
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition: InstrProf.h:169
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition: InstrProf.h:138
Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
Definition: InstrProf.cpp:707
InstrProfSectKind
Definition: InstrProf.h:60
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:101
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
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:1736
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:700
StringRef getInstrProfBitmapBiasVarName()
Definition: InstrProf.h:177
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition: InstrProf.h:87
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition: InstrProf.h:150
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
@ Add
Sum of integers.
Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
Definition: InstrProf.cpp:717
void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1464
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1487
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.
Definition: ModuleUtils.cpp:74
bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
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:81
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition: InstrProf.h:144
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 ...
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:114
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1442
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition: InstrProf.h:110
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."))
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition: InstrProf.h:95
#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
Options for the frontend instrumentation based profiling pass.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117