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