blob: dc032ac0a5bd8822d0b0ff5f6c9f7049de3c041f [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"
Xinliang David Lib67530e2017-06-25 00:26:43 +000021#include "llvm/Analysis/LoopInfo.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000023#include "llvm/IR/Attributes.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DerivedTypes.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000028#include "llvm/IR/Dominators.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000032#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000033#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000035#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000037#include "llvm/IR/Type.h"
38#include "llvm/Pass.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000039#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000040#include "llvm/Support/Casting.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/Error.h"
43#include "llvm/Support/ErrorHandling.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000045#include "llvm/Transforms/Utils/ModuleUtils.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000046#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000047#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000052
53using namespace llvm;
54
55#define DEBUG_TYPE "instrprof"
56
Rong Xu48596b62017-04-04 16:42:20 +000057// The start and end values of precise value profile range for memory
58// intrinsic sizes
59cl::opt<std::string> MemOPSizeRange(
60 "memop-size-range",
61 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
62 "precisely, in a format of <start_val>:<end_val>"),
63 cl::init(""));
64
65// The value that considered to be large value in memory intrinsic.
66cl::opt<unsigned> MemOPSizeLarge(
67 "memop-size-large",
68 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
69 "Value of 0 disables the large value profiling."),
70 cl::init(8192));
71
Justin Bogner61ba2e32014-12-08 18:02:35 +000072namespace {
73
Xinliang David Lia82d6c02016-02-08 18:13:49 +000074cl::opt<bool> DoNameCompression("enable-name-compression",
75 cl::desc("Enable name string compression"),
76 cl::init(true));
77
Rong Xu20f5df12017-01-11 20:19:41 +000078cl::opt<bool> DoHashBasedCounterSplit(
79 "hash-based-counter-split",
80 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
81 cl::init(true));
82
Xinliang David Lib628dd32016-05-21 22:55:34 +000083cl::opt<bool> ValueProfileStaticAlloc(
84 "vp-static-alloc",
85 cl::desc("Do static counter allocation for value profiler"),
86 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000087
Xinliang David Lib628dd32016-05-21 22:55:34 +000088cl::opt<double> NumCountersPerValueSite(
89 "vp-counters-per-site",
90 cl::desc("The average number of profile counters allocated "
91 "per value profiling site."),
92 // This is set to a very small value because in real programs, only
93 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
94 // For those sites with non-zero profile, the average number of targets
95 // is usually smaller than 2.
96 cl::init(1.0));
97
Vedant Kumaree6c2332018-08-16 22:24:47 +000098cl::opt<bool> AtomicCounterUpdateAll(
99 "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
100 cl::desc("Make all profile counter updates atomic (for testing only)"),
101 cl::init(false));
102
Xinliang David Lib67530e2017-06-25 00:26:43 +0000103cl::opt<bool> AtomicCounterUpdatePromoted(
104 "atomic-counter-update-promoted", cl::ZeroOrMore,
105 cl::desc("Do counter update using atomic fetch add "
106 " for promoted counters only"),
107 cl::init(false));
108
109// If the option is not specified, the default behavior about whether
110// counter promotion is done depends on how instrumentaiton lowering
111// pipeline is setup, i.e., the default value of true of this option
112// does not mean the promotion will be done by default. Explicitly
113// setting this option can override the default behavior.
114cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
115 cl::desc("Do counter register promotion"),
116 cl::init(false));
117cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
Xinliang David Lif564c692017-07-12 23:27:44 +0000118 cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
Xinliang David Lib67530e2017-06-25 00:26:43 +0000119 cl::desc("Max number counter promotions per loop to avoid"
120 " increasing register pressure too much"));
121
122// A debug option
123cl::opt<int>
124 MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
125 cl::desc("Max number of allowed counter promotions"));
126
Xinliang David Lif564c692017-07-12 23:27:44 +0000127cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
128 cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
129 cl::desc("The max number of exiting blocks of a loop to allow "
130 " speculative counter promotion"));
131
132cl::opt<bool> SpeculativeCounterPromotionToLoop(
133 cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
134 cl::desc("When the option is false, if the target block is in a loop, "
135 "the promotion will be disallowed unless the promoted counter "
136 " update can be further/iteratively promoted into an acyclic "
137 " region."));
138
139cl::opt<bool> IterativeCounterPromotion(
140 cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
141 cl::desc("Allow counter promotion across the whole loop nest."));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000142
Xinliang David Lie6b89292016-04-18 17:47:38 +0000143class InstrProfilingLegacyPass : public ModulePass {
144 InstrProfiling InstrProf;
145
Justin Bogner61ba2e32014-12-08 18:02:35 +0000146public:
147 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000148
149 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +0000150 InstrProfilingLegacyPass(const InstrProfOptions &Options)
151 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000152
Mehdi Amini117296c2016-10-01 02:56:57 +0000153 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000154 return "Frontend instrumentation-based coverage lowering";
155 }
156
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000157 bool runOnModule(Module &M) override {
158 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
159 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000160
161 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000163 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000164 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000165};
166
Xinliang David Lif564c692017-07-12 23:27:44 +0000167///
Xinliang David Lib67530e2017-06-25 00:26:43 +0000168/// A helper class to promote one counter RMW operation in the loop
169/// into register update.
170///
171/// RWM update for the counter will be sinked out of the loop after
172/// the transformation.
173///
174class PGOCounterPromoterHelper : public LoadAndStorePromoter {
175public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000176 PGOCounterPromoterHelper(
177 Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
178 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
179 ArrayRef<Instruction *> InsertPts,
180 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
181 LoopInfo &LI)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000182 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
Xinliang David Lif564c692017-07-12 23:27:44 +0000183 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000184 assert(isa<LoadInst>(L));
185 assert(isa<StoreInst>(S));
186 SSA.AddAvailableValue(PH, Init);
187 }
Xinliang David Lif564c692017-07-12 23:27:44 +0000188
Xinliang David Lib67530e2017-06-25 00:26:43 +0000189 void doExtraRewritesBeforeFinalDeletion() const override {
190 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
191 BasicBlock *ExitBlock = ExitBlocks[i];
192 Instruction *InsertPos = InsertPts[i];
193 // Get LiveIn value into the ExitBlock. If there are multiple
194 // predecessors, the value is defined by a PHI node in this
195 // block.
196 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
197 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
198 IRBuilder<> Builder(InsertPos);
199 if (AtomicCounterUpdatePromoted)
Xinliang David Lif564c692017-07-12 23:27:44 +0000200 // automic update currently can only be promoted across the current
201 // loop, not the whole loop nest.
Xinliang David Lib67530e2017-06-25 00:26:43 +0000202 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
203 AtomicOrdering::SequentiallyConsistent);
204 else {
205 LoadInst *OldVal = Builder.CreateLoad(Addr, "pgocount.promoted");
206 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
Xinliang David Lif564c692017-07-12 23:27:44 +0000207 auto *NewStore = Builder.CreateStore(NewVal, Addr);
208
209 // Now update the parent loop's candidate list:
210 if (IterativeCounterPromotion) {
211 auto *TargetLoop = LI.getLoopFor(ExitBlock);
212 if (TargetLoop)
213 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
214 }
Xinliang David Lib67530e2017-06-25 00:26:43 +0000215 }
216 }
217 }
218
219private:
220 Instruction *Store;
221 ArrayRef<BasicBlock *> ExitBlocks;
222 ArrayRef<Instruction *> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000223 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
224 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000225};
226
227/// A helper class to do register promotion for all profile counter
228/// updates in a loop.
229///
230class PGOCounterPromoter {
231public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000232 PGOCounterPromoter(
233 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
234 Loop &CurLoop, LoopInfo &LI)
235 : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
236 LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000237
238 SmallVector<BasicBlock *, 8> LoopExitBlocks;
239 SmallPtrSet<BasicBlock *, 8> BlockSet;
Xinliang David Lif564c692017-07-12 23:27:44 +0000240 L.getExitBlocks(LoopExitBlocks);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000241
242 for (BasicBlock *ExitBlock : LoopExitBlocks) {
243 if (BlockSet.insert(ExitBlock).second) {
244 ExitBlocks.push_back(ExitBlock);
245 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
246 }
247 }
248 }
249
250 bool run(int64_t *NumPromoted) {
Xinliang David Lic23d2c62017-11-30 19:16:25 +0000251 // Skip 'infinite' loops:
252 if (ExitBlocks.size() == 0)
253 return false;
Xinliang David Lif564c692017-07-12 23:27:44 +0000254 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
255 if (MaxProm == 0)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000256 return false;
257
258 unsigned Promoted = 0;
Xinliang David Lif564c692017-07-12 23:27:44 +0000259 for (auto &Cand : LoopToCandidates[&L]) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000260
261 SmallVector<PHINode *, 4> NewPHIs;
262 SSAUpdater SSA(&NewPHIs);
263 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
Xinliang David Lif564c692017-07-12 23:27:44 +0000264
Xinliang David Lib67530e2017-06-25 00:26:43 +0000265 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
Xinliang David Lif564c692017-07-12 23:27:44 +0000266 L.getLoopPreheader(), ExitBlocks,
267 InsertPts, LoopToCandidates, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000268 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
269 Promoted++;
Xinliang David Lif564c692017-07-12 23:27:44 +0000270 if (Promoted >= MaxProm)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000271 break;
Xinliang David Lif564c692017-07-12 23:27:44 +0000272
Xinliang David Lib67530e2017-06-25 00:26:43 +0000273 (*NumPromoted)++;
274 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
275 break;
276 }
277
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000278 LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
279 << L.getLoopDepth() << ")\n");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000280 return Promoted != 0;
281 }
282
283private:
Xinliang David Lif564c692017-07-12 23:27:44 +0000284 bool allowSpeculativeCounterPromotion(Loop *LP) {
285 SmallVector<BasicBlock *, 8> ExitingBlocks;
286 L.getExitingBlocks(ExitingBlocks);
287 // Not considierered speculative.
288 if (ExitingBlocks.size() == 1)
289 return true;
290 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
291 return false;
292 return true;
293 }
294
295 // Returns the max number of Counter Promotions for LP.
296 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
297 // We can't insert into a catchswitch.
298 SmallVector<BasicBlock *, 8> LoopExitBlocks;
299 LP->getExitBlocks(LoopExitBlocks);
300 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
301 return isa<CatchSwitchInst>(Exit->getTerminator());
302 }))
303 return 0;
304
305 if (!LP->hasDedicatedExits())
306 return 0;
307
308 BasicBlock *PH = LP->getLoopPreheader();
309 if (!PH)
310 return 0;
311
312 SmallVector<BasicBlock *, 8> ExitingBlocks;
313 LP->getExitingBlocks(ExitingBlocks);
314 // Not considierered speculative.
315 if (ExitingBlocks.size() == 1)
316 return MaxNumOfPromotionsPerLoop;
317
318 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
319 return 0;
320
321 // Whether the target block is in a loop does not matter:
322 if (SpeculativeCounterPromotionToLoop)
323 return MaxNumOfPromotionsPerLoop;
324
325 // Now check the target block:
326 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
327 for (auto *TargetBlock : LoopExitBlocks) {
328 auto *TargetLoop = LI.getLoopFor(TargetBlock);
329 if (!TargetLoop)
330 continue;
331 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
332 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
333 MaxProm =
334 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
335 PendingCandsInTarget);
336 }
337 return MaxProm;
338 }
339
340 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000341 SmallVector<BasicBlock *, 8> ExitBlocks;
342 SmallVector<Instruction *, 8> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000343 Loop &L;
344 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000345};
346
Eugene Zelenko34c23272017-01-18 00:57:48 +0000347} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000348
Sean Silvafd03ac62016-08-09 00:28:38 +0000349PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000350 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
351 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000352 return PreservedAnalyses::all();
353
354 return PreservedAnalyses::none();
355}
356
357char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000358INITIALIZE_PASS_BEGIN(
359 InstrProfilingLegacyPass, "instrprof",
360 "Frontend instrumentation-based coverage lowering.", false, false)
361INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
362INITIALIZE_PASS_END(
363 InstrProfilingLegacyPass, "instrprof",
364 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000365
Xinliang David Li69a00f02016-06-21 02:39:08 +0000366ModulePass *
367llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000368 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000369}
370
Xinliang David Li4ca17332016-09-18 18:34:07 +0000371static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
372 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
373 if (Inc)
374 return Inc;
375 return dyn_cast<InstrProfIncrementInst>(Instr);
376}
377
Xinliang David Lib67530e2017-06-25 00:26:43 +0000378bool InstrProfiling::lowerIntrinsics(Function *F) {
379 bool MadeChange = false;
380 PromotionCandidates.clear();
381 for (BasicBlock &BB : *F) {
382 for (auto I = BB.begin(), E = BB.end(); I != E;) {
383 auto Instr = I++;
384 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
385 if (Inc) {
386 lowerIncrement(Inc);
387 MadeChange = true;
388 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
389 lowerValueProfileInst(Ind);
390 MadeChange = true;
391 }
392 }
393 }
394
395 if (!MadeChange)
396 return false;
397
398 promoteCounterLoadStores(F);
399 return true;
400}
401
402bool InstrProfiling::isCounterPromotionEnabled() const {
403 if (DoCounterPromotion.getNumOccurrences() > 0)
404 return DoCounterPromotion;
405
406 return Options.DoCounterPromotion;
407}
408
409void InstrProfiling::promoteCounterLoadStores(Function *F) {
410 if (!isCounterPromotionEnabled())
411 return;
412
413 DominatorTree DT(*F);
414 LoopInfo LI(DT);
415 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
416
417 for (const auto &LoadStore : PromotionCandidates) {
418 auto *CounterLoad = LoadStore.first;
419 auto *CounterStore = LoadStore.second;
420 BasicBlock *BB = CounterLoad->getParent();
421 Loop *ParentLoop = LI.getLoopFor(BB);
422 if (!ParentLoop)
423 continue;
424 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
425 }
426
427 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
428
Xinliang David Lif564c692017-07-12 23:27:44 +0000429 // Do a post-order traversal of the loops so that counter updates can be
430 // iteratively hoisted outside the loop nest.
431 for (auto *Loop : llvm::reverse(Loops)) {
432 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000433 Promoter.run(&TotalCountersPromoted);
434 }
435}
436
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000437/// Check if the module contains uses of any profiling intrinsics.
438static bool containsProfilingIntrinsics(Module &M) {
439 if (auto *F = M.getFunction(
440 Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000441 if (!F->use_empty())
442 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000443 if (auto *F = M.getFunction(
444 Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000445 if (!F->use_empty())
446 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000447 if (auto *F = M.getFunction(
448 Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000449 if (!F->use_empty())
450 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000451 return false;
452}
453
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000454bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000455 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000456 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000457 NamesVar = nullptr;
458 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000459 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000460 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000461 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
462 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000463 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000464
Vedant Kumar9a041a72018-02-28 19:00:08 +0000465 // Emit the runtime hook even if no counters are present.
466 bool MadeChange = emitRuntimeHook();
467
468 // Improve compile time by avoiding linear scans when there is no work.
469 GlobalVariable *CoverageNamesVar =
470 M.getNamedGlobal(getCoverageUnusedNamesVarName());
471 if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
472 return MadeChange;
473
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000474 // We did not know how many value sites there would be inside
475 // the instrumented function. This is counting the number of instrumented
476 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000477 for (Function &F : M) {
478 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000479 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000480 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
481 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000482 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000483 else if (FirstProfIncInst == nullptr)
484 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
485
486 // Value profiling intrinsic lowering requires per-function profile data
487 // variable to be created first.
488 if (FirstProfIncInst != nullptr)
489 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
490 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000491
492 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000493 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000494
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000495 if (CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000496 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000497 MadeChange = true;
498 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000499
Justin Bogner61ba2e32014-12-08 18:02:35 +0000500 if (!MadeChange)
501 return false;
502
Xinliang David Lib628dd32016-05-21 22:55:34 +0000503 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000504 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000505 emitRegistration();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000506 emitUses();
507 emitInitialization();
508 return true;
509}
510
James Y Knight13680222019-02-01 02:28:03 +0000511static FunctionCallee
512getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI,
513 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000514 LLVMContext &Ctx = M.getContext();
515 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000516
James Y Knight13680222019-02-01 02:28:03 +0000517 AttributeList AL;
518 if (auto AK = TLI.getExtAttrForI32Param(false))
519 AL = AL.addParamAttribute(M.getContext(), 2, AK);
520
Rong Xu60faea12017-03-16 21:15:48 +0000521 if (!IsRange) {
522 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000523#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
524#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000525 };
526 auto *ValueProfilingCallTy =
527 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
James Y Knight13680222019-02-01 02:28:03 +0000528 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
529 ValueProfilingCallTy, AL);
Rong Xu60faea12017-03-16 21:15:48 +0000530 } else {
531 Type *RangeParamTypes[] = {
532#define VALUE_RANGE_PROF 1
533#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
534#include "llvm/ProfileData/InstrProfData.inc"
535#undef VALUE_RANGE_PROF
536 };
537 auto *ValueRangeProfilingCallTy =
538 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
James Y Knight13680222019-02-01 02:28:03 +0000539 return M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
540 ValueRangeProfilingCallTy, AL);
Rong Xu60faea12017-03-16 21:15:48 +0000541 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000542}
543
544void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000545 GlobalVariable *Name = Ind->getName();
546 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
547 uint64_t Index = Ind->getIndex()->getZExtValue();
548 auto It = ProfileDataMap.find(Name);
549 if (It == ProfileDataMap.end()) {
550 PerFunctionProfileData PD;
551 PD.NumValueSites[ValueKind] = Index + 1;
552 ProfileDataMap[Name] = PD;
553 } else if (It->second.NumValueSites[ValueKind] <= Index)
554 It->second.NumValueSites[ValueKind] = Index + 1;
555}
556
557void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000558 GlobalVariable *Name = Ind->getName();
559 auto It = ProfileDataMap.find(Name);
560 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000561 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000562
563 GlobalVariable *DataVar = It->second.DataVar;
564 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
565 uint64_t Index = Ind->getIndex()->getZExtValue();
566 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
567 Index += It->second.NumValueSites[Kind];
568
569 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000570 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
571 llvm::InstrProfValueKind::IPVK_MemOPSize);
572 CallInst *Call = nullptr;
573 if (!IsRange) {
574 Value *Args[3] = {Ind->getTargetValue(),
575 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
576 Builder.getInt32(Index)};
577 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
578 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000579 Value *Args[6] = {
580 Ind->getTargetValue(),
581 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
582 Builder.getInt32(Index),
583 Builder.getInt64(MemOPSizeRangeStart),
584 Builder.getInt64(MemOPSizeRangeLast),
585 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000586 Call =
587 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
588 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000589 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000590 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000591 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000592 Ind->eraseFromParent();
593}
594
Justin Bogner61ba2e32014-12-08 18:02:35 +0000595void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
596 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
597
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000598 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000599 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000600 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Vedant Kumaree6c2332018-08-16 22:24:47 +0000601
602 if (Options.Atomic || AtomicCounterUpdateAll) {
603 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
604 AtomicOrdering::Monotonic);
605 } else {
606 Value *Load = Builder.CreateLoad(Addr, "pgocount");
607 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
608 auto *Store = Builder.CreateStore(Count, Addr);
609 if (isCounterPromotionEnabled())
610 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
611 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000612 Inc->eraseFromParent();
613}
614
Xinliang David Li81056072016-01-07 20:05:49 +0000615void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000616 ConstantArray *Names =
617 cast<ConstantArray>(CoverageNamesVar->getInitializer());
618 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
619 Constant *NC = Names->getOperand(I);
620 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000621 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
622 GlobalVariable *Name = cast<GlobalVariable>(V);
623
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000624 Name->setLinkage(GlobalValue::PrivateLinkage);
625 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000626 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000627 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000628 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000629}
630
Justin Bogner61ba2e32014-12-08 18:02:35 +0000631/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000632static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000633 StringRef NamePrefix = getInstrProfNameVarPrefix();
634 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000635 Function *F = Inc->getParent()->getParent();
636 Module *M = F->getParent();
637 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
638 !canRenameComdatFunc(*F))
639 return (Prefix + Name).str();
640 uint64_t FuncHash = Inc->getHash()->getZExtValue();
641 SmallVector<char, 24> HashPostfix;
642 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
643 return (Prefix + Name).str();
644 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000645}
646
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000647static inline bool shouldRecordFunctionAddr(Function *F) {
648 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000649 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000650 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000651 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000652 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000653
654 // A function marked 'alwaysinline' with available_externally linkage can't
655 // have its address taken. Doing so would create an undefined external ref to
656 // the function, which would fail to link.
657 if (HasAvailableExternallyLinkage &&
658 F->hasFnAttribute(Attribute::AlwaysInline))
659 return false;
660
Rong Xuaf5aeba2016-04-27 21:17:30 +0000661 // Prohibit function address recording if the function is both internal and
662 // COMDAT. This avoids the profile data variable referencing internal symbols
663 // in COMDAT.
664 if (F->hasLocalLinkage() && F->hasComdat())
665 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000666
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000667 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000668 // Inline virtual functions have linkeOnceODR linkage. When a key method
669 // exists, the vtable will only be emitted in the TU where the key method
670 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000671 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000672 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000673 // indirect call target info.
674 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000675}
676
Xinliang David Li985ff202016-02-27 23:11:30 +0000677static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000678 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000679 if (!needsComdatForCounter(F, M))
680 return nullptr;
681
Xinliang David Liab361ef2015-12-21 21:52:27 +0000682 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000683 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000684 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000685 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000686 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000687 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000688 : getInstrProfComdatPrefix());
689 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
690}
691
Xinliang David Lib628dd32016-05-21 22:55:34 +0000692static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
693 // Don't do this for Darwin. compiler-rt uses linker magic.
694 if (Triple(M.getTargetTriple()).isOSDarwin())
695 return false;
696
697 // Use linker script magic to get data/cnts/name start/end.
698 if (Triple(M.getTargetTriple()).isOSLinux() ||
699 Triple(M.getTargetTriple()).isOSFreeBSD() ||
Kamil Rytarowski21e270a2018-12-15 16:51:35 +0000700 Triple(M.getTargetTriple()).isOSNetBSD() ||
Petr Hosek47e5fcb2018-07-25 03:01:35 +0000701 Triple(M.getTargetTriple()).isOSFuchsia() ||
Xinliang David Lib628dd32016-05-21 22:55:34 +0000702 Triple(M.getTargetTriple()).isPS4CPU())
703 return false;
704
705 return true;
706}
707
Justin Bogner61ba2e32014-12-08 18:02:35 +0000708GlobalVariable *
709InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000710 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000711 auto It = ProfileDataMap.find(NamePtr);
712 PerFunctionProfileData PD;
713 if (It != ProfileDataMap.end()) {
714 if (It->second.RegionCounters)
715 return It->second.RegionCounters;
716 PD = It->second;
717 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000718
Wei Mi3cc92042015-09-23 22:40:45 +0000719 // Move the name variable to the right section. Place them in a COMDAT group
720 // if the associated function is a COMDAT. This will make sure that
721 // only one copy of counters of the COMDAT function will be emitted after
722 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000723 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000724 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000725 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000726
727 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
728 LLVMContext &Ctx = M->getContext();
729 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
730
731 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000732 auto *CounterPtr =
733 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000734 Constant::getNullValue(CounterTy),
735 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000736 CounterPtr->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000737 CounterPtr->setSection(
738 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000739 CounterPtr->setAlignment(8);
740 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000741
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000742 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000743 // Allocate statically the array of pointers to value profile nodes for
744 // the current function.
745 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
746 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000747 uint64_t NS = 0;
748 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
749 NS += PD.NumValueSites[Kind];
750 if (NS) {
751 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
752
753 auto *ValuesVar =
754 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
755 Constant::getNullValue(ValuesTy),
756 getVarName(Inc, getInstrProfValuesVarPrefix()));
757 ValuesVar->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000758 ValuesVar->setSection(
759 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000760 ValuesVar->setAlignment(8);
761 ValuesVar->setComdat(ProfileVarsComdat);
762 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000763 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000764 }
765 }
766
767 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000768 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000769 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000770 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000771#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
772#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000773 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000774 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000775
Xinliang David Li69a00f02016-06-21 02:39:08 +0000776 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
777 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
778 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000779
Xinliang David Li69a00f02016-06-21 02:39:08 +0000780 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000781 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
782 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
783
Justin Bogner61ba2e32014-12-08 18:02:35 +0000784 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000785#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
786#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000787 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000788 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000789 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000790 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000791 Data->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000792 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000793 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000794 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000795
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000796 PD.RegionCounters = CounterPtr;
797 PD.DataVar = Data;
798 ProfileDataMap[NamePtr] = PD;
799
Justin Bogner61ba2e32014-12-08 18:02:35 +0000800 // Mark the data variable as used so that it isn't stripped out.
801 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000802 // Now that the linkage set by the FE has been passed to the data and counter
803 // variables, reset Name variable's linkage and visibility to private so that
804 // it can be removed later by the compiler.
805 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
806 // Collect the referenced names to be used by emitNameData.
807 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000808
Xinliang David Li192c7482015-11-05 00:47:26 +0000809 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000810}
811
Xinliang David Lib628dd32016-05-21 22:55:34 +0000812void InstrProfiling::emitVNodes() {
813 if (!ValueProfileStaticAlloc)
814 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000815
Xinliang David Lib628dd32016-05-21 22:55:34 +0000816 // For now only support this on platforms that do
817 // not require runtime registration to discover
818 // named section start/end.
819 if (needsRuntimeRegistrationOfSectionRange(*M))
820 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000821
Xinliang David Lib628dd32016-05-21 22:55:34 +0000822 size_t TotalNS = 0;
823 for (auto &PD : ProfileDataMap) {
824 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
825 TotalNS += PD.second.NumValueSites[Kind];
826 }
827
828 if (!TotalNS)
829 return;
830
831 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000832// Heuristic for small programs with very few total value sites.
833// The default value of vp-counters-per-site is chosen based on
834// the observation that large apps usually have a low percentage
835// of value sites that actually have any profile data, and thus
836// the average number of counters per site is low. For small
837// apps with very few sites, this may not be true. Bump up the
838// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000839#define INSTR_PROF_MIN_VAL_COUNTS 10
840 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000841 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000842
843 auto &Ctx = M->getContext();
844 Type *VNodeTypes[] = {
845#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
846#include "llvm/ProfileData/InstrProfData.inc"
847 };
848 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
849
850 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
851 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000852 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000853 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000854 VNodesVar->setSection(
855 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000856 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000857}
858
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000859void InstrProfiling::emitNameData() {
860 std::string UncompressedData;
861
862 if (ReferencedNames.empty())
863 return;
864
865 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000866 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000867 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000868 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000869 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000870
871 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000872 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000873 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000874 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
875 GlobalValue::PrivateLinkage, NamesVal,
876 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000877 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000878 NamesVar->setSection(
879 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000880 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000881
882 for (auto *NamePtr : ReferencedNames)
883 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000884}
885
Justin Bogner61ba2e32014-12-08 18:02:35 +0000886void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000887 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000888 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000889
Justin Bogner61ba2e32014-12-08 18:02:35 +0000890 // Construct the function.
891 auto *VoidTy = Type::getVoidTy(M->getContext());
892 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000893 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000894 auto *RegisterFTy = FunctionType::get(VoidTy, false);
895 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000896 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000897 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000898 if (Options.NoRedZone)
899 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000900
Diego Novillob3029d22015-06-04 11:45:32 +0000901 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000902 auto *RuntimeRegisterF =
903 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000904 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000905
906 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
907 for (Value *Data : UsedVars)
Reid Klecknerba827882018-07-27 22:21:35 +0000908 if (Data != NamesVar && !isa<Function>(Data))
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000909 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
910
911 if (NamesVar) {
912 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
913 auto *NamesRegisterTy =
914 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
915 auto *NamesRegisterF =
916 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
917 getInstrProfNamesRegFuncName(), M);
918 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
919 IRB.getInt64(NamesSize)});
920 }
921
Justin Bogner61ba2e32014-12-08 18:02:35 +0000922 IRB.CreateRetVoid();
923}
924
Vedant Kumar9a041a72018-02-28 19:00:08 +0000925bool InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000926 // We expect the linker to be invoked with -u<hook_var> flag for linux,
927 // for which case there is no need to emit the user function.
928 if (Triple(M->getTargetTriple()).isOSLinux())
Vedant Kumar9a041a72018-02-28 19:00:08 +0000929 return false;
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000930
Justin Bogner61ba2e32014-12-08 18:02:35 +0000931 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000932 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
Vedant Kumar9a041a72018-02-28 19:00:08 +0000933 return false;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000934
935 // Declare an external variable that will pull in the runtime initialization.
936 auto *Int32Ty = Type::getInt32Ty(M->getContext());
937 auto *Var =
938 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000939 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000940
941 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000942 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
943 GlobalValue::LinkOnceODRLinkage,
944 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000945 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000946 if (Options.NoRedZone)
947 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000948 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000949 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000950 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000951
952 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
953 auto *Load = IRB.CreateLoad(Var);
954 IRB.CreateRet(Load);
955
956 // Mark the user variable as used so that it isn't stripped out.
957 UsedVars.push_back(User);
Vedant Kumar9a041a72018-02-28 19:00:08 +0000958 return true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000959}
960
961void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000962 if (!UsedVars.empty())
963 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000964}
965
966void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000967 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000968
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000969 if (!InstrProfileOutput.empty()) {
970 // Create variable for profile name.
971 Constant *ProfileNameConst =
972 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
973 GlobalVariable *ProfileNameVar = new GlobalVariable(
974 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
975 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000976 if (TT.supportsCOMDAT()) {
977 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
978 ProfileNameVar->setComdat(M->getOrInsertComdat(
979 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
980 }
981 }
982
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000983 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000984 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000985 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000986
987 // Create the initialization function.
988 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000989 auto *F = Function::Create(FunctionType::get(VoidTy, false),
990 GlobalValue::InternalLinkage,
991 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000992 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000993 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000994 if (Options.NoRedZone)
995 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000996
997 // Add the basic block and the necessary calls.
998 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000999 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +00001000 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +00001001 IRB.CreateRetVoid();
1002
1003 appendToGlobalCtors(*M, F, 0);
1004}