blob: adea7e7724476d238e219aa6029281f0b623f833 [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"
Justin Bogner61ba2e32014-12-08 18:02:35 +000017#include "llvm/ADT/Triple.h"
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000019#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/Module.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000022#include "llvm/ProfileData/InstrProf.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000023#include "llvm/Transforms/Utils/ModuleUtils.h"
24
25using namespace llvm;
26
27#define DEBUG_TYPE "instrprof"
28
29namespace {
30
Xinliang David Lia82d6c02016-02-08 18:13:49 +000031cl::opt<bool> DoNameCompression("enable-name-compression",
32 cl::desc("Enable name string compression"),
33 cl::init(true));
34
Rong Xuef1adad2017-01-10 19:30:20 +000035cl::opt<bool> DoHashBasedCounterSplit(
36 "hash-based-counter-split",
37 cl::desc("Rename counter variable of a comdat function based on cfg hash"),
38 cl::init(true));
39
Xinliang David Lib628dd32016-05-21 22:55:34 +000040cl::opt<bool> ValueProfileStaticAlloc(
41 "vp-static-alloc",
42 cl::desc("Do static counter allocation for value profiler"),
43 cl::init(true));
44cl::opt<double> NumCountersPerValueSite(
45 "vp-counters-per-site",
46 cl::desc("The average number of profile counters allocated "
47 "per value profiling site."),
48 // This is set to a very small value because in real programs, only
49 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
50 // For those sites with non-zero profile, the average number of targets
51 // is usually smaller than 2.
52 cl::init(1.0));
53
Xinliang David Lie6b89292016-04-18 17:47:38 +000054class InstrProfilingLegacyPass : public ModulePass {
55 InstrProfiling InstrProf;
56
Justin Bogner61ba2e32014-12-08 18:02:35 +000057public:
58 static char ID;
Xinliang David Lie6b89292016-04-18 17:47:38 +000059 InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
60 InstrProfilingLegacyPass(const InstrProfOptions &Options)
61 : ModulePass(ID), InstrProf(Options) {}
Mehdi Amini117296c2016-10-01 02:56:57 +000062 StringRef getPassName() const override {
Justin Bogner61ba2e32014-12-08 18:02:35 +000063 return "Frontend instrumentation-based coverage lowering";
64 }
65
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000066 bool runOnModule(Module &M) override {
67 return InstrProf.run(M, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
68 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000069
70 void getAnalysisUsage(AnalysisUsage &AU) const override {
71 AU.setPreservesCFG();
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000072 AU.addRequired<TargetLibraryInfoWrapperPass>();
Justin Bogner61ba2e32014-12-08 18:02:35 +000073 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000074};
75
76} // anonymous namespace
77
Sean Silvafd03ac62016-08-09 00:28:38 +000078PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000079 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
80 if (!run(M, TLI))
Xinliang David Lie6b89292016-04-18 17:47:38 +000081 return PreservedAnalyses::all();
82
83 return PreservedAnalyses::none();
84}
85
86char InstrProfilingLegacyPass::ID = 0;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +000087INITIALIZE_PASS_BEGIN(
88 InstrProfilingLegacyPass, "instrprof",
89 "Frontend instrumentation-based coverage lowering.", false, false)
90INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
91INITIALIZE_PASS_END(
92 InstrProfilingLegacyPass, "instrprof",
93 "Frontend instrumentation-based coverage lowering.", false, false)
Justin Bogner61ba2e32014-12-08 18:02:35 +000094
Xinliang David Li69a00f02016-06-21 02:39:08 +000095ModulePass *
96llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +000097 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +000098}
99
Xinliang David Lie6b89292016-04-18 17:47:38 +0000100bool InstrProfiling::isMachO() const {
101 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
102}
103
104/// Get the section name for the counter variables.
105StringRef InstrProfiling::getCountersSection() const {
106 return getInstrProfCountersSectionName(isMachO());
107}
108
109/// Get the section name for the name variables.
110StringRef InstrProfiling::getNameSection() const {
111 return getInstrProfNameSectionName(isMachO());
112}
113
114/// Get the section name for the profile data variables.
115StringRef InstrProfiling::getDataSection() const {
116 return getInstrProfDataSectionName(isMachO());
117}
118
119/// Get the section name for the coverage mapping data.
120StringRef InstrProfiling::getCoverageSection() const {
121 return getInstrProfCoverageSectionName(isMachO());
122}
123
Xinliang David Li4ca17332016-09-18 18:34:07 +0000124static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
125 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
126 if (Inc)
127 return Inc;
128 return dyn_cast<InstrProfIncrementInst>(Instr);
129}
130
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000131bool InstrProfiling::run(Module &M, const TargetLibraryInfo &TLI) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000132 bool MadeChange = false;
133
134 this->M = &M;
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000135 this->TLI = &TLI;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000136 NamesVar = nullptr;
137 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000138 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000139 UsedVars.clear();
140
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000141 // We did not know how many value sites there would be inside
142 // the instrumented function. This is counting the number of instrumented
143 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000144 for (Function &F : M) {
145 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000146 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000147 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
148 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000149 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000150 else if (FirstProfIncInst == nullptr)
151 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
152
153 // Value profiling intrinsic lowering requires per-function profile data
154 // variable to be created first.
155 if (FirstProfIncInst != nullptr)
156 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
157 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000158
159 for (Function &F : M)
160 for (BasicBlock &BB : F)
161 for (auto I = BB.begin(), E = BB.end(); I != E;) {
162 auto Instr = I++;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000163 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
164 if (Inc) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000165 lowerIncrement(Inc);
166 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000167 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
168 lowerValueProfileInst(Ind);
169 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000170 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000171 }
172
Xinliang David Li81056072016-01-07 20:05:49 +0000173 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000174 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000175 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000176 MadeChange = true;
177 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000178
Justin Bogner61ba2e32014-12-08 18:02:35 +0000179 if (!MadeChange)
180 return false;
181
Xinliang David Lib628dd32016-05-21 22:55:34 +0000182 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000183 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000184 emitRegistration();
185 emitRuntimeHook();
186 emitUses();
187 emitInitialization();
188 return true;
189}
190
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000191static Constant *getOrInsertValueProfilingCall(Module &M,
192 const TargetLibraryInfo &TLI) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000193 LLVMContext &Ctx = M.getContext();
194 auto *ReturnTy = Type::getVoidTy(M.getContext());
195 Type *ParamTypes[] = {
196#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
197#include "llvm/ProfileData/InstrProfData.inc"
198 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000199 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000200 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000201 Constant *Res = M.getOrInsertFunction(getInstrProfValueProfFuncName(),
202 ValueProfilingCallTy);
203 if (Function *FunRes = dyn_cast<Function>(Res)) {
204 if (auto AK = TLI.getExtAttrForI32Param(false))
205 FunRes->addAttribute(3, AK);
206 }
207 return Res;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000208}
209
210void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
211
212 GlobalVariable *Name = Ind->getName();
213 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
214 uint64_t Index = Ind->getIndex()->getZExtValue();
215 auto It = ProfileDataMap.find(Name);
216 if (It == ProfileDataMap.end()) {
217 PerFunctionProfileData PD;
218 PD.NumValueSites[ValueKind] = Index + 1;
219 ProfileDataMap[Name] = PD;
220 } else if (It->second.NumValueSites[ValueKind] <= Index)
221 It->second.NumValueSites[ValueKind] = Index + 1;
222}
223
224void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
225
226 GlobalVariable *Name = Ind->getName();
227 auto It = ProfileDataMap.find(Name);
228 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000229 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000230
231 GlobalVariable *DataVar = It->second.DataVar;
232 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
233 uint64_t Index = Ind->getIndex()->getZExtValue();
234 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
235 Index += It->second.NumValueSites[Kind];
236
237 IRBuilder<> Builder(Ind);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000238 Value *Args[3] = {Ind->getTargetValue(),
239 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
240 Builder.getInt32(Index)};
Marcin Koscielnicki1c2bd1e2016-11-21 11:57:19 +0000241 CallInst *Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI),
242 Args);
243 if (auto AK = TLI->getExtAttrForI32Param(false))
244 Call->addAttribute(3, AK);
245 Ind->replaceAllUsesWith(Call);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000246 Ind->eraseFromParent();
247}
248
Justin Bogner61ba2e32014-12-08 18:02:35 +0000249void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
250 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
251
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000252 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000253 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000254 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
255 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Xinliang David Lia754c472016-09-20 19:07:22 +0000256 Count = Builder.CreateAdd(Count, Inc->getStep());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000257 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
258 Inc->eraseFromParent();
259}
260
Xinliang David Li81056072016-01-07 20:05:49 +0000261void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000262
Xinliang David Li81056072016-01-07 20:05:49 +0000263 ConstantArray *Names =
264 cast<ConstantArray>(CoverageNamesVar->getInitializer());
265 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
266 Constant *NC = Names->getOperand(I);
267 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000268 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
269 GlobalVariable *Name = cast<GlobalVariable>(V);
270
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000271 Name->setLinkage(GlobalValue::PrivateLinkage);
272 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000273 }
274}
275
Justin Bogner61ba2e32014-12-08 18:02:35 +0000276/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000277static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000278 StringRef NamePrefix = getInstrProfNameVarPrefix();
279 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Rong Xuef1adad2017-01-10 19:30:20 +0000280 Function *F = Inc->getParent()->getParent();
281 Module *M = F->getParent();
282 if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
283 !canRenameComdatFunc(*F))
284 return (Prefix + Name).str();
285 uint64_t FuncHash = Inc->getHash()->getZExtValue();
286 SmallVector<char, 24> HashPostfix;
287 if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
288 return (Prefix + Name).str();
289 return (Prefix + Name + "." + Twine(FuncHash)).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000290}
291
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000292static inline bool shouldRecordFunctionAddr(Function *F) {
293 // Check the linkage
294 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
295 !F->hasAvailableExternallyLinkage())
296 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000297 // Prohibit function address recording if the function is both internal and
298 // COMDAT. This avoids the profile data variable referencing internal symbols
299 // in COMDAT.
300 if (F->hasLocalLinkage() && F->hasComdat())
301 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000302 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000303 // Inline virtual functions have linkeOnceODR linkage. When a key method
304 // exists, the vtable will only be emitted in the TU where the key method
305 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000306 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000307 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000308 // indirect call target info.
309 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000310}
311
Xinliang David Li985ff202016-02-27 23:11:30 +0000312static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000313 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000314 if (!needsComdatForCounter(F, M))
315 return nullptr;
316
Xinliang David Liab361ef2015-12-21 21:52:27 +0000317 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000318 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000319 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000320 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000321 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000322 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000323 : getInstrProfComdatPrefix());
324 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
325}
326
Xinliang David Lib628dd32016-05-21 22:55:34 +0000327static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
328 // Don't do this for Darwin. compiler-rt uses linker magic.
329 if (Triple(M.getTargetTriple()).isOSDarwin())
330 return false;
331
332 // Use linker script magic to get data/cnts/name start/end.
333 if (Triple(M.getTargetTriple()).isOSLinux() ||
334 Triple(M.getTargetTriple()).isOSFreeBSD() ||
335 Triple(M.getTargetTriple()).isPS4CPU())
336 return false;
337
338 return true;
339}
340
Justin Bogner61ba2e32014-12-08 18:02:35 +0000341GlobalVariable *
342InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000343 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000344 auto It = ProfileDataMap.find(NamePtr);
345 PerFunctionProfileData PD;
346 if (It != ProfileDataMap.end()) {
347 if (It->second.RegionCounters)
348 return It->second.RegionCounters;
349 PD = It->second;
350 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000351
Wei Mi3cc92042015-09-23 22:40:45 +0000352 // Move the name variable to the right section. Place them in a COMDAT group
353 // if the associated function is a COMDAT. This will make sure that
354 // only one copy of counters of the COMDAT function will be emitted after
355 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000356 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000357 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000358 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000359
360 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
361 LLVMContext &Ctx = M->getContext();
362 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
363
364 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000365 auto *CounterPtr =
366 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000367 Constant::getNullValue(CounterTy),
368 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000369 CounterPtr->setVisibility(NamePtr->getVisibility());
370 CounterPtr->setSection(getCountersSection());
371 CounterPtr->setAlignment(8);
372 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000373
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000374 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000375 // Allocate statically the array of pointers to value profile nodes for
376 // the current function.
377 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
378 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
379
380 uint64_t NS = 0;
381 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
382 NS += PD.NumValueSites[Kind];
383 if (NS) {
384 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
385
386 auto *ValuesVar =
387 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
388 Constant::getNullValue(ValuesTy),
389 getVarName(Inc, getInstrProfValuesVarPrefix()));
390 ValuesVar->setVisibility(NamePtr->getVisibility());
391 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
392 ValuesVar->setAlignment(8);
393 ValuesVar->setComdat(ProfileVarsComdat);
394 ValuesPtrExpr =
395 ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
396 }
397 }
398
399 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000400 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000401 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000402 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000403#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
404#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000405 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000406 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000407
Xinliang David Li69a00f02016-06-21 02:39:08 +0000408 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
409 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
410 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000411
Xinliang David Li69a00f02016-06-21 02:39:08 +0000412 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000413 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
414 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
415
Justin Bogner61ba2e32014-12-08 18:02:35 +0000416 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000417#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
418#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000419 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000420 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000421 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000422 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000423 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000424 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000425 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000426 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000427
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000428 PD.RegionCounters = CounterPtr;
429 PD.DataVar = Data;
430 ProfileDataMap[NamePtr] = PD;
431
Justin Bogner61ba2e32014-12-08 18:02:35 +0000432 // Mark the data variable as used so that it isn't stripped out.
433 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000434 // Now that the linkage set by the FE has been passed to the data and counter
435 // variables, reset Name variable's linkage and visibility to private so that
436 // it can be removed later by the compiler.
437 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
438 // Collect the referenced names to be used by emitNameData.
439 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000440
Xinliang David Li192c7482015-11-05 00:47:26 +0000441 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000442}
443
Xinliang David Lib628dd32016-05-21 22:55:34 +0000444void InstrProfiling::emitVNodes() {
445 if (!ValueProfileStaticAlloc)
446 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000447
Xinliang David Lib628dd32016-05-21 22:55:34 +0000448 // For now only support this on platforms that do
449 // not require runtime registration to discover
450 // named section start/end.
451 if (needsRuntimeRegistrationOfSectionRange(*M))
452 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000453
Xinliang David Lib628dd32016-05-21 22:55:34 +0000454 size_t TotalNS = 0;
455 for (auto &PD : ProfileDataMap) {
456 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
457 TotalNS += PD.second.NumValueSites[Kind];
458 }
459
460 if (!TotalNS)
461 return;
462
463 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000464// Heuristic for small programs with very few total value sites.
465// The default value of vp-counters-per-site is chosen based on
466// the observation that large apps usually have a low percentage
467// of value sites that actually have any profile data, and thus
468// the average number of counters per site is low. For small
469// apps with very few sites, this may not be true. Bump up the
470// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000471#define INSTR_PROF_MIN_VAL_COUNTS 10
472 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000473 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000474
475 auto &Ctx = M->getContext();
476 Type *VNodeTypes[] = {
477#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
478#include "llvm/ProfileData/InstrProfData.inc"
479 };
480 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
481
482 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
483 auto *VNodesVar = new GlobalVariable(
484 *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
485 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
486 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
487 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000488}
489
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000490void InstrProfiling::emitNameData() {
491 std::string UncompressedData;
492
493 if (ReferencedNames.empty())
494 return;
495
496 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000497 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000498 DoNameCompression)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000499 llvm::report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000500 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000501
502 auto &Ctx = M->getContext();
503 auto *NamesVal = llvm::ConstantDataArray::getString(
504 Ctx, StringRef(CompressedNameStr), false);
505 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
506 llvm::GlobalValue::PrivateLinkage,
507 NamesVal, getInstrProfNamesVarName());
508 NamesSize = CompressedNameStr.size();
509 NamesVar->setSection(getNameSection());
510 UsedVars.push_back(NamesVar);
511}
512
Justin Bogner61ba2e32014-12-08 18:02:35 +0000513void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000514 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000515 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000516
Justin Bogner61ba2e32014-12-08 18:02:35 +0000517 // Construct the function.
518 auto *VoidTy = Type::getVoidTy(M->getContext());
519 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000520 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000521 auto *RegisterFTy = FunctionType::get(VoidTy, false);
522 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000523 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000524 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000525 if (Options.NoRedZone)
526 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000527
Diego Novillob3029d22015-06-04 11:45:32 +0000528 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000529 auto *RuntimeRegisterF =
530 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000531 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000532
533 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
534 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000535 if (Data != NamesVar)
536 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
537
538 if (NamesVar) {
539 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
540 auto *NamesRegisterTy =
541 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
542 auto *NamesRegisterF =
543 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
544 getInstrProfNamesRegFuncName(), M);
545 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
546 IRB.getInt64(NamesSize)});
547 }
548
Justin Bogner61ba2e32014-12-08 18:02:35 +0000549 IRB.CreateRetVoid();
550}
551
552void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000553
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000554 // We expect the linker to be invoked with -u<hook_var> flag for linux,
555 // for which case there is no need to emit the user function.
556 if (Triple(M->getTargetTriple()).isOSLinux())
557 return;
558
Justin Bogner61ba2e32014-12-08 18:02:35 +0000559 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000560 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
561 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000562
563 // Declare an external variable that will pull in the runtime initialization.
564 auto *Int32Ty = Type::getInt32Ty(M->getContext());
565 auto *Var =
566 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000567 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000568
569 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000570 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
571 GlobalValue::LinkOnceODRLinkage,
572 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000573 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000574 if (Options.NoRedZone)
575 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000576 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000577 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000578 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000579
580 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
581 auto *Load = IRB.CreateLoad(Var);
582 IRB.CreateRet(Load);
583
584 // Mark the user variable as used so that it isn't stripped out.
585 UsedVars.push_back(User);
586}
587
588void InstrProfiling::emitUses() {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000589 if (!UsedVars.empty())
590 appendToUsed(*M, UsedVars);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000591}
592
593void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000594 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000595
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000596 if (!InstrProfileOutput.empty()) {
597 // Create variable for profile name.
598 Constant *ProfileNameConst =
599 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
600 GlobalVariable *ProfileNameVar = new GlobalVariable(
601 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
602 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
603 Triple TT(M->getTargetTriple());
604 if (TT.supportsCOMDAT()) {
605 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
606 ProfileNameVar->setComdat(M->getOrInsertComdat(
607 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
608 }
609 }
610
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000611 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000612 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000613 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000614
615 // Create the initialization function.
616 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000617 auto *F = Function::Create(FunctionType::get(VoidTy, false),
618 GlobalValue::InternalLinkage,
619 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000620 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000621 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000622 if (Options.NoRedZone)
623 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000624
625 // Add the basic block and the necessary calls.
626 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000627 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000628 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000629 IRB.CreateRetVoid();
630
631 appendToGlobalCtors(*M, F, 0);
632}