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 "llvm/Transforms/PGOInstrumentation.h"
52 #include "CFGMST.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/Triple.h"
57 #include "llvm/Analysis/BlockFrequencyInfo.h"
58 #include "llvm/Analysis/BranchProbabilityInfo.h"
59 #include "llvm/Analysis/CFG.h"
60 #include "llvm/Analysis/IndirectCallSiteVisitor.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/IR/CallSite.h"
63 #include "llvm/IR/DiagnosticInfo.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstIterator.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/IntrinsicInst.h"
70 #include "llvm/IR/MDBuilder.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/Pass.h"
73 #include "llvm/ProfileData/InstrProfReader.h"
74 #include "llvm/ProfileData/ProfileCommon.h"
75 #include "llvm/Support/BranchProbability.h"
76 #include "llvm/Support/DOTGraphTraits.h"
77 #include "llvm/Support/Debug.h"
78 #include "llvm/Support/GraphWriter.h"
79 #include "llvm/Support/JamCRC.h"
80 #include "llvm/Transforms/Instrumentation.h"
81 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
82 #include <algorithm>
83 #include <string>
84 #include <unordered_map>
85 #include <utility>
86 #include <vector>
87 
88 using namespace llvm;
89 
90 #define DEBUG_TYPE "pgo-instrumentation"
91 
92 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
93 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
94 STATISTIC(NumOfPGOEdge, "Number of edges.");
95 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
96 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
97 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
98 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
99 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
100 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
101 
102 // Command line option to specify the file to read profile from. This is
103 // mainly used for testing.
104 static cl::opt<std::string>
105     PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
106                        cl::value_desc("filename"),
107                        cl::desc("Specify the path of profile data file. This is"
108                                 "mainly for test purpose."));
109 
110 // Command line option to disable value profiling. The default is false:
111 // i.e. value profiling is enabled by default. This is for debug purpose.
112 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
113                                            cl::Hidden,
114                                            cl::desc("Disable Value Profiling"));
115 
116 // Command line option to set the maximum number of VP annotations to write to
117 // the metadata for a single indirect call callsite.
118 static cl::opt<unsigned> MaxNumAnnotations(
119     "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
120     cl::desc("Max number of annotations for a single indirect "
121              "call callsite"));
122 
123 // Command line option to control appending FunctionHash to the name of a COMDAT
124 // function. This is to avoid the hash mismatch caused by the preinliner.
125 static cl::opt<bool> DoComdatRenaming(
126     "do-comdat-renaming", cl::init(false), cl::Hidden,
127     cl::desc("Append function hash to the name of COMDAT function to avoid "
128              "function hash mismatch due to the preinliner"));
129 
130 // Command line option to enable/disable the warning about missing profile
131 // information.
132 static cl::opt<bool>
133     PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
134                    cl::desc("Use this option to turn on/off "
135                             "warnings about missing profile data for "
136                             "functions."));
137 
138 // Command line option to enable/disable the warning about a hash mismatch in
139 // the profile data.
140 static cl::opt<bool>
141     NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
142                       cl::desc("Use this option to turn off/on "
143                                "warnings about profile cfg mismatch."));
144 
145 // Command line option to enable/disable the warning about a hash mismatch in
146 // the profile data for Comdat functions, which often turns out to be false
147 // positive due to the pre-instrumentation inline.
148 static cl::opt<bool>
149     NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
150                             cl::Hidden,
151                             cl::desc("The option is used to turn on/off "
152                                      "warnings about hash mismatch for comdat "
153                                      "functions."));
154 
155 // Command line option to enable/disable select instruction instrumentation.
156 static cl::opt<bool>
157     PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
158                    cl::desc("Use this option to turn on/off SELECT "
159                             "instruction instrumentation. "));
160 
161 // Command line option to turn on CFG dot dump of raw profile counts
162 static cl::opt<bool>
163     PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
164                      cl::desc("A boolean option to show CFG dag "
165                               "with raw profile counts from "
166                               "profile data. See also option "
167                               "-pgo-view-counts. To limit graph "
168                               "display to only one function, use "
169                               "filtering option -view-bfi-func-name."));
170 
171 // Command line option to turn on CFG dot dump after profile annotation.
172 // Defined in Analysis/BlockFrequencyInfo.cpp:  -pgo-view-counts
173 extern cl::opt<bool> PGOViewCounts;
174 
175 // Command line option to specify the name of the function for CFG dump
176 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
177 extern cl::opt<std::string> ViewBlockFreqFuncName;
178 
179 namespace {
180 
181 /// The select instruction visitor plays three roles specified
182 /// by the mode. In \c VM_counting mode, it simply counts the number of
183 /// select instructions. In \c VM_instrument mode, it inserts code to count
184 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
185 /// it reads the profile data and annotate the select instruction with metadata.
186 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
187 class PGOUseFunc;
188 
189 /// Instruction Visitor class to visit select instructions.
190 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
191   Function &F;
192   unsigned NSIs = 0;             // Number of select instructions instrumented.
193   VisitMode Mode = VM_counting;  // Visiting mode.
194   unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
195   unsigned TotalNumCtrs = 0;     // Total number of counters
196   GlobalVariable *FuncNameVar = nullptr;
197   uint64_t FuncHash = 0;
198   PGOUseFunc *UseFunc = nullptr;
199 
200   SelectInstVisitor(Function &Func) : F(Func) {}
201 
202   void countSelects(Function &Func) {
203     Mode = VM_counting;
204     visit(Func);
205   }
206   // Visit the IR stream and instrument all select instructions. \p
207   // Ind is a pointer to the counter index variable; \p TotalNC
208   // is the total number of counters; \p FNV is the pointer to the
209   // PGO function name var; \p FHash is the function hash.
210   void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
211                          GlobalVariable *FNV, uint64_t FHash) {
212     Mode = VM_instrument;
213     CurCtrIdx = Ind;
214     TotalNumCtrs = TotalNC;
215     FuncHash = FHash;
216     FuncNameVar = FNV;
217     visit(Func);
218   }
219 
220   // Visit the IR stream and annotate all select instructions.
221   void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
222     Mode = VM_annotate;
223     UseFunc = UF;
224     CurCtrIdx = Ind;
225     visit(Func);
226   }
227 
228   void instrumentOneSelectInst(SelectInst &SI);
229   void annotateOneSelectInst(SelectInst &SI);
230   // Visit \p SI instruction and perform tasks according to visit mode.
231   void visitSelectInst(SelectInst &SI);
232   unsigned getNumOfSelectInsts() const { return NSIs; }
233 };
234 
235 class PGOInstrumentationGenLegacyPass : public ModulePass {
236 public:
237   static char ID;
238 
239   PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
240     initializePGOInstrumentationGenLegacyPassPass(
241         *PassRegistry::getPassRegistry());
242   }
243 
244   StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
245 
246 private:
247   bool runOnModule(Module &M) override;
248 
249   void getAnalysisUsage(AnalysisUsage &AU) const override {
250     AU.addRequired<BlockFrequencyInfoWrapperPass>();
251   }
252 };
253 
254 class PGOInstrumentationUseLegacyPass : public ModulePass {
255 public:
256   static char ID;
257 
258   // Provide the profile filename as the parameter.
259   PGOInstrumentationUseLegacyPass(std::string Filename = "")
260       : ModulePass(ID), ProfileFileName(std::move(Filename)) {
261     if (!PGOTestProfileFile.empty())
262       ProfileFileName = PGOTestProfileFile;
263     initializePGOInstrumentationUseLegacyPassPass(
264         *PassRegistry::getPassRegistry());
265   }
266 
267   StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
268 
269 private:
270   std::string ProfileFileName;
271 
272   bool runOnModule(Module &M) override;
273   void getAnalysisUsage(AnalysisUsage &AU) const override {
274     AU.addRequired<BlockFrequencyInfoWrapperPass>();
275   }
276 };
277 
278 } // end anonymous namespace
279 
280 char PGOInstrumentationGenLegacyPass::ID = 0;
281 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
282                       "PGO instrumentation.", false, false)
283 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
284 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
285 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
286                     "PGO instrumentation.", false, false)
287 
288 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
289   return new PGOInstrumentationGenLegacyPass();
290 }
291 
292 char PGOInstrumentationUseLegacyPass::ID = 0;
293 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
294                       "Read PGO instrumentation profile.", false, false)
295 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
296 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
297 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
298                     "Read PGO instrumentation profile.", false, false)
299 
300 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
301   return new PGOInstrumentationUseLegacyPass(Filename.str());
302 }
303 
304 namespace {
305 /// \brief An MST based instrumentation for PGO
306 ///
307 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
308 /// in the function level.
309 struct PGOEdge {
310   // This class implements the CFG edges. Note the CFG can be a multi-graph.
311   // So there might be multiple edges with same SrcBB and DestBB.
312   const BasicBlock *SrcBB;
313   const BasicBlock *DestBB;
314   uint64_t Weight;
315   bool InMST;
316   bool Removed;
317   bool IsCritical;
318   PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
319       : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
320         IsCritical(false) {}
321   // Return the information string of an edge.
322   const std::string infoString() const {
323     return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
324             (IsCritical ? "c" : " ") + "  W=" + Twine(Weight)).str();
325   }
326 };
327 
328 // This class stores the auxiliary information for each BB.
329 struct BBInfo {
330   BBInfo *Group;
331   uint32_t Index;
332   uint32_t Rank;
333 
334   BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
335 
336   // Return the information string of this object.
337   const std::string infoString() const {
338     return (Twine("Index=") + Twine(Index)).str();
339   }
340 };
341 
342 // This class implements the CFG edges. Note the CFG can be a multi-graph.
343 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
344 private:
345   Function &F;
346   void computeCFGHash();
347   void renameComdatFunction();
348   // A map that stores the Comdat group in function F.
349   std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
350 
351 public:
352   std::vector<Instruction *> IndirectCallSites;
353   SelectInstVisitor SIVisitor;
354   std::string FuncName;
355   GlobalVariable *FuncNameVar;
356   // CFG hash value for this function.
357   uint64_t FunctionHash;
358 
359   // The Minimum Spanning Tree of function CFG.
360   CFGMST<Edge, BBInfo> MST;
361 
362   // Give an edge, find the BB that will be instrumented.
363   // Return nullptr if there is no BB to be instrumented.
364   BasicBlock *getInstrBB(Edge *E);
365 
366   // Return the auxiliary BB information.
367   BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
368 
369   // Return the auxiliary BB information if available.
370   BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
371 
372   // Dump edges and BB information.
373   void dumpInfo(std::string Str = "") const {
374     MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
375                               Twine(FunctionHash) + "\t" + Str);
376   }
377 
378   FuncPGOInstrumentation(
379       Function &Func,
380       std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
381       bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
382       BlockFrequencyInfo *BFI = nullptr)
383       : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
384         MST(F, BPI, BFI) {
385 
386     // This should be done before CFG hash computation.
387     SIVisitor.countSelects(Func);
388     NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
389     IndirectCallSites = findIndirectCallSites(Func);
390 
391     FuncName = getPGOFuncName(F);
392     computeCFGHash();
393     if (ComdatMembers.size())
394       renameComdatFunction();
395     DEBUG(dumpInfo("after CFGMST"));
396 
397     NumOfPGOBB += MST.BBInfos.size();
398     for (auto &E : MST.AllEdges) {
399       if (E->Removed)
400         continue;
401       NumOfPGOEdge++;
402       if (!E->InMST)
403         NumOfPGOInstrument++;
404     }
405 
406     if (CreateGlobalVar)
407       FuncNameVar = createPGOFuncNameVar(F, FuncName);
408   }
409 
410   // Return the number of profile counters needed for the function.
411   unsigned getNumCounters() {
412     unsigned NumCounters = 0;
413     for (auto &E : this->MST.AllEdges) {
414       if (!E->InMST && !E->Removed)
415         NumCounters++;
416     }
417     return NumCounters + SIVisitor.getNumOfSelectInsts();
418   }
419 };
420 
421 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
422 // value of each BB in the CFG. The higher 32 bits record the number of edges.
423 template <class Edge, class BBInfo>
424 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
425   std::vector<char> Indexes;
426   JamCRC JC;
427   for (auto &BB : F) {
428     const TerminatorInst *TI = BB.getTerminator();
429     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
430       BasicBlock *Succ = TI->getSuccessor(I);
431       auto BI = findBBInfo(Succ);
432       if (BI == nullptr)
433         continue;
434       uint32_t Index = BI->Index;
435       for (int J = 0; J < 4; J++)
436         Indexes.push_back((char)(Index >> (J * 8)));
437     }
438   }
439   JC.update(Indexes);
440   FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
441                  (uint64_t)IndirectCallSites.size() << 48 |
442                  (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
443 }
444 
445 // Check if we can safely rename this Comdat function.
446 static bool canRenameComdat(
447     Function &F,
448     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
449   if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
450     return false;
451 
452   // FIXME: Current only handle those Comdat groups that only containing one
453   // function and function aliases.
454   // (1) For a Comdat group containing multiple functions, we need to have a
455   // unique postfix based on the hashes for each function. There is a
456   // non-trivial code refactoring to do this efficiently.
457   // (2) Variables can not be renamed, so we can not rename Comdat function in a
458   // group including global vars.
459   Comdat *C = F.getComdat();
460   for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
461     if (dyn_cast<GlobalAlias>(CM.second))
462       continue;
463     Function *FM = dyn_cast<Function>(CM.second);
464     if (FM != &F)
465       return false;
466   }
467   return true;
468 }
469 
470 // Append the CFGHash to the Comdat function name.
471 template <class Edge, class BBInfo>
472 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
473   if (!canRenameComdat(F, ComdatMembers))
474     return;
475   std::string OrigName = F.getName().str();
476   std::string NewFuncName =
477       Twine(F.getName() + "." + Twine(FunctionHash)).str();
478   F.setName(Twine(NewFuncName));
479   GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
480   FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
481   Comdat *NewComdat;
482   Module *M = F.getParent();
483   // For AvailableExternallyLinkage functions, change the linkage to
484   // LinkOnceODR and put them into comdat. This is because after renaming, there
485   // is no backup external copy available for the function.
486   if (!F.hasComdat()) {
487     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
488     NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
489     F.setLinkage(GlobalValue::LinkOnceODRLinkage);
490     F.setComdat(NewComdat);
491     return;
492   }
493 
494   // This function belongs to a single function Comdat group.
495   Comdat *OrigComdat = F.getComdat();
496   std::string NewComdatName =
497       Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
498   NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
499   NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
500 
501   for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
502     if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
503       // For aliases, change the name directly.
504       assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
505       std::string OrigGAName = GA->getName().str();
506       GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
507       GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
508       continue;
509     }
510     // Must be a function.
511     Function *CF = dyn_cast<Function>(CM.second);
512     assert(CF);
513     CF->setComdat(NewComdat);
514   }
515 }
516 
517 // Given a CFG E to be instrumented, find which BB to place the instrumented
518 // code. The function will split the critical edge if necessary.
519 template <class Edge, class BBInfo>
520 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
521   if (E->InMST || E->Removed)
522     return nullptr;
523 
524   BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
525   BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
526   // For a fake edge, instrument the real BB.
527   if (SrcBB == nullptr)
528     return DestBB;
529   if (DestBB == nullptr)
530     return SrcBB;
531 
532   // Instrument the SrcBB if it has a single successor,
533   // otherwise, the DestBB if this is not a critical edge.
534   TerminatorInst *TI = SrcBB->getTerminator();
535   if (TI->getNumSuccessors() <= 1)
536     return SrcBB;
537   if (!E->IsCritical)
538     return DestBB;
539 
540   // For a critical edge, we have to split. Instrument the newly
541   // created BB.
542   NumOfPGOSplit++;
543   DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
544                << getBBInfo(DestBB).Index << "\n");
545   unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
546   BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
547   assert(InstrBB && "Critical edge is not split");
548 
549   E->Removed = true;
550   return InstrBB;
551 }
552 
553 // Visit all edge and instrument the edges not in MST, and do value profiling.
554 // Critical edges will be split.
555 static void instrumentOneFunc(
556     Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
557     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
558   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
559                                                    BFI);
560   unsigned NumCounters = FuncInfo.getNumCounters();
561 
562   uint32_t I = 0;
563   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
564   for (auto &E : FuncInfo.MST.AllEdges) {
565     BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
566     if (!InstrBB)
567       continue;
568 
569     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
570     assert(Builder.GetInsertPoint() != InstrBB->end() &&
571            "Cannot get the Instrumentation point");
572     Builder.CreateCall(
573         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
574         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
575          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
576          Builder.getInt32(I++)});
577   }
578 
579   // Now instrument select instructions:
580   FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
581                                        FuncInfo.FunctionHash);
582   assert(I == NumCounters);
583 
584   if (DisableValueProfiling)
585     return;
586 
587   unsigned NumIndirectCallSites = 0;
588   for (auto &I : FuncInfo.IndirectCallSites) {
589     CallSite CS(I);
590     Value *Callee = CS.getCalledValue();
591     DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
592                  << NumIndirectCallSites << "\n");
593     IRBuilder<> Builder(I);
594     assert(Builder.GetInsertPoint() != I->getParent()->end() &&
595            "Cannot get the Instrumentation point");
596     Builder.CreateCall(
597         Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
598         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
599          Builder.getInt64(FuncInfo.FunctionHash),
600          Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
601          Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
602          Builder.getInt32(NumIndirectCallSites++)});
603   }
604   NumOfPGOICall += NumIndirectCallSites;
605 }
606 
607 // This class represents a CFG edge in profile use compilation.
608 struct PGOUseEdge : public PGOEdge {
609   bool CountValid;
610   uint64_t CountValue;
611   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
612       : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
613 
614   // Set edge count value
615   void setEdgeCount(uint64_t Value) {
616     CountValue = Value;
617     CountValid = true;
618   }
619 
620   // Return the information string for this object.
621   const std::string infoString() const {
622     if (!CountValid)
623       return PGOEdge::infoString();
624     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
625         .str();
626   }
627 };
628 
629 typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
630 
631 // This class stores the auxiliary information for each BB.
632 struct UseBBInfo : public BBInfo {
633   uint64_t CountValue;
634   bool CountValid;
635   int32_t UnknownCountInEdge;
636   int32_t UnknownCountOutEdge;
637   DirectEdges InEdges;
638   DirectEdges OutEdges;
639   UseBBInfo(unsigned IX)
640       : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
641         UnknownCountOutEdge(0) {}
642   UseBBInfo(unsigned IX, uint64_t C)
643       : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
644         UnknownCountOutEdge(0) {}
645 
646   // Set the profile count value for this BB.
647   void setBBInfoCount(uint64_t Value) {
648     CountValue = Value;
649     CountValid = true;
650   }
651 
652   // Return the information string of this object.
653   const std::string infoString() const {
654     if (!CountValid)
655       return BBInfo::infoString();
656     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
657   }
658 };
659 
660 // Sum up the count values for all the edges.
661 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
662   uint64_t Total = 0;
663   for (auto &E : Edges) {
664     if (E->Removed)
665       continue;
666     Total += E->CountValue;
667   }
668   return Total;
669 }
670 
671 class PGOUseFunc {
672 public:
673   PGOUseFunc(Function &Func, Module *Modu,
674              std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
675              BranchProbabilityInfo *BPI = nullptr,
676              BlockFrequencyInfo *BFI = nullptr)
677       : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
678         CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
679 
680   // Read counts for the instrumented BB from profile.
681   bool readCounters(IndexedInstrProfReader *PGOReader);
682 
683   // Populate the counts for all BBs.
684   void populateCounters();
685 
686   // Set the branch weights based on the count values.
687   void setBranchWeights();
688 
689   // Annotate the indirect call sites.
690   void annotateIndirectCallSites();
691 
692   // The hotness of the function from the profile count.
693   enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
694 
695   // Return the function hotness from the profile.
696   FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
697 
698   // Return the function hash.
699   uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
700   // Return the profile record for this function;
701   InstrProfRecord &getProfileRecord() { return ProfileRecord; }
702 
703   // Return the auxiliary BB information.
704   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
705     return FuncInfo.getBBInfo(BB);
706   }
707 
708   // Return the auxiliary BB information if available.
709   UseBBInfo *findBBInfo(const BasicBlock *BB) const {
710     return FuncInfo.findBBInfo(BB);
711   }
712 
713   Function &getFunc() const { return F; }
714 
715 private:
716   Function &F;
717   Module *M;
718   // This member stores the shared information with class PGOGenFunc.
719   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
720 
721   // The maximum count value in the profile. This is only used in PGO use
722   // compilation.
723   uint64_t ProgramMaxCount;
724 
725   // Position of counter that remains to be read.
726   uint32_t CountPosition;
727 
728   // Total size of the profile count for this function.
729   uint32_t ProfileCountSize;
730 
731   // ProfileRecord for this function.
732   InstrProfRecord ProfileRecord;
733 
734   // Function hotness info derived from profile.
735   FuncFreqAttr FreqAttr;
736 
737   // Find the Instrumented BB and set the value.
738   void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
739 
740   // Set the edge counter value for the unknown edge -- there should be only
741   // one unknown edge.
742   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
743 
744   // Return FuncName string;
745   const std::string getFuncName() const { return FuncInfo.FuncName; }
746 
747   // Set the hot/cold inline hints based on the count values.
748   // FIXME: This function should be removed once the functionality in
749   // the inliner is implemented.
750   void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
751     if (ProgramMaxCount == 0)
752       return;
753     // Threshold of the hot functions.
754     const BranchProbability HotFunctionThreshold(1, 100);
755     // Threshold of the cold functions.
756     const BranchProbability ColdFunctionThreshold(2, 10000);
757     if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
758       FreqAttr = FFA_Hot;
759     else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
760       FreqAttr = FFA_Cold;
761   }
762 };
763 
764 // Visit all the edges and assign the count value for the instrumented
765 // edges and the BB.
766 void PGOUseFunc::setInstrumentedCounts(
767     const std::vector<uint64_t> &CountFromProfile) {
768 
769   assert(FuncInfo.getNumCounters() == CountFromProfile.size());
770   // Use a worklist as we will update the vector during the iteration.
771   std::vector<PGOUseEdge *> WorkList;
772   for (auto &E : FuncInfo.MST.AllEdges)
773     WorkList.push_back(E.get());
774 
775   uint32_t I = 0;
776   for (auto &E : WorkList) {
777     BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
778     if (!InstrBB)
779       continue;
780     uint64_t CountValue = CountFromProfile[I++];
781     if (!E->Removed) {
782       getBBInfo(InstrBB).setBBInfoCount(CountValue);
783       E->setEdgeCount(CountValue);
784       continue;
785     }
786 
787     // Need to add two new edges.
788     BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
789     BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
790     // Add new edge of SrcBB->InstrBB.
791     PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
792     NewEdge.setEdgeCount(CountValue);
793     // Add new edge of InstrBB->DestBB.
794     PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
795     NewEdge1.setEdgeCount(CountValue);
796     NewEdge1.InMST = true;
797     getBBInfo(InstrBB).setBBInfoCount(CountValue);
798   }
799   ProfileCountSize =  CountFromProfile.size();
800   CountPosition = I;
801 }
802 
803 // Set the count value for the unknown edge. There should be one and only one
804 // unknown edge in Edges vector.
805 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
806   for (auto &E : Edges) {
807     if (E->CountValid)
808       continue;
809     E->setEdgeCount(Value);
810 
811     getBBInfo(E->SrcBB).UnknownCountOutEdge--;
812     getBBInfo(E->DestBB).UnknownCountInEdge--;
813     return;
814   }
815   llvm_unreachable("Cannot find the unknown count edge");
816 }
817 
818 // Read the profile from ProfileFileName and assign the value to the
819 // instrumented BB and the edges. This function also updates ProgramMaxCount.
820 // Return true if the profile are successfully read, and false on errors.
821 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
822   auto &Ctx = M->getContext();
823   Expected<InstrProfRecord> Result =
824       PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
825   if (Error E = Result.takeError()) {
826     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
827       auto Err = IPE.get();
828       bool SkipWarning = false;
829       if (Err == instrprof_error::unknown_function) {
830         NumOfPGOMissing++;
831         SkipWarning = !PGOWarnMissing;
832       } else if (Err == instrprof_error::hash_mismatch ||
833                  Err == instrprof_error::malformed) {
834         NumOfPGOMismatch++;
835         SkipWarning =
836             NoPGOWarnMismatch ||
837             (NoPGOWarnMismatchComdat &&
838              (F.hasComdat() ||
839               F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
840       }
841 
842       if (SkipWarning)
843         return;
844 
845       std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
846       Ctx.diagnose(
847           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
848     });
849     return false;
850   }
851   ProfileRecord = std::move(Result.get());
852   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
853 
854   NumOfPGOFunc++;
855   DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
856   uint64_t ValueSum = 0;
857   for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
858     DEBUG(dbgs() << "  " << I << ": " << CountFromProfile[I] << "\n");
859     ValueSum += CountFromProfile[I];
860   }
861 
862   DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
863 
864   getBBInfo(nullptr).UnknownCountOutEdge = 2;
865   getBBInfo(nullptr).UnknownCountInEdge = 2;
866 
867   setInstrumentedCounts(CountFromProfile);
868   ProgramMaxCount = PGOReader->getMaximumFunctionCount();
869   return true;
870 }
871 
872 // Populate the counters from instrumented BBs to all BBs.
873 // In the end of this operation, all BBs should have a valid count value.
874 void PGOUseFunc::populateCounters() {
875   // First set up Count variable for all BBs.
876   for (auto &E : FuncInfo.MST.AllEdges) {
877     if (E->Removed)
878       continue;
879 
880     const BasicBlock *SrcBB = E->SrcBB;
881     const BasicBlock *DestBB = E->DestBB;
882     UseBBInfo &SrcInfo = getBBInfo(SrcBB);
883     UseBBInfo &DestInfo = getBBInfo(DestBB);
884     SrcInfo.OutEdges.push_back(E.get());
885     DestInfo.InEdges.push_back(E.get());
886     SrcInfo.UnknownCountOutEdge++;
887     DestInfo.UnknownCountInEdge++;
888 
889     if (!E->CountValid)
890       continue;
891     DestInfo.UnknownCountInEdge--;
892     SrcInfo.UnknownCountOutEdge--;
893   }
894 
895   bool Changes = true;
896   unsigned NumPasses = 0;
897   while (Changes) {
898     NumPasses++;
899     Changes = false;
900 
901     // For efficient traversal, it's better to start from the end as most
902     // of the instrumented edges are at the end.
903     for (auto &BB : reverse(F)) {
904       UseBBInfo *Count = findBBInfo(&BB);
905       if (Count == nullptr)
906         continue;
907       if (!Count->CountValid) {
908         if (Count->UnknownCountOutEdge == 0) {
909           Count->CountValue = sumEdgeCount(Count->OutEdges);
910           Count->CountValid = true;
911           Changes = true;
912         } else if (Count->UnknownCountInEdge == 0) {
913           Count->CountValue = sumEdgeCount(Count->InEdges);
914           Count->CountValid = true;
915           Changes = true;
916         }
917       }
918       if (Count->CountValid) {
919         if (Count->UnknownCountOutEdge == 1) {
920           uint64_t Total = 0;
921           uint64_t OutSum = sumEdgeCount(Count->OutEdges);
922           // If the one of the successor block can early terminate (no-return),
923           // we can end up with situation where out edge sum count is larger as
924           // the source BB's count is collected by a post-dominated block.
925           if (Count->CountValue > OutSum)
926             Total = Count->CountValue - OutSum;
927           setEdgeCount(Count->OutEdges, Total);
928           Changes = true;
929         }
930         if (Count->UnknownCountInEdge == 1) {
931           uint64_t Total = 0;
932           uint64_t InSum = sumEdgeCount(Count->InEdges);
933           if (Count->CountValue > InSum)
934             Total = Count->CountValue - InSum;
935           setEdgeCount(Count->InEdges, Total);
936           Changes = true;
937         }
938       }
939     }
940   }
941 
942   DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
943 #ifndef NDEBUG
944   // Assert every BB has a valid counter.
945   for (auto &BB : F) {
946     auto BI = findBBInfo(&BB);
947     if (BI == nullptr)
948       continue;
949     assert(BI->CountValid && "BB count is not valid");
950   }
951 #endif
952   uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
953   F.setEntryCount(FuncEntryCount);
954   uint64_t FuncMaxCount = FuncEntryCount;
955   for (auto &BB : F) {
956     auto BI = findBBInfo(&BB);
957     if (BI == nullptr)
958       continue;
959     FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
960   }
961   markFunctionAttributes(FuncEntryCount, FuncMaxCount);
962 
963   // Now annotate select instructions
964   FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
965   assert(CountPosition == ProfileCountSize);
966 
967   DEBUG(FuncInfo.dumpInfo("after reading profile."));
968 }
969 
970 static void setProfMetadata(Module *M, Instruction *TI,
971                             ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
972   MDBuilder MDB(M->getContext());
973   assert(MaxCount > 0 && "Bad max count");
974   uint64_t Scale = calculateCountScale(MaxCount);
975   SmallVector<unsigned, 4> Weights;
976   for (const auto &ECI : EdgeCounts)
977     Weights.push_back(scaleBranchCount(ECI, Scale));
978 
979   DEBUG(dbgs() << "Weight is: ";
980         for (const auto &W : Weights) { dbgs() << W << " "; }
981         dbgs() << "\n";);
982   TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
983 }
984 
985 // Assign the scaled count values to the BB with multiple out edges.
986 void PGOUseFunc::setBranchWeights() {
987   // Generate MD_prof metadata for every branch instruction.
988   DEBUG(dbgs() << "\nSetting branch weights.\n");
989   for (auto &BB : F) {
990     TerminatorInst *TI = BB.getTerminator();
991     if (TI->getNumSuccessors() < 2)
992       continue;
993     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
994       continue;
995     if (getBBInfo(&BB).CountValue == 0)
996       continue;
997 
998     // We have a non-zero Branch BB.
999     const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1000     unsigned Size = BBCountInfo.OutEdges.size();
1001     SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1002     uint64_t MaxCount = 0;
1003     for (unsigned s = 0; s < Size; s++) {
1004       const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1005       const BasicBlock *SrcBB = E->SrcBB;
1006       const BasicBlock *DestBB = E->DestBB;
1007       if (DestBB == nullptr)
1008         continue;
1009       unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1010       uint64_t EdgeCount = E->CountValue;
1011       if (EdgeCount > MaxCount)
1012         MaxCount = EdgeCount;
1013       EdgeCounts[SuccNum] = EdgeCount;
1014     }
1015     setProfMetadata(M, TI, EdgeCounts, MaxCount);
1016   }
1017 }
1018 
1019 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1020   Module *M = F.getParent();
1021   IRBuilder<> Builder(&SI);
1022   Type *Int64Ty = Builder.getInt64Ty();
1023   Type *I8PtrTy = Builder.getInt8PtrTy();
1024   auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1025   Builder.CreateCall(
1026       Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1027       {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1028        Builder.getInt64(FuncHash),
1029        Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
1030   ++(*CurCtrIdx);
1031 }
1032 
1033 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1034   std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1035   assert(*CurCtrIdx < CountFromProfile.size() &&
1036          "Out of bound access of counters");
1037   uint64_t SCounts[2];
1038   SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1039   ++(*CurCtrIdx);
1040   uint64_t TotalCount = 0;
1041   auto BI = UseFunc->findBBInfo(SI.getParent());
1042   if (BI != nullptr)
1043     TotalCount = BI->CountValue;
1044   // False Count
1045   SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1046   uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1047   if (MaxCount)
1048     setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1049 }
1050 
1051 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1052   if (!PGOInstrSelect)
1053     return;
1054   // FIXME: do not handle this yet.
1055   if (SI.getCondition()->getType()->isVectorTy())
1056     return;
1057 
1058   NSIs++;
1059   switch (Mode) {
1060   case VM_counting:
1061     return;
1062   case VM_instrument:
1063     instrumentOneSelectInst(SI);
1064     return;
1065   case VM_annotate:
1066     annotateOneSelectInst(SI);
1067     return;
1068   }
1069 
1070   llvm_unreachable("Unknown visiting mode");
1071 }
1072 
1073 // Traverse all the indirect callsites and annotate the instructions.
1074 void PGOUseFunc::annotateIndirectCallSites() {
1075   if (DisableValueProfiling)
1076     return;
1077 
1078   // Create the PGOFuncName meta data.
1079   createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1080 
1081   unsigned IndirectCallSiteIndex = 0;
1082   auto &IndirectCallSites = FuncInfo.IndirectCallSites;
1083   unsigned NumValueSites =
1084       ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
1085   if (NumValueSites != IndirectCallSites.size()) {
1086     std::string Msg =
1087         std::string("Inconsistent number of indirect call sites: ") +
1088         F.getName().str();
1089     auto &Ctx = M->getContext();
1090     Ctx.diagnose(
1091         DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1092     return;
1093   }
1094 
1095   for (auto &I : IndirectCallSites) {
1096     DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
1097                  << IndirectCallSiteIndex << " out of " << NumValueSites
1098                  << "\n");
1099     annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
1100                       IndirectCallSiteIndex, MaxNumAnnotations);
1101     IndirectCallSiteIndex++;
1102   }
1103 }
1104 } // end anonymous namespace
1105 
1106 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1107 // aware this is an ir_level profile so it can set the version flag.
1108 static void createIRLevelProfileFlagVariable(Module &M) {
1109   Type *IntTy64 = Type::getInt64Ty(M.getContext());
1110   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1111   auto IRLevelVersionVariable = new GlobalVariable(
1112       M, IntTy64, true, GlobalVariable::ExternalLinkage,
1113       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
1114       INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1115   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1116   Triple TT(M.getTargetTriple());
1117   if (!TT.supportsCOMDAT())
1118     IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
1119   else
1120     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
1121         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1122 }
1123 
1124 // Collect the set of members for each Comdat in module M and store
1125 // in ComdatMembers.
1126 static void collectComdatMembers(
1127     Module &M,
1128     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1129   if (!DoComdatRenaming)
1130     return;
1131   for (Function &F : M)
1132     if (Comdat *C = F.getComdat())
1133       ComdatMembers.insert(std::make_pair(C, &F));
1134   for (GlobalVariable &GV : M.globals())
1135     if (Comdat *C = GV.getComdat())
1136       ComdatMembers.insert(std::make_pair(C, &GV));
1137   for (GlobalAlias &GA : M.aliases())
1138     if (Comdat *C = GA.getComdat())
1139       ComdatMembers.insert(std::make_pair(C, &GA));
1140 }
1141 
1142 static bool InstrumentAllFunctions(
1143     Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1144     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1145   createIRLevelProfileFlagVariable(M);
1146   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1147   collectComdatMembers(M, ComdatMembers);
1148 
1149   for (auto &F : M) {
1150     if (F.isDeclaration())
1151       continue;
1152     auto *BPI = LookupBPI(F);
1153     auto *BFI = LookupBFI(F);
1154     instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
1155   }
1156   return true;
1157 }
1158 
1159 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1160   if (skipModule(M))
1161     return false;
1162 
1163   auto LookupBPI = [this](Function &F) {
1164     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1165   };
1166   auto LookupBFI = [this](Function &F) {
1167     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1168   };
1169   return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1170 }
1171 
1172 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1173                                              ModuleAnalysisManager &AM) {
1174 
1175   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1176   auto LookupBPI = [&FAM](Function &F) {
1177     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1178   };
1179 
1180   auto LookupBFI = [&FAM](Function &F) {
1181     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1182   };
1183 
1184   if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1185     return PreservedAnalyses::all();
1186 
1187   return PreservedAnalyses::none();
1188 }
1189 
1190 static bool annotateAllFunctions(
1191     Module &M, StringRef ProfileFileName,
1192     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1193     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1194   DEBUG(dbgs() << "Read in profile counters: ");
1195   auto &Ctx = M.getContext();
1196   // Read the counter array from file.
1197   auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
1198   if (Error E = ReaderOrErr.takeError()) {
1199     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1200       Ctx.diagnose(
1201           DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1202     });
1203     return false;
1204   }
1205 
1206   std::unique_ptr<IndexedInstrProfReader> PGOReader =
1207       std::move(ReaderOrErr.get());
1208   if (!PGOReader) {
1209     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1210                                           StringRef("Cannot get PGOReader")));
1211     return false;
1212   }
1213   // TODO: might need to change the warning once the clang option is finalized.
1214   if (!PGOReader->isIRLevelProfile()) {
1215     Ctx.diagnose(DiagnosticInfoPGOProfile(
1216         ProfileFileName.data(), "Not an IR level instrumentation profile"));
1217     return false;
1218   }
1219 
1220   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1221   collectComdatMembers(M, ComdatMembers);
1222   std::vector<Function *> HotFunctions;
1223   std::vector<Function *> ColdFunctions;
1224   for (auto &F : M) {
1225     if (F.isDeclaration())
1226       continue;
1227     auto *BPI = LookupBPI(F);
1228     auto *BFI = LookupBFI(F);
1229     PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
1230     if (!Func.readCounters(PGOReader.get()))
1231       continue;
1232     Func.populateCounters();
1233     Func.setBranchWeights();
1234     Func.annotateIndirectCallSites();
1235     PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1236     if (FreqAttr == PGOUseFunc::FFA_Cold)
1237       ColdFunctions.push_back(&F);
1238     else if (FreqAttr == PGOUseFunc::FFA_Hot)
1239       HotFunctions.push_back(&F);
1240     if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1241                           F.getName().equals(ViewBlockFreqFuncName))) {
1242       LoopInfo LI{DominatorTree(F)};
1243       std::unique_ptr<BranchProbabilityInfo> NewBPI =
1244           llvm::make_unique<BranchProbabilityInfo>(F, LI);
1245       std::unique_ptr<BlockFrequencyInfo> NewBFI =
1246           llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1247 
1248       NewBFI->view();
1249     }
1250     if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1251                              F.getName().equals(ViewBlockFreqFuncName))) {
1252       if (ViewBlockFreqFuncName.empty())
1253         WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1254       else
1255         ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1256     }
1257   }
1258   M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1259   // Set function hotness attribute from the profile.
1260   // We have to apply these attributes at the end because their presence
1261   // can affect the BranchProbabilityInfo of any callers, resulting in an
1262   // inconsistent MST between prof-gen and prof-use.
1263   for (auto &F : HotFunctions) {
1264     F->addFnAttr(llvm::Attribute::InlineHint);
1265     DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1266                  << "\n");
1267   }
1268   for (auto &F : ColdFunctions) {
1269     F->addFnAttr(llvm::Attribute::Cold);
1270     DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1271   }
1272   return true;
1273 }
1274 
1275 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
1276     : ProfileFileName(std::move(Filename)) {
1277   if (!PGOTestProfileFile.empty())
1278     ProfileFileName = PGOTestProfileFile;
1279 }
1280 
1281 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1282                                              ModuleAnalysisManager &AM) {
1283 
1284   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1285   auto LookupBPI = [&FAM](Function &F) {
1286     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1287   };
1288 
1289   auto LookupBFI = [&FAM](Function &F) {
1290     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1291   };
1292 
1293   if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1294     return PreservedAnalyses::all();
1295 
1296   return PreservedAnalyses::none();
1297 }
1298 
1299 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1300   if (skipModule(M))
1301     return false;
1302 
1303   auto LookupBPI = [this](Function &F) {
1304     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1305   };
1306   auto LookupBFI = [this](Function &F) {
1307     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1308   };
1309 
1310   return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
1311 }
1312 
1313 namespace llvm {
1314 template <> struct GraphTraits<PGOUseFunc *> {
1315   typedef const BasicBlock *NodeRef;
1316   typedef succ_const_iterator ChildIteratorType;
1317   typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1318 
1319   static NodeRef getEntryNode(const PGOUseFunc *G) {
1320     return &G->getFunc().front();
1321   }
1322   static ChildIteratorType child_begin(const NodeRef N) {
1323     return succ_begin(N);
1324   }
1325   static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1326   static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1327     return nodes_iterator(G->getFunc().begin());
1328   }
1329   static nodes_iterator nodes_end(const PGOUseFunc *G) {
1330     return nodes_iterator(G->getFunc().end());
1331   }
1332 };
1333 
1334 static std::string getSimpleNodeName(const BasicBlock *Node) {
1335   if (!Node->getName().empty())
1336     return Node->getName();
1337 
1338   std::string SimpleNodeName;
1339   raw_string_ostream OS(SimpleNodeName);
1340   Node->printAsOperand(OS, false);
1341   return OS.str();
1342 }
1343 
1344 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1345   explicit DOTGraphTraits(bool isSimple = false)
1346       : DefaultDOTGraphTraits(isSimple) {}
1347 
1348   static std::string getGraphName(const PGOUseFunc *G) {
1349     return G->getFunc().getName();
1350   }
1351 
1352   std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1353     std::string Result;
1354     raw_string_ostream OS(Result);
1355 
1356     OS << getSimpleNodeName(Node) << ":\\l";
1357     UseBBInfo *BI = Graph->findBBInfo(Node);
1358     OS << "Count : ";
1359     if (BI && BI->CountValid)
1360       OS << BI->CountValue << "\\l";
1361     else
1362       OS << "Unknown\\l";
1363 
1364     if (!PGOInstrSelect)
1365       return Result;
1366 
1367     for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1368       auto *I = &*BI;
1369       if (!isa<SelectInst>(I))
1370         continue;
1371       // Display scaled counts for SELECT instruction:
1372       OS << "SELECT : { T = ";
1373       uint64_t TC, FC;
1374       bool HasProf = I->extractProfMetadata(TC, FC);
1375       if (!HasProf)
1376         OS << "Unknown, F = Unknown }\\l";
1377       else
1378         OS << TC << ", F = " << FC << " }\\l";
1379     }
1380     return Result;
1381   }
1382 };
1383 }
1384