1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements PGO instrumentation using a minimum spanning tree based
10 // on the following paper:
11 //   [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12 //   for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13 //   Issue 3, pp 313-322
14 // The idea of the algorithm based on the fact that for each node (except for
15 // the entry and exit), the sum of incoming edge counts equals the sum of
16 // outgoing edge counts. The count of edge on spanning tree can be derived from
17 // those edges not on the spanning tree. Knuth proves this method instruments
18 // the minimum number of edges.
19 //
20 // The minimal spanning tree here is actually a maximum weight tree -- on-tree
21 // edges have higher frequencies (more likely to execute). The idea is to
22 // instrument those less frequently executed edges to reduce the runtime
23 // overhead of instrumented binaries.
24 //
25 // This file contains two passes:
26 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
27 // count profile, and generates the instrumentation for indirect call
28 // profiling.
29 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
30 // annotates the branch weights. It also reads the indirect call value
31 // profiling records and annotate the indirect call instructions.
32 //
33 // To get the precise counter information, These two passes need to invoke at
34 // the same compilation point (so they see the same IR). For pass
35 // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36 // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37 // the profile is opened in module level and passed to each PGOUseFunc instance.
38 // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39 // in class FuncPGOInstrumentation.
40 //
41 // Class PGOEdge represents a CFG edge and some auxiliary information. Class
42 // BBInfo contains auxiliary information for each BB. These two classes are used
43 // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44 // class of PGOEdge and BBInfo, respectively. They contains extra data structure
45 // used in populating profile counters.
46 // The MST implementation is in Class CFGMST (CFGMST.h).
47 //
48 //===----------------------------------------------------------------------===//
49 
50 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
51 #include "CFGMST.h"
52 #include "ValueProfileCollector.h"
53 #include "llvm/ADT/APInt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/MapVector.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/ADT/iterator_range.h"
64 #include "llvm/Analysis/BlockFrequencyInfo.h"
65 #include "llvm/Analysis/BranchProbabilityInfo.h"
66 #include "llvm/Analysis/CFG.h"
67 #include "llvm/Analysis/EHPersonalities.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
70 #include "llvm/Analysis/ProfileSummaryInfo.h"
71 #include "llvm/IR/Attributes.h"
72 #include "llvm/IR/BasicBlock.h"
73 #include "llvm/IR/CFG.h"
74 #include "llvm/IR/Comdat.h"
75 #include "llvm/IR/Constant.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DiagnosticInfo.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GlobalAlias.h"
81 #include "llvm/IR/GlobalValue.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/InstVisitor.h"
85 #include "llvm/IR/InstrTypes.h"
86 #include "llvm/IR/Instruction.h"
87 #include "llvm/IR/Instructions.h"
88 #include "llvm/IR/IntrinsicInst.h"
89 #include "llvm/IR/Intrinsics.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/MDBuilder.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/ProfileSummary.h"
95 #include "llvm/IR/Type.h"
96 #include "llvm/IR/Value.h"
97 #include "llvm/InitializePasses.h"
98 #include "llvm/Pass.h"
99 #include "llvm/ProfileData/InstrProf.h"
100 #include "llvm/ProfileData/InstrProfReader.h"
101 #include "llvm/Support/BranchProbability.h"
102 #include "llvm/Support/CRC.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/DOTGraphTraits.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/Error.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/GraphWriter.h"
110 #include "llvm/Support/raw_ostream.h"
111 #include "llvm/Transforms/Instrumentation.h"
112 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
113 #include "llvm/Transforms/Utils/MisExpect.h"
114 #include <algorithm>
115 #include <cassert>
116 #include <cstdint>
117 #include <memory>
118 #include <numeric>
119 #include <string>
120 #include <unordered_map>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using ProfileCount = Function::ProfileCount;
126 using VPCandidateInfo = ValueProfileCollector::CandidateInfo;
127 
128 #define DEBUG_TYPE "pgo-instrumentation"
129 
130 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
131 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
132 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
133 STATISTIC(NumOfPGOEdge, "Number of edges.");
134 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
135 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
136 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
137 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
138 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
139 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
140 STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
141 STATISTIC(NumOfCSPGOSelectInsts,
142           "Number of select instruction instrumented in CSPGO.");
143 STATISTIC(NumOfCSPGOMemIntrinsics,
144           "Number of mem intrinsics instrumented in CSPGO.");
145 STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
146 STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
147 STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
148 STATISTIC(NumOfCSPGOFunc,
149           "Number of functions having valid profile counts in CSPGO.");
150 STATISTIC(NumOfCSPGOMismatch,
151           "Number of functions having mismatch profile in CSPGO.");
152 STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
153 
154 // Command line option to specify the file to read profile from. This is
155 // mainly used for testing.
156 static cl::opt<std::string>
157     PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
158                        cl::value_desc("filename"),
159                        cl::desc("Specify the path of profile data file. This is"
160                                 "mainly for test purpose."));
161 static cl::opt<std::string> PGOTestProfileRemappingFile(
162     "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
163     cl::value_desc("filename"),
164     cl::desc("Specify the path of profile remapping file. This is mainly for "
165              "test purpose."));
166 
167 // Command line option to disable value profiling. The default is false:
168 // i.e. value profiling is enabled by default. This is for debug purpose.
169 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
170                                            cl::Hidden,
171                                            cl::desc("Disable Value Profiling"));
172 
173 // Command line option to set the maximum number of VP annotations to write to
174 // the metadata for a single indirect call callsite.
175 static cl::opt<unsigned> MaxNumAnnotations(
176     "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
177     cl::desc("Max number of annotations for a single indirect "
178              "call callsite"));
179 
180 // Command line option to set the maximum number of value annotations
181 // to write to the metadata for a single memop intrinsic.
182 static cl::opt<unsigned> MaxNumMemOPAnnotations(
183     "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
184     cl::desc("Max number of preicise value annotations for a single memop"
185              "intrinsic"));
186 
187 // Command line option to control appending FunctionHash to the name of a COMDAT
188 // function. This is to avoid the hash mismatch caused by the preinliner.
189 static cl::opt<bool> DoComdatRenaming(
190     "do-comdat-renaming", cl::init(false), cl::Hidden,
191     cl::desc("Append function hash to the name of COMDAT function to avoid "
192              "function hash mismatch due to the preinliner"));
193 
194 // Command line option to enable/disable the warning about missing profile
195 // information.
196 static cl::opt<bool>
197     PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
198                    cl::desc("Use this option to turn on/off "
199                             "warnings about missing profile data for "
200                             "functions."));
201 
202 // Command line option to enable/disable the warning about a hash mismatch in
203 // the profile data.
204 static cl::opt<bool>
205     NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
206                       cl::desc("Use this option to turn off/on "
207                                "warnings about profile cfg mismatch."));
208 
209 // Command line option to enable/disable the warning about a hash mismatch in
210 // the profile data for Comdat functions, which often turns out to be false
211 // positive due to the pre-instrumentation inline.
212 static cl::opt<bool>
213     NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
214                             cl::Hidden,
215                             cl::desc("The option is used to turn on/off "
216                                      "warnings about hash mismatch for comdat "
217                                      "functions."));
218 
219 // Command line option to enable/disable select instruction instrumentation.
220 static cl::opt<bool>
221     PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
222                    cl::desc("Use this option to turn on/off SELECT "
223                             "instruction instrumentation. "));
224 
225 // Command line option to turn on CFG dot or text dump of raw profile counts
226 static cl::opt<PGOViewCountsType> PGOViewRawCounts(
227     "pgo-view-raw-counts", cl::Hidden,
228     cl::desc("A boolean option to show CFG dag or text "
229              "with raw profile counts from "
230              "profile data. See also option "
231              "-pgo-view-counts. To limit graph "
232              "display to only one function, use "
233              "filtering option -view-bfi-func-name."),
234     cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
235                clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
236                clEnumValN(PGOVCT_Text, "text", "show in text.")));
237 
238 // Command line option to enable/disable memop intrinsic call.size profiling.
239 static cl::opt<bool>
240     PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
241                   cl::desc("Use this option to turn on/off "
242                            "memory intrinsic size profiling."));
243 
244 // Emit branch probability as optimization remarks.
245 static cl::opt<bool>
246     EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
247                           cl::desc("When this option is on, the annotated "
248                                    "branch probability will be emitted as "
249                                    "optimization remarks: -{Rpass|"
250                                    "pass-remarks}=pgo-instrumentation"));
251 
252 static cl::opt<bool> PGOInstrumentEntry(
253     "pgo-instrument-entry", cl::init(false), cl::Hidden,
254     cl::desc("Force to instrument function entry basicblock."));
255 
256 // Command line option to turn on CFG dot dump after profile annotation.
257 // Defined in Analysis/BlockFrequencyInfo.cpp:  -pgo-view-counts
258 extern cl::opt<PGOViewCountsType> PGOViewCounts;
259 
260 // Command line option to specify the name of the function for CFG dump
261 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
262 extern cl::opt<std::string> ViewBlockFreqFuncName;
263 
264 static cl::opt<bool>
265     PGOOldCFGHashing("pgo-instr-old-cfg-hashing", cl::init(false), cl::Hidden,
266                      cl::desc("Use the old CFG function hashing"));
267 
268 // Return a string describing the branch condition that can be
269 // used in static branch probability heuristics:
270 static std::string getBranchCondString(Instruction *TI) {
271   BranchInst *BI = dyn_cast<BranchInst>(TI);
272   if (!BI || !BI->isConditional())
273     return std::string();
274 
275   Value *Cond = BI->getCondition();
276   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
277   if (!CI)
278     return std::string();
279 
280   std::string result;
281   raw_string_ostream OS(result);
282   OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
283   CI->getOperand(0)->getType()->print(OS, true);
284 
285   Value *RHS = CI->getOperand(1);
286   ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
287   if (CV) {
288     if (CV->isZero())
289       OS << "_Zero";
290     else if (CV->isOne())
291       OS << "_One";
292     else if (CV->isMinusOne())
293       OS << "_MinusOne";
294     else
295       OS << "_Const";
296   }
297   OS.flush();
298   return result;
299 }
300 
301 static const char *ValueProfKindDescr[] = {
302 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
303 #include "llvm/ProfileData/InstrProfData.inc"
304 };
305 
306 namespace {
307 
308 /// The select instruction visitor plays three roles specified
309 /// by the mode. In \c VM_counting mode, it simply counts the number of
310 /// select instructions. In \c VM_instrument mode, it inserts code to count
311 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
312 /// it reads the profile data and annotate the select instruction with metadata.
313 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
314 class PGOUseFunc;
315 
316 /// Instruction Visitor class to visit select instructions.
317 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
318   Function &F;
319   unsigned NSIs = 0;             // Number of select instructions instrumented.
320   VisitMode Mode = VM_counting;  // Visiting mode.
321   unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
322   unsigned TotalNumCtrs = 0;     // Total number of counters
323   GlobalVariable *FuncNameVar = nullptr;
324   uint64_t FuncHash = 0;
325   PGOUseFunc *UseFunc = nullptr;
326 
327   SelectInstVisitor(Function &Func) : F(Func) {}
328 
329   void countSelects(Function &Func) {
330     NSIs = 0;
331     Mode = VM_counting;
332     visit(Func);
333   }
334 
335   // Visit the IR stream and instrument all select instructions. \p
336   // Ind is a pointer to the counter index variable; \p TotalNC
337   // is the total number of counters; \p FNV is the pointer to the
338   // PGO function name var; \p FHash is the function hash.
339   void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
340                          GlobalVariable *FNV, uint64_t FHash) {
341     Mode = VM_instrument;
342     CurCtrIdx = Ind;
343     TotalNumCtrs = TotalNC;
344     FuncHash = FHash;
345     FuncNameVar = FNV;
346     visit(Func);
347   }
348 
349   // Visit the IR stream and annotate all select instructions.
350   void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
351     Mode = VM_annotate;
352     UseFunc = UF;
353     CurCtrIdx = Ind;
354     visit(Func);
355   }
356 
357   void instrumentOneSelectInst(SelectInst &SI);
358   void annotateOneSelectInst(SelectInst &SI);
359 
360   // Visit \p SI instruction and perform tasks according to visit mode.
361   void visitSelectInst(SelectInst &SI);
362 
363   // Return the number of select instructions. This needs be called after
364   // countSelects().
365   unsigned getNumOfSelectInsts() const { return NSIs; }
366 };
367 
368 
369 class PGOInstrumentationGenLegacyPass : public ModulePass {
370 public:
371   static char ID;
372 
373   PGOInstrumentationGenLegacyPass(bool IsCS = false)
374       : ModulePass(ID), IsCS(IsCS) {
375     initializePGOInstrumentationGenLegacyPassPass(
376         *PassRegistry::getPassRegistry());
377   }
378 
379   StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
380 
381 private:
382   // Is this is context-sensitive instrumentation.
383   bool IsCS;
384   bool runOnModule(Module &M) override;
385 
386   void getAnalysisUsage(AnalysisUsage &AU) const override {
387     AU.addRequired<BlockFrequencyInfoWrapperPass>();
388     AU.addRequired<TargetLibraryInfoWrapperPass>();
389   }
390 };
391 
392 class PGOInstrumentationUseLegacyPass : public ModulePass {
393 public:
394   static char ID;
395 
396   // Provide the profile filename as the parameter.
397   PGOInstrumentationUseLegacyPass(std::string Filename = "", bool IsCS = false)
398       : ModulePass(ID), ProfileFileName(std::move(Filename)), IsCS(IsCS) {
399     if (!PGOTestProfileFile.empty())
400       ProfileFileName = PGOTestProfileFile;
401     initializePGOInstrumentationUseLegacyPassPass(
402         *PassRegistry::getPassRegistry());
403   }
404 
405   StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
406 
407 private:
408   std::string ProfileFileName;
409   // Is this is context-sensitive instrumentation use.
410   bool IsCS;
411 
412   bool runOnModule(Module &M) override;
413 
414   void getAnalysisUsage(AnalysisUsage &AU) const override {
415     AU.addRequired<ProfileSummaryInfoWrapperPass>();
416     AU.addRequired<BlockFrequencyInfoWrapperPass>();
417     AU.addRequired<TargetLibraryInfoWrapperPass>();
418   }
419 };
420 
421 class PGOInstrumentationGenCreateVarLegacyPass : public ModulePass {
422 public:
423   static char ID;
424   StringRef getPassName() const override {
425     return "PGOInstrumentationGenCreateVarPass";
426   }
427   PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName = "")
428       : ModulePass(ID), InstrProfileOutput(CSInstrName) {
429     initializePGOInstrumentationGenCreateVarLegacyPassPass(
430         *PassRegistry::getPassRegistry());
431   }
432 
433 private:
434   bool runOnModule(Module &M) override {
435     createProfileFileNameVar(M, InstrProfileOutput);
436     createIRLevelProfileFlagVar(M, /* IsCS */ true, PGOInstrumentEntry);
437     return false;
438   }
439   std::string InstrProfileOutput;
440 };
441 
442 } // end anonymous namespace
443 
444 char PGOInstrumentationGenLegacyPass::ID = 0;
445 
446 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
447                       "PGO instrumentation.", false, false)
448 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
449 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
450 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
451 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
452                     "PGO instrumentation.", false, false)
453 
454 ModulePass *llvm::createPGOInstrumentationGenLegacyPass(bool IsCS) {
455   return new PGOInstrumentationGenLegacyPass(IsCS);
456 }
457 
458 char PGOInstrumentationUseLegacyPass::ID = 0;
459 
460 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
461                       "Read PGO instrumentation profile.", false, false)
462 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
463 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
464 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
465 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
466                     "Read PGO instrumentation profile.", false, false)
467 
468 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename,
469                                                         bool IsCS) {
470   return new PGOInstrumentationUseLegacyPass(Filename.str(), IsCS);
471 }
472 
473 char PGOInstrumentationGenCreateVarLegacyPass::ID = 0;
474 
475 INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass,
476                 "pgo-instr-gen-create-var",
477                 "Create PGO instrumentation version variable for CSPGO.", false,
478                 false)
479 
480 ModulePass *
481 llvm::createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName) {
482   return new PGOInstrumentationGenCreateVarLegacyPass(std::string(CSInstrName));
483 }
484 
485 namespace {
486 
487 /// An MST based instrumentation for PGO
488 ///
489 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
490 /// in the function level.
491 struct PGOEdge {
492   // This class implements the CFG edges. Note the CFG can be a multi-graph.
493   // So there might be multiple edges with same SrcBB and DestBB.
494   const BasicBlock *SrcBB;
495   const BasicBlock *DestBB;
496   uint64_t Weight;
497   bool InMST = false;
498   bool Removed = false;
499   bool IsCritical = false;
500 
501   PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
502       : SrcBB(Src), DestBB(Dest), Weight(W) {}
503 
504   // Return the information string of an edge.
505   const std::string infoString() const {
506     return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
507             (IsCritical ? "c" : " ") + "  W=" + Twine(Weight)).str();
508   }
509 };
510 
511 // This class stores the auxiliary information for each BB.
512 struct BBInfo {
513   BBInfo *Group;
514   uint32_t Index;
515   uint32_t Rank = 0;
516 
517   BBInfo(unsigned IX) : Group(this), Index(IX) {}
518 
519   // Return the information string of this object.
520   const std::string infoString() const {
521     return (Twine("Index=") + Twine(Index)).str();
522   }
523 
524   // Empty function -- only applicable to UseBBInfo.
525   void addOutEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
526 
527   // Empty function -- only applicable to UseBBInfo.
528   void addInEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
529 };
530 
531 // This class implements the CFG edges. Note the CFG can be a multi-graph.
532 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
533 private:
534   Function &F;
535 
536   // Is this is context-sensitive instrumentation.
537   bool IsCS;
538 
539   // If we instrument function entry BB by default.
540   bool InstrumentFuncEntry;
541 
542   // A map that stores the Comdat group in function F.
543   std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
544 
545   ValueProfileCollector VPC;
546 
547   void computeCFGHash();
548   void renameComdatFunction();
549 
550 public:
551   std::vector<std::vector<VPCandidateInfo>> ValueSites;
552   SelectInstVisitor SIVisitor;
553   std::string FuncName;
554   GlobalVariable *FuncNameVar;
555 
556   // CFG hash value for this function.
557   uint64_t FunctionHash = 0;
558 
559   // The Minimum Spanning Tree of function CFG.
560   CFGMST<Edge, BBInfo> MST;
561 
562   // Collect all the BBs that will be instrumented, and store them in
563   // InstrumentBBs.
564   void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
565 
566   // Give an edge, find the BB that will be instrumented.
567   // Return nullptr if there is no BB to be instrumented.
568   BasicBlock *getInstrBB(Edge *E);
569 
570   // Return the auxiliary BB information.
571   BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
572 
573   // Return the auxiliary BB information if available.
574   BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
575 
576   // Dump edges and BB information.
577   void dumpInfo(std::string Str = "") const {
578     MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
579                               Twine(FunctionHash) + "\t" + Str);
580   }
581 
582   FuncPGOInstrumentation(
583       Function &Func, TargetLibraryInfo &TLI,
584       std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
585       bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
586       BlockFrequencyInfo *BFI = nullptr, bool IsCS = false,
587       bool InstrumentFuncEntry = true)
588       : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers), VPC(Func, TLI),
589         ValueSites(IPVK_Last + 1), SIVisitor(Func),
590         MST(F, InstrumentFuncEntry, BPI, BFI) {
591     // This should be done before CFG hash computation.
592     SIVisitor.countSelects(Func);
593     ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
594     if (!IsCS) {
595       NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
596       NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
597       NumOfPGOBB += MST.BBInfos.size();
598       ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
599     } else {
600       NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
601       NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
602       NumOfCSPGOBB += MST.BBInfos.size();
603     }
604 
605     FuncName = getPGOFuncName(F);
606     computeCFGHash();
607     if (!ComdatMembers.empty())
608       renameComdatFunction();
609     LLVM_DEBUG(dumpInfo("after CFGMST"));
610 
611     for (auto &E : MST.AllEdges) {
612       if (E->Removed)
613         continue;
614       IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
615       if (!E->InMST)
616         IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
617     }
618 
619     if (CreateGlobalVar)
620       FuncNameVar = createPGOFuncNameVar(F, FuncName);
621   }
622 };
623 
624 } // end anonymous namespace
625 
626 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
627 // value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
628 // of selects, indirect calls, mem ops and edges.
629 template <class Edge, class BBInfo>
630 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
631   std::vector<uint8_t> Indexes;
632   JamCRC JC;
633   for (auto &BB : F) {
634     const Instruction *TI = BB.getTerminator();
635     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
636       BasicBlock *Succ = TI->getSuccessor(I);
637       auto BI = findBBInfo(Succ);
638       if (BI == nullptr)
639         continue;
640       uint32_t Index = BI->Index;
641       for (int J = 0; J < 4; J++)
642         Indexes.push_back((uint8_t)(Index >> (J * 8)));
643     }
644   }
645   JC.update(Indexes);
646 
647   JamCRC JCH;
648   if (PGOOldCFGHashing) {
649     // Hash format for context sensitive profile. Reserve 4 bits for other
650     // information.
651     FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
652                    (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
653                    //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
654                    (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
655   } else {
656     // The higher 32 bits.
657     auto updateJCH = [&JCH](uint64_t Num) {
658       uint8_t Data[8];
659       support::endian::write64le(Data, Num);
660       JCH.update(Data);
661     };
662     updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
663     updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
664     updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
665     updateJCH((uint64_t)MST.AllEdges.size());
666 
667     // Hash format for context sensitive profile. Reserve 4 bits for other
668     // information.
669     FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
670   }
671 
672   // Reserve bit 60-63 for other information purpose.
673   FunctionHash &= 0x0FFFFFFFFFFFFFFF;
674   if (IsCS)
675     NamedInstrProfRecord::setCSFlagInHash(FunctionHash);
676   LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
677                     << " CRC = " << JC.getCRC()
678                     << ", Selects = " << SIVisitor.getNumOfSelectInsts()
679                     << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
680                     << ValueSites[IPVK_IndirectCallTarget].size());
681   if (!PGOOldCFGHashing) {
682     LLVM_DEBUG(dbgs() << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
683                       << ", High32 CRC = " << JCH.getCRC());
684   }
685   LLVM_DEBUG(dbgs() << ", Hash = " << FunctionHash << "\n";);
686 }
687 
688 // Check if we can safely rename this Comdat function.
689 static bool canRenameComdat(
690     Function &F,
691     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
692   if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
693     return false;
694 
695   // FIXME: Current only handle those Comdat groups that only containing one
696   // function.
697   // (1) For a Comdat group containing multiple functions, we need to have a
698   // unique postfix based on the hashes for each function. There is a
699   // non-trivial code refactoring to do this efficiently.
700   // (2) Variables can not be renamed, so we can not rename Comdat function in a
701   // group including global vars.
702   Comdat *C = F.getComdat();
703   for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
704     assert(!isa<GlobalAlias>(CM.second));
705     Function *FM = dyn_cast<Function>(CM.second);
706     if (FM != &F)
707       return false;
708   }
709   return true;
710 }
711 
712 // Append the CFGHash to the Comdat function name.
713 template <class Edge, class BBInfo>
714 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
715   if (!canRenameComdat(F, ComdatMembers))
716     return;
717   std::string OrigName = F.getName().str();
718   std::string NewFuncName =
719       Twine(F.getName() + "." + Twine(FunctionHash)).str();
720   F.setName(Twine(NewFuncName));
721   GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
722   FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
723   Comdat *NewComdat;
724   Module *M = F.getParent();
725   // For AvailableExternallyLinkage functions, change the linkage to
726   // LinkOnceODR and put them into comdat. This is because after renaming, there
727   // is no backup external copy available for the function.
728   if (!F.hasComdat()) {
729     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
730     NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
731     F.setLinkage(GlobalValue::LinkOnceODRLinkage);
732     F.setComdat(NewComdat);
733     return;
734   }
735 
736   // This function belongs to a single function Comdat group.
737   Comdat *OrigComdat = F.getComdat();
738   std::string NewComdatName =
739       Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
740   NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
741   NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
742 
743   for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
744     // Must be a function.
745     cast<Function>(CM.second)->setComdat(NewComdat);
746   }
747 }
748 
749 // Collect all the BBs that will be instruments and return them in
750 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
751 template <class Edge, class BBInfo>
752 void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
753     std::vector<BasicBlock *> &InstrumentBBs) {
754   // Use a worklist as we will update the vector during the iteration.
755   std::vector<Edge *> EdgeList;
756   EdgeList.reserve(MST.AllEdges.size());
757   for (auto &E : MST.AllEdges)
758     EdgeList.push_back(E.get());
759 
760   for (auto &E : EdgeList) {
761     BasicBlock *InstrBB = getInstrBB(E);
762     if (InstrBB)
763       InstrumentBBs.push_back(InstrBB);
764   }
765 
766   // Set up InEdges/OutEdges for all BBs.
767   for (auto &E : MST.AllEdges) {
768     if (E->Removed)
769       continue;
770     const BasicBlock *SrcBB = E->SrcBB;
771     const BasicBlock *DestBB = E->DestBB;
772     BBInfo &SrcInfo = getBBInfo(SrcBB);
773     BBInfo &DestInfo = getBBInfo(DestBB);
774     SrcInfo.addOutEdge(E.get());
775     DestInfo.addInEdge(E.get());
776   }
777 }
778 
779 // Given a CFG E to be instrumented, find which BB to place the instrumented
780 // code. The function will split the critical edge if necessary.
781 template <class Edge, class BBInfo>
782 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
783   if (E->InMST || E->Removed)
784     return nullptr;
785 
786   BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
787   BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
788   // For a fake edge, instrument the real BB.
789   if (SrcBB == nullptr)
790     return DestBB;
791   if (DestBB == nullptr)
792     return SrcBB;
793 
794   auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
795     // There are basic blocks (such as catchswitch) cannot be instrumented.
796     // If the returned first insertion point is the end of BB, skip this BB.
797     if (BB->getFirstInsertionPt() == BB->end())
798       return nullptr;
799     return BB;
800   };
801 
802   // Instrument the SrcBB if it has a single successor,
803   // otherwise, the DestBB if this is not a critical edge.
804   Instruction *TI = SrcBB->getTerminator();
805   if (TI->getNumSuccessors() <= 1)
806     return canInstrument(SrcBB);
807   if (!E->IsCritical)
808     return canInstrument(DestBB);
809 
810   // Some IndirectBr critical edges cannot be split by the previous
811   // SplitIndirectBrCriticalEdges call. Bail out.
812   unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
813   BasicBlock *InstrBB =
814       isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
815   if (!InstrBB) {
816     LLVM_DEBUG(
817         dbgs() << "Fail to split critical edge: not instrument this edge.\n");
818     return nullptr;
819   }
820   // For a critical edge, we have to split. Instrument the newly
821   // created BB.
822   IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
823   LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
824                     << " --> " << getBBInfo(DestBB).Index << "\n");
825   // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
826   MST.addEdge(SrcBB, InstrBB, 0);
827   // Second one: Add new edge of InstrBB->DestBB.
828   Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
829   NewEdge1.InMST = true;
830   E->Removed = true;
831 
832   return canInstrument(InstrBB);
833 }
834 
835 // When generating value profiling calls on Windows routines that make use of
836 // handler funclets for exception processing an operand bundle needs to attached
837 // to the called function. This routine will set \p OpBundles to contain the
838 // funclet information, if any is needed, that should be placed on the generated
839 // value profiling call for the value profile candidate call.
840 static void
841 populateEHOperandBundle(VPCandidateInfo &Cand,
842                         DenseMap<BasicBlock *, ColorVector> &BlockColors,
843                         SmallVectorImpl<OperandBundleDef> &OpBundles) {
844   auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
845   if (OrigCall && !isa<IntrinsicInst>(OrigCall)) {
846     // The instrumentation call should belong to the same funclet as a
847     // non-intrinsic call, so just copy the operand bundle, if any exists.
848     Optional<OperandBundleUse> ParentFunclet =
849         OrigCall->getOperandBundle(LLVMContext::OB_funclet);
850     if (ParentFunclet)
851       OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
852   } else {
853     // Intrinsics or other instructions do not get funclet information from the
854     // front-end. Need to use the BlockColors that was computed by the routine
855     // colorEHFunclets to determine whether a funclet is needed.
856     if (!BlockColors.empty()) {
857       const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
858       assert(CV.size() == 1 && "non-unique color for block!");
859       Instruction *EHPad = CV.front()->getFirstNonPHI();
860       if (EHPad->isEHPad())
861         OpBundles.emplace_back("funclet", EHPad);
862     }
863   }
864 }
865 
866 // Visit all edge and instrument the edges not in MST, and do value profiling.
867 // Critical edges will be split.
868 static void instrumentOneFunc(
869     Function &F, Module *M, TargetLibraryInfo &TLI, BranchProbabilityInfo *BPI,
870     BlockFrequencyInfo *BFI,
871     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
872     bool IsCS) {
873   // Split indirectbr critical edges here before computing the MST rather than
874   // later in getInstrBB() to avoid invalidating it.
875   SplitIndirectBrCriticalEdges(F, BPI, BFI);
876 
877   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(
878       F, TLI, ComdatMembers, true, BPI, BFI, IsCS, PGOInstrumentEntry);
879   std::vector<BasicBlock *> InstrumentBBs;
880   FuncInfo.getInstrumentBBs(InstrumentBBs);
881   unsigned NumCounters =
882       InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
883 
884   uint32_t I = 0;
885   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
886   for (auto *InstrBB : InstrumentBBs) {
887     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
888     assert(Builder.GetInsertPoint() != InstrBB->end() &&
889            "Cannot get the Instrumentation point");
890     Builder.CreateCall(
891         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
892         {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
893          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
894          Builder.getInt32(I++)});
895   }
896 
897   // Now instrument select instructions:
898   FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
899                                        FuncInfo.FunctionHash);
900   assert(I == NumCounters);
901 
902   if (DisableValueProfiling)
903     return;
904 
905   NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
906 
907   // Intrinsic function calls do not have funclet operand bundles needed for
908   // Windows exception handling attached to them. However, if value profiling is
909   // inserted for one of these calls, then a funclet value will need to be set
910   // on the instrumentation call based on the funclet coloring.
911   DenseMap<BasicBlock *, ColorVector> BlockColors;
912   if (F.hasPersonalityFn() &&
913       isFuncletEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
914     BlockColors = colorEHFunclets(F);
915 
916   // For each VP Kind, walk the VP candidates and instrument each one.
917   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
918     unsigned SiteIndex = 0;
919     if (Kind == IPVK_MemOPSize && !PGOInstrMemOP)
920       continue;
921 
922     for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
923       LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
924                         << " site: CallSite Index = " << SiteIndex << "\n");
925 
926       IRBuilder<> Builder(Cand.InsertPt);
927       assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
928              "Cannot get the Instrumentation point");
929 
930       Value *ToProfile = nullptr;
931       if (Cand.V->getType()->isIntegerTy())
932         ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
933       else if (Cand.V->getType()->isPointerTy())
934         ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
935       assert(ToProfile && "value profiling Value is of unexpected type");
936 
937       SmallVector<OperandBundleDef, 1> OpBundles;
938       populateEHOperandBundle(Cand, BlockColors, OpBundles);
939       Builder.CreateCall(
940           Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
941           {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
942            Builder.getInt64(FuncInfo.FunctionHash), ToProfile,
943            Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
944           OpBundles);
945     }
946   } // IPVK_First <= Kind <= IPVK_Last
947 }
948 
949 namespace {
950 
951 // This class represents a CFG edge in profile use compilation.
952 struct PGOUseEdge : public PGOEdge {
953   bool CountValid = false;
954   uint64_t CountValue = 0;
955 
956   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
957       : PGOEdge(Src, Dest, W) {}
958 
959   // Set edge count value
960   void setEdgeCount(uint64_t Value) {
961     CountValue = Value;
962     CountValid = true;
963   }
964 
965   // Return the information string for this object.
966   const std::string infoString() const {
967     if (!CountValid)
968       return PGOEdge::infoString();
969     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
970         .str();
971   }
972 };
973 
974 using DirectEdges = SmallVector<PGOUseEdge *, 2>;
975 
976 // This class stores the auxiliary information for each BB.
977 struct UseBBInfo : public BBInfo {
978   uint64_t CountValue = 0;
979   bool CountValid;
980   int32_t UnknownCountInEdge = 0;
981   int32_t UnknownCountOutEdge = 0;
982   DirectEdges InEdges;
983   DirectEdges OutEdges;
984 
985   UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
986 
987   UseBBInfo(unsigned IX, uint64_t C)
988       : BBInfo(IX), CountValue(C), CountValid(true) {}
989 
990   // Set the profile count value for this BB.
991   void setBBInfoCount(uint64_t Value) {
992     CountValue = Value;
993     CountValid = true;
994   }
995 
996   // Return the information string of this object.
997   const std::string infoString() const {
998     if (!CountValid)
999       return BBInfo::infoString();
1000     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
1001   }
1002 
1003   // Add an OutEdge and update the edge count.
1004   void addOutEdge(PGOUseEdge *E) {
1005     OutEdges.push_back(E);
1006     UnknownCountOutEdge++;
1007   }
1008 
1009   // Add an InEdge and update the edge count.
1010   void addInEdge(PGOUseEdge *E) {
1011     InEdges.push_back(E);
1012     UnknownCountInEdge++;
1013   }
1014 };
1015 
1016 } // end anonymous namespace
1017 
1018 // Sum up the count values for all the edges.
1019 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
1020   uint64_t Total = 0;
1021   for (auto &E : Edges) {
1022     if (E->Removed)
1023       continue;
1024     Total += E->CountValue;
1025   }
1026   return Total;
1027 }
1028 
1029 namespace {
1030 
1031 class PGOUseFunc {
1032 public:
1033   PGOUseFunc(Function &Func, Module *Modu, TargetLibraryInfo &TLI,
1034              std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
1035              BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1036              ProfileSummaryInfo *PSI, bool IsCS, bool InstrumentFuncEntry)
1037       : F(Func), M(Modu), BFI(BFIin), PSI(PSI),
1038         FuncInfo(Func, TLI, ComdatMembers, false, BPI, BFIin, IsCS,
1039                  InstrumentFuncEntry),
1040         FreqAttr(FFA_Normal), IsCS(IsCS) {}
1041 
1042   // Read counts for the instrumented BB from profile.
1043   bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
1044                     bool &AllMinusOnes);
1045 
1046   // Populate the counts for all BBs.
1047   void populateCounters();
1048 
1049   // Set the branch weights based on the count values.
1050   void setBranchWeights();
1051 
1052   // Annotate the value profile call sites for all value kind.
1053   void annotateValueSites();
1054 
1055   // Annotate the value profile call sites for one value kind.
1056   void annotateValueSites(uint32_t Kind);
1057 
1058   // Annotate the irreducible loop header weights.
1059   void annotateIrrLoopHeaderWeights();
1060 
1061   // The hotness of the function from the profile count.
1062   enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1063 
1064   // Return the function hotness from the profile.
1065   FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1066 
1067   // Return the function hash.
1068   uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1069 
1070   // Return the profile record for this function;
1071   InstrProfRecord &getProfileRecord() { return ProfileRecord; }
1072 
1073   // Return the auxiliary BB information.
1074   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
1075     return FuncInfo.getBBInfo(BB);
1076   }
1077 
1078   // Return the auxiliary BB information if available.
1079   UseBBInfo *findBBInfo(const BasicBlock *BB) const {
1080     return FuncInfo.findBBInfo(BB);
1081   }
1082 
1083   Function &getFunc() const { return F; }
1084 
1085   void dumpInfo(std::string Str = "") const {
1086     FuncInfo.dumpInfo(Str);
1087   }
1088 
1089   uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1090 private:
1091   Function &F;
1092   Module *M;
1093   BlockFrequencyInfo *BFI;
1094   ProfileSummaryInfo *PSI;
1095 
1096   // This member stores the shared information with class PGOGenFunc.
1097   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
1098 
1099   // The maximum count value in the profile. This is only used in PGO use
1100   // compilation.
1101   uint64_t ProgramMaxCount;
1102 
1103   // Position of counter that remains to be read.
1104   uint32_t CountPosition = 0;
1105 
1106   // Total size of the profile count for this function.
1107   uint32_t ProfileCountSize = 0;
1108 
1109   // ProfileRecord for this function.
1110   InstrProfRecord ProfileRecord;
1111 
1112   // Function hotness info derived from profile.
1113   FuncFreqAttr FreqAttr;
1114 
1115   // Is to use the context sensitive profile.
1116   bool IsCS;
1117 
1118   // Find the Instrumented BB and set the value. Return false on error.
1119   bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1120 
1121   // Set the edge counter value for the unknown edge -- there should be only
1122   // one unknown edge.
1123   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1124 
1125   // Return FuncName string;
1126   const std::string getFuncName() const { return FuncInfo.FuncName; }
1127 
1128   // Set the hot/cold inline hints based on the count values.
1129   // FIXME: This function should be removed once the functionality in
1130   // the inliner is implemented.
1131   void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1132     if (PSI->isHotCount(EntryCount))
1133       FreqAttr = FFA_Hot;
1134     else if (PSI->isColdCount(MaxCount))
1135       FreqAttr = FFA_Cold;
1136   }
1137 };
1138 
1139 } // end anonymous namespace
1140 
1141 // Visit all the edges and assign the count value for the instrumented
1142 // edges and the BB. Return false on error.
1143 bool PGOUseFunc::setInstrumentedCounts(
1144     const std::vector<uint64_t> &CountFromProfile) {
1145 
1146   std::vector<BasicBlock *> InstrumentBBs;
1147   FuncInfo.getInstrumentBBs(InstrumentBBs);
1148   unsigned NumCounters =
1149       InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
1150   // The number of counters here should match the number of counters
1151   // in profile. Return if they mismatch.
1152   if (NumCounters != CountFromProfile.size()) {
1153     return false;
1154   }
1155   auto *FuncEntry = &*F.begin();
1156 
1157   // Set the profile count to the Instrumented BBs.
1158   uint32_t I = 0;
1159   for (BasicBlock *InstrBB : InstrumentBBs) {
1160     uint64_t CountValue = CountFromProfile[I++];
1161     UseBBInfo &Info = getBBInfo(InstrBB);
1162     // If we reach here, we know that we have some nonzero count
1163     // values in this function. The entry count should not be 0.
1164     // Fix it if necessary.
1165     if (InstrBB == FuncEntry && CountValue == 0)
1166       CountValue = 1;
1167     Info.setBBInfoCount(CountValue);
1168   }
1169   ProfileCountSize = CountFromProfile.size();
1170   CountPosition = I;
1171 
1172   // Set the edge count and update the count of unknown edges for BBs.
1173   auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1174     E->setEdgeCount(Value);
1175     this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1176     this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1177   };
1178 
1179   // Set the profile count the Instrumented edges. There are BBs that not in
1180   // MST but not instrumented. Need to set the edge count value so that we can
1181   // populate the profile counts later.
1182   for (auto &E : FuncInfo.MST.AllEdges) {
1183     if (E->Removed || E->InMST)
1184       continue;
1185     const BasicBlock *SrcBB = E->SrcBB;
1186     UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1187 
1188     // If only one out-edge, the edge profile count should be the same as BB
1189     // profile count.
1190     if (SrcInfo.CountValid && SrcInfo.OutEdges.size() == 1)
1191       setEdgeCount(E.get(), SrcInfo.CountValue);
1192     else {
1193       const BasicBlock *DestBB = E->DestBB;
1194       UseBBInfo &DestInfo = getBBInfo(DestBB);
1195       // If only one in-edge, the edge profile count should be the same as BB
1196       // profile count.
1197       if (DestInfo.CountValid && DestInfo.InEdges.size() == 1)
1198         setEdgeCount(E.get(), DestInfo.CountValue);
1199     }
1200     if (E->CountValid)
1201       continue;
1202     // E's count should have been set from profile. If not, this meenas E skips
1203     // the instrumentation. We set the count to 0.
1204     setEdgeCount(E.get(), 0);
1205   }
1206   return true;
1207 }
1208 
1209 // Set the count value for the unknown edge. There should be one and only one
1210 // unknown edge in Edges vector.
1211 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1212   for (auto &E : Edges) {
1213     if (E->CountValid)
1214       continue;
1215     E->setEdgeCount(Value);
1216 
1217     getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1218     getBBInfo(E->DestBB).UnknownCountInEdge--;
1219     return;
1220   }
1221   llvm_unreachable("Cannot find the unknown count edge");
1222 }
1223 
1224 // Read the profile from ProfileFileName and assign the value to the
1225 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1226 // Return true if the profile are successfully read, and false on errors.
1227 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
1228                               bool &AllMinusOnes) {
1229   auto &Ctx = M->getContext();
1230   Expected<InstrProfRecord> Result =
1231       PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
1232   if (Error E = Result.takeError()) {
1233     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1234       auto Err = IPE.get();
1235       bool SkipWarning = false;
1236       LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1237                         << FuncInfo.FuncName << ": ");
1238       if (Err == instrprof_error::unknown_function) {
1239         IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1240         SkipWarning = !PGOWarnMissing;
1241         LLVM_DEBUG(dbgs() << "unknown function");
1242       } else if (Err == instrprof_error::hash_mismatch ||
1243                  Err == instrprof_error::malformed) {
1244         IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1245         SkipWarning =
1246             NoPGOWarnMismatch ||
1247             (NoPGOWarnMismatchComdat &&
1248              (F.hasComdat() ||
1249               F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
1250         LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
1251       }
1252 
1253       LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1254       if (SkipWarning)
1255         return;
1256 
1257       std::string Msg = IPE.message() + std::string(" ") + F.getName().str() +
1258                         std::string(" Hash = ") +
1259                         std::to_string(FuncInfo.FunctionHash);
1260 
1261       Ctx.diagnose(
1262           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1263     });
1264     return false;
1265   }
1266   ProfileRecord = std::move(Result.get());
1267   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1268 
1269   IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1270   LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1271   AllMinusOnes = (CountFromProfile.size() > 0);
1272   uint64_t ValueSum = 0;
1273   for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1274     LLVM_DEBUG(dbgs() << "  " << I << ": " << CountFromProfile[I] << "\n");
1275     ValueSum += CountFromProfile[I];
1276     if (CountFromProfile[I] != (uint64_t)-1)
1277       AllMinusOnes = false;
1278   }
1279   AllZeros = (ValueSum == 0);
1280 
1281   LLVM_DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
1282 
1283   getBBInfo(nullptr).UnknownCountOutEdge = 2;
1284   getBBInfo(nullptr).UnknownCountInEdge = 2;
1285 
1286   if (!setInstrumentedCounts(CountFromProfile)) {
1287     LLVM_DEBUG(
1288         dbgs() << "Inconsistent number of counts, skipping this function");
1289     Ctx.diagnose(DiagnosticInfoPGOProfile(
1290         M->getName().data(),
1291         Twine("Inconsistent number of counts in ") + F.getName().str()
1292         + Twine(": the profile may be stale or there is a function name collision."),
1293         DS_Warning));
1294     return false;
1295   }
1296   ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1297   return true;
1298 }
1299 
1300 // Populate the counters from instrumented BBs to all BBs.
1301 // In the end of this operation, all BBs should have a valid count value.
1302 void PGOUseFunc::populateCounters() {
1303   bool Changes = true;
1304   unsigned NumPasses = 0;
1305   while (Changes) {
1306     NumPasses++;
1307     Changes = false;
1308 
1309     // For efficient traversal, it's better to start from the end as most
1310     // of the instrumented edges are at the end.
1311     for (auto &BB : reverse(F)) {
1312       UseBBInfo *Count = findBBInfo(&BB);
1313       if (Count == nullptr)
1314         continue;
1315       if (!Count->CountValid) {
1316         if (Count->UnknownCountOutEdge == 0) {
1317           Count->CountValue = sumEdgeCount(Count->OutEdges);
1318           Count->CountValid = true;
1319           Changes = true;
1320         } else if (Count->UnknownCountInEdge == 0) {
1321           Count->CountValue = sumEdgeCount(Count->InEdges);
1322           Count->CountValid = true;
1323           Changes = true;
1324         }
1325       }
1326       if (Count->CountValid) {
1327         if (Count->UnknownCountOutEdge == 1) {
1328           uint64_t Total = 0;
1329           uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1330           // If the one of the successor block can early terminate (no-return),
1331           // we can end up with situation where out edge sum count is larger as
1332           // the source BB's count is collected by a post-dominated block.
1333           if (Count->CountValue > OutSum)
1334             Total = Count->CountValue - OutSum;
1335           setEdgeCount(Count->OutEdges, Total);
1336           Changes = true;
1337         }
1338         if (Count->UnknownCountInEdge == 1) {
1339           uint64_t Total = 0;
1340           uint64_t InSum = sumEdgeCount(Count->InEdges);
1341           if (Count->CountValue > InSum)
1342             Total = Count->CountValue - InSum;
1343           setEdgeCount(Count->InEdges, Total);
1344           Changes = true;
1345         }
1346       }
1347     }
1348   }
1349 
1350   LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1351 #ifndef NDEBUG
1352   // Assert every BB has a valid counter.
1353   for (auto &BB : F) {
1354     auto BI = findBBInfo(&BB);
1355     if (BI == nullptr)
1356       continue;
1357     assert(BI->CountValid && "BB count is not valid");
1358   }
1359 #endif
1360   uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1361   uint64_t FuncMaxCount = FuncEntryCount;
1362   for (auto &BB : F) {
1363     auto BI = findBBInfo(&BB);
1364     if (BI == nullptr)
1365       continue;
1366     FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1367   }
1368 
1369   // Fix the obviously inconsistent entry count.
1370   if (FuncMaxCount > 0 && FuncEntryCount == 0)
1371     FuncEntryCount = 1;
1372   F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
1373   markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1374 
1375   // Now annotate select instructions
1376   FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1377   assert(CountPosition == ProfileCountSize);
1378 
1379   LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1380 }
1381 
1382 // Assign the scaled count values to the BB with multiple out edges.
1383 void PGOUseFunc::setBranchWeights() {
1384   // Generate MD_prof metadata for every branch instruction.
1385   LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1386                     << " IsCS=" << IsCS << "\n");
1387   for (auto &BB : F) {
1388     Instruction *TI = BB.getTerminator();
1389     if (TI->getNumSuccessors() < 2)
1390       continue;
1391     if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1392           isa<IndirectBrInst>(TI) || isa<InvokeInst>(TI)))
1393       continue;
1394 
1395     if (getBBInfo(&BB).CountValue == 0)
1396       continue;
1397 
1398     // We have a non-zero Branch BB.
1399     const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1400     unsigned Size = BBCountInfo.OutEdges.size();
1401     SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1402     uint64_t MaxCount = 0;
1403     for (unsigned s = 0; s < Size; s++) {
1404       const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1405       const BasicBlock *SrcBB = E->SrcBB;
1406       const BasicBlock *DestBB = E->DestBB;
1407       if (DestBB == nullptr)
1408         continue;
1409       unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1410       uint64_t EdgeCount = E->CountValue;
1411       if (EdgeCount > MaxCount)
1412         MaxCount = EdgeCount;
1413       EdgeCounts[SuccNum] = EdgeCount;
1414     }
1415     setProfMetadata(M, TI, EdgeCounts, MaxCount);
1416   }
1417 }
1418 
1419 static bool isIndirectBrTarget(BasicBlock *BB) {
1420   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1421     if (isa<IndirectBrInst>((*PI)->getTerminator()))
1422       return true;
1423   }
1424   return false;
1425 }
1426 
1427 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1428   LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1429   // Find irr loop headers
1430   for (auto &BB : F) {
1431     // As a heuristic also annotate indrectbr targets as they have a high chance
1432     // to become an irreducible loop header after the indirectbr tail
1433     // duplication.
1434     if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1435       Instruction *TI = BB.getTerminator();
1436       const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1437       setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1438     }
1439   }
1440 }
1441 
1442 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1443   Module *M = F.getParent();
1444   IRBuilder<> Builder(&SI);
1445   Type *Int64Ty = Builder.getInt64Ty();
1446   Type *I8PtrTy = Builder.getInt8PtrTy();
1447   auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1448   Builder.CreateCall(
1449       Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1450       {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1451        Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1452        Builder.getInt32(*CurCtrIdx), Step});
1453   ++(*CurCtrIdx);
1454 }
1455 
1456 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1457   std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1458   assert(*CurCtrIdx < CountFromProfile.size() &&
1459          "Out of bound access of counters");
1460   uint64_t SCounts[2];
1461   SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1462   ++(*CurCtrIdx);
1463   uint64_t TotalCount = 0;
1464   auto BI = UseFunc->findBBInfo(SI.getParent());
1465   if (BI != nullptr)
1466     TotalCount = BI->CountValue;
1467   // False Count
1468   SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1469   uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1470   if (MaxCount)
1471     setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1472 }
1473 
1474 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1475   if (!PGOInstrSelect)
1476     return;
1477   // FIXME: do not handle this yet.
1478   if (SI.getCondition()->getType()->isVectorTy())
1479     return;
1480 
1481   switch (Mode) {
1482   case VM_counting:
1483     NSIs++;
1484     return;
1485   case VM_instrument:
1486     instrumentOneSelectInst(SI);
1487     return;
1488   case VM_annotate:
1489     annotateOneSelectInst(SI);
1490     return;
1491   }
1492 
1493   llvm_unreachable("Unknown visiting mode");
1494 }
1495 
1496 // Traverse all valuesites and annotate the instructions for all value kind.
1497 void PGOUseFunc::annotateValueSites() {
1498   if (DisableValueProfiling)
1499     return;
1500 
1501   // Create the PGOFuncName meta data.
1502   createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1503 
1504   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1505     annotateValueSites(Kind);
1506 }
1507 
1508 // Annotate the instructions for a specific value kind.
1509 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1510   assert(Kind <= IPVK_Last);
1511   unsigned ValueSiteIndex = 0;
1512   auto &ValueSites = FuncInfo.ValueSites[Kind];
1513   unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1514   if (NumValueSites != ValueSites.size()) {
1515     auto &Ctx = M->getContext();
1516     Ctx.diagnose(DiagnosticInfoPGOProfile(
1517         M->getName().data(),
1518         Twine("Inconsistent number of value sites for ") +
1519             Twine(ValueProfKindDescr[Kind]) +
1520             Twine(" profiling in \"") + F.getName().str() +
1521             Twine("\", possibly due to the use of a stale profile."),
1522         DS_Warning));
1523     return;
1524   }
1525 
1526   for (VPCandidateInfo &I : ValueSites) {
1527     LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1528                       << "): Index = " << ValueSiteIndex << " out of "
1529                       << NumValueSites << "\n");
1530     annotateValueSite(*M, *I.AnnotatedInst, ProfileRecord,
1531                       static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1532                       Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1533                                              : MaxNumAnnotations);
1534     ValueSiteIndex++;
1535   }
1536 }
1537 
1538 // Collect the set of members for each Comdat in module M and store
1539 // in ComdatMembers.
1540 static void collectComdatMembers(
1541     Module &M,
1542     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1543   if (!DoComdatRenaming)
1544     return;
1545   for (Function &F : M)
1546     if (Comdat *C = F.getComdat())
1547       ComdatMembers.insert(std::make_pair(C, &F));
1548   for (GlobalVariable &GV : M.globals())
1549     if (Comdat *C = GV.getComdat())
1550       ComdatMembers.insert(std::make_pair(C, &GV));
1551   for (GlobalAlias &GA : M.aliases())
1552     if (Comdat *C = GA.getComdat())
1553       ComdatMembers.insert(std::make_pair(C, &GA));
1554 }
1555 
1556 static bool InstrumentAllFunctions(
1557     Module &M, function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1558     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1559     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
1560   // For the context-sensitve instrumentation, we should have a separated pass
1561   // (before LTO/ThinLTO linking) to create these variables.
1562   if (!IsCS)
1563     createIRLevelProfileFlagVar(M, /* IsCS */ false, PGOInstrumentEntry);
1564   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1565   collectComdatMembers(M, ComdatMembers);
1566 
1567   for (auto &F : M) {
1568     if (F.isDeclaration())
1569       continue;
1570     auto &TLI = LookupTLI(F);
1571     auto *BPI = LookupBPI(F);
1572     auto *BFI = LookupBFI(F);
1573     instrumentOneFunc(F, &M, TLI, BPI, BFI, ComdatMembers, IsCS);
1574   }
1575   return true;
1576 }
1577 
1578 PreservedAnalyses
1579 PGOInstrumentationGenCreateVar::run(Module &M, ModuleAnalysisManager &AM) {
1580   createProfileFileNameVar(M, CSInstrName);
1581   createIRLevelProfileFlagVar(M, /* IsCS */ true, PGOInstrumentEntry);
1582   return PreservedAnalyses::all();
1583 }
1584 
1585 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1586   if (skipModule(M))
1587     return false;
1588 
1589   auto LookupTLI = [this](Function &F) -> TargetLibraryInfo & {
1590     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1591   };
1592   auto LookupBPI = [this](Function &F) {
1593     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1594   };
1595   auto LookupBFI = [this](Function &F) {
1596     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1597   };
1598   return InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS);
1599 }
1600 
1601 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1602                                              ModuleAnalysisManager &AM) {
1603   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1604   auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1605     return FAM.getResult<TargetLibraryAnalysis>(F);
1606   };
1607   auto LookupBPI = [&FAM](Function &F) {
1608     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1609   };
1610   auto LookupBFI = [&FAM](Function &F) {
1611     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1612   };
1613 
1614   if (!InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS))
1615     return PreservedAnalyses::all();
1616 
1617   return PreservedAnalyses::none();
1618 }
1619 
1620 static bool annotateAllFunctions(
1621     Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
1622     function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1623     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1624     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI,
1625     ProfileSummaryInfo *PSI, bool IsCS) {
1626   LLVM_DEBUG(dbgs() << "Read in profile counters: ");
1627   auto &Ctx = M.getContext();
1628   // Read the counter array from file.
1629   auto ReaderOrErr =
1630       IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
1631   if (Error E = ReaderOrErr.takeError()) {
1632     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1633       Ctx.diagnose(
1634           DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1635     });
1636     return false;
1637   }
1638 
1639   std::unique_ptr<IndexedInstrProfReader> PGOReader =
1640       std::move(ReaderOrErr.get());
1641   if (!PGOReader) {
1642     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1643                                           StringRef("Cannot get PGOReader")));
1644     return false;
1645   }
1646   if (!PGOReader->hasCSIRLevelProfile() && IsCS)
1647     return false;
1648 
1649   // TODO: might need to change the warning once the clang option is finalized.
1650   if (!PGOReader->isIRLevelProfile()) {
1651     Ctx.diagnose(DiagnosticInfoPGOProfile(
1652         ProfileFileName.data(), "Not an IR level instrumentation profile"));
1653     return false;
1654   }
1655 
1656   // Add the profile summary (read from the header of the indexed summary) here
1657   // so that we can use it below when reading counters (which checks if the
1658   // function should be marked with a cold or inlinehint attribute).
1659   M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
1660                       IsCS ? ProfileSummary::PSK_CSInstr
1661                            : ProfileSummary::PSK_Instr);
1662   PSI->refresh();
1663 
1664   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1665   collectComdatMembers(M, ComdatMembers);
1666   std::vector<Function *> HotFunctions;
1667   std::vector<Function *> ColdFunctions;
1668 
1669   // If the profile marked as always instrument the entry BB, do the
1670   // same. Note this can be overwritten by the internal option in CFGMST.h
1671   bool InstrumentFuncEntry = PGOReader->instrEntryBBEnabled();
1672   if (PGOInstrumentEntry.getNumOccurrences() > 0)
1673     InstrumentFuncEntry = PGOInstrumentEntry;
1674   for (auto &F : M) {
1675     if (F.isDeclaration())
1676       continue;
1677     auto &TLI = LookupTLI(F);
1678     auto *BPI = LookupBPI(F);
1679     auto *BFI = LookupBFI(F);
1680     // Split indirectbr critical edges here before computing the MST rather than
1681     // later in getInstrBB() to avoid invalidating it.
1682     SplitIndirectBrCriticalEdges(F, BPI, BFI);
1683     PGOUseFunc Func(F, &M, TLI, ComdatMembers, BPI, BFI, PSI, IsCS,
1684                     InstrumentFuncEntry);
1685     // When AllMinusOnes is true, it means the profile for the function
1686     // is unrepresentative and this function is actually hot. Set the
1687     // entry count of the function to be multiple times of hot threshold
1688     // and drop all its internal counters.
1689     bool AllMinusOnes = false;
1690     bool AllZeros = false;
1691     if (!Func.readCounters(PGOReader.get(), AllZeros, AllMinusOnes))
1692       continue;
1693     if (AllZeros) {
1694       F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1695       if (Func.getProgramMaxCount() != 0)
1696         ColdFunctions.push_back(&F);
1697       continue;
1698     }
1699     const unsigned MultiplyFactor = 3;
1700     if (AllMinusOnes) {
1701       uint64_t HotThreshold = PSI->getHotCountThreshold();
1702       if (HotThreshold)
1703         F.setEntryCount(
1704             ProfileCount(HotThreshold * MultiplyFactor, Function::PCT_Real));
1705       HotFunctions.push_back(&F);
1706       continue;
1707     }
1708     Func.populateCounters();
1709     Func.setBranchWeights();
1710     Func.annotateValueSites();
1711     Func.annotateIrrLoopHeaderWeights();
1712     PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1713     if (FreqAttr == PGOUseFunc::FFA_Cold)
1714       ColdFunctions.push_back(&F);
1715     else if (FreqAttr == PGOUseFunc::FFA_Hot)
1716       HotFunctions.push_back(&F);
1717     if (PGOViewCounts != PGOVCT_None &&
1718         (ViewBlockFreqFuncName.empty() ||
1719          F.getName().equals(ViewBlockFreqFuncName))) {
1720       LoopInfo LI{DominatorTree(F)};
1721       std::unique_ptr<BranchProbabilityInfo> NewBPI =
1722           std::make_unique<BranchProbabilityInfo>(F, LI);
1723       std::unique_ptr<BlockFrequencyInfo> NewBFI =
1724           std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1725       if (PGOViewCounts == PGOVCT_Graph)
1726         NewBFI->view();
1727       else if (PGOViewCounts == PGOVCT_Text) {
1728         dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1729         NewBFI->print(dbgs());
1730       }
1731     }
1732     if (PGOViewRawCounts != PGOVCT_None &&
1733         (ViewBlockFreqFuncName.empty() ||
1734          F.getName().equals(ViewBlockFreqFuncName))) {
1735       if (PGOViewRawCounts == PGOVCT_Graph)
1736         if (ViewBlockFreqFuncName.empty())
1737           WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1738         else
1739           ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1740       else if (PGOViewRawCounts == PGOVCT_Text) {
1741         dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1742         Func.dumpInfo();
1743       }
1744     }
1745   }
1746 
1747   // Set function hotness attribute from the profile.
1748   // We have to apply these attributes at the end because their presence
1749   // can affect the BranchProbabilityInfo of any callers, resulting in an
1750   // inconsistent MST between prof-gen and prof-use.
1751   for (auto &F : HotFunctions) {
1752     F->addFnAttr(Attribute::InlineHint);
1753     LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1754                       << "\n");
1755   }
1756   for (auto &F : ColdFunctions) {
1757     F->addFnAttr(Attribute::Cold);
1758     LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1759                       << "\n");
1760   }
1761   return true;
1762 }
1763 
1764 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
1765                                              std::string RemappingFilename,
1766                                              bool IsCS)
1767     : ProfileFileName(std::move(Filename)),
1768       ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) {
1769   if (!PGOTestProfileFile.empty())
1770     ProfileFileName = PGOTestProfileFile;
1771   if (!PGOTestProfileRemappingFile.empty())
1772     ProfileRemappingFileName = PGOTestProfileRemappingFile;
1773 }
1774 
1775 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1776                                              ModuleAnalysisManager &AM) {
1777 
1778   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1779   auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1780     return FAM.getResult<TargetLibraryAnalysis>(F);
1781   };
1782   auto LookupBPI = [&FAM](Function &F) {
1783     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1784   };
1785   auto LookupBFI = [&FAM](Function &F) {
1786     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1787   };
1788 
1789   auto *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1790 
1791   if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1792                             LookupTLI, LookupBPI, LookupBFI, PSI, IsCS))
1793     return PreservedAnalyses::all();
1794 
1795   return PreservedAnalyses::none();
1796 }
1797 
1798 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1799   if (skipModule(M))
1800     return false;
1801 
1802   auto LookupTLI = [this](Function &F) -> TargetLibraryInfo & {
1803     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1804   };
1805   auto LookupBPI = [this](Function &F) {
1806     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1807   };
1808   auto LookupBFI = [this](Function &F) {
1809     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1810   };
1811 
1812   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1813   return annotateAllFunctions(M, ProfileFileName, "", LookupTLI, LookupBPI,
1814                               LookupBFI, PSI, IsCS);
1815 }
1816 
1817 static std::string getSimpleNodeName(const BasicBlock *Node) {
1818   if (!Node->getName().empty())
1819     return std::string(Node->getName());
1820 
1821   std::string SimpleNodeName;
1822   raw_string_ostream OS(SimpleNodeName);
1823   Node->printAsOperand(OS, false);
1824   return OS.str();
1825 }
1826 
1827 void llvm::setProfMetadata(Module *M, Instruction *TI,
1828                            ArrayRef<uint64_t> EdgeCounts,
1829                            uint64_t MaxCount) {
1830   MDBuilder MDB(M->getContext());
1831   assert(MaxCount > 0 && "Bad max count");
1832   uint64_t Scale = calculateCountScale(MaxCount);
1833   SmallVector<unsigned, 4> Weights;
1834   for (const auto &ECI : EdgeCounts)
1835     Weights.push_back(scaleBranchCount(ECI, Scale));
1836 
1837   LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1838                                            : Weights) {
1839     dbgs() << W << " ";
1840   } dbgs() << "\n";);
1841 
1842   misexpect::verifyMisExpect(TI, Weights, TI->getContext());
1843 
1844   TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1845   if (EmitBranchProbability) {
1846     std::string BrCondStr = getBranchCondString(TI);
1847     if (BrCondStr.empty())
1848       return;
1849 
1850     uint64_t WSum =
1851         std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1852                         [](uint64_t w1, uint64_t w2) { return w1 + w2; });
1853     uint64_t TotalCount =
1854         std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
1855                         [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1856     Scale = calculateCountScale(WSum);
1857     BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1858                          scaleBranchCount(WSum, Scale));
1859     std::string BranchProbStr;
1860     raw_string_ostream OS(BranchProbStr);
1861     OS << BP;
1862     OS << " (total count : " << TotalCount << ")";
1863     OS.flush();
1864     Function *F = TI->getParent()->getParent();
1865     OptimizationRemarkEmitter ORE(F);
1866     ORE.emit([&]() {
1867       return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1868              << BrCondStr << " is true with probability : " << BranchProbStr;
1869     });
1870   }
1871 }
1872 
1873 namespace llvm {
1874 
1875 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1876   MDBuilder MDB(M->getContext());
1877   TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1878                   MDB.createIrrLoopHeaderWeight(Count));
1879 }
1880 
1881 template <> struct GraphTraits<PGOUseFunc *> {
1882   using NodeRef = const BasicBlock *;
1883   using ChildIteratorType = const_succ_iterator;
1884   using nodes_iterator = pointer_iterator<Function::const_iterator>;
1885 
1886   static NodeRef getEntryNode(const PGOUseFunc *G) {
1887     return &G->getFunc().front();
1888   }
1889 
1890   static ChildIteratorType child_begin(const NodeRef N) {
1891     return succ_begin(N);
1892   }
1893 
1894   static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1895 
1896   static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1897     return nodes_iterator(G->getFunc().begin());
1898   }
1899 
1900   static nodes_iterator nodes_end(const PGOUseFunc *G) {
1901     return nodes_iterator(G->getFunc().end());
1902   }
1903 };
1904 
1905 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1906   explicit DOTGraphTraits(bool isSimple = false)
1907       : DefaultDOTGraphTraits(isSimple) {}
1908 
1909   static std::string getGraphName(const PGOUseFunc *G) {
1910     return std::string(G->getFunc().getName());
1911   }
1912 
1913   std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1914     std::string Result;
1915     raw_string_ostream OS(Result);
1916 
1917     OS << getSimpleNodeName(Node) << ":\\l";
1918     UseBBInfo *BI = Graph->findBBInfo(Node);
1919     OS << "Count : ";
1920     if (BI && BI->CountValid)
1921       OS << BI->CountValue << "\\l";
1922     else
1923       OS << "Unknown\\l";
1924 
1925     if (!PGOInstrSelect)
1926       return Result;
1927 
1928     for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1929       auto *I = &*BI;
1930       if (!isa<SelectInst>(I))
1931         continue;
1932       // Display scaled counts for SELECT instruction:
1933       OS << "SELECT : { T = ";
1934       uint64_t TC, FC;
1935       bool HasProf = I->extractProfMetadata(TC, FC);
1936       if (!HasProf)
1937         OS << "Unknown, F = Unknown }\\l";
1938       else
1939         OS << TC << ", F = " << FC << " }\\l";
1940     }
1941     return Result;
1942   }
1943 };
1944 
1945 } // end namespace llvm
1946