blob: 9c14b0149fdc195151997cda05ae8f43bb691049 [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"
46#include "llvm/Transforms/Utils/LoopSimplify.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000047#include "llvm/Transforms/Utils/ModuleUtils.h"
Xinliang David Lib67530e2017-06-25 00:26:43 +000048#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000049#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <string>
Justin Bogner61ba2e32014-12-08 18:02:35 +000054
55using namespace llvm;
56
57#define DEBUG_TYPE "instrprof"
58
Rong Xu48596b62017-04-04 16:42:20 +000059// The start and end values of precise value profile range for memory
60// intrinsic sizes
61cl::opt<std::string> MemOPSizeRange(
62 "memop-size-range",
63 cl::desc("Set the range of size in memory intrinsic calls to be profiled "
64 "precisely, in a format of <start_val>:<end_val>"),
65 cl::init(""));
66
67// The value that considered to be large value in memory intrinsic.
68cl::opt<unsigned> MemOPSizeLarge(
69 "memop-size-large",
70 cl::desc("Set large value thresthold in memory intrinsic size profiling. "
71 "Value of 0 disables the large value profiling."),
72 cl::init(8192));
73
Justin Bogner61ba2e32014-12-08 18:02:35 +000074namespace {
75
Xinliang David Lia82d6c02016-02-08 18:13:49 +000076cl::opt<bool> DoNameCompression("enable-name-compression",
77 cl::desc("Enable name string compression"),
78 cl::init(true));
79
Rong Xu20f5df12017-01-11 20:19:41 +000080cl::opt<bool> DoHashBasedCounterSplit(
81 "hash-based-counter-split",
82 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
83 cl::init(true));
84
Xinliang David Lib628dd32016-05-21 22:55:34 +000085cl::opt<bool> ValueProfileStaticAlloc(
86 "vp-static-alloc",
87 cl::desc("Do static counter allocation for value profiler"),
88 cl::init(true));
Eugene Zelenko34c23272017-01-18 00:57:48 +000089
Xinliang David Lib628dd32016-05-21 22:55:34 +000090cl::opt<double> NumCountersPerValueSite(
91 "vp-counters-per-site",
92 cl::desc("The average number of profile counters allocated "
93 "per value profiling site."),
94 // This is set to a very small value because in real programs, only
95 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
96 // For those sites with non-zero profile, the average number of targets
97 // is usually smaller than 2.
98 cl::init(1.0));
99
Xinliang David Lib67530e2017-06-25 00:26:43 +0000100cl::opt<bool> AtomicCounterUpdatePromoted(
101 "atomic-counter-update-promoted", cl::ZeroOrMore,
102 cl::desc("Do counter update using atomic fetch add "
103 " for promoted counters only"),
104 cl::init(false));
105
106// If the option is not specified, the default behavior about whether
107// counter promotion is done depends on how instrumentaiton lowering
108// pipeline is setup, i.e., the default value of true of this option
109// does not mean the promotion will be done by default. Explicitly
110// setting this option can override the default behavior.
111cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
112 cl::desc("Do counter register promotion"),
113 cl::init(false));
114cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
115 cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(10),
116 cl::desc("Max number counter promotions per loop to avoid"
117 " increasing register pressure too much"));
118
119// A debug option
120cl::opt<int>
121 MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
122 cl::desc("Max number of allowed counter promotions"));
123
124cl::opt<bool> SpeculativeCounterPromotion(
125 cl::ZeroOrMore, "speculative-counter-promotion", cl::init(false),
126 cl::desc("Allow counter promotion for loops with multiple exiting blocks "
127 " or top-tested loops. "));
128
Xinliang David Lie6b89292016-04-18 17:47:38 +0000129class InstrProfilingLegacyPass : public ModulePass {
130 InstrProfiling InstrProf;
131
Justin Bogner61ba2e32014-12-08 18:02:35 +0000132public:
133 static char ID;
Eugene Zelenko34c23272017-01-18 00:57:48 +0000134
135 InstrProfilingLegacyPass() : ModulePass(ID) {}
Xinliang David Lie6b89292016-04-18 17:47:38 +0000136 InstrProfilingLegacyPass(const InstrProfOptions &Options)
137 : ModulePass(ID), InstrProf(Options) {}
Eugene Zelenko34c23272017-01-18 00:57:48 +0000138
Mehdi Amini117296c2016-10-01 02:56:57 +0000139 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000140 return "Frontend instrumentation-based coverage lowering";
141 }
142
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000143 bool runOnModule(Module &M) override {
144 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
145 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000146
147 void getAnalysisUsage(AnalysisUsage &AU) const override {
148 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000149 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000150 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000151};
152
Xinliang David Lib67530e2017-06-25 00:26:43 +0000153/// A helper class to promote one counter RMW operation in the loop
154/// into register update.
155///
156/// RWM update for the counter will be sinked out of the loop after
157/// the transformation.
158///
159class PGOCounterPromoterHelper : public LoadAndStorePromoter {
160public:
161 PGOCounterPromoterHelper(Instruction *L, Instruction *S, SSAUpdater &SSA,
162 Value *Init, BasicBlock *PH,
163 ArrayRef<BasicBlock *> ExitBlocks,
164 ArrayRef<Instruction *> InsertPts)
165 : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
166 InsertPts(InsertPts) {
167 assert(isa<LoadInst>(L));
168 assert(isa<StoreInst>(S));
169 SSA.AddAvailableValue(PH, Init);
170 }
171 void doExtraRewritesBeforeFinalDeletion() const override {
172 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
173 BasicBlock *ExitBlock = ExitBlocks[i];
174 Instruction *InsertPos = InsertPts[i];
175 // Get LiveIn value into the ExitBlock. If there are multiple
176 // predecessors, the value is defined by a PHI node in this
177 // block.
178 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
179 Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
180 IRBuilder<> Builder(InsertPos);
181 if (AtomicCounterUpdatePromoted)
182 Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
183 AtomicOrdering::SequentiallyConsistent);
184 else {
185 LoadInst *OldVal = Builder.CreateLoad(Addr, "pgocount.promoted");
186 auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
187 Builder.CreateStore(NewVal, Addr);
188 }
189 }
190 }
191
192private:
193 Instruction *Store;
194 ArrayRef<BasicBlock *> ExitBlocks;
195 ArrayRef<Instruction *> InsertPts;
196};
197
198/// A helper class to do register promotion for all profile counter
199/// updates in a loop.
200///
201class PGOCounterPromoter {
202public:
203 PGOCounterPromoter(ArrayRef<LoadStorePair> Cands, Loop &Loop)
204 : Candidates(Cands), ExitBlocks(), InsertPts(), ParentLoop(Loop) {
205
206 SmallVector<BasicBlock *, 8> LoopExitBlocks;
207 SmallPtrSet<BasicBlock *, 8> BlockSet;
208 ParentLoop.getExitBlocks(LoopExitBlocks);
209
210 for (BasicBlock *ExitBlock : LoopExitBlocks) {
211 if (BlockSet.insert(ExitBlock).second) {
212 ExitBlocks.push_back(ExitBlock);
213 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
214 }
215 }
216 }
217
218 bool run(int64_t *NumPromoted) {
219 // We can't insert into a catchswitch.
220 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
221 return isa<CatchSwitchInst>(Exit->getTerminator());
222 });
223
224 if (HasCatchSwitch)
225 return false;
226
227 if (!ParentLoop.hasDedicatedExits())
228 return false;
229
230 BasicBlock *PH = ParentLoop.getLoopPreheader();
231 if (!PH)
232 return false;
233
234 BasicBlock *H = ParentLoop.getHeader();
235 bool TopTested =
236 ((ParentLoop.getBlocks().size() > 1) && ParentLoop.isLoopExiting(H));
237 if (!SpeculativeCounterPromotion &&
238 (TopTested || ParentLoop.getExitingBlock() == nullptr))
239 return false;
240
241 unsigned Promoted = 0;
242 for (auto &Cand : Candidates) {
243
244 SmallVector<PHINode *, 4> NewPHIs;
245 SSAUpdater SSA(&NewPHIs);
246 Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
247 PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
248 PH, ExitBlocks, InsertPts);
249 Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
250 Promoted++;
251 if (Promoted >= MaxNumOfPromotionsPerLoop)
252 break;
253 (*NumPromoted)++;
254 if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
255 break;
256 }
257
258 DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
259 << ParentLoop.getLoopDepth() << ")\n");
260 return Promoted != 0;
261 }
262
263private:
264 ArrayRef<LoadStorePair> Candidates;
265 SmallVector<BasicBlock *, 8> ExitBlocks;
266 SmallVector<Instruction *, 8> InsertPts;
267 Loop &ParentLoop;
268};
269
Eugene Zelenko34c23272017-01-18 00:57:48 +0000270} // end anonymous namespace
Justin Bogner61ba2e32014-12-08 18:02:35 +0000271
Sean Silvafd03ac62016-08-09 00:28:38 +0000272PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000273 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
274 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +0000275 return PreservedAnalyses::all();
276
277 return PreservedAnalyses::none();
278}
279
280char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000281INITIALIZE_PASS_BEGIN(
282 InstrProfilingLegacyPass, "instrprof",
283 "Frontend instrumentation-based coverage lowering.", false, false)
284INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
285INITIALIZE_PASS_END(
286 InstrProfilingLegacyPass, "instrprof",
287 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +0000288
Xinliang David Li69a00f02016-06-21 02:39:08 +0000289ModulePass *
290llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +0000291 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000292}
293
Xinliang David Li4ca17332016-09-18 18:34:07 +0000294static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
295 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
296 if (Inc)
297 return Inc;
298 return dyn_cast<InstrProfIncrementInst>(Instr);
299}
300
Xinliang David Lib67530e2017-06-25 00:26:43 +0000301bool InstrProfiling::lowerIntrinsics(Function *F) {
302 bool MadeChange = false;
303 PromotionCandidates.clear();
304 for (BasicBlock &BB : *F) {
305 for (auto I = BB.begin(), E = BB.end(); I != E;) {
306 auto Instr = I++;
307 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
308 if (Inc) {
309 lowerIncrement(Inc);
310 MadeChange = true;
311 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
312 lowerValueProfileInst(Ind);
313 MadeChange = true;
314 }
315 }
316 }
317
318 if (!MadeChange)
319 return false;
320
321 promoteCounterLoadStores(F);
322 return true;
323}
324
325bool InstrProfiling::isCounterPromotionEnabled() const {
326 if (DoCounterPromotion.getNumOccurrences() > 0)
327 return DoCounterPromotion;
328
329 return Options.DoCounterPromotion;
330}
331
332void InstrProfiling::promoteCounterLoadStores(Function *F) {
333 if (!isCounterPromotionEnabled())
334 return;
335
336 DominatorTree DT(*F);
337 LoopInfo LI(DT);
338 DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
339
340 for (const auto &LoadStore : PromotionCandidates) {
341 auto *CounterLoad = LoadStore.first;
342 auto *CounterStore = LoadStore.second;
343 BasicBlock *BB = CounterLoad->getParent();
344 Loop *ParentLoop = LI.getLoopFor(BB);
345 if (!ParentLoop)
346 continue;
347 LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
348 }
349
350 SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
351
352 for (auto *Loop : Loops) {
353 PGOCounterPromoter Promoter(LoopPromotionCandidates[Loop], *Loop);
354 Promoter.run(&TotalCountersPromoted);
355 }
356}
357
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000358bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000359 bool MadeChange = false;
360
361 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000362 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000363 NamesVar = nullptr;
364 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000365 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000366 UsedVars.clear();
Rong Xu48596b62017-04-04 16:42:20 +0000367 getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
368 MemOPSizeRangeLast);
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000369 TT = Triple(M.getTargetTriple());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000370
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000371 // We did not know how many value sites there would be inside
372 // the instrumented function. This is counting the number of instrumented
373 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000374 for (Function &F : M) {
375 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000376 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000377 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
378 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000379 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000380 else if (FirstProfIncInst == nullptr)
381 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
382
383 // Value profiling intrinsic lowering requires per-function profile data
384 // variable to be created first.
385 if (FirstProfIncInst != nullptr)
386 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
387 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000388
389 for (Function &F : M)
Xinliang David Lib67530e2017-06-25 00:26:43 +0000390 MadeChange |= lowerIntrinsics(&F);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000391
Xinliang David Li81056072016-01-07 20:05:49 +0000392 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000393 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000394 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000395 MadeChange = true;
396 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000397
Justin Bogner61ba2e32014-12-08 18:02:35 +0000398 if (!MadeChange)
399 return false;
400
Xinliang David Lib628dd32016-05-21 22:55:34 +0000401 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000402 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000403 emitRegistration();
404 emitRuntimeHook();
405 emitUses();
406 emitInitialization();
407 return true;
408}
409
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000410static Constant *getOrInsertValueProfilingCall(Module &M,
Rong Xu60faea12017-03-16 21:15:48 +0000411 const TargetLibraryInfo &TLI,
412 bool IsRange = false) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000413 LLVMContext &Ctx = M.getContext();
414 auto *ReturnTy = Type::getVoidTy(M.getContext());
Rong Xu60faea12017-03-16 21:15:48 +0000415
416 Constant *Res;
417 if (!IsRange) {
418 Type *ParamTypes[] = {
Xinliang David Lic7673232015-11-22 00:22:07 +0000419#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
420#include "llvm/ProfileData/InstrProfData.inc"
Rong Xu60faea12017-03-16 21:15:48 +0000421 };
422 auto *ValueProfilingCallTy =
423 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
424 Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
425 ValueProfilingCallTy);
426 } else {
427 Type *RangeParamTypes[] = {
428#define VALUE_RANGE_PROF 1
429#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
430#include "llvm/ProfileData/InstrProfData.inc"
431#undef VALUE_RANGE_PROF
432 };
433 auto *ValueRangeProfilingCallTy =
434 FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
435 Res = M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
436 ValueRangeProfilingCallTy);
437 }
438
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000439 if (Function *FunRes = dyn_cast<Function>(Res)) {
440 if (auto AK = TLI.getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000441 FunRes->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000442 }
443 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000444}
445
446void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000447 GlobalVariable *Name = Ind->getName();
448 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
449 uint64_t Index = Ind->getIndex()->getZExtValue();
450 auto It = ProfileDataMap.find(Name);
451 if (It == ProfileDataMap.end()) {
452 PerFunctionProfileData PD;
453 PD.NumValueSites[ValueKind] = Index + 1;
454 ProfileDataMap[Name] = PD;
455 } else if (It->second.NumValueSites[ValueKind] <= Index)
456 It->second.NumValueSites[ValueKind] = Index + 1;
457}
458
459void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000460 GlobalVariable *Name = Ind->getName();
461 auto It = ProfileDataMap.find(Name);
462 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000463 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000464
465 GlobalVariable *DataVar = It->second.DataVar;
466 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
467 uint64_t Index = Ind->getIndex()->getZExtValue();
468 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
469 Index += It->second.NumValueSites[Kind];
470
471 IRBuilder<> Builder(Ind);
Rong Xu60faea12017-03-16 21:15:48 +0000472 bool IsRange = (Ind->getValueKind()->getZExtValue() ==
473 llvm::InstrProfValueKind::IPVK_MemOPSize);
474 CallInst *Call = nullptr;
475 if (!IsRange) {
476 Value *Args[3] = {Ind->getTargetValue(),
477 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
478 Builder.getInt32(Index)};
479 Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args);
480 } else {
Rong Xu48596b62017-04-04 16:42:20 +0000481 Value *Args[6] = {
482 Ind->getTargetValue(),
483 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
484 Builder.getInt32(Index),
485 Builder.getInt64(MemOPSizeRangeStart),
486 Builder.getInt64(MemOPSizeRangeLast),
487 Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
Rong Xu60faea12017-03-16 21:15:48 +0000488 Call =
489 Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true), Args);
490 }
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000491 if (auto AK = TLI->getExtAttrForI32Param(false))
Reid Klecknera0b45f42017-05-03 18:17:31 +0000492 Call->addParamAttr(2, AK);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000493 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000494 Ind->eraseFromParent();
495}
496
Justin Bogner61ba2e32014-12-08 18:02:35 +0000497void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
498 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
499
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000500 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000501 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000502 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Xinliang David Lib67530e2017-06-25 00:26:43 +0000503 Value *Load = Builder.CreateLoad(Addr, "pgocount");
504 auto *Count = Builder.CreateAdd(Load, Inc->getStep());
505 auto *Store = Builder.CreateStore(Count, Addr);
506 Inc->replaceAllUsesWith(Store);
507 if (isCounterPromotionEnabled())
508 PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000509 Inc->eraseFromParent();
510}
511
Xinliang David Li81056072016-01-07 20:05:49 +0000512void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Xinliang David Li81056072016-01-07 20:05:49 +0000513 ConstantArray *Names =
514 cast<ConstantArray>(CoverageNamesVar->getInitializer());
515 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
516 Constant *NC = Names->getOperand(I);
517 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000518 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
519 GlobalVariable *Name = cast<GlobalVariable>(V);
520
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000521 Name->setLinkage(GlobalValue::PrivateLinkage);
522 ReferencedNames.push_back(Name);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000523 NC->dropAllReferences();
Justin Bognerd24e1852015-02-11 02:52:44 +0000524 }
Vedant Kumar55891fc2017-02-14 20:03:48 +0000525 CoverageNamesVar->eraseFromParent();
Justin Bognerd24e1852015-02-11 02:52:44 +0000526}
527
Justin Bogner61ba2e32014-12-08 18:02:35 +0000528/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000529static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000530 StringRef NamePrefix = getInstrProfNameVarPrefix();
531 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xu20f5df12017-01-11 20:19:41 +0000532 Function *F = Inc->getParent()->getParent();
533 Module *M = F->getParent();
534 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
535 !canRenameComdatFunc(*F))
536 return (Prefix + Name).str();
537 uint64_t FuncHash = Inc->getHash()->getZExtValue();
538 SmallVector<char, 24> HashPostfix;
539 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
540 return (Prefix + Name).str();
541 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000542}
543
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000544static inline bool shouldRecordFunctionAddr(Function *F) {
545 // Check the linkage
Vedant Kumar9c056c92017-06-13 22:12:35 +0000546 bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000547 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
Vedant Kumar9c056c92017-06-13 22:12:35 +0000548 !HasAvailableExternallyLinkage)
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000549 return true;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000550
551 // A function marked 'alwaysinline' with available_externally linkage can't
552 // have its address taken. Doing so would create an undefined external ref to
553 // the function, which would fail to link.
554 if (HasAvailableExternallyLinkage &&
555 F->hasFnAttribute(Attribute::AlwaysInline))
556 return false;
557
Rong Xuaf5aeba2016-04-27 21:17:30 +0000558 // Prohibit function address recording if the function is both internal and
559 // COMDAT. This avoids the profile data variable referencing internal symbols
560 // in COMDAT.
561 if (F->hasLocalLinkage() && F->hasComdat())
562 return false;
Vedant Kumar9c056c92017-06-13 22:12:35 +0000563
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000564 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000565 // Inline virtual functions have linkeOnceODR linkage. When a key method
566 // exists, the vtable will only be emitted in the TU where the key method
567 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000568 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000569 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000570 // indirect call target info.
571 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000572}
573
Xinliang David Li985ff202016-02-27 23:11:30 +0000574static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000575 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000576 if (!needsComdatForCounter(F, M))
577 return nullptr;
578
Xinliang David Liab361ef2015-12-21 21:52:27 +0000579 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000580 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000581 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000582 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000583 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000584 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000585 : getInstrProfComdatPrefix());
586 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
587}
588
Xinliang David Lib628dd32016-05-21 22:55:34 +0000589static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
590 // Don't do this for Darwin. compiler-rt uses linker magic.
591 if (Triple(M.getTargetTriple()).isOSDarwin())
592 return false;
593
594 // Use linker script magic to get data/cnts/name start/end.
595 if (Triple(M.getTargetTriple()).isOSLinux() ||
596 Triple(M.getTargetTriple()).isOSFreeBSD() ||
597 Triple(M.getTargetTriple()).isPS4CPU())
598 return false;
599
600 return true;
601}
602
Justin Bogner61ba2e32014-12-08 18:02:35 +0000603GlobalVariable *
604InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000605 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000606 auto It = ProfileDataMap.find(NamePtr);
607 PerFunctionProfileData PD;
608 if (It != ProfileDataMap.end()) {
609 if (It->second.RegionCounters)
610 return It->second.RegionCounters;
611 PD = It->second;
612 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000613
Wei Mi3cc92042015-09-23 22:40:45 +0000614 // Move the name variable to the right section. Place them in a COMDAT group
615 // if the associated function is a COMDAT. This will make sure that
616 // only one copy of counters of the COMDAT function will be emitted after
617 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000618 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000619 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000620 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000621
622 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
623 LLVMContext &Ctx = M->getContext();
624 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
625
626 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000627 auto *CounterPtr =
628 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000629 Constant::getNullValue(CounterTy),
630 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000631 CounterPtr->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000632 CounterPtr->setSection(
633 getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000634 CounterPtr->setAlignment(8);
635 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000636
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000637 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000638 // Allocate statically the array of pointers to value profile nodes for
639 // the current function.
640 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
641 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
Xinliang David Lib628dd32016-05-21 22:55:34 +0000642 uint64_t NS = 0;
643 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
644 NS += PD.NumValueSites[Kind];
645 if (NS) {
646 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
647
648 auto *ValuesVar =
649 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
650 Constant::getNullValue(ValuesTy),
651 getVarName(Inc, getInstrProfValuesVarPrefix()));
652 ValuesVar->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000653 ValuesVar->setSection(
654 getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000655 ValuesVar->setAlignment(8);
656 ValuesVar->setComdat(ProfileVarsComdat);
657 ValuesPtrExpr =
Eugene Zelenko34c23272017-01-18 00:57:48 +0000658 ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000659 }
660 }
661
662 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000663 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000664 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000665 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000666#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
667#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000668 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000669 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000670
Xinliang David Li69a00f02016-06-21 02:39:08 +0000671 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
672 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
673 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000674
Xinliang David Li69a00f02016-06-21 02:39:08 +0000675 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000676 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
677 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
678
Justin Bogner61ba2e32014-12-08 18:02:35 +0000679 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000680#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
681#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000682 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000683 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000684 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000685 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000686 Data->setVisibility(NamePtr->getVisibility());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000687 Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000688 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000689 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000690
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000691 PD.RegionCounters = CounterPtr;
692 PD.DataVar = Data;
693 ProfileDataMap[NamePtr] = PD;
694
Justin Bogner61ba2e32014-12-08 18:02:35 +0000695 // Mark the data variable as used so that it isn't stripped out.
696 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000697 // Now that the linkage set by the FE has been passed to the data and counter
698 // variables, reset Name variable's linkage and visibility to private so that
699 // it can be removed later by the compiler.
700 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
701 // Collect the referenced names to be used by emitNameData.
702 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000703
Xinliang David Li192c7482015-11-05 00:47:26 +0000704 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000705}
706
Xinliang David Lib628dd32016-05-21 22:55:34 +0000707void InstrProfiling::emitVNodes() {
708 if (!ValueProfileStaticAlloc)
709 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000710
Xinliang David Lib628dd32016-05-21 22:55:34 +0000711 // For now only support this on platforms that do
712 // not require runtime registration to discover
713 // named section start/end.
714 if (needsRuntimeRegistrationOfSectionRange(*M))
715 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000716
Xinliang David Lib628dd32016-05-21 22:55:34 +0000717 size_t TotalNS = 0;
718 for (auto &PD : ProfileDataMap) {
719 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
720 TotalNS += PD.second.NumValueSites[Kind];
721 }
722
723 if (!TotalNS)
724 return;
725
726 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000727// Heuristic for small programs with very few total value sites.
728// The default value of vp-counters-per-site is chosen based on
729// the observation that large apps usually have a low percentage
730// of value sites that actually have any profile data, and thus
731// the average number of counters per site is low. For small
732// apps with very few sites, this may not be true. Bump up the
733// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000734#define INSTR_PROF_MIN_VAL_COUNTS 10
735 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000736 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000737
738 auto &Ctx = M->getContext();
739 Type *VNodeTypes[] = {
740#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
741#include "llvm/ProfileData/InstrProfData.inc"
742 };
743 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
744
745 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
746 auto *VNodesVar = new GlobalVariable(
Eugene Zelenko34c23272017-01-18 00:57:48 +0000747 *M, VNodesTy, false, GlobalValue::PrivateLinkage,
Xinliang David Lib628dd32016-05-21 22:55:34 +0000748 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000749 VNodesVar->setSection(
750 getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
Xinliang David Lib628dd32016-05-21 22:55:34 +0000751 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000752}
753
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000754void InstrProfiling::emitNameData() {
755 std::string UncompressedData;
756
757 if (ReferencedNames.empty())
758 return;
759
760 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000761 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000762 DoNameCompression)) {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000763 report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000764 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000765
766 auto &Ctx = M->getContext();
Eugene Zelenko34c23272017-01-18 00:57:48 +0000767 auto *NamesVal = ConstantDataArray::getString(
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000768 Ctx, StringRef(CompressedNameStr), false);
Eugene Zelenko34c23272017-01-18 00:57:48 +0000769 NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
770 GlobalValue::PrivateLinkage, NamesVal,
771 getInstrProfNamesVarName());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000772 NamesSize = CompressedNameStr.size();
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000773 NamesVar->setSection(
774 getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000775 UsedVars.push_back(NamesVar);
Vedant Kumar55891fc2017-02-14 20:03:48 +0000776
777 for (auto *NamePtr : ReferencedNames)
778 NamePtr->eraseFromParent();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000779}
780
Justin Bogner61ba2e32014-12-08 18:02:35 +0000781void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000782 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000783 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000784
Justin Bogner61ba2e32014-12-08 18:02:35 +0000785 // Construct the function.
786 auto *VoidTy = Type::getVoidTy(M->getContext());
787 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000788 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000789 auto *RegisterFTy = FunctionType::get(VoidTy, false);
790 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000791 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000792 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000793 if (Options.NoRedZone)
794 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000795
Diego Novillob3029d22015-06-04 11:45:32 +0000796 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000797 auto *RuntimeRegisterF =
798 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000799 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000800
801 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
802 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000803 if (Data != NamesVar)
804 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
805
806 if (NamesVar) {
807 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
808 auto *NamesRegisterTy =
809 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
810 auto *NamesRegisterF =
811 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
812 getInstrProfNamesRegFuncName(), M);
813 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
814 IRB.getInt64(NamesSize)});
815 }
816
Justin Bogner61ba2e32014-12-08 18:02:35 +0000817 IRB.CreateRetVoid();
818}
819
820void InstrProfiling::emitRuntimeHook() {
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000821 // We expect the linker to be invoked with -u<hook_var> flag for linux,
822 // for which case there is no need to emit the user function.
823 if (Triple(M->getTargetTriple()).isOSLinux())
824 return;
825
Justin Bogner61ba2e32014-12-08 18:02:35 +0000826 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000827 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
828 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000829
830 // Declare an external variable that will pull in the runtime initialization.
831 auto *Int32Ty = Type::getInt32Ty(M->getContext());
832 auto *Var =
833 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000834 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000835
836 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000837 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
838 GlobalValue::LinkOnceODRLinkage,
839 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000840 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000841 if (Options.NoRedZone)
842 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000843 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000844 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000845 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000846
847 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
848 auto *Load = IRB.CreateLoad(Var);
849 IRB.CreateRet(Load);
850
851 // Mark the user variable as used so that it isn't stripped out.
852 UsedVars.push_back(User);
853}
854
855void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000856 if (!UsedVars.empty())
857 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000858}
859
860void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000861 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000862
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000863 if (!InstrProfileOutput.empty()) {
864 // Create variable for profile name.
865 Constant *ProfileNameConst =
866 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
867 GlobalVariable *ProfileNameVar = new GlobalVariable(
868 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
869 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000870 if (TT.supportsCOMDAT()) {
871 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
872 ProfileNameVar->setComdat(M->getOrInsertComdat(
873 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
874 }
875 }
876
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000877 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000878 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000879 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000880
881 // Create the initialization function.
882 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000883 auto *F = Function::Create(FunctionType::get(VoidTy, false),
884 GlobalValue::InternalLinkage,
885 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000886 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000887 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000888 if (Options.NoRedZone)
889 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000890
891 // Add the basic block and the necessary calls.
892 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000893 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000894 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000895 IRB.CreateRetVoid();
896
897 appendToGlobalCtors(*M, F, 0);
898}