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