blob: 0865d16756b962b55744d6be3ff0da1f26e5155b [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
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//
10// This file implements PGO instrumentation using a minimum spanning tree based
11// on the following paper:
12// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14// Issue 3, pp 313-322
15// The idea of the algorithm based on the fact that for each node (except for
16// the entry and exit), the sum of incoming edge counts equals the sum of
17// outgoing edge counts. The count of edge on spanning tree can be derived from
18// those edges not on the spanning tree. Knuth proves this method instruments
19// the minimum number of edges.
20//
21// The minimal spanning tree here is actually a maximum weight tree -- on-tree
22// edges have higher frequencies (more likely to execute). The idea is to
23// instrument those less frequently executed edges to reduce the runtime
24// overhead of instrumented binaries.
25//
26// This file contains two passes:
27// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// To get the precise counter information, These two passes need to invoke at
35// the same compilation point (so they see the same IR). For pass
36// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38// the profile is opened in module level and passed to each PGOUseFunc instance.
39// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40// in class FuncPGOInstrumentation.
41//
42// Class PGOEdge represents a CFG edge and some auxiliary information. Class
43// BBInfo contains auxiliary information for each BB. These two classes are used
44// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45// class of PGOEdge and BBInfo, respectively. They contains extra data structure
46// used in populating profile counters.
47// The MST implementation is in Class CFGMST (CFGMST.h).
48//
49//===----------------------------------------------------------------------===//
50
Xinliang David Li8aebf442016-05-06 05:49:19 +000051#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000052#include "CFGMST.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000054#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000056#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/Analysis/BlockFrequencyInfo.h"
58#include "llvm/Analysis/BranchProbabilityInfo.h"
59#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000060#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Rong Xued9fec72016-01-21 18:11:44 +000061#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000062#include "llvm/IR/DiagnosticInfo.h"
Rong Xu705f7772016-07-25 18:45:37 +000063#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/IRBuilder.h"
65#include "llvm/IR/InstIterator.h"
66#include "llvm/IR/Instructions.h"
67#include "llvm/IR/IntrinsicInst.h"
68#include "llvm/IR/MDBuilder.h"
69#include "llvm/IR/Module.h"
70#include "llvm/Pass.h"
71#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000072#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000073#include "llvm/Support/BranchProbability.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000076#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000078#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000079#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000080#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000081#include <utility>
82#include <vector>
83
84using namespace llvm;
85
86#define DEBUG_TYPE "pgo-instrumentation"
87
88STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
89STATISTIC(NumOfPGOEdge, "Number of edges.");
90STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
91STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
92STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
93STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
94STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000095STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000096
97// Command line option to specify the file to read profile from. This is
98// mainly used for testing.
99static cl::opt<std::string>
100 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
101 cl::value_desc("filename"),
102 cl::desc("Specify the path of profile data file. This is"
103 "mainly for test purpose."));
104
Rong Xuecdc98f2016-03-04 22:08:44 +0000105// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000106// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000107static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
108 cl::Hidden,
109 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000110
Rong Xuecdc98f2016-03-04 22:08:44 +0000111// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000112// the metadata for a single indirect call callsite.
113static cl::opt<unsigned> MaxNumAnnotations(
114 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
115 cl::desc("Max number of annotations for a single indirect "
116 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000117
Rong Xu705f7772016-07-25 18:45:37 +0000118// Command line option to control appending FunctionHash to the name of a COMDAT
119// function. This is to avoid the hash mismatch caused by the preinliner.
120static cl::opt<bool> DoComdatRenaming(
121 "do-comdat-renaming", cl::init(true), cl::Hidden,
122 cl::desc("Append function hash to the name of COMDAT function to avoid "
123 "function hash mismatch due to the preinliner"));
124
Rong Xu0698de92016-05-13 17:26:06 +0000125// Command line option to enable/disable the warning about missing profile
126// information.
Xinliang David Li76a01082016-08-11 05:09:30 +0000127static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function",
128 cl::init(false),
129 cl::Hidden);
Rong Xu0698de92016-05-13 17:26:06 +0000130
131// Command line option to enable/disable the warning about a hash mismatch in
132// the profile data.
133static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
134 cl::Hidden);
135
Rong Xuf430ae42015-12-09 18:08:16 +0000136namespace {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000137class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000138public:
139 static char ID;
140
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000141 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000142 initializePGOInstrumentationGenLegacyPassPass(
143 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000144 }
145
146 const char *getPassName() const override {
147 return "PGOInstrumentationGenPass";
148 }
149
150private:
151 bool runOnModule(Module &M) override;
152
153 void getAnalysisUsage(AnalysisUsage &AU) const override {
154 AU.addRequired<BlockFrequencyInfoWrapperPass>();
155 }
156};
157
Xinliang David Lid55827f2016-05-07 05:39:12 +0000158class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000159public:
160 static char ID;
161
162 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000163 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000164 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000165 if (!PGOTestProfileFile.empty())
166 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000167 initializePGOInstrumentationUseLegacyPassPass(
168 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000169 }
170
171 const char *getPassName() const override {
172 return "PGOInstrumentationUsePass";
173 }
174
175private:
176 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000177
Xinliang David Lida195582016-05-10 21:59:52 +0000178 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000179 void getAnalysisUsage(AnalysisUsage &AU) const override {
180 AU.addRequired<BlockFrequencyInfoWrapperPass>();
181 }
182};
183} // end anonymous namespace
184
Xinliang David Li8aebf442016-05-06 05:49:19 +0000185char PGOInstrumentationGenLegacyPass::ID = 0;
186INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000187 "PGO instrumentation.", false, false)
188INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
189INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000190INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000191 "PGO instrumentation.", false, false)
192
Xinliang David Li8aebf442016-05-06 05:49:19 +0000193ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
194 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000195}
196
Xinliang David Lid55827f2016-05-07 05:39:12 +0000197char PGOInstrumentationUseLegacyPass::ID = 0;
198INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000199 "Read PGO instrumentation profile.", false, false)
200INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
201INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000202INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000203 "Read PGO instrumentation profile.", false, false)
204
Xinliang David Lid55827f2016-05-07 05:39:12 +0000205ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
206 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000207}
208
209namespace {
210/// \brief An MST based instrumentation for PGO
211///
212/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
213/// in the function level.
214struct PGOEdge {
215 // This class implements the CFG edges. Note the CFG can be a multi-graph.
216 // So there might be multiple edges with same SrcBB and DestBB.
217 const BasicBlock *SrcBB;
218 const BasicBlock *DestBB;
219 uint64_t Weight;
220 bool InMST;
221 bool Removed;
222 bool IsCritical;
223 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
224 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
225 IsCritical(false) {}
226 // Return the information string of an edge.
227 const std::string infoString() const {
228 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
229 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
230 }
231};
232
233// This class stores the auxiliary information for each BB.
234struct BBInfo {
235 BBInfo *Group;
236 uint32_t Index;
237 uint32_t Rank;
238
239 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
240
241 // Return the information string of this object.
242 const std::string infoString() const {
243 return (Twine("Index=") + Twine(Index)).str();
244 }
245};
246
247// This class implements the CFG edges. Note the CFG can be a multi-graph.
248template <class Edge, class BBInfo> class FuncPGOInstrumentation {
249private:
250 Function &F;
251 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000252 void renameComdatFunction();
253 // A map that stores the Comdat group in function F.
254 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000255
256public:
257 std::string FuncName;
258 GlobalVariable *FuncNameVar;
259 // CFG hash value for this function.
260 uint64_t FunctionHash;
261
262 // The Minimum Spanning Tree of function CFG.
263 CFGMST<Edge, BBInfo> MST;
264
265 // Give an edge, find the BB that will be instrumented.
266 // Return nullptr if there is no BB to be instrumented.
267 BasicBlock *getInstrBB(Edge *E);
268
269 // Return the auxiliary BB information.
270 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
271
272 // Dump edges and BB information.
273 void dumpInfo(std::string Str = "") const {
274 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000275 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000276 }
277
Rong Xu705f7772016-07-25 18:45:37 +0000278 FuncPGOInstrumentation(
279 Function &Func,
280 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
281 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
282 BlockFrequencyInfo *BFI = nullptr)
283 : F(Func), ComdatMembers(ComdatMembers), FunctionHash(0),
284 MST(F, BPI, BFI) {
Rong Xuf430ae42015-12-09 18:08:16 +0000285 FuncName = getPGOFuncName(F);
286 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000287 if (ComdatMembers.size())
288 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000289 DEBUG(dumpInfo("after CFGMST"));
290
291 NumOfPGOBB += MST.BBInfos.size();
292 for (auto &E : MST.AllEdges) {
293 if (E->Removed)
294 continue;
295 NumOfPGOEdge++;
296 if (!E->InMST)
297 NumOfPGOInstrument++;
298 }
299
300 if (CreateGlobalVar)
301 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000302 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000303
304 // Return the number of profile counters needed for the function.
305 unsigned getNumCounters() {
306 unsigned NumCounters = 0;
307 for (auto &E : this->MST.AllEdges) {
308 if (!E->InMST && !E->Removed)
309 NumCounters++;
310 }
311 return NumCounters;
312 }
Rong Xuf430ae42015-12-09 18:08:16 +0000313};
314
315// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
316// value of each BB in the CFG. The higher 32 bits record the number of edges.
317template <class Edge, class BBInfo>
318void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
319 std::vector<char> Indexes;
320 JamCRC JC;
321 for (auto &BB : F) {
322 const TerminatorInst *TI = BB.getTerminator();
323 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
324 BasicBlock *Succ = TI->getSuccessor(I);
325 uint32_t Index = getBBInfo(Succ).Index;
326 for (int J = 0; J < 4; J++)
327 Indexes.push_back((char)(Index >> (J * 8)));
328 }
329 }
330 JC.update(Indexes);
Rong Xu705f7772016-07-25 18:45:37 +0000331 FunctionHash = (uint64_t)findIndirectCallSites(F).size() << 48 |
332 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
333}
334
335// Check if we can safely rename this Comdat function.
336static bool canRenameComdat(
337 Function &F,
338 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
339 if (F.getName().empty())
340 return false;
341 if (!needsComdatForCounter(F, *(F.getParent())))
342 return false;
343 // Only safe to do if this function may be discarded if it is not used
344 // in the compilation unit.
345 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
346 return false;
347
348 // For AvailableExternallyLinkage functions.
349 if (!F.hasComdat()) {
350 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
351 return true;
352 }
353
354 // FIXME: Current only handle those Comdat groups that only containing one
355 // function and function aliases.
356 // (1) For a Comdat group containing multiple functions, we need to have a
357 // unique postfix based on the hashes for each function. There is a
358 // non-trivial code refactoring to do this efficiently.
359 // (2) Variables can not be renamed, so we can not rename Comdat function in a
360 // group including global vars.
361 Comdat *C = F.getComdat();
362 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
363 if (dyn_cast<GlobalAlias>(CM.second))
364 continue;
365 Function *FM = dyn_cast<Function>(CM.second);
366 if (FM != &F)
367 return false;
368 }
369 return true;
370}
371
372// Append the CFGHash to the Comdat function name.
373template <class Edge, class BBInfo>
374void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
375 if (!canRenameComdat(F, ComdatMembers))
376 return;
377 std::string NewFuncName =
378 Twine(F.getName() + "." + Twine(FunctionHash)).str();
379 F.setName(Twine(NewFuncName));
380 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
381 Comdat *NewComdat;
382 Module *M = F.getParent();
383 // For AvailableExternallyLinkage functions, change the linkage to
384 // LinkOnceODR and put them into comdat. This is because after renaming, there
385 // is no backup external copy available for the function.
386 if (!F.hasComdat()) {
387 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
388 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
389 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
390 F.setComdat(NewComdat);
391 return;
392 }
393
394 // This function belongs to a single function Comdat group.
395 Comdat *OrigComdat = F.getComdat();
396 std::string NewComdatName =
397 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
398 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
399 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
400
401 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
402 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
403 // For aliases, change the name directly.
404 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
405 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
406 continue;
407 }
408 // Must be a function.
409 Function *CF = dyn_cast<Function>(CM.second);
410 assert(CF);
411 CF->setComdat(NewComdat);
412 }
Rong Xuf430ae42015-12-09 18:08:16 +0000413}
414
415// Given a CFG E to be instrumented, find which BB to place the instrumented
416// code. The function will split the critical edge if necessary.
417template <class Edge, class BBInfo>
418BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
419 if (E->InMST || E->Removed)
420 return nullptr;
421
422 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
423 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
424 // For a fake edge, instrument the real BB.
425 if (SrcBB == nullptr)
426 return DestBB;
427 if (DestBB == nullptr)
428 return SrcBB;
429
430 // Instrument the SrcBB if it has a single successor,
431 // otherwise, the DestBB if this is not a critical edge.
432 TerminatorInst *TI = SrcBB->getTerminator();
433 if (TI->getNumSuccessors() <= 1)
434 return SrcBB;
435 if (!E->IsCritical)
436 return DestBB;
437
438 // For a critical edge, we have to split. Instrument the newly
439 // created BB.
440 NumOfPGOSplit++;
441 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
442 << getBBInfo(DestBB).Index << "\n");
443 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
444 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
445 assert(InstrBB && "Critical edge is not split");
446
447 E->Removed = true;
448 return InstrBB;
449}
450
Rong Xued9fec72016-01-21 18:11:44 +0000451// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000452// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000453static void instrumentOneFunc(
454 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
455 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000456 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
457 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000458 unsigned NumCounters = FuncInfo.getNumCounters();
459
Rong Xuf430ae42015-12-09 18:08:16 +0000460 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000461 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000462 for (auto &E : FuncInfo.MST.AllEdges) {
463 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
464 if (!InstrBB)
465 continue;
466
467 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
468 assert(Builder.GetInsertPoint() != InstrBB->end() &&
469 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000470 Builder.CreateCall(
471 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
472 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
473 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
474 Builder.getInt32(I++)});
475 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000476 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000477
478 if (DisableValueProfiling)
479 return;
480
481 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000482 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000483 CallSite CS(I);
484 Value *Callee = CS.getCalledValue();
485 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
486 << NumIndirectCallSites << "\n");
487 IRBuilder<> Builder(I);
488 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
489 "Cannot get the Instrumentation point");
490 Builder.CreateCall(
491 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
492 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
493 Builder.getInt64(FuncInfo.FunctionHash),
494 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
495 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
496 Builder.getInt32(NumIndirectCallSites++)});
497 }
498 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000499}
500
501// This class represents a CFG edge in profile use compilation.
502struct PGOUseEdge : public PGOEdge {
503 bool CountValid;
504 uint64_t CountValue;
505 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
506 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
507
508 // Set edge count value
509 void setEdgeCount(uint64_t Value) {
510 CountValue = Value;
511 CountValid = true;
512 }
513
514 // Return the information string for this object.
515 const std::string infoString() const {
516 if (!CountValid)
517 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000518 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
519 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000520 }
521};
522
523typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
524
525// This class stores the auxiliary information for each BB.
526struct UseBBInfo : public BBInfo {
527 uint64_t CountValue;
528 bool CountValid;
529 int32_t UnknownCountInEdge;
530 int32_t UnknownCountOutEdge;
531 DirectEdges InEdges;
532 DirectEdges OutEdges;
533 UseBBInfo(unsigned IX)
534 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
535 UnknownCountOutEdge(0) {}
536 UseBBInfo(unsigned IX, uint64_t C)
537 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
538 UnknownCountOutEdge(0) {}
539
540 // Set the profile count value for this BB.
541 void setBBInfoCount(uint64_t Value) {
542 CountValue = Value;
543 CountValid = true;
544 }
545
546 // Return the information string of this object.
547 const std::string infoString() const {
548 if (!CountValid)
549 return BBInfo::infoString();
550 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
551 }
552};
553
554// Sum up the count values for all the edges.
555static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
556 uint64_t Total = 0;
557 for (auto &E : Edges) {
558 if (E->Removed)
559 continue;
560 Total += E->CountValue;
561 }
562 return Total;
563}
564
565class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000566public:
Rong Xu705f7772016-07-25 18:45:37 +0000567 PGOUseFunc(Function &Func, Module *Modu,
568 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
569 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000570 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000571 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000572 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000573
574 // Read counts for the instrumented BB from profile.
575 bool readCounters(IndexedInstrProfReader *PGOReader);
576
577 // Populate the counts for all BBs.
578 void populateCounters();
579
580 // Set the branch weights based on the count values.
581 void setBranchWeights();
582
583 // Annotate the indirect call sites.
584 void annotateIndirectCallSites();
585
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000586 // The hotness of the function from the profile count.
587 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
588
589 // Return the function hotness from the profile.
590 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
591
Rong Xu705f7772016-07-25 18:45:37 +0000592 // Return the function hash.
593 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000594 // Return the profile record for this function;
595 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
596
Rong Xuf430ae42015-12-09 18:08:16 +0000597private:
598 Function &F;
599 Module *M;
600 // This member stores the shared information with class PGOGenFunc.
601 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
602
603 // Return the auxiliary BB information.
604 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
605 return FuncInfo.getBBInfo(BB);
606 }
607
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000608 // The maximum count value in the profile. This is only used in PGO use
609 // compilation.
610 uint64_t ProgramMaxCount;
611
Rong Xu13b01dc2016-02-10 18:24:45 +0000612 // ProfileRecord for this function.
613 InstrProfRecord ProfileRecord;
614
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000615 // Function hotness info derived from profile.
616 FuncFreqAttr FreqAttr;
617
Rong Xuf430ae42015-12-09 18:08:16 +0000618 // Find the Instrumented BB and set the value.
619 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
620
621 // Set the edge counter value for the unknown edge -- there should be only
622 // one unknown edge.
623 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
624
625 // Return FuncName string;
626 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000627
628 // Set the hot/cold inline hints based on the count values.
629 // FIXME: This function should be removed once the functionality in
630 // the inliner is implemented.
631 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
632 if (ProgramMaxCount == 0)
633 return;
634 // Threshold of the hot functions.
635 const BranchProbability HotFunctionThreshold(1, 100);
636 // Threshold of the cold functions.
637 const BranchProbability ColdFunctionThreshold(2, 10000);
638 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
639 FreqAttr = FFA_Hot;
640 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
641 FreqAttr = FFA_Cold;
642 }
Rong Xuf430ae42015-12-09 18:08:16 +0000643};
644
645// Visit all the edges and assign the count value for the instrumented
646// edges and the BB.
647void PGOUseFunc::setInstrumentedCounts(
648 const std::vector<uint64_t> &CountFromProfile) {
649
Xinliang David Lid1197612016-08-01 20:25:06 +0000650 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000651 // Use a worklist as we will update the vector during the iteration.
652 std::vector<PGOUseEdge *> WorkList;
653 for (auto &E : FuncInfo.MST.AllEdges)
654 WorkList.push_back(E.get());
655
656 uint32_t I = 0;
657 for (auto &E : WorkList) {
658 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
659 if (!InstrBB)
660 continue;
661 uint64_t CountValue = CountFromProfile[I++];
662 if (!E->Removed) {
663 getBBInfo(InstrBB).setBBInfoCount(CountValue);
664 E->setEdgeCount(CountValue);
665 continue;
666 }
667
668 // Need to add two new edges.
669 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
670 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
671 // Add new edge of SrcBB->InstrBB.
672 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
673 NewEdge.setEdgeCount(CountValue);
674 // Add new edge of InstrBB->DestBB.
675 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
676 NewEdge1.setEdgeCount(CountValue);
677 NewEdge1.InMST = true;
678 getBBInfo(InstrBB).setBBInfoCount(CountValue);
679 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000680 assert(I == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000681}
682
683// Set the count value for the unknown edge. There should be one and only one
684// unknown edge in Edges vector.
685void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
686 for (auto &E : Edges) {
687 if (E->CountValid)
688 continue;
689 E->setEdgeCount(Value);
690
691 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
692 getBBInfo(E->DestBB).UnknownCountInEdge--;
693 return;
694 }
695 llvm_unreachable("Cannot find the unknown count edge");
696}
697
698// Read the profile from ProfileFileName and assign the value to the
699// instrumented BB and the edges. This function also updates ProgramMaxCount.
700// Return true if the profile are successfully read, and false on errors.
701bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
702 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000703 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000704 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000705 if (Error E = Result.takeError()) {
706 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
707 auto Err = IPE.get();
708 bool SkipWarning = false;
709 if (Err == instrprof_error::unknown_function) {
710 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000711 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000712 } else if (Err == instrprof_error::hash_mismatch ||
713 Err == instrprof_error::malformed) {
714 NumOfPGOMismatch++;
715 SkipWarning = NoPGOWarnMismatch;
716 }
Rong Xuf430ae42015-12-09 18:08:16 +0000717
Vedant Kumar9152fd12016-05-19 03:54:45 +0000718 if (SkipWarning)
719 return;
720
721 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
722 Ctx.diagnose(
723 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
724 });
Rong Xuf430ae42015-12-09 18:08:16 +0000725 return false;
726 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000727 ProfileRecord = std::move(Result.get());
728 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000729
730 NumOfPGOFunc++;
731 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
732 uint64_t ValueSum = 0;
733 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
734 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
735 ValueSum += CountFromProfile[I];
736 }
737
738 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
739
740 getBBInfo(nullptr).UnknownCountOutEdge = 2;
741 getBBInfo(nullptr).UnknownCountInEdge = 2;
742
743 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000744 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000745 return true;
746}
747
748// Populate the counters from instrumented BBs to all BBs.
749// In the end of this operation, all BBs should have a valid count value.
750void PGOUseFunc::populateCounters() {
751 // First set up Count variable for all BBs.
752 for (auto &E : FuncInfo.MST.AllEdges) {
753 if (E->Removed)
754 continue;
755
756 const BasicBlock *SrcBB = E->SrcBB;
757 const BasicBlock *DestBB = E->DestBB;
758 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
759 UseBBInfo &DestInfo = getBBInfo(DestBB);
760 SrcInfo.OutEdges.push_back(E.get());
761 DestInfo.InEdges.push_back(E.get());
762 SrcInfo.UnknownCountOutEdge++;
763 DestInfo.UnknownCountInEdge++;
764
765 if (!E->CountValid)
766 continue;
767 DestInfo.UnknownCountInEdge--;
768 SrcInfo.UnknownCountOutEdge--;
769 }
770
771 bool Changes = true;
772 unsigned NumPasses = 0;
773 while (Changes) {
774 NumPasses++;
775 Changes = false;
776
777 // For efficient traversal, it's better to start from the end as most
778 // of the instrumented edges are at the end.
779 for (auto &BB : reverse(F)) {
780 UseBBInfo &Count = getBBInfo(&BB);
781 if (!Count.CountValid) {
782 if (Count.UnknownCountOutEdge == 0) {
783 Count.CountValue = sumEdgeCount(Count.OutEdges);
784 Count.CountValid = true;
785 Changes = true;
786 } else if (Count.UnknownCountInEdge == 0) {
787 Count.CountValue = sumEdgeCount(Count.InEdges);
788 Count.CountValid = true;
789 Changes = true;
790 }
791 }
792 if (Count.CountValid) {
793 if (Count.UnknownCountOutEdge == 1) {
794 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
795 setEdgeCount(Count.OutEdges, Total);
796 Changes = true;
797 }
798 if (Count.UnknownCountInEdge == 1) {
799 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
800 setEdgeCount(Count.InEdges, Total);
801 Changes = true;
802 }
803 }
804 }
805 }
806
807 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000808#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000809 // Assert every BB has a valid counter.
Sean Silva8c7e1212016-05-28 04:19:45 +0000810 for (auto &BB : F)
811 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
812#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000813 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000814 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000815 uint64_t FuncMaxCount = FuncEntryCount;
Sean Silva8c7e1212016-05-28 04:19:45 +0000816 for (auto &BB : F)
817 FuncMaxCount = std::max(FuncMaxCount, getBBInfo(&BB).CountValue);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000818 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000819
820 DEBUG(FuncInfo.dumpInfo("after reading profile."));
821}
822
Xinliang David Li2c933682016-08-19 05:31:33 +0000823static void setProfMetadata(Module *M, TerminatorInst *TI,
824 ArrayRef<unsigned> EdgeCounts, uint64_t MaxCount) {
825 MDBuilder MDB(M->getContext());
826 assert(MaxCount > 0 && "Bad max count");
827 uint64_t Scale = calculateCountScale(MaxCount);
828 SmallVector<unsigned, 4> Weights;
829 for (const auto &ECI : EdgeCounts)
830 Weights.push_back(scaleBranchCount(ECI, Scale));
831
832 DEBUG(dbgs() << "Weight is: ";
833 for (const auto &W : Weights) { dbgs() << W << " "; }
834 dbgs() << "\n";);
835 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
836}
837
Rong Xuf430ae42015-12-09 18:08:16 +0000838// Assign the scaled count values to the BB with multiple out edges.
839void PGOUseFunc::setBranchWeights() {
840 // Generate MD_prof metadata for every branch instruction.
841 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000842 for (auto &BB : F) {
843 TerminatorInst *TI = BB.getTerminator();
844 if (TI->getNumSuccessors() < 2)
845 continue;
846 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
847 continue;
848 if (getBBInfo(&BB).CountValue == 0)
849 continue;
850
851 // We have a non-zero Branch BB.
852 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
853 unsigned Size = BBCountInfo.OutEdges.size();
854 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
855 uint64_t MaxCount = 0;
856 for (unsigned s = 0; s < Size; s++) {
857 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
858 const BasicBlock *SrcBB = E->SrcBB;
859 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000860 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000861 continue;
862 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
863 uint64_t EdgeCount = E->CountValue;
864 if (EdgeCount > MaxCount)
865 MaxCount = EdgeCount;
866 EdgeCounts[SuccNum] = EdgeCount;
867 }
Xinliang David Li2c933682016-08-19 05:31:33 +0000868 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000869 }
870}
Rong Xu13b01dc2016-02-10 18:24:45 +0000871
872// Traverse all the indirect callsites and annotate the instructions.
873void PGOUseFunc::annotateIndirectCallSites() {
874 if (DisableValueProfiling)
875 return;
876
Rong Xu8e8fe852016-04-01 16:43:30 +0000877 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +0000878 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +0000879
Rong Xu13b01dc2016-02-10 18:24:45 +0000880 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000881 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000882 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000883 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +0000884 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000885 std::string Msg =
886 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000887 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000888 auto &Ctx = M->getContext();
889 Ctx.diagnose(
890 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
891 return;
892 }
893
Rong Xu0eb36032016-04-01 23:16:44 +0000894 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000895 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000896 << IndirectCallSiteIndex << " out of " << NumValueSites
897 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000898 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000899 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000900 IndirectCallSiteIndex++;
901 }
902}
Rong Xuf430ae42015-12-09 18:08:16 +0000903} // end anonymous namespace
904
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000905// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +0000906// aware this is an ir_level profile so it can set the version flag.
907static void createIRLevelProfileFlagVariable(Module &M) {
908 Type *IntTy64 = Type::getInt64Ty(M.getContext());
909 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000910 auto IRLevelVersionVariable = new GlobalVariable(
911 M, IntTy64, true, GlobalVariable::ExternalLinkage,
912 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000913 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000914 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
915 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +0000916 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +0000917 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +0000918 else
Rong Xu9e926e82016-02-29 19:16:04 +0000919 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000920 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000921}
922
Rong Xu705f7772016-07-25 18:45:37 +0000923// Collect the set of members for each Comdat in module M and store
924// in ComdatMembers.
925static void collectComdatMembers(
926 Module &M,
927 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
928 if (!DoComdatRenaming)
929 return;
930 for (Function &F : M)
931 if (Comdat *C = F.getComdat())
932 ComdatMembers.insert(std::make_pair(C, &F));
933 for (GlobalVariable &GV : M.globals())
934 if (Comdat *C = GV.getComdat())
935 ComdatMembers.insert(std::make_pair(C, &GV));
936 for (GlobalAlias &GA : M.aliases())
937 if (Comdat *C = GA.getComdat())
938 ComdatMembers.insert(std::make_pair(C, &GA));
939}
940
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000941static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000942 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
943 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +0000944 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +0000945 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
946 collectComdatMembers(M, ComdatMembers);
947
Rong Xuf430ae42015-12-09 18:08:16 +0000948 for (auto &F : M) {
949 if (F.isDeclaration())
950 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000951 auto *BPI = LookupBPI(F);
952 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +0000953 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +0000954 }
955 return true;
956}
957
Xinliang David Li8aebf442016-05-06 05:49:19 +0000958bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000959 if (skipModule(M))
960 return false;
961
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000962 auto LookupBPI = [this](Function &F) {
963 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000964 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000965 auto LookupBFI = [this](Function &F) {
966 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000967 };
968 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
969}
970
Xinliang David Li8aebf442016-05-06 05:49:19 +0000971PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000972 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000973
974 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000975 auto LookupBPI = [&FAM](Function &F) {
976 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000977 };
978
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000979 auto LookupBFI = [&FAM](Function &F) {
980 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000981 };
982
983 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
984 return PreservedAnalyses::all();
985
986 return PreservedAnalyses::none();
987}
988
Xinliang David Lida195582016-05-10 21:59:52 +0000989static bool annotateAllFunctions(
990 Module &M, StringRef ProfileFileName,
991 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000992 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +0000993 DEBUG(dbgs() << "Read in profile counters: ");
994 auto &Ctx = M.getContext();
995 // Read the counter array from file.
996 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000997 if (Error E = ReaderOrErr.takeError()) {
998 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
999 Ctx.diagnose(
1000 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1001 });
Rong Xuf430ae42015-12-09 18:08:16 +00001002 return false;
1003 }
1004
Xinliang David Lida195582016-05-10 21:59:52 +00001005 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1006 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001007 if (!PGOReader) {
1008 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001009 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001010 return false;
1011 }
Rong Xu33c76c02016-02-10 17:18:30 +00001012 // TODO: might need to change the warning once the clang option is finalized.
1013 if (!PGOReader->isIRLevelProfile()) {
1014 Ctx.diagnose(DiagnosticInfoPGOProfile(
1015 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1016 return false;
1017 }
1018
Rong Xu705f7772016-07-25 18:45:37 +00001019 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1020 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001021 std::vector<Function *> HotFunctions;
1022 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001023 for (auto &F : M) {
1024 if (F.isDeclaration())
1025 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001026 auto *BPI = LookupBPI(F);
1027 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001028 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001029 if (!Func.readCounters(PGOReader.get()))
1030 continue;
1031 Func.populateCounters();
1032 Func.setBranchWeights();
1033 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001034 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1035 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001036 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001037 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1038 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001039 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001040 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001041 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001042 // We have to apply these attributes at the end because their presence
1043 // can affect the BranchProbabilityInfo of any callers, resulting in an
1044 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001045 for (auto &F : HotFunctions) {
1046 F->addFnAttr(llvm::Attribute::InlineHint);
1047 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1048 << "\n");
1049 }
1050 for (auto &F : ColdFunctions) {
1051 F->addFnAttr(llvm::Attribute::Cold);
1052 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1053 }
Rong Xuf430ae42015-12-09 18:08:16 +00001054 return true;
1055}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001056
Xinliang David Lida195582016-05-10 21:59:52 +00001057PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001058 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001059 if (!PGOTestProfileFile.empty())
1060 ProfileFileName = PGOTestProfileFile;
1061}
1062
1063PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001064 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001065
1066 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1067 auto LookupBPI = [&FAM](Function &F) {
1068 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1069 };
1070
1071 auto LookupBFI = [&FAM](Function &F) {
1072 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1073 };
1074
1075 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1076 return PreservedAnalyses::all();
1077
1078 return PreservedAnalyses::none();
1079}
1080
Xinliang David Lid55827f2016-05-07 05:39:12 +00001081bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1082 if (skipModule(M))
1083 return false;
1084
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001085 auto LookupBPI = [this](Function &F) {
1086 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001087 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001088 auto LookupBFI = [this](Function &F) {
1089 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001090 };
1091
Xinliang David Lida195582016-05-10 21:59:52 +00001092 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001093}