blob: bf91e6d7fa8e3cb5101ae44f626259ccaad4d5d8 [file] [log] [blame]
Justin Bogner61ba2e32014-12-08 18:02:35 +00001//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Justin Bogner61ba2e32014-12-08 18:02:35 +00006//
7//===----------------------------------------------------------------------===//
8//
Betul Buyukkurt6fac1742015-11-18 18:14:55 +00009// This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
10// It also builds the data structures and initialization code needed for
11// updating execution counts and emitting the profile at runtime.
Justin Bogner61ba2e32014-12-08 18:02:35 +000012//
13//===----------------------------------------------------------------------===//
14
David Blaikie4fe1fe12018-03-23 22:11:06 +000015#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/StringRef.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000019#include "llvm/ADT/Triple.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000020#include "llvm/ADT/Twine.h"
Rong Xu6cdf3d82019-02-27 17:24:33 +000021#include "llvm/Analysis/BlockFrequencyInfo.h"
22#include "llvm/Analysis/BranchProbabilityInfo.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000023#include "llvm/Analysis/LoopInfo.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000025#include "llvm/IR/Attributes.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DerivedTypes.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000030#include "llvm/IR/Dominators.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalValue.h"
33#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000034#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000035#include "llvm/IR/Instruction.h"
36#include "llvm/IR/Instructions.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000037#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000039#include "llvm/IR/Type.h"
40#include "llvm/Pass.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000041#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000042#include "llvm/Support/Casting.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Error.h"
45#include "llvm/Support/ErrorHandling.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000048#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000049#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000054
55using namespace llvm;
56
57#define DEBUG_TYPE "instrprof"
58
Rong Xu48596b62017-04-04 16:42:20 +000059// The start and end values of precise value profile range for memory
60// intrinsic sizes
61cl::opt<std::string> MemOPSizeRange(
62 "memop-size-range",
63 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
64 "precisely, in a format of <start_val>:<end_val>"),
65 cl::init(""));
66
67// The value that considered to be large value in memory intrinsic.
68cl::opt<unsigned> MemOPSizeLarge(
69 "memop-size-large",
70 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
71 "Value of 0 disables the large value profiling."),
72 cl::init(8192));
73
Justin Bogner61ba2e32014-12-08 18:02:35 +000074namespace {
75
Xinliang David Lia82d6c02016-02-08 18:13:49 +000076cl::opt<bool> DoNameCompression("enable-name-compression",
77 cl::desc("Enable name string compression"),
78 cl::init(true));
79
Rong Xu20f5df12017-01-11 20:19:41 +000080cl::opt<bool> DoHashBasedCounterSplit(
81 "hash-based-counter-split",
82 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
83 cl::init(true));
84
Xinliang David Lib628dd32016-05-21 22:55:34 +000085cl::opt<bool> ValueProfileStaticAlloc(
86 "vp-static-alloc",
87 cl::desc("Do static counter allocation for value profiler"),
88 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000089
Xinliang David Lib628dd32016-05-21 22:55:34 +000090cl::opt<double> NumCountersPerValueSite(
91 "vp-counters-per-site",
92 cl::desc("The average number of profile counters allocated "
93 "per value profiling site."),
94 // This is set to a very small value because in real programs, only
95 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
96 // For those sites with non-zero profile, the average number of targets
97 // is usually smaller than 2.
98 cl::init(1.0));
99
Vedant Kumaree6c2332018-08-16 22:24:47 +0000100cl::opt<bool> AtomicCounterUpdateAll(
101 "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
102 cl::desc("Make all profile counter updates atomic (for testing only)"),
103 cl::init(false));
104
Xinliang David Lib67530e2017-06-25 00:26:43 +0000105cl::opt<bool> AtomicCounterUpdatePromoted(
106 "atomic-counter-update-promoted", cl::ZeroOrMore,
107 cl::desc("Do counter update using atomic fetch add "
108 " for promoted counters only"),
109 cl::init(false));
110
111// If the option is not specified, the default behavior about whether
112// counter promotion is done depends on how instrumentaiton lowering
113// pipeline is setup, i.e., the default value of true of this option
114// does not mean the promotion will be done by default. Explicitly
115// setting this option can override the default behavior.
116cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
117 cl::desc("Do counter register promotion"),
118 cl::init(false));
119cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
Xinliang David Lif564c692017-07-12 23:27:44 +0000120 cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
Xinliang David Lib67530e2017-06-25 00:26:43 +0000121 cl::desc("Max number counter promotions per loop to avoid"
122 " increasing register pressure too much"));
123
124// A debug option
125cl::opt<int>
126 MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
127 cl::desc("Max number of allowed counter promotions"));
128
Xinliang David Lif564c692017-07-12 23:27:44 +0000129cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
130 cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
131 cl::desc("The max number of exiting blocks of a loop to allow "
132 " speculative counter promotion"));
133
134cl::opt<bool> SpeculativeCounterPromotionToLoop(
135 cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
136 cl::desc("When the option is false, if the target block is in a loop, "
137 "the promotion will be disallowed unless the promoted counter "
138 " update can be further/iteratively promoted into an acyclic "
139 " region."));
140
141cl::opt<bool> IterativeCounterPromotion(
142 cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
143 cl::desc("Allow counter promotion across the whole loop nest."));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000144
Xinliang David Lie6b89292016-04-18 17:47:38 +0000145class InstrProfilingLegacyPass : public ModulePass {
146 InstrProfiling InstrProf;
147
Justin Bogner61ba2e32014-12-08 18:02:35 +0000148public:
149 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000150
151 InstrProfilingLegacyPass() : ModulePass(ID) {}
Rong Xu6cdf3d82019-02-27 17:24:33 +0000152 InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
153 : ModulePass(ID), InstrProf(Options, IsCS) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000154
Mehdi Amini117296c2016-10-01 02:56:57 +0000155 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000156 return "Frontend instrumentation-based coverage lowering";
157 }
158
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000159 bool runOnModule(Module &M) override {
160 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
161 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000162
163 void getAnalysisUsage(AnalysisUsage &AU) const override {
164 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000165 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000166 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000167};
168
Xinliang David Lif564c692017-07-12 23:27:44 +0000169///
Xinliang David Lib67530e2017-06-25 00:26:43 +0000170/// A helper class to promote one counter RMW operation in the loop
171/// into register update.
172///
173/// RWM update for the counter will be sinked out of the loop after
174/// the transformation.
175///
176class PGOCounterPromoterHelper : public LoadAndStorePromoter {
177public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000178 PGOCounterPromoterHelper(
179 Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
180 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
181 ArrayRef<Instruction *> InsertPts,
182 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
183 LoopInfo &LI)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000184 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
Xinliang David Lif564c692017-07-12 23:27:44 +0000185 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000186 assert(isa<LoadInst>(L));
187 assert(isa<StoreInst>(S));
188 SSA.AddAvailableValue(PH, Init);
189 }
Xinliang David Lif564c692017-07-12 23:27:44 +0000190
Alina Sbirlea6cba96e2019-02-06 20:25:17 +0000191 void doExtraRewritesBeforeFinalDeletion() override {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000192 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
193 BasicBlock *ExitBlock = ExitBlocks[i];
194 Instruction *InsertPos = InsertPts[i];
195 // Get LiveIn value into the ExitBlock. If there are multiple
196 // predecessors, the value is defined by a PHI node in this
197 // block.
198 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
199 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
James Y Knight14359ef2019-02-01 20:44:24 +0000200 Type *Ty = LiveInValue->getType();
Xinliang David Lib67530e2017-06-25 00:26:43 +0000201 IRBuilder<> Builder(InsertPos);
202 if (AtomicCounterUpdatePromoted)
Xinliang David Lif564c692017-07-12 23:27:44 +0000203 // automic update currently can only be promoted across the current
204 // loop, not the whole loop nest.
Xinliang David Lib67530e2017-06-25 00:26:43 +0000205 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
206 AtomicOrdering::SequentiallyConsistent);
207 else {
James Y Knight14359ef2019-02-01 20:44:24 +0000208 LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000209 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
Xinliang David Lif564c692017-07-12 23:27:44 +0000210 auto *NewStore = Builder.CreateStore(NewVal, Addr);
211
212 // Now update the parent loop's candidate list:
213 if (IterativeCounterPromotion) {
214 auto *TargetLoop = LI.getLoopFor(ExitBlock);
215 if (TargetLoop)
216 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
217 }
Xinliang David Lib67530e2017-06-25 00:26:43 +0000218 }
219 }
220 }
221
222private:
223 Instruction *Store;
224 ArrayRef<BasicBlock *> ExitBlocks;
225 ArrayRef<Instruction *> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000226 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
227 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000228};
229
230/// A helper class to do register promotion for all profile counter
231/// updates in a loop.
232///
233class PGOCounterPromoter {
234public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000235 PGOCounterPromoter(
236 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
Rong Xu6cdf3d82019-02-27 17:24:33 +0000237 Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
Xinliang David Lif564c692017-07-12 23:27:44 +0000238 : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
Rong Xu6cdf3d82019-02-27 17:24:33 +0000239 LI(LI), BFI(BFI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000240
241 SmallVector<BasicBlock *, 8> LoopExitBlocks;
242 SmallPtrSet<BasicBlock *, 8> BlockSet;
Xinliang David Lif564c692017-07-12 23:27:44 +0000243 L.getExitBlocks(LoopExitBlocks);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000244
245 for (BasicBlock *ExitBlock : LoopExitBlocks) {
246 if (BlockSet.insert(ExitBlock).second) {
247 ExitBlocks.push_back(ExitBlock);
248 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
249 }
250 }
251 }
252
253 bool run(int64_t *NumPromoted) {
Xinliang David Lic23d2c62017-11-30 19:16:25 +0000254 // Skip 'infinite' loops:
255 if (ExitBlocks.size() == 0)
256 return false;
Xinliang David Lif564c692017-07-12 23:27:44 +0000257 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
258 if (MaxProm == 0)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000259 return false;
260
261 unsigned Promoted = 0;
Xinliang David Lif564c692017-07-12 23:27:44 +0000262 for (auto &Cand : LoopToCandidates[&L]) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000263
264 SmallVector<PHINode *, 4> NewPHIs;
265 SSAUpdater SSA(&NewPHIs);
266 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
Xinliang David Lif564c692017-07-12 23:27:44 +0000267
Rong Xu6cdf3d82019-02-27 17:24:33 +0000268 // If BFI is set, we will use it to guide the promotions.
269 if (BFI) {
270 auto *BB = Cand.first->getParent();
271 auto InstrCount = BFI->getBlockProfileCount(BB);
272 if (!InstrCount)
273 continue;
274 auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
275 // If the average loop trip count is not greater than 1.5, we skip
276 // promotion.
277 if (PreheaderCount &&
278 (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
279 continue;
280 }
281
Xinliang David Lib67530e2017-06-25 00:26:43 +0000282 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
Xinliang David Lif564c692017-07-12 23:27:44 +0000283 L.getLoopPreheader(), ExitBlocks,
284 InsertPts, LoopToCandidates, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000285 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
286 Promoted++;
Xinliang David Lif564c692017-07-12 23:27:44 +0000287 if (Promoted >= MaxProm)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000288 break;
Xinliang David Lif564c692017-07-12 23:27:44 +0000289
Xinliang David Lib67530e2017-06-25 00:26:43 +0000290 (*NumPromoted)++;
291 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
292 break;
293 }
294
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000295 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
296 << L.getLoopDepth() << ")\n");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000297 return Promoted != 0;
298 }
299
300private:
Xinliang David Lif564c692017-07-12 23:27:44 +0000301 bool allowSpeculativeCounterPromotion(Loop *LP) {
302 SmallVector<BasicBlock *, 8> ExitingBlocks;
303 L.getExitingBlocks(ExitingBlocks);
304 // Not considierered speculative.
305 if (ExitingBlocks.size() == 1)
306 return true;
307 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
308 return false;
309 return true;
310 }
311
312 // Returns the max number of Counter Promotions for LP.
313 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
314 // We can't insert into a catchswitch.
315 SmallVector<BasicBlock *, 8> LoopExitBlocks;
316 LP->getExitBlocks(LoopExitBlocks);
317 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
318 return isa<CatchSwitchInst>(Exit->getTerminator());
319 }))
320 return 0;
321
322 if (!LP->hasDedicatedExits())
323 return 0;
324
325 BasicBlock *PH = LP->getLoopPreheader();
326 if (!PH)
327 return 0;
328
329 SmallVector<BasicBlock *, 8> ExitingBlocks;
330 LP->getExitingBlocks(ExitingBlocks);
Rong Xu6cdf3d82019-02-27 17:24:33 +0000331
332 // If BFI is set, we do more aggressive promotions based on BFI.
333 if (BFI)
334 return (unsigned)-1;
335
Xinliang David Lif564c692017-07-12 23:27:44 +0000336 // Not considierered speculative.
337 if (ExitingBlocks.size() == 1)
338 return MaxNumOfPromotionsPerLoop;
339
340 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
341 return 0;
342
343 // Whether the target block is in a loop does not matter:
344 if (SpeculativeCounterPromotionToLoop)
345 return MaxNumOfPromotionsPerLoop;
346
347 // Now check the target block:
348 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
349 for (auto *TargetBlock : LoopExitBlocks) {
350 auto *TargetLoop = LI.getLoopFor(TargetBlock);
351 if (!TargetLoop)
352 continue;
353 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
354 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
355 MaxProm =
356 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
357 PendingCandsInTarget);
358 }
359 return MaxProm;
360 }
361
362 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000363 SmallVector<BasicBlock *, 8> ExitBlocks;
364 SmallVector<Instruction *, 8> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000365 Loop &L;
366 LoopInfo &LI;
Rong Xu6cdf3d82019-02-27 17:24:33 +0000367 BlockFrequencyInfo *BFI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000368};
369
Eugene Zelenko34c23272017-01-18 00:57:48 +0000370} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000371
Sean Silvafd03ac62016-08-09 00:28:38 +0000372PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000373 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
374 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000375 return PreservedAnalyses::all();
376
377 return PreservedAnalyses::none();
378}
379
380char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000381INITIALIZE_PASS_BEGIN(
382 InstrProfilingLegacyPass, "instrprof",
383 "Frontend instrumentation-based coverage lowering.", false, false)
384INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
385INITIALIZE_PASS_END(
386 InstrProfilingLegacyPass, "instrprof",
387 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000388
Xinliang David Li69a00f02016-06-21 02:39:08 +0000389ModulePass *
Rong Xu6cdf3d82019-02-27 17:24:33 +0000390llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
391 bool IsCS) {
392 return new InstrProfilingLegacyPass(Options, IsCS);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000393}
394
Xinliang David Li4ca17332016-09-18 18:34:07 +0000395static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
396 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
397 if (Inc)
398 return Inc;
399 return dyn_cast<InstrProfIncrementInst>(Instr);
400}
401
Xinliang David Lib67530e2017-06-25 00:26:43 +0000402bool InstrProfiling::lowerIntrinsics(Function *F) {
403 bool MadeChange = false;
404 PromotionCandidates.clear();
405 for (BasicBlock &BB : *F) {
406 for (auto I = BB.begin(), E = BB.end(); I != E;) {
407 auto Instr = I++;
408 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
409 if (Inc) {
410 lowerIncrement(Inc);
411 MadeChange = true;
412 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
413 lowerValueProfileInst(Ind);
414 MadeChange = true;
415 }
416 }
417 }
418
419 if (!MadeChange)
420 return false;
421
422 promoteCounterLoadStores(F);
423 return true;
424}
425
426bool InstrProfiling::isCounterPromotionEnabled() const {
427 if (DoCounterPromotion.getNumOccurrences() > 0)
428 return DoCounterPromotion;
429
430 return Options.DoCounterPromotion;
431}
432
433void InstrProfiling::promoteCounterLoadStores(Function *F) {
434 if (!isCounterPromotionEnabled())
435 return;
436
437 DominatorTree DT(*F);
438 LoopInfo LI(DT);
439 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
440
Rong Xu6cdf3d82019-02-27 17:24:33 +0000441 std::unique_ptr<BlockFrequencyInfo> BFI;
442 if (Options.UseBFIInPromotion) {
443 std::unique_ptr<BranchProbabilityInfo> BPI;
444 BPI.reset(new BranchProbabilityInfo(*F, LI, TLI));
445 BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
446 }
447
Xinliang David Lib67530e2017-06-25 00:26:43 +0000448 for (const auto &LoadStore : PromotionCandidates) {
449 auto *CounterLoad = LoadStore.first;
450 auto *CounterStore = LoadStore.second;
451 BasicBlock *BB = CounterLoad->getParent();
452 Loop *ParentLoop = LI.getLoopFor(BB);
453 if (!ParentLoop)
454 continue;
455 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
456 }
457
458 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
459
Xinliang David Lif564c692017-07-12 23:27:44 +0000460 // Do a post-order traversal of the loops so that counter updates can be
461 // iteratively hoisted outside the loop nest.
462 for (auto *Loop : llvm::reverse(Loops)) {
Rong Xu6cdf3d82019-02-27 17:24:33 +0000463 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
Xinliang David Lib67530e2017-06-25 00:26:43 +0000464 Promoter.run(&TotalCountersPromoted);
465 }
466}
467
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000468/// Check if the module contains uses of any profiling intrinsics.
469static bool containsProfilingIntrinsics(Module &M) {
470 if (auto *F = M.getFunction(
471 Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000472 if (!F->use_empty())
473 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000474 if (auto *F = M.getFunction(
475 Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000476 if (!F->use_empty())
477 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000478 if (auto *F = M.getFunction(
479 Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000480 if (!F->use_empty())
481 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000482 return false;
483}
484
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000485bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000486 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000487 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000488 NamesVar = nullptr;
489 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000490 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000491 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000492 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
493 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000494 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000495
Vedant Kumar9a041a72018-02-28 19:00:08 +0000496 // Emit the runtime hook even if no counters are present.
497 bool MadeChange = emitRuntimeHook();
498
499 // Improve compile time by avoiding linear scans when there is no work.
500 GlobalVariable *CoverageNamesVar =
501 M.getNamedGlobal(getCoverageUnusedNamesVarName());
502 if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
503 return MadeChange;
504
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000505 // We did not know how many value sites there would be inside
506 // the instrumented function. This is counting the number of instrumented
507 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000508 for (Function &F : M) {
509 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000510 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000511 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
512 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000513 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000514 else if (FirstProfIncInst == nullptr)
515 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
516
517 // Value profiling intrinsic lowering requires per-function profile data
518 // variable to be created first.
519 if (FirstProfIncInst != nullptr)
520 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
521 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000522
523 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000524 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000525
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000526 if (CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000527 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000528 MadeChange = true;
529 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000530
Justin Bogner61ba2e32014-12-08 18:02:35 +0000531 if (!MadeChange)
532 return false;
533
Xinliang David Lib628dd32016-05-21 22:55:34 +0000534 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000535 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000536 emitRegistration();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000537 emitUses();
538 emitInitialization();
539 return true;
540}
541
James Y Knight13680222019-02-01 02:28:03 +0000542static FunctionCallee
543getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI,
544 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000545 LLVMContext &Ctx = M.getContext();
546 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000547
James Y Knight13680222019-02-01 02:28:03 +0000548 AttributeList AL;
549 if (auto AK = TLI.getExtAttrForI32Param(false))
550 AL = AL.addParamAttribute(M.getContext(), 2, AK);
551
Rong Xu60faea12017-03-16 21:15:48 +0000552 if (!IsRange) {
553 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000554#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
555#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000556 };
557 auto *ValueProfilingCallTy =
558 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
James Y Knight13680222019-02-01 02:28:03 +0000559 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
560 ValueProfilingCallTy, AL);
Rong Xu60faea12017-03-16 21:15:48 +0000561 } else {
562 Type *RangeParamTypes[] = {
563#define VALUE_RANGE_PROF 1
564#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
565#include "llvm/ProfileData/InstrProfData.inc"
566#undef VALUE_RANGE_PROF
567 };
568 auto *ValueRangeProfilingCallTy =
569 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
James Y Knight13680222019-02-01 02:28:03 +0000570 return M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
571 ValueRangeProfilingCallTy, AL);
Rong Xu60faea12017-03-16 21:15:48 +0000572 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000573}
574
575void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000576 GlobalVariable *Name = Ind->getName();
577 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
578 uint64_t Index = Ind->getIndex()->getZExtValue();
579 auto It = ProfileDataMap.find(Name);
580 if (It == ProfileDataMap.end()) {
581 PerFunctionProfileData PD;
582 PD.NumValueSites[ValueKind] = Index + 1;
583 ProfileDataMap[Name] = PD;
584 } else if (It->second.NumValueSites[ValueKind] <= Index)
585 It->second.NumValueSites[ValueKind] = Index + 1;
586}
587
588void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000589 GlobalVariable *Name = Ind->getName();
590 auto It = ProfileDataMap.find(Name);
591 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000592 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000593
594 GlobalVariable *DataVar = It->second.DataVar;
595 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
596 uint64_t Index = Ind->getIndex()->getZExtValue();
597 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
598 Index += It->second.NumValueSites[Kind];
599
600 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000601 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
602 llvm::InstrProfValueKind::IPVK_MemOPSize);
603 CallInst *Call = nullptr;
604 if (!IsRange) {
605 Value *Args[3] = {Ind->getTargetValue(),
606 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
607 Builder.getInt32(Index)};
608 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
609 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000610 Value *Args[6] = {
611 Ind->getTargetValue(),
612 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
613 Builder.getInt32(Index),
614 Builder.getInt64(MemOPSizeRangeStart),
615 Builder.getInt64(MemOPSizeRangeLast),
616 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000617 Call =
618 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
619 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000620 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000621 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000622 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000623 Ind->eraseFromParent();
624}
625
Justin Bogner61ba2e32014-12-08 18:02:35 +0000626void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
627 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
628
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000629 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000630 uint64_t Index = Inc->getIndex()->getZExtValue();
James Y Knight77160752019-02-01 20:44:47 +0000631 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters->getValueType(),
632 Counters, 0, Index);
Vedant Kumaree6c2332018-08-16 22:24:47 +0000633
634 if (Options.Atomic || AtomicCounterUpdateAll) {
635 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
636 AtomicOrdering::Monotonic);
637 } else {
James Y Knight14359ef2019-02-01 20:44:24 +0000638 Value *IncStep = Inc->getStep();
639 Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
Vedant Kumaree6c2332018-08-16 22:24:47 +0000640 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
641 auto *Store = Builder.CreateStore(Count, Addr);
642 if (isCounterPromotionEnabled())
643 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
644 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000645 Inc->eraseFromParent();
646}
647
Xinliang David Li81056072016-01-07 20:05:49 +0000648void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000649 ConstantArray *Names =
650 cast<ConstantArray>(CoverageNamesVar->getInitializer());
651 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
652 Constant *NC = Names->getOperand(I);
653 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000654 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
655 GlobalVariable *Name = cast<GlobalVariable>(V);
656
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000657 Name->setLinkage(GlobalValue::PrivateLinkage);
658 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000659 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000660 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000661 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000662}
663
Justin Bogner61ba2e32014-12-08 18:02:35 +0000664/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000665static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000666 StringRef NamePrefix = getInstrProfNameVarPrefix();
667 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000668 Function *F = Inc->getParent()->getParent();
669 Module *M = F->getParent();
670 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
671 !canRenameComdatFunc(*F))
672 return (Prefix + Name).str();
673 uint64_t FuncHash = Inc->getHash()->getZExtValue();
674 SmallVector<char, 24> HashPostfix;
675 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
676 return (Prefix + Name).str();
677 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000678}
679
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000680static inline bool shouldRecordFunctionAddr(Function *F) {
681 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000682 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000683 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000684 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000685 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000686
687 // A function marked 'alwaysinline' with available_externally linkage can't
688 // have its address taken. Doing so would create an undefined external ref to
689 // the function, which would fail to link.
690 if (HasAvailableExternallyLinkage &&
691 F->hasFnAttribute(Attribute::AlwaysInline))
692 return false;
693
Rong Xuaf5aeba2016-04-27 21:17:30 +0000694 // Prohibit function address recording if the function is both internal and
695 // COMDAT. This avoids the profile data variable referencing internal symbols
696 // in COMDAT.
697 if (F->hasLocalLinkage() && F->hasComdat())
698 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000699
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000700 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000701 // Inline virtual functions have linkeOnceODR linkage. When a key method
702 // exists, the vtable will only be emitted in the TU where the key method
703 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000704 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000705 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000706 // indirect call target info.
707 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000708}
709
Reid Klecknerf21c0222019-02-07 18:16:22 +0000710static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000711 // Don't do this for Darwin. compiler-rt uses linker magic.
Reid Klecknerf21c0222019-02-07 18:16:22 +0000712 if (TT.isOSDarwin())
Xinliang David Lib628dd32016-05-21 22:55:34 +0000713 return false;
Xinliang David Lib628dd32016-05-21 22:55:34 +0000714 // Use linker script magic to get data/cnts/name start/end.
Reid Klecknerf21c0222019-02-07 18:16:22 +0000715 if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
Reid Kleckner987d3312019-02-08 19:03:50 +0000716 TT.isOSFuchsia() || TT.isPS4CPU() || TT.isOSWindows())
Xinliang David Lib628dd32016-05-21 22:55:34 +0000717 return false;
718
719 return true;
720}
721
Justin Bogner61ba2e32014-12-08 18:02:35 +0000722GlobalVariable *
723InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000724 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000725 auto It = ProfileDataMap.find(NamePtr);
726 PerFunctionProfileData PD;
727 if (It != ProfileDataMap.end()) {
728 if (It->second.RegionCounters)
729 return It->second.RegionCounters;
730 PD = It->second;
731 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000732
Reid Kleckner987d3312019-02-08 19:03:50 +0000733 // Match the linkage and visibility of the name global, except on COFF, where
734 // the linkage must be local and consequentially the visibility must be
735 // default.
Diego Novillodf4837b2015-05-27 19:34:01 +0000736 Function *Fn = Inc->getParent()->getParent();
Reid Kleckner987d3312019-02-08 19:03:50 +0000737 GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
738 GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
739 if (TT.isOSBinFormatCOFF()) {
740 Linkage = GlobalValue::InternalLinkage;
741 Visibility = GlobalValue::DefaultVisibility;
742 }
743
744 // Move the name variable to the right section. Place them in a COMDAT group
745 // if the associated function is a COMDAT. This will make sure that only one
746 // copy of counters of the COMDAT function will be emitted after linking.
747 Comdat *Cmdt = nullptr;
748 GlobalValue::LinkageTypes CounterLinkage = Linkage;
749 if (needsComdatForCounter(*Fn, *M)) {
750 if (TT.isOSBinFormatCOFF()) {
751 // There are two cases that need a comdat on COFF:
752 // 1. Functions that already have comdats (standard case)
753 // 2. available_externally functions (dllimport and C99 inline)
754 // In the first case, put all the data in the original function comdat. In
755 // the second case, create a new comdat group using the counter as the
756 // leader. It's linkage must be external, so use linkonce_odr linkage in
757 // that case.
758 if (Comdat *C = Fn->getComdat()) {
759 Cmdt = C;
760 } else {
761 Cmdt = M->getOrInsertComdat(
762 getVarName(Inc, getInstrProfCountersVarPrefix()));
763 CounterLinkage = GlobalValue::LinkOnceODRLinkage;
764 }
765 } else {
766 // For other platforms that use comdats (ELF), make a new comdat group for
767 // all the profile data. It will be deduplicated within the current DSO.
768 Cmdt = M->getOrInsertComdat(getVarName(Inc, getInstrProfComdatPrefix()));
769 }
770 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000771
772 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
773 LLVMContext &Ctx = M->getContext();
774 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
775
776 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000777 auto *CounterPtr =
Reid Kleckner987d3312019-02-08 19:03:50 +0000778 new GlobalVariable(*M, CounterTy, false, Linkage,
Xinliang David Li83bc4222015-10-22 20:32:12 +0000779 Constant::getNullValue(CounterTy),
780 getVarName(Inc, getInstrProfCountersVarPrefix()));
Reid Kleckner987d3312019-02-08 19:03:50 +0000781 CounterPtr->setVisibility(Visibility);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000782 CounterPtr->setSection(
783 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000784 CounterPtr->setAlignment(8);
Reid Kleckner987d3312019-02-08 19:03:50 +0000785 CounterPtr->setComdat(Cmdt);
786 CounterPtr->setLinkage(CounterLinkage);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000787
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000788 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000789 // Allocate statically the array of pointers to value profile nodes for
790 // the current function.
791 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
Reid Klecknerf21c0222019-02-07 18:16:22 +0000792 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(TT)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000793 uint64_t NS = 0;
794 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
795 NS += PD.NumValueSites[Kind];
796 if (NS) {
797 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
798
799 auto *ValuesVar =
Reid Kleckner987d3312019-02-08 19:03:50 +0000800 new GlobalVariable(*M, ValuesTy, false, Linkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000801 Constant::getNullValue(ValuesTy),
802 getVarName(Inc, getInstrProfValuesVarPrefix()));
Reid Kleckner987d3312019-02-08 19:03:50 +0000803 ValuesVar->setVisibility(Visibility);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000804 ValuesVar->setSection(
805 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000806 ValuesVar->setAlignment(8);
Reid Kleckner987d3312019-02-08 19:03:50 +0000807 ValuesVar->setComdat(Cmdt);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000808 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000809 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000810 }
811 }
812
813 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000814 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000815 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000816 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000817#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
818#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000819 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000820 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000821
Xinliang David Li69a00f02016-06-21 02:39:08 +0000822 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
823 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
824 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000825
Xinliang David Li69a00f02016-06-21 02:39:08 +0000826 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000827 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
828 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
829
Justin Bogner61ba2e32014-12-08 18:02:35 +0000830 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000831#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
832#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000833 };
Reid Kleckner987d3312019-02-08 19:03:50 +0000834 auto *Data = new GlobalVariable(*M, DataTy, false, Linkage,
Justin Bogner61ba2e32014-12-08 18:02:35 +0000835 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000836 getVarName(Inc, getInstrProfDataVarPrefix()));
Reid Kleckner987d3312019-02-08 19:03:50 +0000837 Data->setVisibility(Visibility);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000838 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000839 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Reid Kleckner987d3312019-02-08 19:03:50 +0000840 Data->setComdat(Cmdt);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000841
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000842 PD.RegionCounters = CounterPtr;
843 PD.DataVar = Data;
844 ProfileDataMap[NamePtr] = PD;
845
Justin Bogner61ba2e32014-12-08 18:02:35 +0000846 // Mark the data variable as used so that it isn't stripped out.
847 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000848 // Now that the linkage set by the FE has been passed to the data and counter
849 // variables, reset Name variable's linkage and visibility to private so that
850 // it can be removed later by the compiler.
851 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
852 // Collect the referenced names to be used by emitNameData.
853 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000854
Xinliang David Li192c7482015-11-05 00:47:26 +0000855 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000856}
857
Xinliang David Lib628dd32016-05-21 22:55:34 +0000858void InstrProfiling::emitVNodes() {
859 if (!ValueProfileStaticAlloc)
860 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000861
Xinliang David Lib628dd32016-05-21 22:55:34 +0000862 // For now only support this on platforms that do
863 // not require runtime registration to discover
864 // named section start/end.
Reid Klecknerf21c0222019-02-07 18:16:22 +0000865 if (needsRuntimeRegistrationOfSectionRange(TT))
Xinliang David Lib628dd32016-05-21 22:55:34 +0000866 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000867
Xinliang David Lib628dd32016-05-21 22:55:34 +0000868 size_t TotalNS = 0;
869 for (auto &PD : ProfileDataMap) {
870 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
871 TotalNS += PD.second.NumValueSites[Kind];
872 }
873
874 if (!TotalNS)
875 return;
876
877 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000878// Heuristic for small programs with very few total value sites.
879// The default value of vp-counters-per-site is chosen based on
880// the observation that large apps usually have a low percentage
881// of value sites that actually have any profile data, and thus
882// the average number of counters per site is low. For small
883// apps with very few sites, this may not be true. Bump up the
884// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000885#define INSTR_PROF_MIN_VAL_COUNTS 10
886 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000887 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000888
889 auto &Ctx = M->getContext();
890 Type *VNodeTypes[] = {
891#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
892#include "llvm/ProfileData/InstrProfData.inc"
893 };
894 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
895
896 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
897 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000898 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000899 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000900 VNodesVar->setSection(
901 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000902 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000903}
904
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000905void InstrProfiling::emitNameData() {
906 std::string UncompressedData;
907
908 if (ReferencedNames.empty())
909 return;
910
911 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000912 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000913 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000914 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000915 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000916
917 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000918 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000919 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000920 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
921 GlobalValue::PrivateLinkage, NamesVal,
922 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000923 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000924 NamesVar->setSection(
925 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Reid Kleckner987d3312019-02-08 19:03:50 +0000926 // On COFF, it's important to reduce the alignment down to 1 to prevent the
927 // linker from inserting padding before the start of the names section or
928 // between names entries.
929 NamesVar->setAlignment(1);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000930 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000931
932 for (auto *NamePtr : ReferencedNames)
933 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000934}
935
Justin Bogner61ba2e32014-12-08 18:02:35 +0000936void InstrProfiling::emitRegistration() {
Reid Klecknerf21c0222019-02-07 18:16:22 +0000937 if (!needsRuntimeRegistrationOfSectionRange(TT))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000938 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000939
Justin Bogner61ba2e32014-12-08 18:02:35 +0000940 // Construct the function.
941 auto *VoidTy = Type::getVoidTy(M->getContext());
942 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000943 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000944 auto *RegisterFTy = FunctionType::get(VoidTy, false);
945 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000946 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000947 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000948 if (Options.NoRedZone)
949 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000950
Diego Novillob3029d22015-06-04 11:45:32 +0000951 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000952 auto *RuntimeRegisterF =
953 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000954 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000955
956 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
957 for (Value *Data : UsedVars)
Reid Klecknerba827882018-07-27 22:21:35 +0000958 if (Data != NamesVar && !isa<Function>(Data))
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000959 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
960
961 if (NamesVar) {
962 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
963 auto *NamesRegisterTy =
964 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
965 auto *NamesRegisterF =
966 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
967 getInstrProfNamesRegFuncName(), M);
968 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
969 IRB.getInt64(NamesSize)});
970 }
971
Justin Bogner61ba2e32014-12-08 18:02:35 +0000972 IRB.CreateRetVoid();
973}
974
Vedant Kumar9a041a72018-02-28 19:00:08 +0000975bool InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000976 // We expect the linker to be invoked with -u<hook_var> flag for linux,
977 // for which case there is no need to emit the user function.
Reid Klecknerf21c0222019-02-07 18:16:22 +0000978 if (TT.isOSLinux())
Vedant Kumar9a041a72018-02-28 19:00:08 +0000979 return false;
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000980
Justin Bogner61ba2e32014-12-08 18:02:35 +0000981 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000982 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
Vedant Kumar9a041a72018-02-28 19:00:08 +0000983 return false;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000984
985 // Declare an external variable that will pull in the runtime initialization.
986 auto *Int32Ty = Type::getInt32Ty(M->getContext());
987 auto *Var =
988 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000989 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000990
991 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000992 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
993 GlobalValue::LinkOnceODRLinkage,
994 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000995 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000996 if (Options.NoRedZone)
997 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000998 User->setVisibility(GlobalValue::HiddenVisibility);
Reid Klecknerf21c0222019-02-07 18:16:22 +0000999 if (TT.supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +00001000 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +00001001
1002 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
James Y Knight14359ef2019-02-01 20:44:24 +00001003 auto *Load = IRB.CreateLoad(Int32Ty, Var);
Justin Bogner61ba2e32014-12-08 18:02:35 +00001004 IRB.CreateRet(Load);
1005
1006 // Mark the user variable as used so that it isn't stripped out.
1007 UsedVars.push_back(User);
Vedant Kumar9a041a72018-02-28 19:00:08 +00001008 return true;
Justin Bogner61ba2e32014-12-08 18:02:35 +00001009}
1010
1011void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +00001012 if (!UsedVars.empty())
1013 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +00001014}
1015
1016void InstrProfiling::emitInitialization() {
Rong Xu6cdf3d82019-02-27 17:24:33 +00001017 // Create ProfileFileName variable. Don't don't this for the
1018 // context-sensitive instrumentation lowering: This lowering is after
1019 // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1020 // have already create the variable before LTO/ThinLTO linking.
1021 if (!IsCS)
1022 createProfileFileNameVar(*M, Options.InstrProfileOutput);
James Y Knight7976eb52019-02-01 20:43:25 +00001023 Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +00001024 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +00001025 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +00001026
1027 // Create the initialization function.
1028 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +00001029 auto *F = Function::Create(FunctionType::get(VoidTy, false),
1030 GlobalValue::InternalLinkage,
1031 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001032 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +00001033 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +00001034 if (Options.NoRedZone)
1035 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +00001036
1037 // Add the basic block and the necessary calls.
1038 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
James Y Knight7976eb52019-02-01 20:43:25 +00001039 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +00001040 IRB.CreateRetVoid();
1041
1042 appendToGlobalCtors(*M, F, 0);
1043}