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