blob: fa46811e4853a24c567e84de188f9ffaa15e026c [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 Xu9e926e82016-02-29 19:16:04 +0000102static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
103 cl::Hidden,
104 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000105
Rong Xuf430ae42015-12-09 18:08:16 +0000106namespace {
107class PGOInstrumentationGen : public ModulePass {
108public:
109 static char ID;
110
111 PGOInstrumentationGen() : ModulePass(ID) {
112 initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());
113 }
114
115 const char *getPassName() const override {
116 return "PGOInstrumentationGenPass";
117 }
118
119private:
120 bool runOnModule(Module &M) override;
121
122 void getAnalysisUsage(AnalysisUsage &AU) const override {
123 AU.addRequired<BlockFrequencyInfoWrapperPass>();
124 }
125};
126
127class PGOInstrumentationUse : public ModulePass {
128public:
129 static char ID;
130
131 // Provide the profile filename as the parameter.
132 PGOInstrumentationUse(std::string Filename = "")
133 : ModulePass(ID), ProfileFileName(Filename) {
134 if (!PGOTestProfileFile.empty())
135 ProfileFileName = PGOTestProfileFile;
136 initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
137 }
138
139 const char *getPassName() const override {
140 return "PGOInstrumentationUsePass";
141 }
142
143private:
144 std::string ProfileFileName;
145 std::unique_ptr<IndexedInstrProfReader> PGOReader;
146 bool runOnModule(Module &M) override;
147
148 void getAnalysisUsage(AnalysisUsage &AU) const override {
149 AU.addRequired<BlockFrequencyInfoWrapperPass>();
150 }
151};
152} // end anonymous namespace
153
154char PGOInstrumentationGen::ID = 0;
155INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
156 "PGO instrumentation.", false, false)
157INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
158INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
159INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
160 "PGO instrumentation.", false, false)
161
162ModulePass *llvm::createPGOInstrumentationGenPass() {
163 return new PGOInstrumentationGen();
164}
165
166char PGOInstrumentationUse::ID = 0;
167INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
168 "Read PGO instrumentation profile.", false, false)
169INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
170INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
171INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
172 "Read PGO instrumentation profile.", false, false)
173
174ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
175 return new PGOInstrumentationUse(Filename.str());
176}
177
178namespace {
179/// \brief An MST based instrumentation for PGO
180///
181/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
182/// in the function level.
183struct PGOEdge {
184 // This class implements the CFG edges. Note the CFG can be a multi-graph.
185 // So there might be multiple edges with same SrcBB and DestBB.
186 const BasicBlock *SrcBB;
187 const BasicBlock *DestBB;
188 uint64_t Weight;
189 bool InMST;
190 bool Removed;
191 bool IsCritical;
192 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
193 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
194 IsCritical(false) {}
195 // Return the information string of an edge.
196 const std::string infoString() const {
197 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
198 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
199 }
200};
201
202// This class stores the auxiliary information for each BB.
203struct BBInfo {
204 BBInfo *Group;
205 uint32_t Index;
206 uint32_t Rank;
207
208 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
209
210 // Return the information string of this object.
211 const std::string infoString() const {
212 return (Twine("Index=") + Twine(Index)).str();
213 }
214};
215
216// This class implements the CFG edges. Note the CFG can be a multi-graph.
217template <class Edge, class BBInfo> class FuncPGOInstrumentation {
218private:
219 Function &F;
220 void computeCFGHash();
221
222public:
223 std::string FuncName;
224 GlobalVariable *FuncNameVar;
225 // CFG hash value for this function.
226 uint64_t FunctionHash;
227
228 // The Minimum Spanning Tree of function CFG.
229 CFGMST<Edge, BBInfo> MST;
230
231 // Give an edge, find the BB that will be instrumented.
232 // Return nullptr if there is no BB to be instrumented.
233 BasicBlock *getInstrBB(Edge *E);
234
235 // Return the auxiliary BB information.
236 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
237
238 // Dump edges and BB information.
239 void dumpInfo(std::string Str = "") const {
240 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000241 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000242 }
243
244 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
245 BranchProbabilityInfo *BPI = nullptr,
246 BlockFrequencyInfo *BFI = nullptr)
247 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
248 FuncName = getPGOFuncName(F);
249 computeCFGHash();
250 DEBUG(dumpInfo("after CFGMST"));
251
252 NumOfPGOBB += MST.BBInfos.size();
253 for (auto &E : MST.AllEdges) {
254 if (E->Removed)
255 continue;
256 NumOfPGOEdge++;
257 if (!E->InMST)
258 NumOfPGOInstrument++;
259 }
260
261 if (CreateGlobalVar)
262 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000263 }
Rong Xuf430ae42015-12-09 18:08:16 +0000264};
265
266// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
267// value of each BB in the CFG. The higher 32 bits record the number of edges.
268template <class Edge, class BBInfo>
269void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
270 std::vector<char> Indexes;
271 JamCRC JC;
272 for (auto &BB : F) {
273 const TerminatorInst *TI = BB.getTerminator();
274 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
275 BasicBlock *Succ = TI->getSuccessor(I);
276 uint32_t Index = getBBInfo(Succ).Index;
277 for (int J = 0; J < 4; J++)
278 Indexes.push_back((char)(Index >> (J * 8)));
279 }
280 }
281 JC.update(Indexes);
282 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
283}
284
285// Given a CFG E to be instrumented, find which BB to place the instrumented
286// code. The function will split the critical edge if necessary.
287template <class Edge, class BBInfo>
288BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
289 if (E->InMST || E->Removed)
290 return nullptr;
291
292 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
293 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
294 // For a fake edge, instrument the real BB.
295 if (SrcBB == nullptr)
296 return DestBB;
297 if (DestBB == nullptr)
298 return SrcBB;
299
300 // Instrument the SrcBB if it has a single successor,
301 // otherwise, the DestBB if this is not a critical edge.
302 TerminatorInst *TI = SrcBB->getTerminator();
303 if (TI->getNumSuccessors() <= 1)
304 return SrcBB;
305 if (!E->IsCritical)
306 return DestBB;
307
308 // For a critical edge, we have to split. Instrument the newly
309 // created BB.
310 NumOfPGOSplit++;
311 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
312 << getBBInfo(DestBB).Index << "\n");
313 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
314 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
315 assert(InstrBB && "Critical edge is not split");
316
317 E->Removed = true;
318 return InstrBB;
319}
320
Rong Xued9fec72016-01-21 18:11:44 +0000321// Visitor class that finds all indirect call sites.
322struct PGOIndirectCallSiteVisitor
323 : public InstVisitor<PGOIndirectCallSiteVisitor> {
324 std::vector<CallInst *> IndirectCallInsts;
325 PGOIndirectCallSiteVisitor() {}
326
327 void visitCallInst(CallInst &I) {
328 CallSite CS(&I);
329 if (CS.getCalledFunction() || !CS.getCalledValue())
330 return;
331 IndirectCallInsts.push_back(&I);
332 }
333};
334
335// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000336// Critical edges will be split.
337static void instrumentOneFunc(Function &F, Module *M,
338 BranchProbabilityInfo *BPI,
339 BlockFrequencyInfo *BFI) {
340 unsigned NumCounters = 0;
341 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
342 for (auto &E : FuncInfo.MST.AllEdges) {
343 if (!E->InMST && !E->Removed)
344 NumCounters++;
345 }
346
347 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000348 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000349 for (auto &E : FuncInfo.MST.AllEdges) {
350 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
351 if (!InstrBB)
352 continue;
353
354 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
355 assert(Builder.GetInsertPoint() != InstrBB->end() &&
356 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000357 Builder.CreateCall(
358 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
359 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
360 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
361 Builder.getInt32(I++)});
362 }
Rong Xued9fec72016-01-21 18:11:44 +0000363
364 if (DisableValueProfiling)
365 return;
366
367 unsigned NumIndirectCallSites = 0;
368 PGOIndirectCallSiteVisitor ICV;
369 ICV.visit(F);
370 for (auto &I : ICV.IndirectCallInsts) {
371 CallSite CS(I);
372 Value *Callee = CS.getCalledValue();
373 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
374 << NumIndirectCallSites << "\n");
375 IRBuilder<> Builder(I);
376 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
377 "Cannot get the Instrumentation point");
378 Builder.CreateCall(
379 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
380 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
381 Builder.getInt64(FuncInfo.FunctionHash),
382 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
383 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
384 Builder.getInt32(NumIndirectCallSites++)});
385 }
386 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000387}
388
389// This class represents a CFG edge in profile use compilation.
390struct PGOUseEdge : public PGOEdge {
391 bool CountValid;
392 uint64_t CountValue;
393 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
394 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
395
396 // Set edge count value
397 void setEdgeCount(uint64_t Value) {
398 CountValue = Value;
399 CountValid = true;
400 }
401
402 // Return the information string for this object.
403 const std::string infoString() const {
404 if (!CountValid)
405 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000406 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
407 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000408 }
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);
Rong Xu9e926e82016-02-29 19:16:04 +0000734 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000735 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
736 if (NumValueSites != ICV.IndirectCallInsts.size()) {
737 std::string Msg =
738 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000739 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000740 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="
Rong Xu9e926e82016-02-29 19:16:04 +0000748 << IndirectCallSiteIndex << " out of " << NumValueSites
749 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000750 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);
Rong Xu9e926e82016-02-29 19:16:04 +0000762 auto IRLevelVersionVariable = new GlobalVariable(
763 M, IntTy64, true, GlobalVariable::ExternalLinkage,
764 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
765 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000766 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
767 Triple TT(M.getTargetTriple());
768 if (TT.isOSBinFormatMachO())
769 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
770 else
Rong Xu9e926e82016-02-29 19:16:04 +0000771 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
772 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000773}
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 for (auto &F : M) {
823 if (F.isDeclaration())
824 continue;
825 BranchProbabilityInfo *BPI =
826 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
827 BlockFrequencyInfo *BFI =
828 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
829 PGOUseFunc Func(F, &M, BPI, BFI);
830 setPGOCountOnFunc(Func, PGOReader.get());
831 }
832 return true;
833}