blob: 4d6a5048797f1f6b357ff9220a908bd653904f90 [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.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000089STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000090STATISTIC(NumOfPGOEdge, "Number of edges.");
91STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
92STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
93STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
94STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
95STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000096STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000097
98// Command line option to specify the file to read profile from. This is
99// mainly used for testing.
100static cl::opt<std::string>
101 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
102 cl::value_desc("filename"),
103 cl::desc("Specify the path of profile data file. This is"
104 "mainly for test purpose."));
105
Rong Xuecdc98f2016-03-04 22:08:44 +0000106// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000107// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000108static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
109 cl::Hidden,
110 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000111
Rong Xuecdc98f2016-03-04 22:08:44 +0000112// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000113// the metadata for a single indirect call callsite.
114static cl::opt<unsigned> MaxNumAnnotations(
115 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
116 cl::desc("Max number of annotations for a single indirect "
117 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000118
Rong Xu705f7772016-07-25 18:45:37 +0000119// Command line option to control appending FunctionHash to the name of a COMDAT
120// function. This is to avoid the hash mismatch caused by the preinliner.
121static cl::opt<bool> DoComdatRenaming(
122 "do-comdat-renaming", cl::init(true), cl::Hidden,
123 cl::desc("Append function hash to the name of COMDAT function to avoid "
124 "function hash mismatch due to the preinliner"));
125
Rong Xu0698de92016-05-13 17:26:06 +0000126// Command line option to enable/disable the warning about missing profile
127// information.
Xinliang David Li76a01082016-08-11 05:09:30 +0000128static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function",
129 cl::init(false),
130 cl::Hidden);
Rong Xu0698de92016-05-13 17:26:06 +0000131
132// Command line option to enable/disable the warning about a hash mismatch in
133// the profile data.
134static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
135 cl::Hidden);
136
Xinliang David Li4ca17332016-09-18 18:34:07 +0000137// Command line option to enable/disable select instruction instrumentation.
138static cl::opt<bool> PGOInstrSelect("pgo-instr-select", cl::init(true),
139 cl::Hidden);
Rong Xuf430ae42015-12-09 18:08:16 +0000140namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000141
142/// The select instruction visitor plays three roles specified
143/// by the mode. In \c VM_counting mode, it simply counts the number of
144/// select instructions. In \c VM_instrument mode, it inserts code to count
145/// the number times TrueValue of select is taken. In \c VM_annotate mode,
146/// it reads the profile data and annotate the select instruction with metadata.
147enum VisitMode { VM_counting, VM_instrument, VM_annotate };
148class PGOUseFunc;
149
150/// Instruction Visitor class to visit select instructions.
151struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
152 Function &F;
153 unsigned NSIs = 0; // Number of select instructions instrumented.
154 VisitMode Mode = VM_counting; // Visiting mode.
155 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
156 unsigned TotalNumCtrs = 0; // Total number of counters
157 GlobalVariable *FuncNameVar = nullptr;
158 uint64_t FuncHash = 0;
159 PGOUseFunc *UseFunc = nullptr;
160
161 SelectInstVisitor(Function &Func) : F(Func) {}
162
163 void countSelects(Function &Func) {
164 Mode = VM_counting;
165 visit(Func);
166 }
167 // Visit the IR stream and instrument all select instructions. \p
168 // Ind is a pointer to the counter index variable; \p TotalNC
169 // is the total number of counters; \p FNV is the pointer to the
170 // PGO function name var; \p FHash is the function hash.
171 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
172 GlobalVariable *FNV, uint64_t FHash) {
173 Mode = VM_instrument;
174 CurCtrIdx = Ind;
175 TotalNumCtrs = TotalNC;
176 FuncHash = FHash;
177 FuncNameVar = FNV;
178 visit(Func);
179 }
180
181 // Visit the IR stream and annotate all select instructions.
182 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
183 Mode = VM_annotate;
184 UseFunc = UF;
185 CurCtrIdx = Ind;
186 visit(Func);
187 }
188
189 void instrumentOneSelectInst(SelectInst &SI);
190 void annotateOneSelectInst(SelectInst &SI);
191 // Visit \p SI instruction and perform tasks according to visit mode.
192 void visitSelectInst(SelectInst &SI);
193 unsigned getNumOfSelectInsts() const { return NSIs; }
194};
195
Xinliang David Li8aebf442016-05-06 05:49:19 +0000196class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000197public:
198 static char ID;
199
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000200 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000201 initializePGOInstrumentationGenLegacyPassPass(
202 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000203 }
204
Mehdi Amini117296c2016-10-01 02:56:57 +0000205 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000206
207private:
208 bool runOnModule(Module &M) override;
209
210 void getAnalysisUsage(AnalysisUsage &AU) const override {
211 AU.addRequired<BlockFrequencyInfoWrapperPass>();
212 }
213};
214
Xinliang David Lid55827f2016-05-07 05:39:12 +0000215class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000216public:
217 static char ID;
218
219 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000220 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000221 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000222 if (!PGOTestProfileFile.empty())
223 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000224 initializePGOInstrumentationUseLegacyPassPass(
225 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000226 }
227
Mehdi Amini117296c2016-10-01 02:56:57 +0000228 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000229
230private:
231 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000232
Xinliang David Lida195582016-05-10 21:59:52 +0000233 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<BlockFrequencyInfoWrapperPass>();
236 }
237};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000238
Rong Xuf430ae42015-12-09 18:08:16 +0000239} // end anonymous namespace
240
Xinliang David Li8aebf442016-05-06 05:49:19 +0000241char PGOInstrumentationGenLegacyPass::ID = 0;
242INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000243 "PGO instrumentation.", false, false)
244INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
245INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000246INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000247 "PGO instrumentation.", false, false)
248
Xinliang David Li8aebf442016-05-06 05:49:19 +0000249ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
250 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000251}
252
Xinliang David Lid55827f2016-05-07 05:39:12 +0000253char PGOInstrumentationUseLegacyPass::ID = 0;
254INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000255 "Read PGO instrumentation profile.", false, false)
256INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
257INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000258INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000259 "Read PGO instrumentation profile.", false, false)
260
Xinliang David Lid55827f2016-05-07 05:39:12 +0000261ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
262 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000263}
264
265namespace {
266/// \brief An MST based instrumentation for PGO
267///
268/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
269/// in the function level.
270struct PGOEdge {
271 // This class implements the CFG edges. Note the CFG can be a multi-graph.
272 // So there might be multiple edges with same SrcBB and DestBB.
273 const BasicBlock *SrcBB;
274 const BasicBlock *DestBB;
275 uint64_t Weight;
276 bool InMST;
277 bool Removed;
278 bool IsCritical;
279 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
280 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
281 IsCritical(false) {}
282 // Return the information string of an edge.
283 const std::string infoString() const {
284 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
285 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
286 }
287};
288
289// This class stores the auxiliary information for each BB.
290struct BBInfo {
291 BBInfo *Group;
292 uint32_t Index;
293 uint32_t Rank;
294
295 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
296
297 // Return the information string of this object.
298 const std::string infoString() const {
299 return (Twine("Index=") + Twine(Index)).str();
300 }
301};
302
303// This class implements the CFG edges. Note the CFG can be a multi-graph.
304template <class Edge, class BBInfo> class FuncPGOInstrumentation {
305private:
306 Function &F;
307 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000308 void renameComdatFunction();
309 // A map that stores the Comdat group in function F.
310 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000311
312public:
Xinliang David Li9780fc12016-09-20 22:39:47 +0000313 std::vector<Instruction *> IndirectCallSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000314 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000315 std::string FuncName;
316 GlobalVariable *FuncNameVar;
317 // CFG hash value for this function.
318 uint64_t FunctionHash;
319
320 // The Minimum Spanning Tree of function CFG.
321 CFGMST<Edge, BBInfo> MST;
322
323 // Give an edge, find the BB that will be instrumented.
324 // Return nullptr if there is no BB to be instrumented.
325 BasicBlock *getInstrBB(Edge *E);
326
327 // Return the auxiliary BB information.
328 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
329
330 // Dump edges and BB information.
331 void dumpInfo(std::string Str = "") const {
332 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000333 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000334 }
335
Rong Xu705f7772016-07-25 18:45:37 +0000336 FuncPGOInstrumentation(
337 Function &Func,
338 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
339 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
340 BlockFrequencyInfo *BFI = nullptr)
Xinliang David Li4ca17332016-09-18 18:34:07 +0000341 : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
Rong Xu705f7772016-07-25 18:45:37 +0000342 MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000343
344 // This should be done before CFG hash computation.
345 SIVisitor.countSelects(Func);
346 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Xinliang David Li9780fc12016-09-20 22:39:47 +0000347 IndirectCallSites = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000348
Rong Xuf430ae42015-12-09 18:08:16 +0000349 FuncName = getPGOFuncName(F);
350 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000351 if (ComdatMembers.size())
352 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000353 DEBUG(dumpInfo("after CFGMST"));
354
355 NumOfPGOBB += MST.BBInfos.size();
356 for (auto &E : MST.AllEdges) {
357 if (E->Removed)
358 continue;
359 NumOfPGOEdge++;
360 if (!E->InMST)
361 NumOfPGOInstrument++;
362 }
363
364 if (CreateGlobalVar)
365 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000366 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000367
368 // Return the number of profile counters needed for the function.
369 unsigned getNumCounters() {
370 unsigned NumCounters = 0;
371 for (auto &E : this->MST.AllEdges) {
372 if (!E->InMST && !E->Removed)
373 NumCounters++;
374 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000375 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000376 }
Rong Xuf430ae42015-12-09 18:08:16 +0000377};
378
379// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
380// value of each BB in the CFG. The higher 32 bits record the number of edges.
381template <class Edge, class BBInfo>
382void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
383 std::vector<char> Indexes;
384 JamCRC JC;
385 for (auto &BB : F) {
386 const TerminatorInst *TI = BB.getTerminator();
387 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
388 BasicBlock *Succ = TI->getSuccessor(I);
389 uint32_t Index = getBBInfo(Succ).Index;
390 for (int J = 0; J < 4; J++)
391 Indexes.push_back((char)(Index >> (J * 8)));
392 }
393 }
394 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000395 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Xinliang David Li9780fc12016-09-20 22:39:47 +0000396 (uint64_t)IndirectCallSites.size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000397 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
398}
399
400// Check if we can safely rename this Comdat function.
401static bool canRenameComdat(
402 Function &F,
403 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
404 if (F.getName().empty())
405 return false;
406 if (!needsComdatForCounter(F, *(F.getParent())))
407 return false;
408 // Only safe to do if this function may be discarded if it is not used
409 // in the compilation unit.
410 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
411 return false;
412
413 // For AvailableExternallyLinkage functions.
414 if (!F.hasComdat()) {
415 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
416 return true;
417 }
418
419 // FIXME: Current only handle those Comdat groups that only containing one
420 // function and function aliases.
421 // (1) For a Comdat group containing multiple functions, we need to have a
422 // unique postfix based on the hashes for each function. There is a
423 // non-trivial code refactoring to do this efficiently.
424 // (2) Variables can not be renamed, so we can not rename Comdat function in a
425 // group including global vars.
426 Comdat *C = F.getComdat();
427 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
428 if (dyn_cast<GlobalAlias>(CM.second))
429 continue;
430 Function *FM = dyn_cast<Function>(CM.second);
431 if (FM != &F)
432 return false;
433 }
434 return true;
435}
436
437// Append the CFGHash to the Comdat function name.
438template <class Edge, class BBInfo>
439void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
440 if (!canRenameComdat(F, ComdatMembers))
441 return;
442 std::string NewFuncName =
443 Twine(F.getName() + "." + Twine(FunctionHash)).str();
444 F.setName(Twine(NewFuncName));
445 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
446 Comdat *NewComdat;
447 Module *M = F.getParent();
448 // For AvailableExternallyLinkage functions, change the linkage to
449 // LinkOnceODR and put them into comdat. This is because after renaming, there
450 // is no backup external copy available for the function.
451 if (!F.hasComdat()) {
452 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
453 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
454 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
455 F.setComdat(NewComdat);
456 return;
457 }
458
459 // This function belongs to a single function Comdat group.
460 Comdat *OrigComdat = F.getComdat();
461 std::string NewComdatName =
462 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
463 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
464 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
465
466 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
467 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
468 // For aliases, change the name directly.
469 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
470 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
471 continue;
472 }
473 // Must be a function.
474 Function *CF = dyn_cast<Function>(CM.second);
475 assert(CF);
476 CF->setComdat(NewComdat);
477 }
Rong Xuf430ae42015-12-09 18:08:16 +0000478}
479
480// Given a CFG E to be instrumented, find which BB to place the instrumented
481// code. The function will split the critical edge if necessary.
482template <class Edge, class BBInfo>
483BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
484 if (E->InMST || E->Removed)
485 return nullptr;
486
487 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
488 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
489 // For a fake edge, instrument the real BB.
490 if (SrcBB == nullptr)
491 return DestBB;
492 if (DestBB == nullptr)
493 return SrcBB;
494
495 // Instrument the SrcBB if it has a single successor,
496 // otherwise, the DestBB if this is not a critical edge.
497 TerminatorInst *TI = SrcBB->getTerminator();
498 if (TI->getNumSuccessors() <= 1)
499 return SrcBB;
500 if (!E->IsCritical)
501 return DestBB;
502
503 // For a critical edge, we have to split. Instrument the newly
504 // created BB.
505 NumOfPGOSplit++;
506 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
507 << getBBInfo(DestBB).Index << "\n");
508 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
509 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
510 assert(InstrBB && "Critical edge is not split");
511
512 E->Removed = true;
513 return InstrBB;
514}
515
Rong Xued9fec72016-01-21 18:11:44 +0000516// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000517// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000518static void instrumentOneFunc(
519 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
520 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000521 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
522 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000523 unsigned NumCounters = FuncInfo.getNumCounters();
524
Rong Xuf430ae42015-12-09 18:08:16 +0000525 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000526 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000527 for (auto &E : FuncInfo.MST.AllEdges) {
528 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
529 if (!InstrBB)
530 continue;
531
532 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
533 assert(Builder.GetInsertPoint() != InstrBB->end() &&
534 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000535 Builder.CreateCall(
536 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
537 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
538 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
539 Builder.getInt32(I++)});
540 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000541
542 // Now instrument select instructions:
543 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
544 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000545 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000546
547 if (DisableValueProfiling)
548 return;
549
550 unsigned NumIndirectCallSites = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +0000551 for (auto &I : FuncInfo.IndirectCallSites) {
Rong Xued9fec72016-01-21 18:11:44 +0000552 CallSite CS(I);
553 Value *Callee = CS.getCalledValue();
554 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
555 << NumIndirectCallSites << "\n");
556 IRBuilder<> Builder(I);
557 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
558 "Cannot get the Instrumentation point");
559 Builder.CreateCall(
560 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
561 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
562 Builder.getInt64(FuncInfo.FunctionHash),
563 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
564 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
565 Builder.getInt32(NumIndirectCallSites++)});
566 }
567 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000568}
569
570// This class represents a CFG edge in profile use compilation.
571struct PGOUseEdge : public PGOEdge {
572 bool CountValid;
573 uint64_t CountValue;
574 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
575 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
576
577 // Set edge count value
578 void setEdgeCount(uint64_t Value) {
579 CountValue = Value;
580 CountValid = true;
581 }
582
583 // Return the information string for this object.
584 const std::string infoString() const {
585 if (!CountValid)
586 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000587 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
588 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000589 }
590};
591
592typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
593
594// This class stores the auxiliary information for each BB.
595struct UseBBInfo : public BBInfo {
596 uint64_t CountValue;
597 bool CountValid;
598 int32_t UnknownCountInEdge;
599 int32_t UnknownCountOutEdge;
600 DirectEdges InEdges;
601 DirectEdges OutEdges;
602 UseBBInfo(unsigned IX)
603 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
604 UnknownCountOutEdge(0) {}
605 UseBBInfo(unsigned IX, uint64_t C)
606 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
607 UnknownCountOutEdge(0) {}
608
609 // Set the profile count value for this BB.
610 void setBBInfoCount(uint64_t Value) {
611 CountValue = Value;
612 CountValid = true;
613 }
614
615 // Return the information string of this object.
616 const std::string infoString() const {
617 if (!CountValid)
618 return BBInfo::infoString();
619 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
620 }
621};
622
623// Sum up the count values for all the edges.
624static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
625 uint64_t Total = 0;
626 for (auto &E : Edges) {
627 if (E->Removed)
628 continue;
629 Total += E->CountValue;
630 }
631 return Total;
632}
633
634class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000635public:
Rong Xu705f7772016-07-25 18:45:37 +0000636 PGOUseFunc(Function &Func, Module *Modu,
637 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
638 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000639 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000640 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000641 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000642
643 // Read counts for the instrumented BB from profile.
644 bool readCounters(IndexedInstrProfReader *PGOReader);
645
646 // Populate the counts for all BBs.
647 void populateCounters();
648
649 // Set the branch weights based on the count values.
650 void setBranchWeights();
651
652 // Annotate the indirect call sites.
653 void annotateIndirectCallSites();
654
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000655 // The hotness of the function from the profile count.
656 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
657
658 // Return the function hotness from the profile.
659 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
660
Rong Xu705f7772016-07-25 18:45:37 +0000661 // Return the function hash.
662 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000663 // Return the profile record for this function;
664 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
665
Xinliang David Li4ca17332016-09-18 18:34:07 +0000666 // Return the auxiliary BB information.
667 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
668 return FuncInfo.getBBInfo(BB);
669 }
670
Rong Xuf430ae42015-12-09 18:08:16 +0000671private:
672 Function &F;
673 Module *M;
674 // This member stores the shared information with class PGOGenFunc.
675 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
676
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000677 // The maximum count value in the profile. This is only used in PGO use
678 // compilation.
679 uint64_t ProgramMaxCount;
680
Rong Xu13b01dc2016-02-10 18:24:45 +0000681 // ProfileRecord for this function.
682 InstrProfRecord ProfileRecord;
683
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000684 // Function hotness info derived from profile.
685 FuncFreqAttr FreqAttr;
686
Rong Xuf430ae42015-12-09 18:08:16 +0000687 // Find the Instrumented BB and set the value.
688 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
689
690 // Set the edge counter value for the unknown edge -- there should be only
691 // one unknown edge.
692 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
693
694 // Return FuncName string;
695 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000696
697 // Set the hot/cold inline hints based on the count values.
698 // FIXME: This function should be removed once the functionality in
699 // the inliner is implemented.
700 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
701 if (ProgramMaxCount == 0)
702 return;
703 // Threshold of the hot functions.
704 const BranchProbability HotFunctionThreshold(1, 100);
705 // Threshold of the cold functions.
706 const BranchProbability ColdFunctionThreshold(2, 10000);
707 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
708 FreqAttr = FFA_Hot;
709 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
710 FreqAttr = FFA_Cold;
711 }
Rong Xuf430ae42015-12-09 18:08:16 +0000712};
713
714// Visit all the edges and assign the count value for the instrumented
715// edges and the BB.
716void PGOUseFunc::setInstrumentedCounts(
717 const std::vector<uint64_t> &CountFromProfile) {
718
Xinliang David Lid1197612016-08-01 20:25:06 +0000719 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000720 // Use a worklist as we will update the vector during the iteration.
721 std::vector<PGOUseEdge *> WorkList;
722 for (auto &E : FuncInfo.MST.AllEdges)
723 WorkList.push_back(E.get());
724
725 uint32_t I = 0;
726 for (auto &E : WorkList) {
727 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
728 if (!InstrBB)
729 continue;
730 uint64_t CountValue = CountFromProfile[I++];
731 if (!E->Removed) {
732 getBBInfo(InstrBB).setBBInfoCount(CountValue);
733 E->setEdgeCount(CountValue);
734 continue;
735 }
736
737 // Need to add two new edges.
738 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
739 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
740 // Add new edge of SrcBB->InstrBB.
741 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
742 NewEdge.setEdgeCount(CountValue);
743 // Add new edge of InstrBB->DestBB.
744 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
745 NewEdge1.setEdgeCount(CountValue);
746 NewEdge1.InMST = true;
747 getBBInfo(InstrBB).setBBInfoCount(CountValue);
748 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000749 // Now annotate select instructions
750 FuncInfo.SIVisitor.annotateSelects(F, this, &I);
Xinliang David Lid1197612016-08-01 20:25:06 +0000751 assert(I == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000752}
753
754// Set the count value for the unknown edge. There should be one and only one
755// unknown edge in Edges vector.
756void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
757 for (auto &E : Edges) {
758 if (E->CountValid)
759 continue;
760 E->setEdgeCount(Value);
761
762 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
763 getBBInfo(E->DestBB).UnknownCountInEdge--;
764 return;
765 }
766 llvm_unreachable("Cannot find the unknown count edge");
767}
768
769// Read the profile from ProfileFileName and assign the value to the
770// instrumented BB and the edges. This function also updates ProgramMaxCount.
771// Return true if the profile are successfully read, and false on errors.
772bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
773 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000774 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000775 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000776 if (Error E = Result.takeError()) {
777 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
778 auto Err = IPE.get();
779 bool SkipWarning = false;
780 if (Err == instrprof_error::unknown_function) {
781 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000782 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000783 } else if (Err == instrprof_error::hash_mismatch ||
784 Err == instrprof_error::malformed) {
785 NumOfPGOMismatch++;
786 SkipWarning = NoPGOWarnMismatch;
787 }
Rong Xuf430ae42015-12-09 18:08:16 +0000788
Vedant Kumar9152fd12016-05-19 03:54:45 +0000789 if (SkipWarning)
790 return;
791
792 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
793 Ctx.diagnose(
794 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
795 });
Rong Xuf430ae42015-12-09 18:08:16 +0000796 return false;
797 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000798 ProfileRecord = std::move(Result.get());
799 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000800
801 NumOfPGOFunc++;
802 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
803 uint64_t ValueSum = 0;
804 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
805 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
806 ValueSum += CountFromProfile[I];
807 }
808
809 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
810
811 getBBInfo(nullptr).UnknownCountOutEdge = 2;
812 getBBInfo(nullptr).UnknownCountInEdge = 2;
813
814 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000815 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000816 return true;
817}
818
819// Populate the counters from instrumented BBs to all BBs.
820// In the end of this operation, all BBs should have a valid count value.
821void PGOUseFunc::populateCounters() {
822 // First set up Count variable for all BBs.
823 for (auto &E : FuncInfo.MST.AllEdges) {
824 if (E->Removed)
825 continue;
826
827 const BasicBlock *SrcBB = E->SrcBB;
828 const BasicBlock *DestBB = E->DestBB;
829 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
830 UseBBInfo &DestInfo = getBBInfo(DestBB);
831 SrcInfo.OutEdges.push_back(E.get());
832 DestInfo.InEdges.push_back(E.get());
833 SrcInfo.UnknownCountOutEdge++;
834 DestInfo.UnknownCountInEdge++;
835
836 if (!E->CountValid)
837 continue;
838 DestInfo.UnknownCountInEdge--;
839 SrcInfo.UnknownCountOutEdge--;
840 }
841
842 bool Changes = true;
843 unsigned NumPasses = 0;
844 while (Changes) {
845 NumPasses++;
846 Changes = false;
847
848 // For efficient traversal, it's better to start from the end as most
849 // of the instrumented edges are at the end.
850 for (auto &BB : reverse(F)) {
851 UseBBInfo &Count = getBBInfo(&BB);
852 if (!Count.CountValid) {
853 if (Count.UnknownCountOutEdge == 0) {
854 Count.CountValue = sumEdgeCount(Count.OutEdges);
855 Count.CountValid = true;
856 Changes = true;
857 } else if (Count.UnknownCountInEdge == 0) {
858 Count.CountValue = sumEdgeCount(Count.InEdges);
859 Count.CountValid = true;
860 Changes = true;
861 }
862 }
863 if (Count.CountValid) {
864 if (Count.UnknownCountOutEdge == 1) {
865 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
866 setEdgeCount(Count.OutEdges, Total);
867 Changes = true;
868 }
869 if (Count.UnknownCountInEdge == 1) {
870 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
871 setEdgeCount(Count.InEdges, Total);
872 Changes = true;
873 }
874 }
875 }
876 }
877
878 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000879#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000880 // Assert every BB has a valid counter.
Sean Silva8c7e1212016-05-28 04:19:45 +0000881 for (auto &BB : F)
882 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
883#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000884 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000885 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000886 uint64_t FuncMaxCount = FuncEntryCount;
Sean Silva8c7e1212016-05-28 04:19:45 +0000887 for (auto &BB : F)
888 FuncMaxCount = std::max(FuncMaxCount, getBBInfo(&BB).CountValue);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000889 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000890
891 DEBUG(FuncInfo.dumpInfo("after reading profile."));
892}
893
Xinliang David Li4ca17332016-09-18 18:34:07 +0000894static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000895 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000896 MDBuilder MDB(M->getContext());
897 assert(MaxCount > 0 && "Bad max count");
898 uint64_t Scale = calculateCountScale(MaxCount);
899 SmallVector<unsigned, 4> Weights;
900 for (const auto &ECI : EdgeCounts)
901 Weights.push_back(scaleBranchCount(ECI, Scale));
902
903 DEBUG(dbgs() << "Weight is: ";
904 for (const auto &W : Weights) { dbgs() << W << " "; }
905 dbgs() << "\n";);
906 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
907}
908
Rong Xuf430ae42015-12-09 18:08:16 +0000909// Assign the scaled count values to the BB with multiple out edges.
910void PGOUseFunc::setBranchWeights() {
911 // Generate MD_prof metadata for every branch instruction.
912 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000913 for (auto &BB : F) {
914 TerminatorInst *TI = BB.getTerminator();
915 if (TI->getNumSuccessors() < 2)
916 continue;
917 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
918 continue;
919 if (getBBInfo(&BB).CountValue == 0)
920 continue;
921
922 // We have a non-zero Branch BB.
923 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
924 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +0000925 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +0000926 uint64_t MaxCount = 0;
927 for (unsigned s = 0; s < Size; s++) {
928 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
929 const BasicBlock *SrcBB = E->SrcBB;
930 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000931 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000932 continue;
933 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
934 uint64_t EdgeCount = E->CountValue;
935 if (EdgeCount > MaxCount)
936 MaxCount = EdgeCount;
937 EdgeCounts[SuccNum] = EdgeCount;
938 }
Xinliang David Li2c933682016-08-19 05:31:33 +0000939 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000940 }
941}
Rong Xu13b01dc2016-02-10 18:24:45 +0000942
Xinliang David Li4ca17332016-09-18 18:34:07 +0000943void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
944 Module *M = F.getParent();
945 IRBuilder<> Builder(&SI);
946 Type *Int64Ty = Builder.getInt64Ty();
947 Type *I8PtrTy = Builder.getInt8PtrTy();
948 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
949 Builder.CreateCall(
950 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
951 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
952 Builder.getInt64(FuncHash),
953 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
954 ++(*CurCtrIdx);
955}
956
957void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
958 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
959 assert(*CurCtrIdx < CountFromProfile.size() &&
960 "Out of bound access of counters");
961 uint64_t SCounts[2];
962 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
963 ++(*CurCtrIdx);
964 uint64_t TotalCount = UseFunc->getBBInfo(SI.getParent()).CountValue;
965 // False Count
966 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
967 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +0000968 if (MaxCount)
969 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000970}
971
972void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
973 if (!PGOInstrSelect)
974 return;
975 // FIXME: do not handle this yet.
976 if (SI.getCondition()->getType()->isVectorTy())
977 return;
978
979 NSIs++;
980 switch (Mode) {
981 case VM_counting:
982 return;
983 case VM_instrument:
984 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +0000985 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000986 case VM_annotate:
987 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +0000988 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000989 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +0000990
991 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000992}
993
Rong Xu13b01dc2016-02-10 18:24:45 +0000994// Traverse all the indirect callsites and annotate the instructions.
995void PGOUseFunc::annotateIndirectCallSites() {
996 if (DisableValueProfiling)
997 return;
998
Rong Xu8e8fe852016-04-01 16:43:30 +0000999 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001000 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001001
Rong Xu13b01dc2016-02-10 18:24:45 +00001002 unsigned IndirectCallSiteIndex = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +00001003 auto &IndirectCallSites = FuncInfo.IndirectCallSites;
Rong Xu9e926e82016-02-29 19:16:04 +00001004 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001005 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001006 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001007 std::string Msg =
1008 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001009 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001010 auto &Ctx = M->getContext();
1011 Ctx.diagnose(
1012 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1013 return;
1014 }
1015
Rong Xu0eb36032016-04-01 23:16:44 +00001016 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001017 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001018 << IndirectCallSiteIndex << " out of " << NumValueSites
1019 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001020 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001021 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001022 IndirectCallSiteIndex++;
1023 }
1024}
Rong Xuf430ae42015-12-09 18:08:16 +00001025} // end anonymous namespace
1026
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001027// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001028// aware this is an ir_level profile so it can set the version flag.
1029static void createIRLevelProfileFlagVariable(Module &M) {
1030 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1031 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001032 auto IRLevelVersionVariable = new GlobalVariable(
1033 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1034 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001035 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001036 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1037 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001038 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001039 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001040 else
Rong Xu9e926e82016-02-29 19:16:04 +00001041 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001042 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001043}
1044
Rong Xu705f7772016-07-25 18:45:37 +00001045// Collect the set of members for each Comdat in module M and store
1046// in ComdatMembers.
1047static void collectComdatMembers(
1048 Module &M,
1049 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1050 if (!DoComdatRenaming)
1051 return;
1052 for (Function &F : M)
1053 if (Comdat *C = F.getComdat())
1054 ComdatMembers.insert(std::make_pair(C, &F));
1055 for (GlobalVariable &GV : M.globals())
1056 if (Comdat *C = GV.getComdat())
1057 ComdatMembers.insert(std::make_pair(C, &GV));
1058 for (GlobalAlias &GA : M.aliases())
1059 if (Comdat *C = GA.getComdat())
1060 ComdatMembers.insert(std::make_pair(C, &GA));
1061}
1062
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001063static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001064 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1065 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001066 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001067 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1068 collectComdatMembers(M, ComdatMembers);
1069
Rong Xuf430ae42015-12-09 18:08:16 +00001070 for (auto &F : M) {
1071 if (F.isDeclaration())
1072 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001073 auto *BPI = LookupBPI(F);
1074 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001075 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001076 }
1077 return true;
1078}
1079
Xinliang David Li8aebf442016-05-06 05:49:19 +00001080bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001081 if (skipModule(M))
1082 return false;
1083
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001084 auto LookupBPI = [this](Function &F) {
1085 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001086 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001087 auto LookupBFI = [this](Function &F) {
1088 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001089 };
1090 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1091}
1092
Xinliang David Li8aebf442016-05-06 05:49:19 +00001093PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001094 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001095
1096 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001097 auto LookupBPI = [&FAM](Function &F) {
1098 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001099 };
1100
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001101 auto LookupBFI = [&FAM](Function &F) {
1102 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001103 };
1104
1105 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1106 return PreservedAnalyses::all();
1107
1108 return PreservedAnalyses::none();
1109}
1110
Xinliang David Lida195582016-05-10 21:59:52 +00001111static bool annotateAllFunctions(
1112 Module &M, StringRef ProfileFileName,
1113 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001114 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001115 DEBUG(dbgs() << "Read in profile counters: ");
1116 auto &Ctx = M.getContext();
1117 // Read the counter array from file.
1118 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001119 if (Error E = ReaderOrErr.takeError()) {
1120 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1121 Ctx.diagnose(
1122 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1123 });
Rong Xuf430ae42015-12-09 18:08:16 +00001124 return false;
1125 }
1126
Xinliang David Lida195582016-05-10 21:59:52 +00001127 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1128 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001129 if (!PGOReader) {
1130 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001131 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001132 return false;
1133 }
Rong Xu33c76c02016-02-10 17:18:30 +00001134 // TODO: might need to change the warning once the clang option is finalized.
1135 if (!PGOReader->isIRLevelProfile()) {
1136 Ctx.diagnose(DiagnosticInfoPGOProfile(
1137 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1138 return false;
1139 }
1140
Rong Xu705f7772016-07-25 18:45:37 +00001141 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1142 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001143 std::vector<Function *> HotFunctions;
1144 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001145 for (auto &F : M) {
1146 if (F.isDeclaration())
1147 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001148 auto *BPI = LookupBPI(F);
1149 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001150 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001151 if (!Func.readCounters(PGOReader.get()))
1152 continue;
1153 Func.populateCounters();
1154 Func.setBranchWeights();
1155 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001156 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1157 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001158 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001159 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1160 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001161 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001162 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001163 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001164 // We have to apply these attributes at the end because their presence
1165 // can affect the BranchProbabilityInfo of any callers, resulting in an
1166 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001167 for (auto &F : HotFunctions) {
1168 F->addFnAttr(llvm::Attribute::InlineHint);
1169 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1170 << "\n");
1171 }
1172 for (auto &F : ColdFunctions) {
1173 F->addFnAttr(llvm::Attribute::Cold);
1174 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1175 }
Rong Xuf430ae42015-12-09 18:08:16 +00001176 return true;
1177}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001178
Xinliang David Lida195582016-05-10 21:59:52 +00001179PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001180 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001181 if (!PGOTestProfileFile.empty())
1182 ProfileFileName = PGOTestProfileFile;
1183}
1184
1185PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001186 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001187
1188 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1189 auto LookupBPI = [&FAM](Function &F) {
1190 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1191 };
1192
1193 auto LookupBFI = [&FAM](Function &F) {
1194 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1195 };
1196
1197 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1198 return PreservedAnalyses::all();
1199
1200 return PreservedAnalyses::none();
1201}
1202
Xinliang David Lid55827f2016-05-07 05:39:12 +00001203bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1204 if (skipModule(M))
1205 return false;
1206
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001207 auto LookupBPI = [this](Function &F) {
1208 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001209 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001210 auto LookupBFI = [this](Function &F) {
1211 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001212 };
1213
Xinliang David Lida195582016-05-10 21:59:52 +00001214 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001215}