blob: 62d67112bb9c0a68a0df1e4ca1139ef11c73d76b [file] [log] [blame]
Justin Bogner61ba2e32014-12-08 18:02:35 +00001//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000010// This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
11// It also builds the data structures and initialization code needed for
12// updating execution counts and emitting the profile at runtime.
Justin Bogner61ba2e32014-12-08 18:02:35 +000013//
14//===----------------------------------------------------------------------===//
15
Xinliang David Li69a00f02016-06-21 02:39:08 +000016#include "llvm/Transforms/InstrProfiling.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000020#include "llvm/ADT/Triple.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000021#include "llvm/ADT/Twine.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000022#include "llvm/Analysis/LoopInfo.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000024#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000029#include "llvm/IR/Dominators.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalValue.h"
32#include "llvm/IR/GlobalVariable.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/IR/IRBuilder.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000038#include "llvm/IR/Type.h"
39#include "llvm/Pass.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000040#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000041#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Error.h"
44#include "llvm/Support/ErrorHandling.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000046#include "llvm/Transforms/Utils/ModuleUtils.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000048#include <algorithm>
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000053
54using namespace llvm;
55
56#define DEBUG_TYPE "instrprof"
57
Rong Xu48596b62017-04-04 16:42:20 +000058// The start and end values of precise value profile range for memory
59// intrinsic sizes
60cl::opt<std::string> MemOPSizeRange(
61 "memop-size-range",
62 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
63 "precisely, in a format of <start_val>:<end_val>"),
64 cl::init(""));
65
66// The value that considered to be large value in memory intrinsic.
67cl::opt<unsigned> MemOPSizeLarge(
68 "memop-size-large",
69 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
70 "Value of 0 disables the large value profiling."),
71 cl::init(8192));
72
Justin Bogner61ba2e32014-12-08 18:02:35 +000073namespace {
74
Xinliang David Lia82d6c02016-02-08 18:13:49 +000075cl::opt<bool> DoNameCompression("enable-name-compression",
76 cl::desc("Enable name string compression"),
77 cl::init(true));
78
Rong Xu20f5df12017-01-11 20:19:41 +000079cl::opt<bool> DoHashBasedCounterSplit(
80 "hash-based-counter-split",
81 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
82 cl::init(true));
83
Xinliang David Lib628dd32016-05-21 22:55:34 +000084cl::opt<bool> ValueProfileStaticAlloc(
85 "vp-static-alloc",
86 cl::desc("Do static counter allocation for value profiler"),
87 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000088
Xinliang David Lib628dd32016-05-21 22:55:34 +000089cl::opt<double> NumCountersPerValueSite(
90 "vp-counters-per-site",
91 cl::desc("The average number of profile counters allocated "
92 "per value profiling site."),
93 // This is set to a very small value because in real programs, only
94 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
95 // For those sites with non-zero profile, the average number of targets
96 // is usually smaller than 2.
97 cl::init(1.0));
98
Xinliang David Lib67530e2017-06-25 00:26:43 +000099cl::opt<bool> AtomicCounterUpdatePromoted(
100 "atomic-counter-update-promoted", cl::ZeroOrMore,
101 cl::desc("Do counter update using atomic fetch add "
102 " for promoted counters only"),
103 cl::init(false));
104
105// If the option is not specified, the default behavior about whether
106// counter promotion is done depends on how instrumentaiton lowering
107// pipeline is setup, i.e., the default value of true of this option
108// does not mean the promotion will be done by default. Explicitly
109// setting this option can override the default behavior.
110cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
111 cl::desc("Do counter register promotion"),
112 cl::init(false));
113cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
Xinliang David Lif564c692017-07-12 23:27:44 +0000114 cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
Xinliang David Lib67530e2017-06-25 00:26:43 +0000115 cl::desc("Max number counter promotions per loop to avoid"
116 " increasing register pressure too much"));
117
118// A debug option
119cl::opt<int>
120 MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
121 cl::desc("Max number of allowed counter promotions"));
122
Xinliang David Lif564c692017-07-12 23:27:44 +0000123cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
124 cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
125 cl::desc("The max number of exiting blocks of a loop to allow "
126 " speculative counter promotion"));
127
128cl::opt<bool> SpeculativeCounterPromotionToLoop(
129 cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
130 cl::desc("When the option is false, if the target block is in a loop, "
131 "the promotion will be disallowed unless the promoted counter "
132 " update can be further/iteratively promoted into an acyclic "
133 " region."));
134
135cl::opt<bool> IterativeCounterPromotion(
136 cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
137 cl::desc("Allow counter promotion across the whole loop nest."));
Xinliang David Lib67530e2017-06-25 00:26:43 +0000138
Xinliang David Lie6b89292016-04-18 17:47:38 +0000139class InstrProfilingLegacyPass : public ModulePass {
140 InstrProfiling InstrProf;
141
Justin Bogner61ba2e32014-12-08 18:02:35 +0000142public:
143 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000144
145 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +0000146 InstrProfilingLegacyPass(const InstrProfOptions &Options)
147 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000148
Mehdi Amini117296c2016-10-01 02:56:57 +0000149 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000150 return "Frontend instrumentation-based coverage lowering";
151 }
152
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000153 bool runOnModule(Module &M) override {
154 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
155 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000156
157 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000159 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000160 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000161};
162
Xinliang David Lif564c692017-07-12 23:27:44 +0000163///
Xinliang David Lib67530e2017-06-25 00:26:43 +0000164/// A helper class to promote one counter RMW operation in the loop
165/// into register update.
166///
167/// RWM update for the counter will be sinked out of the loop after
168/// the transformation.
169///
170class PGOCounterPromoterHelper : public LoadAndStorePromoter {
171public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000172 PGOCounterPromoterHelper(
173 Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
174 BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
175 ArrayRef<Instruction *> InsertPts,
176 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
177 LoopInfo &LI)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000178 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
Xinliang David Lif564c692017-07-12 23:27:44 +0000179 InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000180 assert(isa<LoadInst>(L));
181 assert(isa<StoreInst>(S));
182 SSA.AddAvailableValue(PH, Init);
183 }
Xinliang David Lif564c692017-07-12 23:27:44 +0000184
Xinliang David Lib67530e2017-06-25 00:26:43 +0000185 void doExtraRewritesBeforeFinalDeletion() const override {
186 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
187 BasicBlock *ExitBlock = ExitBlocks[i];
188 Instruction *InsertPos = InsertPts[i];
189 // Get LiveIn value into the ExitBlock. If there are multiple
190 // predecessors, the value is defined by a PHI node in this
191 // block.
192 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
193 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
194 IRBuilder<> Builder(InsertPos);
195 if (AtomicCounterUpdatePromoted)
Xinliang David Lif564c692017-07-12 23:27:44 +0000196 // automic update currently can only be promoted across the current
197 // loop, not the whole loop nest.
Xinliang David Lib67530e2017-06-25 00:26:43 +0000198 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
199 AtomicOrdering::SequentiallyConsistent);
200 else {
201 LoadInst *OldVal = Builder.CreateLoad(Addr, "pgocount.promoted");
202 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
Xinliang David Lif564c692017-07-12 23:27:44 +0000203 auto *NewStore = Builder.CreateStore(NewVal, Addr);
204
205 // Now update the parent loop's candidate list:
206 if (IterativeCounterPromotion) {
207 auto *TargetLoop = LI.getLoopFor(ExitBlock);
208 if (TargetLoop)
209 LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
210 }
Xinliang David Lib67530e2017-06-25 00:26:43 +0000211 }
212 }
213 }
214
215private:
216 Instruction *Store;
217 ArrayRef<BasicBlock *> ExitBlocks;
218 ArrayRef<Instruction *> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000219 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
220 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000221};
222
223/// A helper class to do register promotion for all profile counter
224/// updates in a loop.
225///
226class PGOCounterPromoter {
227public:
Xinliang David Lif564c692017-07-12 23:27:44 +0000228 PGOCounterPromoter(
229 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
230 Loop &CurLoop, LoopInfo &LI)
231 : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
232 LI(LI) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000233
234 SmallVector<BasicBlock *, 8> LoopExitBlocks;
235 SmallPtrSet<BasicBlock *, 8> BlockSet;
Xinliang David Lif564c692017-07-12 23:27:44 +0000236 L.getExitBlocks(LoopExitBlocks);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000237
238 for (BasicBlock *ExitBlock : LoopExitBlocks) {
239 if (BlockSet.insert(ExitBlock).second) {
240 ExitBlocks.push_back(ExitBlock);
241 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
242 }
243 }
244 }
245
246 bool run(int64_t *NumPromoted) {
Xinliang David Lic23d2c62017-11-30 19:16:25 +0000247 // Skip 'infinite' loops:
248 if (ExitBlocks.size() == 0)
249 return false;
Xinliang David Lif564c692017-07-12 23:27:44 +0000250 unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
251 if (MaxProm == 0)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000252 return false;
253
254 unsigned Promoted = 0;
Xinliang David Lif564c692017-07-12 23:27:44 +0000255 for (auto &Cand : LoopToCandidates[&L]) {
Xinliang David Lib67530e2017-06-25 00:26:43 +0000256
257 SmallVector<PHINode *, 4> NewPHIs;
258 SSAUpdater SSA(&NewPHIs);
259 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
Xinliang David Lif564c692017-07-12 23:27:44 +0000260
Xinliang David Lib67530e2017-06-25 00:26:43 +0000261 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
Xinliang David Lif564c692017-07-12 23:27:44 +0000262 L.getLoopPreheader(), ExitBlocks,
263 InsertPts, LoopToCandidates, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000264 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
265 Promoted++;
Xinliang David Lif564c692017-07-12 23:27:44 +0000266 if (Promoted >= MaxProm)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000267 break;
Xinliang David Lif564c692017-07-12 23:27:44 +0000268
Xinliang David Lib67530e2017-06-25 00:26:43 +0000269 (*NumPromoted)++;
270 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
271 break;
272 }
273
274 DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
Xinliang David Lif564c692017-07-12 23:27:44 +0000275 << L.getLoopDepth() << ")\n");
Xinliang David Lib67530e2017-06-25 00:26:43 +0000276 return Promoted != 0;
277 }
278
279private:
Xinliang David Lif564c692017-07-12 23:27:44 +0000280 bool allowSpeculativeCounterPromotion(Loop *LP) {
281 SmallVector<BasicBlock *, 8> ExitingBlocks;
282 L.getExitingBlocks(ExitingBlocks);
283 // Not considierered speculative.
284 if (ExitingBlocks.size() == 1)
285 return true;
286 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
287 return false;
288 return true;
289 }
290
291 // Returns the max number of Counter Promotions for LP.
292 unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
293 // We can't insert into a catchswitch.
294 SmallVector<BasicBlock *, 8> LoopExitBlocks;
295 LP->getExitBlocks(LoopExitBlocks);
296 if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
297 return isa<CatchSwitchInst>(Exit->getTerminator());
298 }))
299 return 0;
300
301 if (!LP->hasDedicatedExits())
302 return 0;
303
304 BasicBlock *PH = LP->getLoopPreheader();
305 if (!PH)
306 return 0;
307
308 SmallVector<BasicBlock *, 8> ExitingBlocks;
309 LP->getExitingBlocks(ExitingBlocks);
310 // Not considierered speculative.
311 if (ExitingBlocks.size() == 1)
312 return MaxNumOfPromotionsPerLoop;
313
314 if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
315 return 0;
316
317 // Whether the target block is in a loop does not matter:
318 if (SpeculativeCounterPromotionToLoop)
319 return MaxNumOfPromotionsPerLoop;
320
321 // Now check the target block:
322 unsigned MaxProm = MaxNumOfPromotionsPerLoop;
323 for (auto *TargetBlock : LoopExitBlocks) {
324 auto *TargetLoop = LI.getLoopFor(TargetBlock);
325 if (!TargetLoop)
326 continue;
327 unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
328 unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
329 MaxProm =
330 std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
331 PendingCandsInTarget);
332 }
333 return MaxProm;
334 }
335
336 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000337 SmallVector<BasicBlock *, 8> ExitBlocks;
338 SmallVector<Instruction *, 8> InsertPts;
Xinliang David Lif564c692017-07-12 23:27:44 +0000339 Loop &L;
340 LoopInfo &LI;
Xinliang David Lib67530e2017-06-25 00:26:43 +0000341};
342
Eugene Zelenko34c23272017-01-18 00:57:48 +0000343} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000344
Sean Silvafd03ac62016-08-09 00:28:38 +0000345PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000346 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
347 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000348 return PreservedAnalyses::all();
349
350 return PreservedAnalyses::none();
351}
352
353char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000354INITIALIZE_PASS_BEGIN(
355 InstrProfilingLegacyPass, "instrprof",
356 "Frontend instrumentation-based coverage lowering.", false, false)
357INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
358INITIALIZE_PASS_END(
359 InstrProfilingLegacyPass, "instrprof",
360 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000361
Xinliang David Li69a00f02016-06-21 02:39:08 +0000362ModulePass *
363llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000364 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000365}
366
Xinliang David Li4ca17332016-09-18 18:34:07 +0000367static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
368 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
369 if (Inc)
370 return Inc;
371 return dyn_cast<InstrProfIncrementInst>(Instr);
372}
373
Xinliang David Lib67530e2017-06-25 00:26:43 +0000374bool InstrProfiling::lowerIntrinsics(Function *F) {
375 bool MadeChange = false;
376 PromotionCandidates.clear();
377 for (BasicBlock &BB : *F) {
378 for (auto I = BB.begin(), E = BB.end(); I != E;) {
379 auto Instr = I++;
380 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
381 if (Inc) {
382 lowerIncrement(Inc);
383 MadeChange = true;
384 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
385 lowerValueProfileInst(Ind);
386 MadeChange = true;
387 }
388 }
389 }
390
391 if (!MadeChange)
392 return false;
393
394 promoteCounterLoadStores(F);
395 return true;
396}
397
398bool InstrProfiling::isCounterPromotionEnabled() const {
399 if (DoCounterPromotion.getNumOccurrences() > 0)
400 return DoCounterPromotion;
401
402 return Options.DoCounterPromotion;
403}
404
405void InstrProfiling::promoteCounterLoadStores(Function *F) {
406 if (!isCounterPromotionEnabled())
407 return;
408
409 DominatorTree DT(*F);
410 LoopInfo LI(DT);
411 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
412
413 for (const auto &LoadStore : PromotionCandidates) {
414 auto *CounterLoad = LoadStore.first;
415 auto *CounterStore = LoadStore.second;
416 BasicBlock *BB = CounterLoad->getParent();
417 Loop *ParentLoop = LI.getLoopFor(BB);
418 if (!ParentLoop)
419 continue;
420 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
421 }
422
423 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
424
Xinliang David Lif564c692017-07-12 23:27:44 +0000425 // Do a post-order traversal of the loops so that counter updates can be
426 // iteratively hoisted outside the loop nest.
427 for (auto *Loop : llvm::reverse(Loops)) {
428 PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000429 Promoter.run(&TotalCountersPromoted);
430 }
431}
432
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000433/// Check if the module contains uses of any profiling intrinsics.
434static bool containsProfilingIntrinsics(Module &M) {
435 if (auto *F = M.getFunction(
436 Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000437 if (!F->use_empty())
438 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000439 if (auto *F = M.getFunction(
440 Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
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_value_profile)))
Vedant Kumarcff94622018-01-27 00:01:04 +0000445 if (!F->use_empty())
446 return true;
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000447 return false;
448}
449
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000450bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000451 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000452 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000453 NamesVar = nullptr;
454 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000455 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000456 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000457 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
458 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000459 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000460
Vedant Kumar9a041a72018-02-28 19:00:08 +0000461 // Emit the runtime hook even if no counters are present.
462 bool MadeChange = emitRuntimeHook();
463
464 // Improve compile time by avoiding linear scans when there is no work.
465 GlobalVariable *CoverageNamesVar =
466 M.getNamedGlobal(getCoverageUnusedNamesVarName());
467 if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
468 return MadeChange;
469
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000470 // We did not know how many value sites there would be inside
471 // the instrumented function. This is counting the number of instrumented
472 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000473 for (Function &F : M) {
474 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000475 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000476 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
477 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000478 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000479 else if (FirstProfIncInst == nullptr)
480 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
481
482 // Value profiling intrinsic lowering requires per-function profile data
483 // variable to be created first.
484 if (FirstProfIncInst != nullptr)
485 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
486 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000487
488 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000489 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000490
Vedant Kumar1ee511c2018-01-26 23:54:24 +0000491 if (CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000492 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000493 MadeChange = true;
494 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000495
Justin Bogner61ba2e32014-12-08 18:02:35 +0000496 if (!MadeChange)
497 return false;
498
Xinliang David Lib628dd32016-05-21 22:55:34 +0000499 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000500 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000501 emitRegistration();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000502 emitUses();
503 emitInitialization();
504 return true;
505}
506
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000507static Constant *getOrInsertValueProfilingCall(Module &M,
Rong Xu60faea12017-03-16 21:15:48 +0000508 const TargetLibraryInfo &TLI,
509 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000510 LLVMContext &Ctx = M.getContext();
511 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000512
513 Constant *Res;
514 if (!IsRange) {
515 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000516#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
517#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000518 };
519 auto *ValueProfilingCallTy =
520 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
521 Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
522 ValueProfilingCallTy);
523 } else {
524 Type *RangeParamTypes[] = {
525#define VALUE_RANGE_PROF 1
526#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
527#include "llvm/ProfileData/InstrProfData.inc"
528#undef VALUE_RANGE_PROF
529 };
530 auto *ValueRangeProfilingCallTy =
531 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
532 Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
533 ValueRangeProfilingCallTy);
534 }
535
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000536 if (Function *FunRes = dyn_cast<Function>(Res)) {
537 if (auto AK = TLI.getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000538 FunRes->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000539 }
540 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000541}
542
543void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000544 GlobalVariable *Name = Ind->getName();
545 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
546 uint64_t Index = Ind->getIndex()->getZExtValue();
547 auto It = ProfileDataMap.find(Name);
548 if (It == ProfileDataMap.end()) {
549 PerFunctionProfileData PD;
550 PD.NumValueSites[ValueKind] = Index + 1;
551 ProfileDataMap[Name] = PD;
552 } else if (It->second.NumValueSites[ValueKind] <= Index)
553 It->second.NumValueSites[ValueKind] = Index + 1;
554}
555
556void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000557 GlobalVariable *Name = Ind->getName();
558 auto It = ProfileDataMap.find(Name);
559 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000560 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000561
562 GlobalVariable *DataVar = It->second.DataVar;
563 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
564 uint64_t Index = Ind->getIndex()->getZExtValue();
565 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
566 Index += It->second.NumValueSites[Kind];
567
568 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000569 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
570 llvm::InstrProfValueKind::IPVK_MemOPSize);
571 CallInst *Call = nullptr;
572 if (!IsRange) {
573 Value *Args[3] = {Ind->getTargetValue(),
574 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
575 Builder.getInt32(Index)};
576 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
577 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000578 Value *Args[6] = {
579 Ind->getTargetValue(),
580 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
581 Builder.getInt32(Index),
582 Builder.getInt64(MemOPSizeRangeStart),
583 Builder.getInt64(MemOPSizeRangeLast),
584 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000585 Call =
586 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
587 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000588 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000589 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000590 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000591 Ind->eraseFromParent();
592}
593
Justin Bogner61ba2e32014-12-08 18:02:35 +0000594void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
595 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
596
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000597 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000598 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000599 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000600 Value *Load = Builder.CreateLoad(Addr, "pgocount");
601 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
602 auto *Store = Builder.CreateStore(Count, Addr);
603 Inc->replaceAllUsesWith(Store);
604 if (isCounterPromotionEnabled())
605 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000606 Inc->eraseFromParent();
607}
608
Xinliang David Li81056072016-01-07 20:05:49 +0000609void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000610 ConstantArray *Names =
611 cast<ConstantArray>(CoverageNamesVar->getInitializer());
612 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
613 Constant *NC = Names->getOperand(I);
614 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000615 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
616 GlobalVariable *Name = cast<GlobalVariable>(V);
617
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000618 Name->setLinkage(GlobalValue::PrivateLinkage);
619 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000620 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000621 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000622 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000623}
624
Justin Bogner61ba2e32014-12-08 18:02:35 +0000625/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000626static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000627 StringRef NamePrefix = getInstrProfNameVarPrefix();
628 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000629 Function *F = Inc->getParent()->getParent();
630 Module *M = F->getParent();
631 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
632 !canRenameComdatFunc(*F))
633 return (Prefix + Name).str();
634 uint64_t FuncHash = Inc->getHash()->getZExtValue();
635 SmallVector<char, 24> HashPostfix;
636 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
637 return (Prefix + Name).str();
638 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000639}
640
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000641static inline bool shouldRecordFunctionAddr(Function *F) {
642 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000643 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000644 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000645 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000646 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000647
648 // A function marked 'alwaysinline' with available_externally linkage can't
649 // have its address taken. Doing so would create an undefined external ref to
650 // the function, which would fail to link.
651 if (HasAvailableExternallyLinkage &&
652 F->hasFnAttribute(Attribute::AlwaysInline))
653 return false;
654
Rong Xuaf5aeba2016-04-27 21:17:30 +0000655 // Prohibit function address recording if the function is both internal and
656 // COMDAT. This avoids the profile data variable referencing internal symbols
657 // in COMDAT.
658 if (F->hasLocalLinkage() && F->hasComdat())
659 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000660
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000661 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000662 // Inline virtual functions have linkeOnceODR linkage. When a key method
663 // exists, the vtable will only be emitted in the TU where the key method
664 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000665 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000666 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000667 // indirect call target info.
668 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000669}
670
Xinliang David Li985ff202016-02-27 23:11:30 +0000671static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000672 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000673 if (!needsComdatForCounter(F, M))
674 return nullptr;
675
Xinliang David Liab361ef2015-12-21 21:52:27 +0000676 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000677 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000678 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000679 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000680 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000681 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000682 : getInstrProfComdatPrefix());
683 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
684}
685
Xinliang David Lib628dd32016-05-21 22:55:34 +0000686static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
687 // Don't do this for Darwin. compiler-rt uses linker magic.
688 if (Triple(M.getTargetTriple()).isOSDarwin())
689 return false;
690
691 // Use linker script magic to get data/cnts/name start/end.
692 if (Triple(M.getTargetTriple()).isOSLinux() ||
693 Triple(M.getTargetTriple()).isOSFreeBSD() ||
694 Triple(M.getTargetTriple()).isPS4CPU())
695 return false;
696
697 return true;
698}
699
Justin Bogner61ba2e32014-12-08 18:02:35 +0000700GlobalVariable *
701InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000702 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000703 auto It = ProfileDataMap.find(NamePtr);
704 PerFunctionProfileData PD;
705 if (It != ProfileDataMap.end()) {
706 if (It->second.RegionCounters)
707 return It->second.RegionCounters;
708 PD = It->second;
709 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000710
Wei Mi3cc92042015-09-23 22:40:45 +0000711 // Move the name variable to the right section. Place them in a COMDAT group
712 // if the associated function is a COMDAT. This will make sure that
713 // only one copy of counters of the COMDAT function will be emitted after
714 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000715 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000716 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000717 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000718
719 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
720 LLVMContext &Ctx = M->getContext();
721 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
722
723 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000724 auto *CounterPtr =
725 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000726 Constant::getNullValue(CounterTy),
727 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000728 CounterPtr->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000729 CounterPtr->setSection(
730 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000731 CounterPtr->setAlignment(8);
732 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000733
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000734 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000735 // Allocate statically the array of pointers to value profile nodes for
736 // the current function.
737 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
738 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000739 uint64_t NS = 0;
740 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
741 NS += PD.NumValueSites[Kind];
742 if (NS) {
743 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
744
745 auto *ValuesVar =
746 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
747 Constant::getNullValue(ValuesTy),
748 getVarName(Inc, getInstrProfValuesVarPrefix()));
749 ValuesVar->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000750 ValuesVar->setSection(
751 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000752 ValuesVar->setAlignment(8);
753 ValuesVar->setComdat(ProfileVarsComdat);
754 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000755 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000756 }
757 }
758
759 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000760 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000761 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000762 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000763#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
764#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000765 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000766 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000767
Xinliang David Li69a00f02016-06-21 02:39:08 +0000768 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
769 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
770 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000771
Xinliang David Li69a00f02016-06-21 02:39:08 +0000772 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000773 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
774 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
775
Justin Bogner61ba2e32014-12-08 18:02:35 +0000776 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000777#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
778#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000779 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000780 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000781 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000782 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000783 Data->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000784 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000785 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000786 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000787
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000788 PD.RegionCounters = CounterPtr;
789 PD.DataVar = Data;
790 ProfileDataMap[NamePtr] = PD;
791
Justin Bogner61ba2e32014-12-08 18:02:35 +0000792 // Mark the data variable as used so that it isn't stripped out.
793 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000794 // Now that the linkage set by the FE has been passed to the data and counter
795 // variables, reset Name variable's linkage and visibility to private so that
796 // it can be removed later by the compiler.
797 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
798 // Collect the referenced names to be used by emitNameData.
799 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000800
Xinliang David Li192c7482015-11-05 00:47:26 +0000801 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000802}
803
Xinliang David Lib628dd32016-05-21 22:55:34 +0000804void InstrProfiling::emitVNodes() {
805 if (!ValueProfileStaticAlloc)
806 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000807
Xinliang David Lib628dd32016-05-21 22:55:34 +0000808 // For now only support this on platforms that do
809 // not require runtime registration to discover
810 // named section start/end.
811 if (needsRuntimeRegistrationOfSectionRange(*M))
812 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000813
Xinliang David Lib628dd32016-05-21 22:55:34 +0000814 size_t TotalNS = 0;
815 for (auto &PD : ProfileDataMap) {
816 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
817 TotalNS += PD.second.NumValueSites[Kind];
818 }
819
820 if (!TotalNS)
821 return;
822
823 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000824// Heuristic for small programs with very few total value sites.
825// The default value of vp-counters-per-site is chosen based on
826// the observation that large apps usually have a low percentage
827// of value sites that actually have any profile data, and thus
828// the average number of counters per site is low. For small
829// apps with very few sites, this may not be true. Bump up the
830// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000831#define INSTR_PROF_MIN_VAL_COUNTS 10
832 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000833 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000834
835 auto &Ctx = M->getContext();
836 Type *VNodeTypes[] = {
837#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
838#include "llvm/ProfileData/InstrProfData.inc"
839 };
840 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
841
842 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
843 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000844 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000845 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000846 VNodesVar->setSection(
847 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000848 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000849}
850
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000851void InstrProfiling::emitNameData() {
852 std::string UncompressedData;
853
854 if (ReferencedNames.empty())
855 return;
856
857 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000858 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000859 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000860 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000861 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000862
863 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000864 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000865 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000866 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
867 GlobalValue::PrivateLinkage, NamesVal,
868 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000869 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000870 NamesVar->setSection(
871 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000872 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000873
874 for (auto *NamePtr : ReferencedNames)
875 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000876}
877
Justin Bogner61ba2e32014-12-08 18:02:35 +0000878void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000879 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000880 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000881
Justin Bogner61ba2e32014-12-08 18:02:35 +0000882 // Construct the function.
883 auto *VoidTy = Type::getVoidTy(M->getContext());
884 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000885 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000886 auto *RegisterFTy = FunctionType::get(VoidTy, false);
887 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000888 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000889 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000890 if (Options.NoRedZone)
891 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000892
Diego Novillob3029d22015-06-04 11:45:32 +0000893 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000894 auto *RuntimeRegisterF =
895 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000896 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000897
898 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
899 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000900 if (Data != NamesVar)
901 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
902
903 if (NamesVar) {
904 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
905 auto *NamesRegisterTy =
906 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
907 auto *NamesRegisterF =
908 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
909 getInstrProfNamesRegFuncName(), M);
910 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
911 IRB.getInt64(NamesSize)});
912 }
913
Justin Bogner61ba2e32014-12-08 18:02:35 +0000914 IRB.CreateRetVoid();
915}
916
Vedant Kumar9a041a72018-02-28 19:00:08 +0000917bool InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000918 // We expect the linker to be invoked with -u<hook_var> flag for linux,
919 // for which case there is no need to emit the user function.
920 if (Triple(M->getTargetTriple()).isOSLinux())
Vedant Kumar9a041a72018-02-28 19:00:08 +0000921 return false;
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000922
Justin Bogner61ba2e32014-12-08 18:02:35 +0000923 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000924 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
Vedant Kumar9a041a72018-02-28 19:00:08 +0000925 return false;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000926
927 // Declare an external variable that will pull in the runtime initialization.
928 auto *Int32Ty = Type::getInt32Ty(M->getContext());
929 auto *Var =
930 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000931 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000932
933 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000934 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
935 GlobalValue::LinkOnceODRLinkage,
936 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000937 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000938 if (Options.NoRedZone)
939 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000940 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000941 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000942 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000943
944 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
945 auto *Load = IRB.CreateLoad(Var);
946 IRB.CreateRet(Load);
947
948 // Mark the user variable as used so that it isn't stripped out.
949 UsedVars.push_back(User);
Vedant Kumar9a041a72018-02-28 19:00:08 +0000950 return true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000951}
952
953void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000954 if (!UsedVars.empty())
955 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000956}
957
958void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000959 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000960
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000961 if (!InstrProfileOutput.empty()) {
962 // Create variable for profile name.
963 Constant *ProfileNameConst =
964 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
965 GlobalVariable *ProfileNameVar = new GlobalVariable(
966 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
967 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000968 if (TT.supportsCOMDAT()) {
969 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
970 ProfileNameVar->setComdat(M->getOrInsertComdat(
971 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
972 }
973 }
974
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000975 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000976 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000977 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000978
979 // Create the initialization function.
980 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000981 auto *F = Function::Create(FunctionType::get(VoidTy, false),
982 GlobalValue::InternalLinkage,
983 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000984 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000985 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000986 if (Options.NoRedZone)
987 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000988
989 // Add the basic block and the necessary calls.
990 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000991 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000992 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000993 IRB.CreateRetVoid();
994
995 appendToGlobalCtors(*M, F, 0);
996}