blob: a8ad7c3fbda648cb176e22940632c248e3c65690 [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
Rong Xuf430ae42015-12-09 18:08:16 +000051#include "CFGMST.h"
52#include "llvm/ADT/DenseMap.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000055#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000056#include "llvm/Analysis/BlockFrequencyInfo.h"
57#include "llvm/Analysis/BranchProbabilityInfo.h"
58#include "llvm/Analysis/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000059#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000060#include "llvm/IR/DiagnosticInfo.h"
61#include "llvm/IR/IRBuilder.h"
62#include "llvm/IR/InstIterator.h"
Rong Xued9fec72016-01-21 18:11:44 +000063#include "llvm/IR/InstVisitor.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#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"
75#include <string>
76#include <utility>
77#include <vector>
78
79using namespace llvm;
80
81#define DEBUG_TYPE "pgo-instrumentation"
82
83STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
84STATISTIC(NumOfPGOEdge, "Number of edges.");
85STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
86STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
87STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
88STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
89STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000090STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000091
92// Command line option to specify the file to read profile from. This is
93// mainly used for testing.
94static cl::opt<std::string>
95 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
96 cl::value_desc("filename"),
97 cl::desc("Specify the path of profile data file. This is"
98 "mainly for test purpose."));
99
Rong Xued9fec72016-01-21 18:11:44 +0000100// Command line options to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000101// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xued9fec72016-01-21 18:11:44 +0000102static cl::opt<bool>
103DisableValueProfiling("disable-vp", cl::init(false),
104 cl::Hidden,
105 cl::desc("Disable Value Profiling"));
106
Rong Xuf430ae42015-12-09 18:08:16 +0000107namespace {
108class PGOInstrumentationGen : public ModulePass {
109public:
110 static char ID;
111
112 PGOInstrumentationGen() : ModulePass(ID) {
113 initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());
114 }
115
116 const char *getPassName() const override {
117 return "PGOInstrumentationGenPass";
118 }
119
120private:
121 bool runOnModule(Module &M) override;
122
123 void getAnalysisUsage(AnalysisUsage &AU) const override {
124 AU.addRequired<BlockFrequencyInfoWrapperPass>();
125 }
126};
127
128class PGOInstrumentationUse : public ModulePass {
129public:
130 static char ID;
131
132 // Provide the profile filename as the parameter.
133 PGOInstrumentationUse(std::string Filename = "")
134 : ModulePass(ID), ProfileFileName(Filename) {
135 if (!PGOTestProfileFile.empty())
136 ProfileFileName = PGOTestProfileFile;
137 initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
138 }
139
140 const char *getPassName() const override {
141 return "PGOInstrumentationUsePass";
142 }
143
144private:
145 std::string ProfileFileName;
146 std::unique_ptr<IndexedInstrProfReader> PGOReader;
147 bool runOnModule(Module &M) override;
148
149 void getAnalysisUsage(AnalysisUsage &AU) const override {
150 AU.addRequired<BlockFrequencyInfoWrapperPass>();
151 }
152};
153} // end anonymous namespace
154
155char PGOInstrumentationGen::ID = 0;
156INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
157 "PGO instrumentation.", false, false)
158INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
159INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
160INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
161 "PGO instrumentation.", false, false)
162
163ModulePass *llvm::createPGOInstrumentationGenPass() {
164 return new PGOInstrumentationGen();
165}
166
167char PGOInstrumentationUse::ID = 0;
168INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
169 "Read PGO instrumentation profile.", false, false)
170INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
171INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
172INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
173 "Read PGO instrumentation profile.", false, false)
174
175ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
176 return new PGOInstrumentationUse(Filename.str());
177}
178
179namespace {
180/// \brief An MST based instrumentation for PGO
181///
182/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
183/// in the function level.
184struct PGOEdge {
185 // This class implements the CFG edges. Note the CFG can be a multi-graph.
186 // So there might be multiple edges with same SrcBB and DestBB.
187 const BasicBlock *SrcBB;
188 const BasicBlock *DestBB;
189 uint64_t Weight;
190 bool InMST;
191 bool Removed;
192 bool IsCritical;
193 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
194 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
195 IsCritical(false) {}
196 // Return the information string of an edge.
197 const std::string infoString() const {
198 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
199 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
200 }
201};
202
203// This class stores the auxiliary information for each BB.
204struct BBInfo {
205 BBInfo *Group;
206 uint32_t Index;
207 uint32_t Rank;
208
209 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
210
211 // Return the information string of this object.
212 const std::string infoString() const {
213 return (Twine("Index=") + Twine(Index)).str();
214 }
215};
216
217// This class implements the CFG edges. Note the CFG can be a multi-graph.
218template <class Edge, class BBInfo> class FuncPGOInstrumentation {
219private:
220 Function &F;
221 void computeCFGHash();
222
223public:
224 std::string FuncName;
225 GlobalVariable *FuncNameVar;
226 // CFG hash value for this function.
227 uint64_t FunctionHash;
228
229 // The Minimum Spanning Tree of function CFG.
230 CFGMST<Edge, BBInfo> MST;
231
232 // Give an edge, find the BB that will be instrumented.
233 // Return nullptr if there is no BB to be instrumented.
234 BasicBlock *getInstrBB(Edge *E);
235
236 // Return the auxiliary BB information.
237 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
238
239 // Dump edges and BB information.
240 void dumpInfo(std::string Str = "") const {
241 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000242 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000243 }
244
245 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
246 BranchProbabilityInfo *BPI = nullptr,
247 BlockFrequencyInfo *BFI = nullptr)
248 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
249 FuncName = getPGOFuncName(F);
250 computeCFGHash();
251 DEBUG(dumpInfo("after CFGMST"));
252
253 NumOfPGOBB += MST.BBInfos.size();
254 for (auto &E : MST.AllEdges) {
255 if (E->Removed)
256 continue;
257 NumOfPGOEdge++;
258 if (!E->InMST)
259 NumOfPGOInstrument++;
260 }
261
262 if (CreateGlobalVar)
263 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000264 }
Rong Xuf430ae42015-12-09 18:08:16 +0000265};
266
267// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
268// value of each BB in the CFG. The higher 32 bits record the number of edges.
269template <class Edge, class BBInfo>
270void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
271 std::vector<char> Indexes;
272 JamCRC JC;
273 for (auto &BB : F) {
274 const TerminatorInst *TI = BB.getTerminator();
275 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
276 BasicBlock *Succ = TI->getSuccessor(I);
277 uint32_t Index = getBBInfo(Succ).Index;
278 for (int J = 0; J < 4; J++)
279 Indexes.push_back((char)(Index >> (J * 8)));
280 }
281 }
282 JC.update(Indexes);
283 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
284}
285
286// Given a CFG E to be instrumented, find which BB to place the instrumented
287// code. The function will split the critical edge if necessary.
288template <class Edge, class BBInfo>
289BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
290 if (E->InMST || E->Removed)
291 return nullptr;
292
293 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
294 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
295 // For a fake edge, instrument the real BB.
296 if (SrcBB == nullptr)
297 return DestBB;
298 if (DestBB == nullptr)
299 return SrcBB;
300
301 // Instrument the SrcBB if it has a single successor,
302 // otherwise, the DestBB if this is not a critical edge.
303 TerminatorInst *TI = SrcBB->getTerminator();
304 if (TI->getNumSuccessors() <= 1)
305 return SrcBB;
306 if (!E->IsCritical)
307 return DestBB;
308
309 // For a critical edge, we have to split. Instrument the newly
310 // created BB.
311 NumOfPGOSplit++;
312 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
313 << getBBInfo(DestBB).Index << "\n");
314 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
315 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
316 assert(InstrBB && "Critical edge is not split");
317
318 E->Removed = true;
319 return InstrBB;
320}
321
Rong Xued9fec72016-01-21 18:11:44 +0000322// Visitor class that finds all indirect call sites.
323struct PGOIndirectCallSiteVisitor
324 : public InstVisitor<PGOIndirectCallSiteVisitor> {
325 std::vector<CallInst *> IndirectCallInsts;
326 PGOIndirectCallSiteVisitor() {}
327
328 void visitCallInst(CallInst &I) {
329 CallSite CS(&I);
330 if (CS.getCalledFunction() || !CS.getCalledValue())
331 return;
332 IndirectCallInsts.push_back(&I);
333 }
334};
335
336// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000337// Critical edges will be split.
338static void instrumentOneFunc(Function &F, Module *M,
339 BranchProbabilityInfo *BPI,
340 BlockFrequencyInfo *BFI) {
341 unsigned NumCounters = 0;
342 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
343 for (auto &E : FuncInfo.MST.AllEdges) {
344 if (!E->InMST && !E->Removed)
345 NumCounters++;
346 }
347
348 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000349 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000350 for (auto &E : FuncInfo.MST.AllEdges) {
351 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
352 if (!InstrBB)
353 continue;
354
355 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
356 assert(Builder.GetInsertPoint() != InstrBB->end() &&
357 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000358 Builder.CreateCall(
359 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
360 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
361 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
362 Builder.getInt32(I++)});
363 }
Rong Xued9fec72016-01-21 18:11:44 +0000364
365 if (DisableValueProfiling)
366 return;
367
368 unsigned NumIndirectCallSites = 0;
369 PGOIndirectCallSiteVisitor ICV;
370 ICV.visit(F);
371 for (auto &I : ICV.IndirectCallInsts) {
372 CallSite CS(I);
373 Value *Callee = CS.getCalledValue();
374 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
375 << NumIndirectCallSites << "\n");
376 IRBuilder<> Builder(I);
377 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
378 "Cannot get the Instrumentation point");
379 Builder.CreateCall(
380 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
381 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
382 Builder.getInt64(FuncInfo.FunctionHash),
383 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
384 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
385 Builder.getInt32(NumIndirectCallSites++)});
386 }
387 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000388}
389
390// This class represents a CFG edge in profile use compilation.
391struct PGOUseEdge : public PGOEdge {
392 bool CountValid;
393 uint64_t CountValue;
394 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
395 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
396
397 // Set edge count value
398 void setEdgeCount(uint64_t Value) {
399 CountValue = Value;
400 CountValid = true;
401 }
402
403 // Return the information string for this object.
404 const std::string infoString() const {
405 if (!CountValid)
406 return PGOEdge::infoString();
407 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)).str();
408 }
409};
410
411typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
412
413// This class stores the auxiliary information for each BB.
414struct UseBBInfo : public BBInfo {
415 uint64_t CountValue;
416 bool CountValid;
417 int32_t UnknownCountInEdge;
418 int32_t UnknownCountOutEdge;
419 DirectEdges InEdges;
420 DirectEdges OutEdges;
421 UseBBInfo(unsigned IX)
422 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
423 UnknownCountOutEdge(0) {}
424 UseBBInfo(unsigned IX, uint64_t C)
425 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
426 UnknownCountOutEdge(0) {}
427
428 // Set the profile count value for this BB.
429 void setBBInfoCount(uint64_t Value) {
430 CountValue = Value;
431 CountValid = true;
432 }
433
434 // Return the information string of this object.
435 const std::string infoString() const {
436 if (!CountValid)
437 return BBInfo::infoString();
438 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
439 }
440};
441
442// Sum up the count values for all the edges.
443static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
444 uint64_t Total = 0;
445 for (auto &E : Edges) {
446 if (E->Removed)
447 continue;
448 Total += E->CountValue;
449 }
450 return Total;
451}
452
453class PGOUseFunc {
454private:
455 Function &F;
456 Module *M;
457 // This member stores the shared information with class PGOGenFunc.
458 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
459
460 // Return the auxiliary BB information.
461 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
462 return FuncInfo.getBBInfo(BB);
463 }
464
465 // The maximum count value in the profile. This is only used in PGO use
466 // compilation.
467 uint64_t ProgramMaxCount;
468
Rong Xu13b01dc2016-02-10 18:24:45 +0000469 // ProfileRecord for this function.
470 InstrProfRecord ProfileRecord;
471
Rong Xuf430ae42015-12-09 18:08:16 +0000472 // Find the Instrumented BB and set the value.
473 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
474
475 // Set the edge counter value for the unknown edge -- there should be only
476 // one unknown edge.
477 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
478
479 // Return FuncName string;
480 const std::string getFuncName() const { return FuncInfo.FuncName; }
481
482 // Set the hot/cold inline hints based on the count values.
483 // FIXME: This function should be removed once the functionality in
484 // the inliner is implemented.
485 void applyFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
486 if (ProgramMaxCount == 0)
487 return;
488 // Threshold of the hot functions.
489 const BranchProbability HotFunctionThreshold(1, 100);
490 // Threshold of the cold functions.
491 const BranchProbability ColdFunctionThreshold(2, 10000);
492 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
493 F.addFnAttr(llvm::Attribute::InlineHint);
494 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
495 F.addFnAttr(llvm::Attribute::Cold);
496 }
497
498public:
499 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
500 BlockFrequencyInfo *BFI = nullptr)
501 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI) {}
502
503 // Read counts for the instrumented BB from profile.
504 bool readCounters(IndexedInstrProfReader *PGOReader);
505
506 // Populate the counts for all BBs.
507 void populateCounters();
508
509 // Set the branch weights based on the count values.
510 void setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000511
512 // Annotate the indirect call sites.
513 void annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000514};
515
516// Visit all the edges and assign the count value for the instrumented
517// edges and the BB.
518void PGOUseFunc::setInstrumentedCounts(
519 const std::vector<uint64_t> &CountFromProfile) {
520
521 // Use a worklist as we will update the vector during the iteration.
522 std::vector<PGOUseEdge *> WorkList;
523 for (auto &E : FuncInfo.MST.AllEdges)
524 WorkList.push_back(E.get());
525
526 uint32_t I = 0;
527 for (auto &E : WorkList) {
528 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
529 if (!InstrBB)
530 continue;
531 uint64_t CountValue = CountFromProfile[I++];
532 if (!E->Removed) {
533 getBBInfo(InstrBB).setBBInfoCount(CountValue);
534 E->setEdgeCount(CountValue);
535 continue;
536 }
537
538 // Need to add two new edges.
539 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
540 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
541 // Add new edge of SrcBB->InstrBB.
542 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
543 NewEdge.setEdgeCount(CountValue);
544 // Add new edge of InstrBB->DestBB.
545 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
546 NewEdge1.setEdgeCount(CountValue);
547 NewEdge1.InMST = true;
548 getBBInfo(InstrBB).setBBInfoCount(CountValue);
549 }
550}
551
552// Set the count value for the unknown edge. There should be one and only one
553// unknown edge in Edges vector.
554void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
555 for (auto &E : Edges) {
556 if (E->CountValid)
557 continue;
558 E->setEdgeCount(Value);
559
560 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
561 getBBInfo(E->DestBB).UnknownCountInEdge--;
562 return;
563 }
564 llvm_unreachable("Cannot find the unknown count edge");
565}
566
567// Read the profile from ProfileFileName and assign the value to the
568// instrumented BB and the edges. This function also updates ProgramMaxCount.
569// Return true if the profile are successfully read, and false on errors.
570bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
571 auto &Ctx = M->getContext();
572 ErrorOr<InstrProfRecord> Result =
573 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
574 if (std::error_code EC = Result.getError()) {
575 if (EC == instrprof_error::unknown_function)
576 NumOfPGOMissing++;
577 else if (EC == instrprof_error::hash_mismatch ||
578 EC == llvm::instrprof_error::malformed)
579 NumOfPGOMismatch++;
580
581 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
582 Ctx.diagnose(
583 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
584 return false;
585 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000586 ProfileRecord = std::move(Result.get());
587 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000588
589 NumOfPGOFunc++;
590 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
591 uint64_t ValueSum = 0;
592 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
593 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
594 ValueSum += CountFromProfile[I];
595 }
596
597 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
598
599 getBBInfo(nullptr).UnknownCountOutEdge = 2;
600 getBBInfo(nullptr).UnknownCountInEdge = 2;
601
602 setInstrumentedCounts(CountFromProfile);
603 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
604 return true;
605}
606
607// Populate the counters from instrumented BBs to all BBs.
608// In the end of this operation, all BBs should have a valid count value.
609void PGOUseFunc::populateCounters() {
610 // First set up Count variable for all BBs.
611 for (auto &E : FuncInfo.MST.AllEdges) {
612 if (E->Removed)
613 continue;
614
615 const BasicBlock *SrcBB = E->SrcBB;
616 const BasicBlock *DestBB = E->DestBB;
617 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
618 UseBBInfo &DestInfo = getBBInfo(DestBB);
619 SrcInfo.OutEdges.push_back(E.get());
620 DestInfo.InEdges.push_back(E.get());
621 SrcInfo.UnknownCountOutEdge++;
622 DestInfo.UnknownCountInEdge++;
623
624 if (!E->CountValid)
625 continue;
626 DestInfo.UnknownCountInEdge--;
627 SrcInfo.UnknownCountOutEdge--;
628 }
629
630 bool Changes = true;
631 unsigned NumPasses = 0;
632 while (Changes) {
633 NumPasses++;
634 Changes = false;
635
636 // For efficient traversal, it's better to start from the end as most
637 // of the instrumented edges are at the end.
638 for (auto &BB : reverse(F)) {
639 UseBBInfo &Count = getBBInfo(&BB);
640 if (!Count.CountValid) {
641 if (Count.UnknownCountOutEdge == 0) {
642 Count.CountValue = sumEdgeCount(Count.OutEdges);
643 Count.CountValid = true;
644 Changes = true;
645 } else if (Count.UnknownCountInEdge == 0) {
646 Count.CountValue = sumEdgeCount(Count.InEdges);
647 Count.CountValid = true;
648 Changes = true;
649 }
650 }
651 if (Count.CountValid) {
652 if (Count.UnknownCountOutEdge == 1) {
653 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
654 setEdgeCount(Count.OutEdges, Total);
655 Changes = true;
656 }
657 if (Count.UnknownCountInEdge == 1) {
658 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
659 setEdgeCount(Count.InEdges, Total);
660 Changes = true;
661 }
662 }
663 }
664 }
665
666 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
667 // Assert every BB has a valid counter.
668 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
669 uint64_t FuncMaxCount = FuncEntryCount;
670 for (auto &BB : F) {
671 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
672 uint64_t Count = getBBInfo(&BB).CountValue;
673 if (Count > FuncMaxCount)
674 FuncMaxCount = Count;
675 }
676 applyFunctionAttributes(FuncEntryCount, FuncMaxCount);
677
678 DEBUG(FuncInfo.dumpInfo("after reading profile."));
679}
680
681// Assign the scaled count values to the BB with multiple out edges.
682void PGOUseFunc::setBranchWeights() {
683 // Generate MD_prof metadata for every branch instruction.
684 DEBUG(dbgs() << "\nSetting branch weights.\n");
685 MDBuilder MDB(M->getContext());
686 for (auto &BB : F) {
687 TerminatorInst *TI = BB.getTerminator();
688 if (TI->getNumSuccessors() < 2)
689 continue;
690 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
691 continue;
692 if (getBBInfo(&BB).CountValue == 0)
693 continue;
694
695 // We have a non-zero Branch BB.
696 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
697 unsigned Size = BBCountInfo.OutEdges.size();
698 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
699 uint64_t MaxCount = 0;
700 for (unsigned s = 0; s < Size; s++) {
701 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
702 const BasicBlock *SrcBB = E->SrcBB;
703 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000704 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000705 continue;
706 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
707 uint64_t EdgeCount = E->CountValue;
708 if (EdgeCount > MaxCount)
709 MaxCount = EdgeCount;
710 EdgeCounts[SuccNum] = EdgeCount;
711 }
712 assert(MaxCount > 0 && "Bad max count");
713 uint64_t Scale = calculateCountScale(MaxCount);
714 SmallVector<unsigned, 4> Weights;
715 for (const auto &ECI : EdgeCounts)
716 Weights.push_back(scaleBranchCount(ECI, Scale));
717
718 TI->setMetadata(llvm::LLVMContext::MD_prof,
719 MDB.createBranchWeights(Weights));
720 DEBUG(dbgs() << "Weight is: ";
721 for (const auto &W : Weights) { dbgs() << W << " "; }
722 dbgs() << "\n";);
723 }
724}
Rong Xu13b01dc2016-02-10 18:24:45 +0000725
726// Traverse all the indirect callsites and annotate the instructions.
727void PGOUseFunc::annotateIndirectCallSites() {
728 if (DisableValueProfiling)
729 return;
730
731 unsigned IndirectCallSiteIndex = 0;
732 PGOIndirectCallSiteVisitor ICV;
733 ICV.visit(F);
734 unsigned NumValueSites=
735 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
736 if (NumValueSites != ICV.IndirectCallInsts.size()) {
737 std::string Msg =
738 std::string("Inconsistent number of indirect call sites: ") +
739 F.getName().str();
740 auto &Ctx = M->getContext();
741 Ctx.diagnose(
742 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
743 return;
744 }
745
746 for (auto &I : ICV.IndirectCallInsts) {
747 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
748 << IndirectCallSiteIndex << " out of "
749 << NumValueSites<< "\n");
750 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
751 IndirectCallSiteIndex);
752 IndirectCallSiteIndex++;
753 }
754}
Rong Xuf430ae42015-12-09 18:08:16 +0000755} // end anonymous namespace
756
Rong Xu33c76c02016-02-10 17:18:30 +0000757// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
758// aware this is an ir_level profile so it can set the version flag.
759static void createIRLevelProfileFlagVariable(Module &M) {
760 Type *IntTy64 = Type::getInt64Ty(M.getContext());
761 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
762 auto IRLevelVersionVariable =
763 new GlobalVariable(M, IntTy64, true, GlobalVariable::ExternalLinkage,
764 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
765 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
766 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
767 Triple TT(M.getTargetTriple());
768 if (TT.isOSBinFormatMachO())
769 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
770 else
771 IRLevelVersionVariable->setComdat(
772 M.getOrInsertComdat(StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
773}
774
Rong Xuf430ae42015-12-09 18:08:16 +0000775bool PGOInstrumentationGen::runOnModule(Module &M) {
Rong Xu33c76c02016-02-10 17:18:30 +0000776 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000777 for (auto &F : M) {
778 if (F.isDeclaration())
779 continue;
780 BranchProbabilityInfo *BPI =
781 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
782 BlockFrequencyInfo *BFI =
783 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
784 instrumentOneFunc(F, &M, BPI, BFI);
785 }
786 return true;
787}
788
789static void setPGOCountOnFunc(PGOUseFunc &Func,
790 IndexedInstrProfReader *PGOReader) {
791 if (Func.readCounters(PGOReader)) {
792 Func.populateCounters();
793 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000794 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000795 }
796}
797
798bool PGOInstrumentationUse::runOnModule(Module &M) {
799 DEBUG(dbgs() << "Read in profile counters: ");
800 auto &Ctx = M.getContext();
801 // Read the counter array from file.
802 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
803 if (std::error_code EC = ReaderOrErr.getError()) {
804 Ctx.diagnose(
805 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
806 return false;
807 }
808
809 PGOReader = std::move(ReaderOrErr.get());
810 if (!PGOReader) {
811 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
812 "Cannot get PGOReader"));
813 return false;
814 }
Rong Xu33c76c02016-02-10 17:18:30 +0000815 // TODO: might need to change the warning once the clang option is finalized.
816 if (!PGOReader->isIRLevelProfile()) {
817 Ctx.diagnose(DiagnosticInfoPGOProfile(
818 ProfileFileName.data(), "Not an IR level instrumentation profile"));
819 return false;
820 }
821
Rong Xuf430ae42015-12-09 18:08:16 +0000822
823 for (auto &F : M) {
824 if (F.isDeclaration())
825 continue;
826 BranchProbabilityInfo *BPI =
827 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
828 BlockFrequencyInfo *BFI =
829 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
830 PGOUseFunc Func(F, &M, BPI, BFI);
831 setPGOCountOnFunc(Func, PGOReader.get());
832 }
833 return true;
834}