LLVM 18.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 a frontend for profiling.
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"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DIBuilder.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalValue.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
42#include "llvm/Pass.h"
47#include "llvm/Support/Error.h"
52#include <algorithm>
53#include <cassert>
54#include <cstdint>
55#include <string>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "instrprof"
60
61namespace llvm {
63 DebugInfoCorrelate("debug-info-correlate",
64 cl::desc("Use debug info to correlate profiles."),
65 cl::init(false));
66} // namespace llvm
67
68namespace {
69
70cl::opt<bool> DoHashBasedCounterSplit(
71 "hash-based-counter-split",
72 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
73 cl::init(true));
74
76 RuntimeCounterRelocation("runtime-counter-relocation",
77 cl::desc("Enable relocating counters at runtime."),
78 cl::init(false));
79
80cl::opt<bool> ValueProfileStaticAlloc(
81 "vp-static-alloc",
82 cl::desc("Do static counter allocation for value profiler"),
83 cl::init(true));
84
85cl::opt<double> NumCountersPerValueSite(
86 "vp-counters-per-site",
87 cl::desc("The average number of profile counters allocated "
88 "per value profiling site."),
89 // This is set to a very small value because in real programs, only
90 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
91 // For those sites with non-zero profile, the average number of targets
92 // is usually smaller than 2.
93 cl::init(1.0));
94
95cl::opt<bool> AtomicCounterUpdateAll(
96 "instrprof-atomic-counter-update-all",
97 cl::desc("Make all profile counter updates atomic (for testing only)"),
98 cl::init(false));
99
100cl::opt<bool> AtomicCounterUpdatePromoted(
101 "atomic-counter-update-promoted",
102 cl::desc("Do counter update using atomic fetch add "
103 " for promoted counters only"),
104 cl::init(false));
105
106cl::opt<bool> AtomicFirstCounter(
107 "atomic-first-counter",
108 cl::desc("Use atomic fetch add for first counter in a function (usually "
109 "the entry counter)"),
110 cl::init(false));
111
112// If the option is not specified, the default behavior about whether
113// counter promotion is done depends on how instrumentaiton lowering
114// pipeline is setup, i.e., the default value of true of this option
115// does not mean the promotion will be done by default. Explicitly
116// setting this option can override the default behavior.
117cl::opt<bool> DoCounterPromotion("do-counter-promotion",
118 cl::desc("Do counter register promotion"),
119 cl::init(false));
120cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
121 "max-counter-promotions-per-loop", cl::init(20),
122 cl::desc("Max number counter promotions per loop to avoid"
123 " increasing register pressure too much"));
124
125// A debug option
127 MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
128 cl::desc("Max number of allowed counter promotions"));
129
130cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
131 "speculative-counter-promotion-max-exiting", cl::init(3),
132 cl::desc("The max number of exiting blocks of a loop to allow "
133 " speculative counter promotion"));
134
135cl::opt<bool> SpeculativeCounterPromotionToLoop(
136 "speculative-counter-promotion-to-loop",
137 cl::desc("When the option is false, if the target block is in a loop, "
138 "the promotion will be disallowed unless the promoted counter "
139 " update can be further/iteratively promoted into an acyclic "
140 " region."));
141
142cl::opt<bool> IterativeCounterPromotion(
143 "iterative-counter-promotion", cl::init(true),
144 cl::desc("Allow counter promotion across the whole loop nest."));
145
146cl::opt<bool> SkipRetExitBlock(
147 "skip-ret-exit-block", cl::init(true),
148 cl::desc("Suppress counter promotion if exit blocks contain ret."));
149
150///
151/// A helper class to promote one counter RMW operation in the loop
152/// into register update.
153///
154/// RWM update for the counter will be sinked out of the loop after
155/// the transformation.
156///
157class PGOCounterPromoterHelper : public LoadAndStorePromoter {
158public:
159 PGOCounterPromoterHelper(
161 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
162 ArrayRef<Instruction *> InsertPts,
164 LoopInfo &LI)
165 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
166 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
167 assert(isa<LoadInst>(L));
168 assert(isa<StoreInst>(S));
169 SSA.AddAvailableValue(PH, Init);
170 }
171
172 void doExtraRewritesBeforeFinalDeletion() override {
173 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
174 BasicBlock *ExitBlock = ExitBlocks[i];
175 Instruction *InsertPos = InsertPts[i];
176 // Get LiveIn value into the ExitBlock. If there are multiple
177 // predecessors, the value is defined by a PHI node in this
178 // block.
179 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
180 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
181 Type *Ty = LiveInValue->getType();
182 IRBuilder<> Builder(InsertPos);
183 if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
184 // If isRuntimeCounterRelocationEnabled() is true then the address of
185 // the store instruction is computed with two instructions in
186 // InstrProfiling::getCounterAddress(). We need to copy those
187 // instructions to this block to compute Addr correctly.
188 // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
189 // %Addr = inttoptr i64 %BiasAdd to i64*
190 auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
191 assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
192 Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
193 Addr = Builder.CreateIntToPtr(BiasInst,
194 PointerType::getUnqual(Ty->getContext()));
195 }
196 if (AtomicCounterUpdatePromoted)
197 // automic update currently can only be promoted across the current
198 // loop, not the whole loop nest.
199 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
200 MaybeAlign(),
201 AtomicOrdering::SequentiallyConsistent);
202 else {
203 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
204 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
205 auto *NewStore = Builder.CreateStore(NewVal, Addr);
206
207 // Now update the parent loop's candidate list:
208 if (IterativeCounterPromotion) {
209 auto *TargetLoop = LI.getLoopFor(ExitBlock);
210 if (TargetLoop)
211 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
212 }
213 }
214 }
215 }
216
217private:
219 ArrayRef<BasicBlock *> ExitBlocks;
220 ArrayRef<Instruction *> InsertPts;
222 LoopInfo &LI;
223};
224
225/// A helper class to do register promotion for all profile counter
226/// updates in a loop.
227///
228class PGOCounterPromoter {
229public:
230 PGOCounterPromoter(
232 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
233 : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
234
235 // Skip collection of ExitBlocks and InsertPts for loops that will not be
236 // able to have counters promoted.
237 SmallVector<BasicBlock *, 8> LoopExitBlocks;
239
240 L.getExitBlocks(LoopExitBlocks);
241 if (!isPromotionPossible(&L, LoopExitBlocks))
242 return;
243
244 for (BasicBlock *ExitBlock : LoopExitBlocks) {
245 if (BlockSet.insert(ExitBlock).second) {
246 ExitBlocks.push_back(ExitBlock);
247 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
248 }
249 }
250 }
251
252 bool run(int64_t *NumPromoted) {
253 // Skip 'infinite' loops:
254 if (ExitBlocks.size() == 0)
255 return false;
256
257 // Skip if any of the ExitBlocks contains a ret instruction.
258 // This is to prevent dumping of incomplete profile -- if the
259 // the loop is a long running loop and dump is called in the middle
260 // of the loop, the result profile is incomplete.
261 // FIXME: add other heuristics to detect long running loops.
262 if (SkipRetExitBlock) {
263 for (auto *BB : ExitBlocks)
264 if (isa<ReturnInst>(BB->getTerminator()))
265 return false;
266 }
267
268 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
269 if (MaxProm == 0)
270 return false;
271
272 unsigned Promoted = 0;
273 for (auto &Cand : LoopToCandidates[&L]) {
274
276 SSAUpdater SSA(&NewPHIs);
277 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
278
279 // If BFI is set, we will use it to guide the promotions.
280 if (BFI) {
281 auto *BB = Cand.first->getParent();
282 auto InstrCount = BFI->getBlockProfileCount(BB);
283 if (!InstrCount)
284 continue;
285 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
286 // If the average loop trip count is not greater than 1.5, we skip
287 // promotion.
288 if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
289 continue;
290 }
291
292 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
293 L.getLoopPreheader(), ExitBlocks,
294 InsertPts, LoopToCandidates, LI);
295 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
296 Promoted++;
297 if (Promoted >= MaxProm)
298 break;
299
300 (*NumPromoted)++;
301 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
302 break;
303 }
304
305 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
306 << L.getLoopDepth() << ")\n");
307 return Promoted != 0;
308 }
309
310private:
311 bool allowSpeculativeCounterPromotion(Loop *LP) {
312 SmallVector<BasicBlock *, 8> ExitingBlocks;
313 L.getExitingBlocks(ExitingBlocks);
314 // Not considierered speculative.
315 if (ExitingBlocks.size() == 1)
316 return true;
317 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
318 return false;
319 return true;
320 }
321
322 // Check whether the loop satisfies the basic conditions needed to perform
323 // Counter Promotions.
324 bool
325 isPromotionPossible(Loop *LP,
326 const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
327 // We can't insert into a catchswitch.
328 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
329 return isa<CatchSwitchInst>(Exit->getTerminator());
330 }))
331 return false;
332
333 if (!LP->hasDedicatedExits())
334 return false;
335
336 BasicBlock *PH = LP->getLoopPreheader();
337 if (!PH)
338 return false;
339
340 return true;
341 }
342
343 // Returns the max number of Counter Promotions for LP.
344 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
345 SmallVector<BasicBlock *, 8> LoopExitBlocks;
346 LP->getExitBlocks(LoopExitBlocks);
347 if (!isPromotionPossible(LP, LoopExitBlocks))
348 return 0;
349
350 SmallVector<BasicBlock *, 8> ExitingBlocks;
351 LP->getExitingBlocks(ExitingBlocks);
352
353 // If BFI is set, we do more aggressive promotions based on BFI.
354 if (BFI)
355 return (unsigned)-1;
356
357 // Not considierered speculative.
358 if (ExitingBlocks.size() == 1)
359 return MaxNumOfPromotionsPerLoop;
360
361 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
362 return 0;
363
364 // Whether the target block is in a loop does not matter:
365 if (SpeculativeCounterPromotionToLoop)
366 return MaxNumOfPromotionsPerLoop;
367
368 // Now check the target block:
369 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
370 for (auto *TargetBlock : LoopExitBlocks) {
371 auto *TargetLoop = LI.getLoopFor(TargetBlock);
372 if (!TargetLoop)
373 continue;
374 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
375 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
376 MaxProm =
377 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
378 PendingCandsInTarget);
379 }
380 return MaxProm;
381 }
382
386 Loop &L;
387 LoopInfo &LI;
389};
390
391enum class ValueProfilingCallType {
392 // Individual values are tracked. Currently used for indiret call target
393 // profiling.
394 Default,
395
396 // MemOp: the memop size value profiling.
397 MemOp
398};
399
400} // end anonymous namespace
401
405 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
407 };
408 if (!run(M, GetTLI))
409 return PreservedAnalyses::all();
410
412}
413
414bool InstrProfiling::lowerIntrinsics(Function *F) {
415 bool MadeChange = false;
416 PromotionCandidates.clear();
417 for (BasicBlock &BB : *F) {
418 for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
419 if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
420 lowerIncrement(IPIS);
421 MadeChange = true;
422 } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
423 lowerIncrement(IPI);
424 MadeChange = true;
425 } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(&Instr)) {
426 lowerTimestamp(IPC);
427 MadeChange = true;
428 } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
429 lowerCover(IPC);
430 MadeChange = true;
431 } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
432 lowerValueProfileInst(IPVP);
433 MadeChange = true;
434 }
435 }
436 }
437
438 if (!MadeChange)
439 return false;
440
441 promoteCounterLoadStores(F);
442 return true;
443}
444
445bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
446 // Mach-O don't support weak external references.
447 if (TT.isOSBinFormatMachO())
448 return false;
449
450 if (RuntimeCounterRelocation.getNumOccurrences() > 0)
451 return RuntimeCounterRelocation;
452
453 // Fuchsia uses runtime counter relocation by default.
454 return TT.isOSFuchsia();
455}
456
457bool InstrProfiling::isCounterPromotionEnabled() const {
458 if (DoCounterPromotion.getNumOccurrences() > 0)
459 return DoCounterPromotion;
460
461 return Options.DoCounterPromotion;
462}
463
464void InstrProfiling::promoteCounterLoadStores(Function *F) {
465 if (!isCounterPromotionEnabled())
466 return;
467
468 DominatorTree DT(*F);
469 LoopInfo LI(DT);
470 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
471
472 std::unique_ptr<BlockFrequencyInfo> BFI;
473 if (Options.UseBFIInPromotion) {
474 std::unique_ptr<BranchProbabilityInfo> BPI;
475 BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
476 BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
477 }
478
479 for (const auto &LoadStore : PromotionCandidates) {
480 auto *CounterLoad = LoadStore.first;
481 auto *CounterStore = LoadStore.second;
482 BasicBlock *BB = CounterLoad->getParent();
483 Loop *ParentLoop = LI.getLoopFor(BB);
484 if (!ParentLoop)
485 continue;
486 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
487 }
488
490
491 // Do a post-order traversal of the loops so that counter updates can be
492 // iteratively hoisted outside the loop nest.
493 for (auto *Loop : llvm::reverse(Loops)) {
494 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
495 Promoter.run(&TotalCountersPromoted);
496 }
497}
498
500 // On Fuchsia, we only need runtime hook if any counters are present.
501 if (TT.isOSFuchsia())
502 return false;
503
504 return true;
505}
506
507/// Check if the module contains uses of any profiling intrinsics.
509 auto containsIntrinsic = [&](int ID) {
510 if (auto *F = M.getFunction(Intrinsic::getName(ID)))
511 return !F->use_empty();
512 return false;
513 };
514 return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
515 containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
516 containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
517 containsIntrinsic(llvm::Intrinsic::instrprof_timestamp) ||
518 containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
519}
520
522 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
523 this->M = &M;
524 this->GetTLI = std::move(GetTLI);
525 NamesVar = nullptr;
526 NamesSize = 0;
527 ProfileDataMap.clear();
528 CompilerUsedVars.clear();
529 UsedVars.clear();
530 TT = Triple(M.getTargetTriple());
531
532 bool MadeChange = false;
533 bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
534 if (NeedsRuntimeHook)
535 MadeChange = emitRuntimeHook();
536
537 bool ContainsProfiling = containsProfilingIntrinsics(M);
538 GlobalVariable *CoverageNamesVar =
539 M.getNamedGlobal(getCoverageUnusedNamesVarName());
540 // Improve compile time by avoiding linear scans when there is no work.
541 if (!ContainsProfiling && !CoverageNamesVar)
542 return MadeChange;
543
544 // We did not know how many value sites there would be inside
545 // the instrumented function. This is counting the number of instrumented
546 // target value sites to enter it as field in the profile data variable.
547 for (Function &F : M) {
548 InstrProfInstBase *FirstProfInst = nullptr;
549 for (BasicBlock &BB : F)
550 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
551 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
552 computeNumValueSiteCounts(Ind);
553 else if (FirstProfInst == nullptr &&
554 (isa<InstrProfIncrementInst>(I) || isa<InstrProfCoverInst>(I)))
555 FirstProfInst = dyn_cast<InstrProfInstBase>(I);
556
557 // Value profiling intrinsic lowering requires per-function profile data
558 // variable to be created first.
559 if (FirstProfInst != nullptr)
560 static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
561 }
562
563 for (Function &F : M)
564 MadeChange |= lowerIntrinsics(&F);
565
566 if (CoverageNamesVar) {
567 lowerCoverageData(CoverageNamesVar);
568 MadeChange = true;
569 }
570
571 if (!MadeChange)
572 return false;
573
574 emitVNodes();
575 emitNameData();
576
577 // Emit runtime hook for the cases where the target does not unconditionally
578 // require pulling in profile runtime, and coverage is enabled on code that is
579 // not eliminated by the front-end, e.g. unused functions with internal
580 // linkage.
581 if (!NeedsRuntimeHook && ContainsProfiling)
582 emitRuntimeHook();
583
584 emitRegistration();
585 emitUses();
586 emitInitialization();
587 return true;
588}
589
591 Module &M, const TargetLibraryInfo &TLI,
592 ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
593 LLVMContext &Ctx = M.getContext();
594 auto *ReturnTy = Type::getVoidTy(M.getContext());
595
596 AttributeList AL;
597 if (auto AK = TLI.getExtAttrForI32Param(false))
598 AL = AL.addParamAttribute(M.getContext(), 2, AK);
599
600 assert((CallType == ValueProfilingCallType::Default ||
601 CallType == ValueProfilingCallType::MemOp) &&
602 "Must be Default or MemOp");
603 Type *ParamTypes[] = {
604#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
606 };
607 auto *ValueProfilingCallTy =
608 FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
609 StringRef FuncName = CallType == ValueProfilingCallType::Default
612 return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
613}
614
615void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
616 GlobalVariable *Name = Ind->getName();
619 auto &PD = ProfileDataMap[Name];
620 PD.NumValueSites[ValueKind] =
621 std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
622}
623
624void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
625 // TODO: Value profiling heavily depends on the data section which is omitted
626 // in lightweight mode. We need to move the value profile pointer to the
627 // Counter struct to get this working.
628 assert(
630 "Value profiling is not yet supported with lightweight instrumentation");
631 GlobalVariable *Name = Ind->getName();
632 auto It = ProfileDataMap.find(Name);
633 assert(It != ProfileDataMap.end() && It->second.DataVar &&
634 "value profiling detected in function with no counter incerement");
635
636 GlobalVariable *DataVar = It->second.DataVar;
639 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
640 Index += It->second.NumValueSites[Kind];
641
642 IRBuilder<> Builder(Ind);
643 bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
644 llvm::InstrProfValueKind::IPVK_MemOPSize);
645 CallInst *Call = nullptr;
646 auto *TLI = &GetTLI(*Ind->getFunction());
647
648 // To support value profiling calls within Windows exception handlers, funclet
649 // information contained within operand bundles needs to be copied over to
650 // the library call. This is required for the IR to be processed by the
651 // WinEHPrepare pass.
653 Ind->getOperandBundlesAsDefs(OpBundles);
654 if (!IsMemOpSize) {
655 Value *Args[3] = {Ind->getTargetValue(),
656 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
657 Builder.getInt32(Index)};
658 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
659 OpBundles);
660 } else {
661 Value *Args[3] = {Ind->getTargetValue(),
662 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
663 Builder.getInt32(Index)};
664 Call = Builder.CreateCall(
665 getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
666 Args, OpBundles);
667 }
668 if (auto AK = TLI->getExtAttrForI32Param(false))
669 Call->addParamAttr(2, AK);
670 Ind->replaceAllUsesWith(Call);
671 Ind->eraseFromParent();
672}
673
674Value *InstrProfiling::getCounterAddress(InstrProfInstBase *I) {
675 auto *Counters = getOrCreateRegionCounters(I);
677
678 if (isa<InstrProfTimestampInst>(I))
679 Counters->setAlignment(Align(8));
680
681 auto *Addr = Builder.CreateConstInBoundsGEP2_32(
682 Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
683
684 if (!isRuntimeCounterRelocationEnabled())
685 return Addr;
686
687 Type *Int64Ty = Type::getInt64Ty(M->getContext());
688 Function *Fn = I->getParent()->getParent();
689 LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
690 if (!BiasLI) {
691 IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
692 auto *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
693 if (!Bias) {
694 // Compiler must define this variable when runtime counter relocation
695 // is being used. Runtime has a weak external reference that is used
696 // to check whether that's the case or not.
697 Bias = new GlobalVariable(
698 *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
700 Bias->setVisibility(GlobalVariable::HiddenVisibility);
701 // A definition that's weak (linkonce_odr) without being in a COMDAT
702 // section wouldn't lead to link errors, but it would lead to a dead
703 // data word from every TU but one. Putting it in COMDAT ensures there
704 // will be exactly one data slot in the link.
705 if (TT.supportsCOMDAT())
706 Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
707 }
708 BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias);
709 }
710 auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
711 return Builder.CreateIntToPtr(Add, Addr->getType());
712}
713
714void InstrProfiling::lowerCover(InstrProfCoverInst *CoverInstruction) {
715 auto *Addr = getCounterAddress(CoverInstruction);
716 IRBuilder<> Builder(CoverInstruction);
717 // We store zero to represent that this block is covered.
718 Builder.CreateStore(Builder.getInt8(0), Addr);
719 CoverInstruction->eraseFromParent();
720}
721
722void InstrProfiling::lowerTimestamp(
723 InstrProfTimestampInst *TimestampInstruction) {
724 assert(TimestampInstruction->getIndex()->isZeroValue() &&
725 "timestamp probes are always the first probe for a function");
726 auto &Ctx = M->getContext();
727 auto *TimestampAddr = getCounterAddress(TimestampInstruction);
728 IRBuilder<> Builder(TimestampInstruction);
729 auto *CalleeTy =
730 FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
731 auto Callee = M->getOrInsertFunction(
732 INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SET_TIMESTAMP), CalleeTy);
733 Builder.CreateCall(Callee, {TimestampAddr});
734 TimestampInstruction->eraseFromParent();
735}
736
737void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
738 auto *Addr = getCounterAddress(Inc);
739
740 IRBuilder<> Builder(Inc);
741 if (Options.Atomic || AtomicCounterUpdateAll ||
742 (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
743 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
745 } else {
746 Value *IncStep = Inc->getStep();
747 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
748 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
749 auto *Store = Builder.CreateStore(Count, Addr);
750 if (isCounterPromotionEnabled())
751 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
752 }
753 Inc->eraseFromParent();
754}
755
756void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
757 ConstantArray *Names =
758 cast<ConstantArray>(CoverageNamesVar->getInitializer());
759 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
760 Constant *NC = Names->getOperand(I);
761 Value *V = NC->stripPointerCasts();
762 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
763 GlobalVariable *Name = cast<GlobalVariable>(V);
764
766 ReferencedNames.push_back(Name);
767 if (isa<ConstantExpr>(NC))
768 NC->dropAllReferences();
769 }
770 if (DebugInfoCorrelate && !ReferencedNames.empty()) {
771 MDNode *Node = *M->debug_compile_units_begin();
772 DICompileUnit *CU = cast<DICompileUnit>(Node);
773 DIBuilder DB(*M, true, CU);
774 LLVMContext &Ctx = M->getContext();
776 for (auto *NameVar: ReferencedNames) {
777 Metadata *CovFunctionNameAnnotation[] = {
779 MDString::get(Ctx,
780 std::string(getPGOFuncNameVarInitializer(NameVar))),
781 };
782 Annots.push_back(MDNode::get(Ctx, CovFunctionNameAnnotation));
783 }
784 auto Annotations = DB.getOrCreateArray(Annots);
785 auto *DICovName = DB.createGlobalVariableExpression(
786 CU, CoverageNamesVar->getName(), /*LinkageName=*/StringRef(),
787 CU->getFile(),
788 /*LineNo=*/0, DB.createUnspecifiedType("Coverage Type"),
789 /*IsLocalToUnit=*/true, /*IsDefined=*/true, /*Expr=*/nullptr,
790 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
792 CoverageNamesVar->addDebugInfo(DICovName);
793 DB.finalize();
794 ReferencedNames.clear();
795 return;
796 }
797
798 CoverageNamesVar->eraseFromParent();
799}
800
801/// Get the name of a profiling variable for a particular function.
802static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
803 bool &Renamed) {
805 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
806 Function *F = Inc->getParent()->getParent();
807 Module *M = F->getParent();
808 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
810 Renamed = false;
811 return (Prefix + Name).str();
812 }
813 Renamed = true;
814 uint64_t FuncHash = Inc->getHash()->getZExtValue();
815 SmallVector<char, 24> HashPostfix;
816 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
817 return (Prefix + Name).str();
818 return (Prefix + Name + "." + Twine(FuncHash)).str();
819}
820
822 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
823 if (!MD)
824 return 0;
825
826 // If the flag is a ConstantAsMetadata, it should be an integer representable
827 // in 64-bits.
828 return cast<ConstantInt>(MD->getValue())->getZExtValue();
829}
830
831static bool enablesValueProfiling(const Module &M) {
832 return isIRPGOFlagSet(&M) ||
833 getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
834}
835
836// Conservatively returns true if data variables may be referenced by code.
837static bool profDataReferencedByCode(const Module &M) {
838 return enablesValueProfiling(M);
839}
840
841static inline bool shouldRecordFunctionAddr(Function *F) {
842 // Only record function addresses if IR PGO is enabled or if clang value
843 // profiling is enabled. Recording function addresses greatly increases object
844 // file size, because it prevents the inliner from deleting functions that
845 // have been inlined everywhere.
846 if (!profDataReferencedByCode(*F->getParent()))
847 return false;
848
849 // Check the linkage
850 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
851 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
852 !HasAvailableExternallyLinkage)
853 return true;
854
855 // A function marked 'alwaysinline' with available_externally linkage can't
856 // have its address taken. Doing so would create an undefined external ref to
857 // the function, which would fail to link.
858 if (HasAvailableExternallyLinkage &&
859 F->hasFnAttribute(Attribute::AlwaysInline))
860 return false;
861
862 // Prohibit function address recording if the function is both internal and
863 // COMDAT. This avoids the profile data variable referencing internal symbols
864 // in COMDAT.
865 if (F->hasLocalLinkage() && F->hasComdat())
866 return false;
867
868 // Check uses of this function for other than direct calls or invokes to it.
869 // Inline virtual functions have linkeOnceODR linkage. When a key method
870 // exists, the vtable will only be emitted in the TU where the key method
871 // is defined. In a TU where vtable is not available, the function won't
872 // be 'addresstaken'. If its address is not recorded here, the profile data
873 // with missing address may be picked by the linker leading to missing
874 // indirect call target info.
875 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
876}
877
878static inline bool shouldUsePublicSymbol(Function *Fn) {
879 // It isn't legal to make an alias of this function at all
880 if (Fn->isDeclarationForLinker())
881 return true;
882
883 // Symbols with local linkage can just use the symbol directly without
884 // introducing relocations
885 if (Fn->hasLocalLinkage())
886 return true;
887
888 // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
889 // unfavorable interaction between the new alias and the alias renaming done
890 // in LowerTypeTests under ThinLTO. For comdat functions that would normally
891 // be deduplicated, but the renaming scheme ends up preventing renaming, since
892 // it creates unique names for each alias, resulting in duplicated symbols. In
893 // the future, we should update the CFI related passes to migrate these
894 // aliases to the same module as the jump-table they refer to will be defined.
895 if (Fn->hasMetadata(LLVMContext::MD_type))
896 return true;
897
898 // For comdat functions, an alias would need the same linkage as the original
899 // function and hidden visibility. There is no point in adding an alias with
900 // identical linkage an visibility to avoid introducing symbolic relocations.
901 if (Fn->hasComdat() &&
903 return true;
904
905 // its OK to use an alias
906 return false;
907}
908
910 auto *Int8PtrTy = Type::getInt8PtrTy(Fn->getContext());
911 // Store a nullptr in __llvm_profd, if we shouldn't use a real address
913 return ConstantPointerNull::get(Int8PtrTy);
914
915 // If we can't use an alias, we must use the public symbol, even though this
916 // may require a symbolic relocation.
917 if (shouldUsePublicSymbol(Fn))
918 return ConstantExpr::getBitCast(Fn, Int8PtrTy);
919
920 // When possible use a private alias to avoid symbolic relocations.
922 Fn->getName() + ".local", Fn);
923
924 // When the instrumented function is a COMDAT function, we cannot use a
925 // private alias. If we did, we would create reference to a local label in
926 // this function's section. If this version of the function isn't selected by
927 // the linker, then the metadata would introduce a reference to a discarded
928 // section. So, for COMDAT functions, we need to adjust the linkage of the
929 // alias. Using hidden visibility avoids a dynamic relocation and an entry in
930 // the dynamic symbol table.
931 //
932 // Note that this handles COMDAT functions with visibility other than Hidden,
933 // since that case is covered in shouldUsePublicSymbol()
934 if (Fn->hasComdat()) {
935 GA->setLinkage(Fn->getLinkage());
937 }
938
939 // appendToCompilerUsed(*Fn->getParent(), {GA});
940
941 return ConstantExpr::getBitCast(GA, Int8PtrTy);
942}
943
945 // Don't do this for Darwin. compiler-rt uses linker magic.
946 if (TT.isOSDarwin())
947 return false;
948 // Use linker script magic to get data/cnts/name start/end.
949 if (TT.isOSAIX() || TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
950 TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS() || TT.isOSWindows())
951 return false;
952
953 return true;
954}
955
957InstrProfiling::createRegionCounters(InstrProfInstBase *Inc, StringRef Name,
959 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
960 auto &Ctx = M->getContext();
961 GlobalVariable *GV;
962 if (isa<InstrProfCoverInst>(Inc)) {
963 auto *CounterTy = Type::getInt8Ty(Ctx);
964 auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
965 // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
966 std::vector<Constant *> InitialValues(NumCounters,
967 Constant::getAllOnesValue(CounterTy));
968 GV = new GlobalVariable(*M, CounterArrTy, false, Linkage,
969 ConstantArray::get(CounterArrTy, InitialValues),
970 Name);
971 GV->setAlignment(Align(1));
972 } else {
973 auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
974 GV = new GlobalVariable(*M, CounterTy, false, Linkage,
975 Constant::getNullValue(CounterTy), Name);
976 GV->setAlignment(Align(8));
977 }
978 return GV;
979}
980
982InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
983 GlobalVariable *NamePtr = Inc->getName();
984 auto &PD = ProfileDataMap[NamePtr];
985 if (PD.RegionCounters)
986 return PD.RegionCounters;
987
988 // Match the linkage and visibility of the name global.
989 Function *Fn = Inc->getParent()->getParent();
991 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
992
993 // Use internal rather than private linkage so the counter variable shows up
994 // in the symbol table when using debug info for correlation.
998
999 // Due to the limitation of binder as of 2021/09/28, the duplicate weak
1000 // symbols in the same csect won't be discarded. When there are duplicate weak
1001 // symbols, we can NOT guarantee that the relocations get resolved to the
1002 // intended weak symbol, so we can not ensure the correctness of the relative
1003 // CounterPtr, so we have to use private linkage for counter and data symbols.
1004 if (TT.isOSBinFormatXCOFF()) {
1006 Visibility = GlobalValue::DefaultVisibility;
1007 }
1008 // Move the name variable to the right section. Place them in a COMDAT group
1009 // if the associated function is a COMDAT. This will make sure that only one
1010 // copy of counters of the COMDAT function will be emitted after linking. Keep
1011 // in mind that this pass may run before the inliner, so we need to create a
1012 // new comdat group for the counters and profiling data. If we use the comdat
1013 // of the parent function, that will result in relocations against discarded
1014 // sections.
1015 //
1016 // If the data variable is referenced by code, counters and data have to be
1017 // in different comdats for COFF because the Visual C++ linker will report
1018 // duplicate symbol errors if there are multiple external symbols with the
1019 // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
1020 //
1021 // For ELF, when not using COMDAT, put counters, data and values into a
1022 // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
1023 // allows -z start-stop-gc to discard the entire group when the function is
1024 // discarded.
1025 bool DataReferencedByCode = profDataReferencedByCode(*M);
1026 bool NeedComdat = needsComdatForCounter(*Fn, *M);
1027 bool Renamed;
1028 std::string CntsVarName =
1030 std::string DataVarName =
1031 getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
1032 auto MaybeSetComdat = [&](GlobalVariable *GV) {
1033 bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1034 if (UseComdat) {
1035 StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1036 ? GV->getName()
1037 : CntsVarName;
1038 Comdat *C = M->getOrInsertComdat(GroupName);
1039 if (!NeedComdat)
1040 C->setSelectionKind(Comdat::NoDeduplicate);
1041 GV->setComdat(C);
1042 // COFF doesn't allow the comdat group leader to have private linkage, so
1043 // upgrade private linkage to internal linkage to produce a symbol table
1044 // entry.
1045 if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1047 }
1048 };
1049
1050 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1051 LLVMContext &Ctx = M->getContext();
1052
1053 auto *CounterPtr = createRegionCounters(Inc, CntsVarName, Linkage);
1054 CounterPtr->setVisibility(Visibility);
1055 CounterPtr->setSection(
1056 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
1057 CounterPtr->setLinkage(Linkage);
1058 MaybeSetComdat(CounterPtr);
1059 PD.RegionCounters = CounterPtr;
1060 if (DebugInfoCorrelate) {
1061 if (auto *SP = Fn->getSubprogram()) {
1062 DIBuilder DB(*M, true, SP->getUnit());
1063 Metadata *FunctionNameAnnotation[] = {
1066 };
1067 Metadata *CFGHashAnnotation[] = {
1070 };
1071 Metadata *NumCountersAnnotation[] = {
1074 };
1075 auto Annotations = DB.getOrCreateArray({
1076 MDNode::get(Ctx, FunctionNameAnnotation),
1077 MDNode::get(Ctx, CFGHashAnnotation),
1078 MDNode::get(Ctx, NumCountersAnnotation),
1079 });
1080 auto *DICounter = DB.createGlobalVariableExpression(
1081 SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
1082 /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
1083 CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
1084 /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
1085 Annotations);
1086 CounterPtr->addDebugInfo(DICounter);
1087 DB.finalize();
1088 }
1089 }
1090
1091 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
1092 // Allocate statically the array of pointers to value profile nodes for
1093 // the current function.
1094 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1095 uint64_t NS = 0;
1096 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1097 NS += PD.NumValueSites[Kind];
1098 if (NS > 0 && ValueProfileStaticAlloc &&
1100 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1101 auto *ValuesVar = new GlobalVariable(
1102 *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1103 getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
1104 ValuesVar->setVisibility(Visibility);
1105 ValuesVar->setSection(
1106 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1107 ValuesVar->setAlignment(Align(8));
1108 MaybeSetComdat(ValuesVar);
1109 ValuesPtrExpr =
1111 }
1112
1113 if (DebugInfoCorrelate) {
1114 // Mark the counter variable as used so that it isn't optimized out.
1115 CompilerUsedVars.push_back(PD.RegionCounters);
1116 return PD.RegionCounters;
1117 }
1118
1119 // Create data variable.
1120 auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
1121 auto *Int16Ty = Type::getInt16Ty(Ctx);
1122 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1123 Type *DataTypes[] = {
1124#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1126 };
1127 auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
1128
1129 Constant *FunctionAddr = getFuncAddrForProfData(Fn);
1130
1131 Constant *Int16ArrayVals[IPVK_Last + 1];
1132 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1133 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1134
1135 // If the data variable is not referenced by code (if we don't emit
1136 // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1137 // data variable live under linker GC, the data variable can be private. This
1138 // optimization applies to ELF.
1139 //
1140 // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1141 // to be false.
1142 //
1143 // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1144 // that other copies must have the same CFG and cannot have value profiling.
1145 // If no hash suffix, other profd copies may be referenced by code.
1146 if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1147 (TT.isOSBinFormatELF() ||
1148 (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1150 Visibility = GlobalValue::DefaultVisibility;
1151 }
1152 auto *Data =
1153 new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1154 // Reference the counter variable with a label difference (link-time
1155 // constant).
1156 auto *RelativeCounterPtr =
1157 ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1158 ConstantExpr::getPtrToInt(Data, IntPtrTy));
1159
1160 Constant *DataVals[] = {
1161#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1163 };
1164 Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1165
1166 Data->setVisibility(Visibility);
1167 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
1168 Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1169 MaybeSetComdat(Data);
1170
1171 PD.DataVar = Data;
1172
1173 // Mark the data variable as used so that it isn't stripped out.
1174 CompilerUsedVars.push_back(Data);
1175 // Now that the linkage set by the FE has been passed to the data and counter
1176 // variables, reset Name variable's linkage and visibility to private so that
1177 // it can be removed later by the compiler.
1179 // Collect the referenced names to be used by emitNameData.
1180 ReferencedNames.push_back(NamePtr);
1181
1182 return PD.RegionCounters;
1183}
1184
1185void InstrProfiling::emitVNodes() {
1186 if (!ValueProfileStaticAlloc)
1187 return;
1188
1189 // For now only support this on platforms that do
1190 // not require runtime registration to discover
1191 // named section start/end.
1193 return;
1194
1195 size_t TotalNS = 0;
1196 for (auto &PD : ProfileDataMap) {
1197 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1198 TotalNS += PD.second.NumValueSites[Kind];
1199 }
1200
1201 if (!TotalNS)
1202 return;
1203
1204 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1205// Heuristic for small programs with very few total value sites.
1206// The default value of vp-counters-per-site is chosen based on
1207// the observation that large apps usually have a low percentage
1208// of value sites that actually have any profile data, and thus
1209// the average number of counters per site is low. For small
1210// apps with very few sites, this may not be true. Bump up the
1211// number of counters in this case.
1212#define INSTR_PROF_MIN_VAL_COUNTS 10
1213 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1214 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1215
1216 auto &Ctx = M->getContext();
1217 Type *VNodeTypes[] = {
1218#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1220 };
1221 auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
1222
1223 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1224 auto *VNodesVar = new GlobalVariable(
1225 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
1227 VNodesVar->setSection(
1228 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1229 VNodesVar->setAlignment(M->getDataLayout().getABITypeAlign(VNodesTy));
1230 // VNodesVar is used by runtime but not referenced via relocation by other
1231 // sections. Conservatively make it linker retained.
1232 UsedVars.push_back(VNodesVar);
1233}
1234
1235void InstrProfiling::emitNameData() {
1236 std::string UncompressedData;
1237
1238 if (ReferencedNames.empty())
1239 return;
1240
1241 std::string CompressedNameStr;
1242 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
1244 report_fatal_error(Twine(toString(std::move(E))), false);
1245 }
1246
1247 auto &Ctx = M->getContext();
1248 auto *NamesVal =
1249 ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1250 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
1253 NamesSize = CompressedNameStr.size();
1254 NamesVar->setSection(
1255 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1256 // On COFF, it's important to reduce the alignment down to 1 to prevent the
1257 // linker from inserting padding before the start of the names section or
1258 // between names entries.
1259 NamesVar->setAlignment(Align(1));
1260 // NamesVar is used by runtime but not referenced via relocation by other
1261 // sections. Conservatively make it linker retained.
1262 UsedVars.push_back(NamesVar);
1263
1264 for (auto *NamePtr : ReferencedNames)
1265 NamePtr->eraseFromParent();
1266}
1267
1268void InstrProfiling::emitRegistration() {
1270 return;
1271
1272 // Construct the function.
1273 auto *VoidTy = Type::getVoidTy(M->getContext());
1274 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1275 auto *Int64Ty = Type::getInt64Ty(M->getContext());
1276 auto *RegisterFTy = FunctionType::get(VoidTy, false);
1277 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1279 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1280 if (Options.NoRedZone)
1281 RegisterF->addFnAttr(Attribute::NoRedZone);
1282
1283 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1284 auto *RuntimeRegisterF =
1287
1288 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1289 for (Value *Data : CompilerUsedVars)
1290 if (!isa<Function>(Data))
1291 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1292 for (Value *Data : UsedVars)
1293 if (Data != NamesVar && !isa<Function>(Data))
1294 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1295
1296 if (NamesVar) {
1297 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1298 auto *NamesRegisterTy =
1299 FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
1300 auto *NamesRegisterF =
1303 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1304 IRB.getInt64(NamesSize)});
1305 }
1306
1307 IRB.CreateRetVoid();
1308}
1309
1310bool InstrProfiling::emitRuntimeHook() {
1311 // We expect the linker to be invoked with -u<hook_var> flag for Linux
1312 // in which case there is no need to emit the external variable.
1313 if (TT.isOSLinux() || TT.isOSAIX())
1314 return false;
1315
1316 // If the module's provided its own runtime, we don't need to do anything.
1317 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1318 return false;
1319
1320 // Declare an external variable that will pull in the runtime initialization.
1321 auto *Int32Ty = Type::getInt32Ty(M->getContext());
1322 auto *Var =
1325 Var->setVisibility(GlobalValue::HiddenVisibility);
1326
1327 if (TT.isOSBinFormatELF() && !TT.isPS()) {
1328 // Mark the user variable as used so that it isn't stripped out.
1329 CompilerUsedVars.push_back(Var);
1330 } else {
1331 // Make a function that uses it.
1335 User->addFnAttr(Attribute::NoInline);
1336 if (Options.NoRedZone)
1337 User->addFnAttr(Attribute::NoRedZone);
1338 User->setVisibility(GlobalValue::HiddenVisibility);
1339 if (TT.supportsCOMDAT())
1340 User->setComdat(M->getOrInsertComdat(User->getName()));
1341
1342 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1343 auto *Load = IRB.CreateLoad(Int32Ty, Var);
1344 IRB.CreateRet(Load);
1345
1346 // Mark the function as used so that it isn't stripped out.
1347 CompilerUsedVars.push_back(User);
1348 }
1349 return true;
1350}
1351
1352void InstrProfiling::emitUses() {
1353 // The metadata sections are parallel arrays. Optimizers (e.g.
1354 // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1355 // we conservatively retain all unconditionally in the compiler.
1356 //
1357 // On ELF and Mach-O, the linker can guarantee the associated sections will be
1358 // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1359 // Similarly on COFF, if prof data is not referenced by code we use one comdat
1360 // and ensure this GC property as well. Otherwise, we have to conservatively
1361 // make all of the sections retained by the linker.
1362 if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1364 appendToCompilerUsed(*M, CompilerUsedVars);
1365 else
1366 appendToUsed(*M, CompilerUsedVars);
1367
1368 // We do not add proper references from used metadata sections to NamesVar and
1369 // VNodesVar, so we have to be conservative and place them in llvm.used
1370 // regardless of the target,
1371 appendToUsed(*M, UsedVars);
1372}
1373
1374void InstrProfiling::emitInitialization() {
1375 // Create ProfileFileName variable. Don't don't this for the
1376 // context-sensitive instrumentation lowering: This lowering is after
1377 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1378 // have already create the variable before LTO/ThinLTO linking.
1379 if (!IsCS)
1381 Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1382 if (!RegisterF)
1383 return;
1384
1385 // Create the initialization function.
1386 auto *VoidTy = Type::getVoidTy(M->getContext());
1387 auto *F = Function::Create(FunctionType::get(VoidTy, false),
1390 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1391 F->addFnAttr(Attribute::NoInline);
1392 if (Options.NoRedZone)
1393 F->addFnAttr(Attribute::NoRedZone);
1394
1395 // Add the basic block and the necessary calls.
1396 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1397 IRB.CreateCall(RegisterF, {});
1398 IRB.CreateRetVoid();
1399
1400 appendToGlobalCtors(*M, F, 0);
1401}
assume Assume Builder
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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
static bool enablesValueProfiling(const Module &M)
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 uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag)
static bool profDataReferencedByCode(const Module &M)
static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT)
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Memory SSA
Definition: MemorySSA.cpp:71
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
if(VerifyEach)
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
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:648
@ Add
*p = old + v
Definition: Instructions.h:734
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator end()
Definition: BasicBlock.h:337
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:335
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:257
const Instruction & front() const
Definition: BasicBlock.h:347
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:112
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
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.
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
ConstantArray - Constant Array Declarations.
Definition: Constants.h:408
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1235
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:419
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:2890
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2573
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2185
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2213
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
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:145
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1691
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1300
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:403
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:62
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
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:165
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:138
const BasicBlock & getEntryBlock() const
Definition: Function.h:747
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1727
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:320
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:506
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:585
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
void setComdat(Comdat *C)
Definition: Globals.cpp:196
bool hasComdat() const
Definition: GlobalObject.h:127
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:250
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:244
LinkageTypes getLinkage() const
Definition: GlobalValue.h:541
bool hasLocalLinkage() const
Definition: GlobalValue.h:523
bool hasPrivateLinkage() const
Definition: GlobalValue.h:522
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:532
bool isDeclarationForLinker() const
Definition: GlobalValue.h:614
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:63
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
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:454
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1740
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2628
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:933
static const char * FunctionNameAttributeName
static const char * CFGHashAttributeName
static const char * CovFunctionNameAttributeName
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.
ConstantInt * getNumCounters() const
GlobalVariable * getName() const
ConstantInt * getHash() const
ConstantInt * getIndex() 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)
const BasicBlock * getParent() const
Definition: Instruction.h:90
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:75
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:83
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:147
virtual void doExtraRewritesBeforeFinalDeletion()
This hook is invoked after all the stores are found and inserted as available values.
Definition: SSAUpdater.h:172
An instruction for reading from memory.
Definition: Instructions.h:177
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:47
Metadata node.
Definition: Metadata.h:950
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1416
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:499
Root of the metadata hierarchy.
Definition: Metadata.h:61
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:39
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:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
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:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
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:575
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:374
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
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition: Triple.h:381
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:688
bool supportsCOMDAT() const
Tests whether the target supports comdat.
Definition: Triple.h:1002
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:680
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition: Triple.h:698
bool isOSLinux() const
Tests whether the OS is Linux.
Definition: Triple.h:638
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:670
bool isPS() const
Tests whether the target is the PS4 or PS5 platform.
Definition: Triple.h:722
bool isOSFuchsia() const
Definition: Triple.h:548
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:675
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:129
static IntegerType * getInt8Ty(LLVMContext &C)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
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:535
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
ValueKind
Value kinds.
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:988
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
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:91
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition: InstrProf.h:155
cl::opt< bool > DoInstrProfNameCompression
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:666
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition: InstrProf.h:94
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition: InstrProf.h:122
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:218
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition: InstrProf.h:150
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition: InstrProf.h:100
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:1734
StringRef getInstrProfCounterBiasVarName()
Definition: InstrProf.h:165
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:429
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition: InstrProf.h:161
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition: InstrProf.h:131
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition: InstrProf.h:97
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:535
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition: InstrProf.h:86
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition: InstrProf.h:142
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
@ Add
Sum of integers.
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1235
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1283
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1306
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:73
Error collectPGOFuncNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
Definition: InstrProf.cpp:497
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition: InstrProf.h:80
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition: InstrProf.h:137
cl::opt< bool > DebugInfoCorrelate("debug-info-correlate", cl::desc("Use debug info to correlate profiles."), cl::init(false))
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:107
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1261
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition: InstrProf.h:103
#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
std::string InstrProfileOutput
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117