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