blob: 500d08d46a01a1834c40cc5b3da89be77cdb42e3 [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 Xu0eb36032016-04-01 23:16:44 +000053#include "IndirectCallSiteVisitor.h"
Rong Xuf430ae42015-12-09 18:08:16 +000054#include "llvm/ADT/STLExtras.h"
55#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"
Rong Xued9fec72016-01-21 18:11:44 +000060#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/IRBuilder.h"
63#include "llvm/IR/InstIterator.h"
64#include "llvm/IR/Instructions.h"
65#include "llvm/IR/IntrinsicInst.h"
66#include "llvm/IR/MDBuilder.h"
67#include "llvm/IR/Module.h"
68#include "llvm/Pass.h"
69#include "llvm/ProfileData/InstrProfReader.h"
70#include "llvm/Support/BranchProbability.h"
71#include "llvm/Support/Debug.h"
72#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000073#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000075#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000076#include <string>
77#include <utility>
78#include <vector>
79
80using namespace llvm;
81
82#define DEBUG_TYPE "pgo-instrumentation"
83
84STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
85STATISTIC(NumOfPGOEdge, "Number of edges.");
86STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
87STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
88STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
89STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
90STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000091STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000092
93// Command line option to specify the file to read profile from. This is
94// mainly used for testing.
95static cl::opt<std::string>
96 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
97 cl::value_desc("filename"),
98 cl::desc("Specify the path of profile data file. This is"
99 "mainly for test purpose."));
100
Rong Xuecdc98f2016-03-04 22:08:44 +0000101// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000102// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000103static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
104 cl::Hidden,
105 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000106
Rong Xuecdc98f2016-03-04 22:08:44 +0000107// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000108// the metadata for a single indirect call callsite.
109static cl::opt<unsigned> MaxNumAnnotations(
110 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
111 cl::desc("Max number of annotations for a single indirect "
112 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000113
Rong Xuf430ae42015-12-09 18:08:16 +0000114namespace {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000115class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000116public:
117 static char ID;
118
Xinliang David Li8aebf442016-05-06 05:49:19 +0000119 PGOInstrumentationGenLegacyPass() : ModulePass(ID), PGOInstrGen() {
120 initializePGOInstrumentationGenLegacyPassPass(
121 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000122 }
123
124 const char *getPassName() const override {
125 return "PGOInstrumentationGenPass";
126 }
127
128private:
Xinliang David Li8aebf442016-05-06 05:49:19 +0000129 PGOInstrumentationGen PGOInstrGen;
Rong Xuf430ae42015-12-09 18:08:16 +0000130 bool runOnModule(Module &M) override;
131
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.addRequired<BlockFrequencyInfoWrapperPass>();
134 }
135};
136
137class PGOInstrumentationUse : public ModulePass {
138public:
139 static char ID;
140
141 // Provide the profile filename as the parameter.
142 PGOInstrumentationUse(std::string Filename = "")
143 : ModulePass(ID), ProfileFileName(Filename) {
144 if (!PGOTestProfileFile.empty())
145 ProfileFileName = PGOTestProfileFile;
146 initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
147 }
148
149 const char *getPassName() const override {
150 return "PGOInstrumentationUsePass";
151 }
152
153private:
154 std::string ProfileFileName;
155 std::unique_ptr<IndexedInstrProfReader> PGOReader;
156 bool runOnModule(Module &M) override;
157
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.addRequired<BlockFrequencyInfoWrapperPass>();
160 }
161};
162} // end anonymous namespace
163
Xinliang David Li8aebf442016-05-06 05:49:19 +0000164char PGOInstrumentationGenLegacyPass::ID = 0;
165INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000166 "PGO instrumentation.", false, false)
167INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
168INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000169INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000170 "PGO instrumentation.", false, false)
171
Xinliang David Li8aebf442016-05-06 05:49:19 +0000172ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
173 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000174}
175
176char PGOInstrumentationUse::ID = 0;
177INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
178 "Read PGO instrumentation profile.", false, false)
179INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
180INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
181INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
182 "Read PGO instrumentation profile.", false, false)
183
184ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
185 return new PGOInstrumentationUse(Filename.str());
186}
187
188namespace {
189/// \brief An MST based instrumentation for PGO
190///
191/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
192/// in the function level.
193struct PGOEdge {
194 // This class implements the CFG edges. Note the CFG can be a multi-graph.
195 // So there might be multiple edges with same SrcBB and DestBB.
196 const BasicBlock *SrcBB;
197 const BasicBlock *DestBB;
198 uint64_t Weight;
199 bool InMST;
200 bool Removed;
201 bool IsCritical;
202 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
203 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
204 IsCritical(false) {}
205 // Return the information string of an edge.
206 const std::string infoString() const {
207 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
208 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
209 }
210};
211
212// This class stores the auxiliary information for each BB.
213struct BBInfo {
214 BBInfo *Group;
215 uint32_t Index;
216 uint32_t Rank;
217
218 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
219
220 // Return the information string of this object.
221 const std::string infoString() const {
222 return (Twine("Index=") + Twine(Index)).str();
223 }
224};
225
226// This class implements the CFG edges. Note the CFG can be a multi-graph.
227template <class Edge, class BBInfo> class FuncPGOInstrumentation {
228private:
229 Function &F;
230 void computeCFGHash();
231
232public:
233 std::string FuncName;
234 GlobalVariable *FuncNameVar;
235 // CFG hash value for this function.
236 uint64_t FunctionHash;
237
238 // The Minimum Spanning Tree of function CFG.
239 CFGMST<Edge, BBInfo> MST;
240
241 // Give an edge, find the BB that will be instrumented.
242 // Return nullptr if there is no BB to be instrumented.
243 BasicBlock *getInstrBB(Edge *E);
244
245 // Return the auxiliary BB information.
246 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
247
248 // Dump edges and BB information.
249 void dumpInfo(std::string Str = "") const {
250 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000251 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000252 }
253
254 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
255 BranchProbabilityInfo *BPI = nullptr,
256 BlockFrequencyInfo *BFI = nullptr)
257 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
258 FuncName = getPGOFuncName(F);
259 computeCFGHash();
260 DEBUG(dumpInfo("after CFGMST"));
261
262 NumOfPGOBB += MST.BBInfos.size();
263 for (auto &E : MST.AllEdges) {
264 if (E->Removed)
265 continue;
266 NumOfPGOEdge++;
267 if (!E->InMST)
268 NumOfPGOInstrument++;
269 }
270
271 if (CreateGlobalVar)
272 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000273 }
Rong Xuf430ae42015-12-09 18:08:16 +0000274};
275
276// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
277// value of each BB in the CFG. The higher 32 bits record the number of edges.
278template <class Edge, class BBInfo>
279void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
280 std::vector<char> Indexes;
281 JamCRC JC;
282 for (auto &BB : F) {
283 const TerminatorInst *TI = BB.getTerminator();
284 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
285 BasicBlock *Succ = TI->getSuccessor(I);
286 uint32_t Index = getBBInfo(Succ).Index;
287 for (int J = 0; J < 4; J++)
288 Indexes.push_back((char)(Index >> (J * 8)));
289 }
290 }
291 JC.update(Indexes);
292 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
293}
294
295// Given a CFG E to be instrumented, find which BB to place the instrumented
296// code. The function will split the critical edge if necessary.
297template <class Edge, class BBInfo>
298BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
299 if (E->InMST || E->Removed)
300 return nullptr;
301
302 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
303 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
304 // For a fake edge, instrument the real BB.
305 if (SrcBB == nullptr)
306 return DestBB;
307 if (DestBB == nullptr)
308 return SrcBB;
309
310 // Instrument the SrcBB if it has a single successor,
311 // otherwise, the DestBB if this is not a critical edge.
312 TerminatorInst *TI = SrcBB->getTerminator();
313 if (TI->getNumSuccessors() <= 1)
314 return SrcBB;
315 if (!E->IsCritical)
316 return DestBB;
317
318 // For a critical edge, we have to split. Instrument the newly
319 // created BB.
320 NumOfPGOSplit++;
321 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
322 << getBBInfo(DestBB).Index << "\n");
323 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
324 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
325 assert(InstrBB && "Critical edge is not split");
326
327 E->Removed = true;
328 return InstrBB;
329}
330
Rong Xued9fec72016-01-21 18:11:44 +0000331// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000332// Critical edges will be split.
333static void instrumentOneFunc(Function &F, Module *M,
334 BranchProbabilityInfo *BPI,
335 BlockFrequencyInfo *BFI) {
336 unsigned NumCounters = 0;
337 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
338 for (auto &E : FuncInfo.MST.AllEdges) {
339 if (!E->InMST && !E->Removed)
340 NumCounters++;
341 }
342
343 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000344 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000345 for (auto &E : FuncInfo.MST.AllEdges) {
346 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
347 if (!InstrBB)
348 continue;
349
350 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
351 assert(Builder.GetInsertPoint() != InstrBB->end() &&
352 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000353 Builder.CreateCall(
354 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
355 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
356 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
357 Builder.getInt32(I++)});
358 }
Rong Xued9fec72016-01-21 18:11:44 +0000359
360 if (DisableValueProfiling)
361 return;
362
363 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000364 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000365 CallSite CS(I);
366 Value *Callee = CS.getCalledValue();
367 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
368 << NumIndirectCallSites << "\n");
369 IRBuilder<> Builder(I);
370 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
371 "Cannot get the Instrumentation point");
372 Builder.CreateCall(
373 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
374 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
375 Builder.getInt64(FuncInfo.FunctionHash),
376 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
377 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
378 Builder.getInt32(NumIndirectCallSites++)});
379 }
380 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000381}
382
383// This class represents a CFG edge in profile use compilation.
384struct PGOUseEdge : public PGOEdge {
385 bool CountValid;
386 uint64_t CountValue;
387 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
388 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
389
390 // Set edge count value
391 void setEdgeCount(uint64_t Value) {
392 CountValue = Value;
393 CountValid = true;
394 }
395
396 // Return the information string for this object.
397 const std::string infoString() const {
398 if (!CountValid)
399 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000400 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
401 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000402 }
403};
404
405typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
406
407// This class stores the auxiliary information for each BB.
408struct UseBBInfo : public BBInfo {
409 uint64_t CountValue;
410 bool CountValid;
411 int32_t UnknownCountInEdge;
412 int32_t UnknownCountOutEdge;
413 DirectEdges InEdges;
414 DirectEdges OutEdges;
415 UseBBInfo(unsigned IX)
416 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
417 UnknownCountOutEdge(0) {}
418 UseBBInfo(unsigned IX, uint64_t C)
419 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
420 UnknownCountOutEdge(0) {}
421
422 // Set the profile count value for this BB.
423 void setBBInfoCount(uint64_t Value) {
424 CountValue = Value;
425 CountValid = true;
426 }
427
428 // Return the information string of this object.
429 const std::string infoString() const {
430 if (!CountValid)
431 return BBInfo::infoString();
432 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
433 }
434};
435
436// Sum up the count values for all the edges.
437static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
438 uint64_t Total = 0;
439 for (auto &E : Edges) {
440 if (E->Removed)
441 continue;
442 Total += E->CountValue;
443 }
444 return Total;
445}
446
447class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000448public:
449 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
450 BlockFrequencyInfo *BFI = nullptr)
451 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
452 FreqAttr(FFA_Normal) {}
453
454 // Read counts for the instrumented BB from profile.
455 bool readCounters(IndexedInstrProfReader *PGOReader);
456
457 // Populate the counts for all BBs.
458 void populateCounters();
459
460 // Set the branch weights based on the count values.
461 void setBranchWeights();
462
463 // Annotate the indirect call sites.
464 void annotateIndirectCallSites();
465
466 // The hotness of the function from the profile count.
467 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
468
Rong Xu08afb052016-04-28 17:31:22 +0000469 // Return the function hotness from the profile.
470 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
Rong Xu6090afd2016-03-28 17:08:56 +0000471
Rong Xuf430ae42015-12-09 18:08:16 +0000472private:
473 Function &F;
474 Module *M;
475 // This member stores the shared information with class PGOGenFunc.
476 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
477
478 // Return the auxiliary BB information.
479 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
480 return FuncInfo.getBBInfo(BB);
481 }
482
483 // The maximum count value in the profile. This is only used in PGO use
484 // compilation.
485 uint64_t ProgramMaxCount;
486
Rong Xu13b01dc2016-02-10 18:24:45 +0000487 // ProfileRecord for this function.
488 InstrProfRecord ProfileRecord;
489
Rong Xu6090afd2016-03-28 17:08:56 +0000490 // Function hotness info derived from profile.
491 FuncFreqAttr FreqAttr;
492
Rong Xuf430ae42015-12-09 18:08:16 +0000493 // Find the Instrumented BB and set the value.
494 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
495
496 // Set the edge counter value for the unknown edge -- there should be only
497 // one unknown edge.
498 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
499
500 // Return FuncName string;
501 const std::string getFuncName() const { return FuncInfo.FuncName; }
502
503 // Set the hot/cold inline hints based on the count values.
504 // FIXME: This function should be removed once the functionality in
505 // the inliner is implemented.
Rong Xu6090afd2016-03-28 17:08:56 +0000506 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
Rong Xuf430ae42015-12-09 18:08:16 +0000507 if (ProgramMaxCount == 0)
508 return;
509 // Threshold of the hot functions.
510 const BranchProbability HotFunctionThreshold(1, 100);
511 // Threshold of the cold functions.
512 const BranchProbability ColdFunctionThreshold(2, 10000);
513 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000514 FreqAttr = FFA_Hot;
Rong Xuf430ae42015-12-09 18:08:16 +0000515 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000516 FreqAttr = FFA_Cold;
Rong Xuf430ae42015-12-09 18:08:16 +0000517 }
Rong Xuf430ae42015-12-09 18:08:16 +0000518};
519
520// Visit all the edges and assign the count value for the instrumented
521// edges and the BB.
522void PGOUseFunc::setInstrumentedCounts(
523 const std::vector<uint64_t> &CountFromProfile) {
524
525 // Use a worklist as we will update the vector during the iteration.
526 std::vector<PGOUseEdge *> WorkList;
527 for (auto &E : FuncInfo.MST.AllEdges)
528 WorkList.push_back(E.get());
529
530 uint32_t I = 0;
531 for (auto &E : WorkList) {
532 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
533 if (!InstrBB)
534 continue;
535 uint64_t CountValue = CountFromProfile[I++];
536 if (!E->Removed) {
537 getBBInfo(InstrBB).setBBInfoCount(CountValue);
538 E->setEdgeCount(CountValue);
539 continue;
540 }
541
542 // Need to add two new edges.
543 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
544 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
545 // Add new edge of SrcBB->InstrBB.
546 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
547 NewEdge.setEdgeCount(CountValue);
548 // Add new edge of InstrBB->DestBB.
549 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
550 NewEdge1.setEdgeCount(CountValue);
551 NewEdge1.InMST = true;
552 getBBInfo(InstrBB).setBBInfoCount(CountValue);
553 }
554}
555
556// Set the count value for the unknown edge. There should be one and only one
557// unknown edge in Edges vector.
558void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
559 for (auto &E : Edges) {
560 if (E->CountValid)
561 continue;
562 E->setEdgeCount(Value);
563
564 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
565 getBBInfo(E->DestBB).UnknownCountInEdge--;
566 return;
567 }
568 llvm_unreachable("Cannot find the unknown count edge");
569}
570
571// Read the profile from ProfileFileName and assign the value to the
572// instrumented BB and the edges. This function also updates ProgramMaxCount.
573// Return true if the profile are successfully read, and false on errors.
574bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
575 auto &Ctx = M->getContext();
576 ErrorOr<InstrProfRecord> Result =
577 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
578 if (std::error_code EC = Result.getError()) {
579 if (EC == instrprof_error::unknown_function)
580 NumOfPGOMissing++;
581 else if (EC == instrprof_error::hash_mismatch ||
582 EC == llvm::instrprof_error::malformed)
583 NumOfPGOMismatch++;
584
585 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
586 Ctx.diagnose(
587 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
588 return false;
589 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000590 ProfileRecord = std::move(Result.get());
591 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000592
593 NumOfPGOFunc++;
594 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
595 uint64_t ValueSum = 0;
596 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
597 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
598 ValueSum += CountFromProfile[I];
599 }
600
601 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
602
603 getBBInfo(nullptr).UnknownCountOutEdge = 2;
604 getBBInfo(nullptr).UnknownCountInEdge = 2;
605
606 setInstrumentedCounts(CountFromProfile);
607 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
608 return true;
609}
610
611// Populate the counters from instrumented BBs to all BBs.
612// In the end of this operation, all BBs should have a valid count value.
613void PGOUseFunc::populateCounters() {
614 // First set up Count variable for all BBs.
615 for (auto &E : FuncInfo.MST.AllEdges) {
616 if (E->Removed)
617 continue;
618
619 const BasicBlock *SrcBB = E->SrcBB;
620 const BasicBlock *DestBB = E->DestBB;
621 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
622 UseBBInfo &DestInfo = getBBInfo(DestBB);
623 SrcInfo.OutEdges.push_back(E.get());
624 DestInfo.InEdges.push_back(E.get());
625 SrcInfo.UnknownCountOutEdge++;
626 DestInfo.UnknownCountInEdge++;
627
628 if (!E->CountValid)
629 continue;
630 DestInfo.UnknownCountInEdge--;
631 SrcInfo.UnknownCountOutEdge--;
632 }
633
634 bool Changes = true;
635 unsigned NumPasses = 0;
636 while (Changes) {
637 NumPasses++;
638 Changes = false;
639
640 // For efficient traversal, it's better to start from the end as most
641 // of the instrumented edges are at the end.
642 for (auto &BB : reverse(F)) {
643 UseBBInfo &Count = getBBInfo(&BB);
644 if (!Count.CountValid) {
645 if (Count.UnknownCountOutEdge == 0) {
646 Count.CountValue = sumEdgeCount(Count.OutEdges);
647 Count.CountValid = true;
648 Changes = true;
649 } else if (Count.UnknownCountInEdge == 0) {
650 Count.CountValue = sumEdgeCount(Count.InEdges);
651 Count.CountValid = true;
652 Changes = true;
653 }
654 }
655 if (Count.CountValid) {
656 if (Count.UnknownCountOutEdge == 1) {
657 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
658 setEdgeCount(Count.OutEdges, Total);
659 Changes = true;
660 }
661 if (Count.UnknownCountInEdge == 1) {
662 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
663 setEdgeCount(Count.InEdges, Total);
664 Changes = true;
665 }
666 }
667 }
668 }
669
670 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
671 // Assert every BB has a valid counter.
672 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
673 uint64_t FuncMaxCount = FuncEntryCount;
674 for (auto &BB : F) {
675 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
676 uint64_t Count = getBBInfo(&BB).CountValue;
677 if (Count > FuncMaxCount)
678 FuncMaxCount = Count;
679 }
Rong Xu6090afd2016-03-28 17:08:56 +0000680 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000681
682 DEBUG(FuncInfo.dumpInfo("after reading profile."));
683}
684
685// Assign the scaled count values to the BB with multiple out edges.
686void PGOUseFunc::setBranchWeights() {
687 // Generate MD_prof metadata for every branch instruction.
688 DEBUG(dbgs() << "\nSetting branch weights.\n");
689 MDBuilder MDB(M->getContext());
690 for (auto &BB : F) {
691 TerminatorInst *TI = BB.getTerminator();
692 if (TI->getNumSuccessors() < 2)
693 continue;
694 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
695 continue;
696 if (getBBInfo(&BB).CountValue == 0)
697 continue;
698
699 // We have a non-zero Branch BB.
700 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
701 unsigned Size = BBCountInfo.OutEdges.size();
702 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
703 uint64_t MaxCount = 0;
704 for (unsigned s = 0; s < Size; s++) {
705 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
706 const BasicBlock *SrcBB = E->SrcBB;
707 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000708 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000709 continue;
710 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
711 uint64_t EdgeCount = E->CountValue;
712 if (EdgeCount > MaxCount)
713 MaxCount = EdgeCount;
714 EdgeCounts[SuccNum] = EdgeCount;
715 }
716 assert(MaxCount > 0 && "Bad max count");
717 uint64_t Scale = calculateCountScale(MaxCount);
718 SmallVector<unsigned, 4> Weights;
719 for (const auto &ECI : EdgeCounts)
720 Weights.push_back(scaleBranchCount(ECI, Scale));
721
722 TI->setMetadata(llvm::LLVMContext::MD_prof,
723 MDB.createBranchWeights(Weights));
724 DEBUG(dbgs() << "Weight is: ";
725 for (const auto &W : Weights) { dbgs() << W << " "; }
726 dbgs() << "\n";);
727 }
728}
Rong Xu13b01dc2016-02-10 18:24:45 +0000729
730// Traverse all the indirect callsites and annotate the instructions.
731void PGOUseFunc::annotateIndirectCallSites() {
732 if (DisableValueProfiling)
733 return;
734
Rong Xu8e8fe852016-04-01 16:43:30 +0000735 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +0000736 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +0000737
Rong Xu13b01dc2016-02-10 18:24:45 +0000738 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000739 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000740 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000741 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +0000742 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000743 std::string Msg =
744 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000745 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000746 auto &Ctx = M->getContext();
747 Ctx.diagnose(
748 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
749 return;
750 }
751
Rong Xu0eb36032016-04-01 23:16:44 +0000752 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000753 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000754 << IndirectCallSiteIndex << " out of " << NumValueSites
755 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000756 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000757 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000758 IndirectCallSiteIndex++;
759 }
760}
Rong Xuf430ae42015-12-09 18:08:16 +0000761} // end anonymous namespace
762
Rong Xu33c76c02016-02-10 17:18:30 +0000763// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
764// aware this is an ir_level profile so it can set the version flag.
765static void createIRLevelProfileFlagVariable(Module &M) {
766 Type *IntTy64 = Type::getInt64Ty(M.getContext());
767 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000768 auto IRLevelVersionVariable = new GlobalVariable(
769 M, IntTy64, true, GlobalVariable::ExternalLinkage,
770 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
771 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000772 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
773 Triple TT(M.getTargetTriple());
774 if (TT.isOSBinFormatMachO())
775 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
776 else
Rong Xu9e926e82016-02-29 19:16:04 +0000777 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
778 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000779}
780
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000781static bool InstrumentAllFunctions(
782 Module &M, function_ref<BranchProbabilityInfo &(Function &)> LookupBPI,
783 function_ref<BlockFrequencyInfo &(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +0000784 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000785 for (auto &F : M) {
786 if (F.isDeclaration())
787 continue;
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000788 auto &BPI = LookupBPI(F);
789 auto &BFI = LookupBFI(F);
790 instrumentOneFunc(F, &M, &BPI, &BFI);
Rong Xuf430ae42015-12-09 18:08:16 +0000791 }
792 return true;
793}
794
Xinliang David Li8aebf442016-05-06 05:49:19 +0000795bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000796 if (skipModule(M))
797 return false;
798
799 auto LookupBPI = [this](Function &F) -> BranchProbabilityInfo & {
800 return this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
801 };
802 auto LookupBFI = [this](Function &F) -> BlockFrequencyInfo & {
803 return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
804 };
805 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
806}
807
Xinliang David Li8aebf442016-05-06 05:49:19 +0000808PreservedAnalyses PGOInstrumentationGen::run(Module &M,
809 AnalysisManager<Module> &AM) {
810
811 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
812 auto LookupBPI = [&FAM](Function &F) -> BranchProbabilityInfo & {
813 return FAM.getResult<BranchProbabilityAnalysis>(F);
814 };
815
816 auto LookupBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
817 return FAM.getResult<BlockFrequencyAnalysis>(F);
818 };
819
820 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
821 return PreservedAnalyses::all();
822
823 return PreservedAnalyses::none();
824}
825
Rong Xuf430ae42015-12-09 18:08:16 +0000826static void setPGOCountOnFunc(PGOUseFunc &Func,
827 IndexedInstrProfReader *PGOReader) {
828 if (Func.readCounters(PGOReader)) {
829 Func.populateCounters();
830 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000831 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000832 }
833}
834
835bool PGOInstrumentationUse::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000836 if (skipModule(M))
837 return false;
838
Rong Xuf430ae42015-12-09 18:08:16 +0000839 DEBUG(dbgs() << "Read in profile counters: ");
840 auto &Ctx = M.getContext();
841 // Read the counter array from file.
842 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
843 if (std::error_code EC = ReaderOrErr.getError()) {
844 Ctx.diagnose(
845 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
846 return false;
847 }
848
849 PGOReader = std::move(ReaderOrErr.get());
850 if (!PGOReader) {
851 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
852 "Cannot get PGOReader"));
853 return false;
854 }
Rong Xu33c76c02016-02-10 17:18:30 +0000855 // TODO: might need to change the warning once the clang option is finalized.
856 if (!PGOReader->isIRLevelProfile()) {
857 Ctx.diagnose(DiagnosticInfoPGOProfile(
858 ProfileFileName.data(), "Not an IR level instrumentation profile"));
859 return false;
860 }
861
Rong Xu6090afd2016-03-28 17:08:56 +0000862 std::vector<Function *> HotFunctions;
863 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +0000864 for (auto &F : M) {
865 if (F.isDeclaration())
866 continue;
867 BranchProbabilityInfo *BPI =
868 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
869 BlockFrequencyInfo *BFI =
870 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
871 PGOUseFunc Func(F, &M, BPI, BFI);
872 setPGOCountOnFunc(Func, PGOReader.get());
Rong Xu6090afd2016-03-28 17:08:56 +0000873 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
874 if (FreqAttr == PGOUseFunc::FFA_Cold)
875 ColdFunctions.push_back(&F);
876 else if (FreqAttr == PGOUseFunc::FFA_Hot)
877 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +0000878 }
Rong Xu6090afd2016-03-28 17:08:56 +0000879
880 // Set function hotness attribute from the profile.
881 for (auto &F : HotFunctions) {
882 F->addFnAttr(llvm::Attribute::InlineHint);
883 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
884 << "\n");
885 }
886 for (auto &F : ColdFunctions) {
887 F->addFnAttr(llvm::Attribute::Cold);
888 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
889 }
890
Rong Xuf430ae42015-12-09 18:08:16 +0000891 return true;
892}