1 //===-- 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
28 // count profile, and generates the instrumentation for indirect call
29 // profiling.
30 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
31 // annotates the branch weights. It also reads the indirect call value
32 // profiling records and annotate the indirect call instructions.
33 //
34 // 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 
51 #include "CFGMST.h"
52 #include "IndirectCallSiteVisitor.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/Triple.h"
56 #include "llvm/Analysis/BlockFrequencyInfo.h"
57 #include "llvm/Analysis/BranchProbabilityInfo.h"
58 #include "llvm/Analysis/CFG.h"
59 #include "llvm/IR/CallSite.h"
60 #include "llvm/IR/DiagnosticInfo.h"
61 #include "llvm/IR/IRBuilder.h"
62 #include "llvm/IR/InstIterator.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/MDBuilder.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/Pass.h"
68 #include "llvm/ProfileData/InstrProfReader.h"
69 #include "llvm/Support/BranchProbability.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/JamCRC.h"
72 #include "llvm/Transforms/Instrumentation.h"
73 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
74 #include <string>
75 #include <utility>
76 #include <vector>
77 
78 using namespace llvm;
79 
80 #define DEBUG_TYPE "pgo-instrumentation"
81 
82 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
83 STATISTIC(NumOfPGOEdge, "Number of edges.");
84 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
85 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
86 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
87 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
88 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
89 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
90 
91 // Command line option to specify the file to read profile from. This is
92 // mainly used for testing.
93 static cl::opt<std::string>
94     PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
95                        cl::value_desc("filename"),
96                        cl::desc("Specify the path of profile data file. This is"
97                                 "mainly for test purpose."));
98 
99 // Command line option to disable value profiling. The default is false:
100 // i.e. value profiling is enabled by default. This is for debug purpose.
101 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
102                                            cl::Hidden,
103                                            cl::desc("Disable Value Profiling"));
104 
105 // Command line option to set the maximum number of VP annotations to write to
106 // the metadata for a single indirect call callsite.
107 static cl::opt<unsigned> MaxNumAnnotations(
108     "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
109     cl::desc("Max number of annotations for a single indirect "
110              "call callsite"));
111 
112 namespace {
113 class PGOInstrumentationGen : public ModulePass {
114 public:
115   static char ID;
116 
117   PGOInstrumentationGen() : ModulePass(ID) {
118     initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());
119   }
120 
121   const char *getPassName() const override {
122     return "PGOInstrumentationGenPass";
123   }
124 
125 private:
126   bool runOnModule(Module &M) override;
127 
128   void getAnalysisUsage(AnalysisUsage &AU) const override {
129     AU.addRequired<BlockFrequencyInfoWrapperPass>();
130   }
131 };
132 
133 class PGOInstrumentationUse : public ModulePass {
134 public:
135   static char ID;
136 
137   // Provide the profile filename as the parameter.
138   PGOInstrumentationUse(std::string Filename = "")
139       : ModulePass(ID), ProfileFileName(Filename) {
140     if (!PGOTestProfileFile.empty())
141       ProfileFileName = PGOTestProfileFile;
142     initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
143   }
144 
145   const char *getPassName() const override {
146     return "PGOInstrumentationUsePass";
147   }
148 
149 private:
150   std::string ProfileFileName;
151   std::unique_ptr<IndexedInstrProfReader> PGOReader;
152   bool runOnModule(Module &M) override;
153 
154   void getAnalysisUsage(AnalysisUsage &AU) const override {
155     AU.addRequired<BlockFrequencyInfoWrapperPass>();
156   }
157 };
158 } // end anonymous namespace
159 
160 char PGOInstrumentationGen::ID = 0;
161 INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
162                       "PGO instrumentation.", false, false)
163 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
164 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
165 INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
166                     "PGO instrumentation.", false, false)
167 
168 ModulePass *llvm::createPGOInstrumentationGenPass() {
169   return new PGOInstrumentationGen();
170 }
171 
172 char PGOInstrumentationUse::ID = 0;
173 INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
174                       "Read PGO instrumentation profile.", false, false)
175 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
176 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
177 INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
178                     "Read PGO instrumentation profile.", false, false)
179 
180 ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
181   return new PGOInstrumentationUse(Filename.str());
182 }
183 
184 namespace {
185 /// \brief An MST based instrumentation for PGO
186 ///
187 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
188 /// in the function level.
189 struct PGOEdge {
190   // This class implements the CFG edges. Note the CFG can be a multi-graph.
191   // So there might be multiple edges with same SrcBB and DestBB.
192   const BasicBlock *SrcBB;
193   const BasicBlock *DestBB;
194   uint64_t Weight;
195   bool InMST;
196   bool Removed;
197   bool IsCritical;
198   PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
199       : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
200         IsCritical(false) {}
201   // Return the information string of an edge.
202   const std::string infoString() const {
203     return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
204             (IsCritical ? "c" : " ") + "  W=" + Twine(Weight)).str();
205   }
206 };
207 
208 // This class stores the auxiliary information for each BB.
209 struct BBInfo {
210   BBInfo *Group;
211   uint32_t Index;
212   uint32_t Rank;
213 
214   BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
215 
216   // Return the information string of this object.
217   const std::string infoString() const {
218     return (Twine("Index=") + Twine(Index)).str();
219   }
220 };
221 
222 // This class implements the CFG edges. Note the CFG can be a multi-graph.
223 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
224 private:
225   Function &F;
226   void computeCFGHash();
227 
228 public:
229   std::string FuncName;
230   GlobalVariable *FuncNameVar;
231   // CFG hash value for this function.
232   uint64_t FunctionHash;
233 
234   // The Minimum Spanning Tree of function CFG.
235   CFGMST<Edge, BBInfo> MST;
236 
237   // Give an edge, find the BB that will be instrumented.
238   // Return nullptr if there is no BB to be instrumented.
239   BasicBlock *getInstrBB(Edge *E);
240 
241   // Return the auxiliary BB information.
242   BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
243 
244   // Dump edges and BB information.
245   void dumpInfo(std::string Str = "") const {
246     MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
247                               Twine(FunctionHash) + "\t" + Str);
248   }
249 
250   FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
251                          BranchProbabilityInfo *BPI = nullptr,
252                          BlockFrequencyInfo *BFI = nullptr)
253       : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
254     FuncName = getPGOFuncName(F);
255     computeCFGHash();
256     DEBUG(dumpInfo("after CFGMST"));
257 
258     NumOfPGOBB += MST.BBInfos.size();
259     for (auto &E : MST.AllEdges) {
260       if (E->Removed)
261         continue;
262       NumOfPGOEdge++;
263       if (!E->InMST)
264         NumOfPGOInstrument++;
265     }
266 
267     if (CreateGlobalVar)
268       FuncNameVar = createPGOFuncNameVar(F, FuncName);
269   }
270 };
271 
272 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
273 // value of each BB in the CFG. The higher 32 bits record the number of edges.
274 template <class Edge, class BBInfo>
275 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
276   std::vector<char> Indexes;
277   JamCRC JC;
278   for (auto &BB : F) {
279     const TerminatorInst *TI = BB.getTerminator();
280     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
281       BasicBlock *Succ = TI->getSuccessor(I);
282       uint32_t Index = getBBInfo(Succ).Index;
283       for (int J = 0; J < 4; J++)
284         Indexes.push_back((char)(Index >> (J * 8)));
285     }
286   }
287   JC.update(Indexes);
288   FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
289 }
290 
291 // Given a CFG E to be instrumented, find which BB to place the instrumented
292 // code. The function will split the critical edge if necessary.
293 template <class Edge, class BBInfo>
294 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
295   if (E->InMST || E->Removed)
296     return nullptr;
297 
298   BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
299   BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
300   // For a fake edge, instrument the real BB.
301   if (SrcBB == nullptr)
302     return DestBB;
303   if (DestBB == nullptr)
304     return SrcBB;
305 
306   // Instrument the SrcBB if it has a single successor,
307   // otherwise, the DestBB if this is not a critical edge.
308   TerminatorInst *TI = SrcBB->getTerminator();
309   if (TI->getNumSuccessors() <= 1)
310     return SrcBB;
311   if (!E->IsCritical)
312     return DestBB;
313 
314   // For a critical edge, we have to split. Instrument the newly
315   // created BB.
316   NumOfPGOSplit++;
317   DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
318                << getBBInfo(DestBB).Index << "\n");
319   unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
320   BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
321   assert(InstrBB && "Critical edge is not split");
322 
323   E->Removed = true;
324   return InstrBB;
325 }
326 
327 // Visit all edge and instrument the edges not in MST, and do value profiling.
328 // Critical edges will be split.
329 static void instrumentOneFunc(Function &F, Module *M,
330                               BranchProbabilityInfo *BPI,
331                               BlockFrequencyInfo *BFI) {
332   unsigned NumCounters = 0;
333   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
334   for (auto &E : FuncInfo.MST.AllEdges) {
335     if (!E->InMST && !E->Removed)
336       NumCounters++;
337   }
338 
339   uint32_t I = 0;
340   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
341   for (auto &E : FuncInfo.MST.AllEdges) {
342     BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
343     if (!InstrBB)
344       continue;
345 
346     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
347     assert(Builder.GetInsertPoint() != InstrBB->end() &&
348            "Cannot get the Instrumentation point");
349     Builder.CreateCall(
350         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
351         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
352          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
353          Builder.getInt32(I++)});
354   }
355 
356   if (DisableValueProfiling)
357     return;
358 
359   unsigned NumIndirectCallSites = 0;
360   for (auto &I : findIndirectCallSites(F)) {
361     CallSite CS(I);
362     Value *Callee = CS.getCalledValue();
363     DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
364                  << NumIndirectCallSites << "\n");
365     IRBuilder<> Builder(I);
366     assert(Builder.GetInsertPoint() != I->getParent()->end() &&
367            "Cannot get the Instrumentation point");
368     Builder.CreateCall(
369         Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
370         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
371          Builder.getInt64(FuncInfo.FunctionHash),
372          Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
373          Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
374          Builder.getInt32(NumIndirectCallSites++)});
375   }
376   NumOfPGOICall += NumIndirectCallSites;
377 }
378 
379 // This class represents a CFG edge in profile use compilation.
380 struct PGOUseEdge : public PGOEdge {
381   bool CountValid;
382   uint64_t CountValue;
383   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
384       : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
385 
386   // Set edge count value
387   void setEdgeCount(uint64_t Value) {
388     CountValue = Value;
389     CountValid = true;
390   }
391 
392   // Return the information string for this object.
393   const std::string infoString() const {
394     if (!CountValid)
395       return PGOEdge::infoString();
396     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
397         .str();
398   }
399 };
400 
401 typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
402 
403 // This class stores the auxiliary information for each BB.
404 struct UseBBInfo : public BBInfo {
405   uint64_t CountValue;
406   bool CountValid;
407   int32_t UnknownCountInEdge;
408   int32_t UnknownCountOutEdge;
409   DirectEdges InEdges;
410   DirectEdges OutEdges;
411   UseBBInfo(unsigned IX)
412       : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
413         UnknownCountOutEdge(0) {}
414   UseBBInfo(unsigned IX, uint64_t C)
415       : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
416         UnknownCountOutEdge(0) {}
417 
418   // Set the profile count value for this BB.
419   void setBBInfoCount(uint64_t Value) {
420     CountValue = Value;
421     CountValid = true;
422   }
423 
424   // Return the information string of this object.
425   const std::string infoString() const {
426     if (!CountValid)
427       return BBInfo::infoString();
428     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
429   }
430 };
431 
432 // Sum up the count values for all the edges.
433 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
434   uint64_t Total = 0;
435   for (auto &E : Edges) {
436     if (E->Removed)
437       continue;
438     Total += E->CountValue;
439   }
440   return Total;
441 }
442 
443 class PGOUseFunc {
444 public:
445   PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
446              BlockFrequencyInfo *BFI = nullptr)
447       : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
448         FreqAttr(FFA_Normal) {}
449 
450   // Read counts for the instrumented BB from profile.
451   bool readCounters(IndexedInstrProfReader *PGOReader);
452 
453   // Populate the counts for all BBs.
454   void populateCounters();
455 
456   // Set the branch weights based on the count values.
457   void setBranchWeights();
458 
459   // Annotate the indirect call sites.
460   void annotateIndirectCallSites();
461 
462   // The hotness of the function from the profile count.
463   enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
464 
465   // Return the function hotness from the profile.
466   FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
467 
468 private:
469   Function &F;
470   Module *M;
471   // This member stores the shared information with class PGOGenFunc.
472   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
473 
474   // Return the auxiliary BB information.
475   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
476     return FuncInfo.getBBInfo(BB);
477   }
478 
479   // The maximum count value in the profile. This is only used in PGO use
480   // compilation.
481   uint64_t ProgramMaxCount;
482 
483   // ProfileRecord for this function.
484   InstrProfRecord ProfileRecord;
485 
486   // Function hotness info derived from profile.
487   FuncFreqAttr FreqAttr;
488 
489   // Find the Instrumented BB and set the value.
490   void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
491 
492   // Set the edge counter value for the unknown edge -- there should be only
493   // one unknown edge.
494   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
495 
496   // Return FuncName string;
497   const std::string getFuncName() const { return FuncInfo.FuncName; }
498 
499   // Set the hot/cold inline hints based on the count values.
500   // FIXME: This function should be removed once the functionality in
501   // the inliner is implemented.
502   void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
503     if (ProgramMaxCount == 0)
504       return;
505     // Threshold of the hot functions.
506     const BranchProbability HotFunctionThreshold(1, 100);
507     // Threshold of the cold functions.
508     const BranchProbability ColdFunctionThreshold(2, 10000);
509     if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
510       FreqAttr = FFA_Hot;
511     else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
512       FreqAttr = FFA_Cold;
513   }
514 };
515 
516 // Visit all the edges and assign the count value for the instrumented
517 // edges and the BB.
518 void 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.
554 void 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.
570 bool 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   }
586   ProfileRecord = std::move(Result.get());
587   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
588 
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.
609 void 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   markFunctionAttributes(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.
682 void 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;
704       if (DestBB == nullptr)
705         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 }
725 
726 // Traverse all the indirect callsites and annotate the instructions.
727 void PGOUseFunc::annotateIndirectCallSites() {
728   if (DisableValueProfiling)
729     return;
730 
731   // Create the PGOFuncName meta data.
732   createPGOFuncNameMetadata(F, FuncInfo.FuncName);
733 
734   unsigned IndirectCallSiteIndex = 0;
735   auto IndirectCallSites = findIndirectCallSites(F);
736   unsigned NumValueSites =
737       ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
738   if (NumValueSites != IndirectCallSites.size()) {
739     std::string Msg =
740         std::string("Inconsistent number of indirect call sites: ") +
741         F.getName().str();
742     auto &Ctx = M->getContext();
743     Ctx.diagnose(
744         DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
745     return;
746   }
747 
748   for (auto &I : IndirectCallSites) {
749     DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
750                  << IndirectCallSiteIndex << " out of " << NumValueSites
751                  << "\n");
752     annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
753                       IndirectCallSiteIndex, MaxNumAnnotations);
754     IndirectCallSiteIndex++;
755   }
756 }
757 } // end anonymous namespace
758 
759 // Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
760 // aware this is an ir_level profile so it can set the version flag.
761 static void createIRLevelProfileFlagVariable(Module &M) {
762   Type *IntTy64 = Type::getInt64Ty(M.getContext());
763   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
764   auto IRLevelVersionVariable = new GlobalVariable(
765       M, IntTy64, true, GlobalVariable::ExternalLinkage,
766       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
767       INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
768   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
769   Triple TT(M.getTargetTriple());
770   if (TT.isOSBinFormatMachO())
771     IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
772   else
773     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
774         StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
775 }
776 
777 bool PGOInstrumentationGen::runOnModule(Module &M) {
778   if (skipModule(M))
779     return false;
780 
781   createIRLevelProfileFlagVariable(M);
782   for (auto &F : M) {
783     if (F.isDeclaration())
784       continue;
785     BranchProbabilityInfo *BPI =
786         &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
787     BlockFrequencyInfo *BFI =
788         &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
789     instrumentOneFunc(F, &M, BPI, BFI);
790   }
791   return true;
792 }
793 
794 static void setPGOCountOnFunc(PGOUseFunc &Func,
795                               IndexedInstrProfReader *PGOReader) {
796   if (Func.readCounters(PGOReader)) {
797     Func.populateCounters();
798     Func.setBranchWeights();
799     Func.annotateIndirectCallSites();
800   }
801 }
802 
803 bool PGOInstrumentationUse::runOnModule(Module &M) {
804   if (skipModule(M))
805     return false;
806 
807   DEBUG(dbgs() << "Read in profile counters: ");
808   auto &Ctx = M.getContext();
809   // Read the counter array from file.
810   auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
811   if (std::error_code EC = ReaderOrErr.getError()) {
812     Ctx.diagnose(
813         DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
814     return false;
815   }
816 
817   PGOReader = std::move(ReaderOrErr.get());
818   if (!PGOReader) {
819     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
820                                           "Cannot get PGOReader"));
821     return false;
822   }
823   // TODO: might need to change the warning once the clang option is finalized.
824   if (!PGOReader->isIRLevelProfile()) {
825     Ctx.diagnose(DiagnosticInfoPGOProfile(
826         ProfileFileName.data(), "Not an IR level instrumentation profile"));
827     return false;
828   }
829 
830   std::vector<Function *> HotFunctions;
831   std::vector<Function *> ColdFunctions;
832   for (auto &F : M) {
833     if (F.isDeclaration())
834       continue;
835     BranchProbabilityInfo *BPI =
836         &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
837     BlockFrequencyInfo *BFI =
838         &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
839     PGOUseFunc Func(F, &M, BPI, BFI);
840     setPGOCountOnFunc(Func, PGOReader.get());
841     PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
842     if (FreqAttr == PGOUseFunc::FFA_Cold)
843       ColdFunctions.push_back(&F);
844     else if (FreqAttr == PGOUseFunc::FFA_Hot)
845       HotFunctions.push_back(&F);
846   }
847 
848   // Set function hotness attribute from the profile.
849   for (auto &F : HotFunctions) {
850     F->addFnAttr(llvm::Attribute::InlineHint);
851     DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
852                  << "\n");
853   }
854   for (auto &F : ColdFunctions) {
855     F->addFnAttr(llvm::Attribute::Cold);
856     DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
857   }
858 
859   return true;
860 }
861