LLVM  6.0.0svn
PGOInstrumentation.cpp
Go to the documentation of this file.
1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements PGO instrumentation using a minimum spanning tree based
11 // on the following paper:
12 // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13 // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14 // Issue 3, pp 313-322
15 // The idea of the algorithm based on the fact that for each node (except for
16 // the entry and exit), the sum of incoming edge counts equals the sum of
17 // outgoing edge counts. The count of edge on spanning tree can be derived from
18 // those edges not on the spanning tree. Knuth proves this method instruments
19 // the minimum number of edges.
20 //
21 // The minimal spanning tree here is actually a maximum weight tree -- on-tree
22 // edges have higher frequencies (more likely to execute). The idea is to
23 // instrument those less frequently executed edges to reduce the runtime
24 // overhead of instrumented binaries.
25 //
26 // This file contains two passes:
27 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
28 // count profile, and generates the instrumentation for indirect call
29 // profiling.
30 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
31 // annotates the branch weights. It also reads the indirect call value
32 // profiling records and annotate the indirect call instructions.
33 //
34 // To get the precise counter information, These two passes need to invoke at
35 // the same compilation point (so they see the same IR). For pass
36 // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37 // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38 // the profile is opened in module level and passed to each PGOUseFunc instance.
39 // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40 // in class FuncPGOInstrumentation.
41 //
42 // Class PGOEdge represents a CFG edge and some auxiliary information. Class
43 // BBInfo contains auxiliary information for each BB. These two classes are used
44 // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45 // class of PGOEdge and BBInfo, respectively. They contains extra data structure
46 // used in populating profile counters.
47 // The MST implementation is in Class CFGMST (CFGMST.h).
48 //
49 //===----------------------------------------------------------------------===//
50 
52 #include "CFGMST.h"
53 #include "llvm/ADT/APInt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/ADT/Triple.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/ADT/iterator.h"
65 #include "llvm/Analysis/CFG.h"
67 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/Comdat.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DiagnosticInfo.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalValue.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/IRBuilder.h"
83 #include "llvm/IR/InstVisitor.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/LLVMContext.h"
90 #include "llvm/IR/MDBuilder.h"
91 #include "llvm/IR/Module.h"
92 #include "llvm/IR/PassManager.h"
93 #include "llvm/IR/ProfileSummary.h"
94 #include "llvm/IR/Type.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/Pass.h"
100 #include "llvm/Support/Casting.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/Error.h"
107 #include "llvm/Support/JamCRC.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstdint>
114 #include <memory>
115 #include <numeric>
116 #include <string>
117 #include <unordered_map>
118 #include <utility>
119 #include <vector>
120 
121 using namespace llvm;
122 
123 #define DEBUG_TYPE "pgo-instrumentation"
124 
125 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
126 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
127 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
128 STATISTIC(NumOfPGOEdge, "Number of edges.");
129 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
130 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
131 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
132 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
133 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
134 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
135 
136 // Command line option to specify the file to read profile from. This is
137 // mainly used for testing.
139  PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
140  cl::value_desc("filename"),
141  cl::desc("Specify the path of profile data file. This is"
142  "mainly for test purpose."));
143 
144 // Command line option to disable value profiling. The default is false:
145 // i.e. value profiling is enabled by default. This is for debug purpose.
146 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
147  cl::Hidden,
148  cl::desc("Disable Value Profiling"));
149 
150 // Command line option to set the maximum number of VP annotations to write to
151 // the metadata for a single indirect call callsite.
153  "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
154  cl::desc("Max number of annotations for a single indirect "
155  "call callsite"));
156 
157 // Command line option to set the maximum number of value annotations
158 // to write to the metadata for a single memop intrinsic.
160  "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
161  cl::desc("Max number of preicise value annotations for a single memop"
162  "intrinsic"));
163 
164 // Command line option to control appending FunctionHash to the name of a COMDAT
165 // function. This is to avoid the hash mismatch caused by the preinliner.
167  "do-comdat-renaming", cl::init(false), cl::Hidden,
168  cl::desc("Append function hash to the name of COMDAT function to avoid "
169  "function hash mismatch due to the preinliner"));
170 
171 // Command line option to enable/disable the warning about missing profile
172 // information.
173 static cl::opt<bool>
174  PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
175  cl::desc("Use this option to turn on/off "
176  "warnings about missing profile data for "
177  "functions."));
178 
179 // Command line option to enable/disable the warning about a hash mismatch in
180 // the profile data.
181 static cl::opt<bool>
182  NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
183  cl::desc("Use this option to turn off/on "
184  "warnings about profile cfg mismatch."));
185 
186 // Command line option to enable/disable the warning about a hash mismatch in
187 // the profile data for Comdat functions, which often turns out to be false
188 // positive due to the pre-instrumentation inline.
189 static cl::opt<bool>
190  NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
191  cl::Hidden,
192  cl::desc("The option is used to turn on/off "
193  "warnings about hash mismatch for comdat "
194  "functions."));
195 
196 // Command line option to enable/disable select instruction instrumentation.
197 static cl::opt<bool>
198  PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
199  cl::desc("Use this option to turn on/off SELECT "
200  "instruction instrumentation. "));
201 
202 // Command line option to turn on CFG dot or text dump of raw profile counts
204  "pgo-view-raw-counts", cl::Hidden,
205  cl::desc("A boolean option to show CFG dag or text "
206  "with raw profile counts from "
207  "profile data. See also option "
208  "-pgo-view-counts. To limit graph "
209  "display to only one function, use "
210  "filtering option -view-bfi-func-name."),
211  cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
212  clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
213  clEnumValN(PGOVCT_Text, "text", "show in text.")));
214 
215 // Command line option to enable/disable memop intrinsic call.size profiling.
216 static cl::opt<bool>
217  PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
218  cl::desc("Use this option to turn on/off "
219  "memory intrinsic size profiling."));
220 
221 // Emit branch probability as optimization remarks.
222 static cl::opt<bool>
223  EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
224  cl::desc("When this option is on, the annotated "
225  "branch probability will be emitted as "
226  " optimization remarks: -Rpass-analysis="
227  "pgo-instr-use"));
228 
229 // Command line option to turn on CFG dot dump after profile annotation.
230 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
232 
233 // Command line option to specify the name of the function for CFG dump
234 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
236 
237 // Return a string describing the branch condition that can be
238 // used in static branch probability heuristics:
239 static std::string getBranchCondString(Instruction *TI) {
240  BranchInst *BI = dyn_cast<BranchInst>(TI);
241  if (!BI || !BI->isConditional())
242  return std::string();
243 
244  Value *Cond = BI->getCondition();
245  ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
246  if (!CI)
247  return std::string();
248 
249  std::string result;
250  raw_string_ostream OS(result);
251  OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
252  CI->getOperand(0)->getType()->print(OS, true);
253 
254  Value *RHS = CI->getOperand(1);
255  ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
256  if (CV) {
257  if (CV->isZero())
258  OS << "_Zero";
259  else if (CV->isOne())
260  OS << "_One";
261  else if (CV->isMinusOne())
262  OS << "_MinusOne";
263  else
264  OS << "_Const";
265  }
266  OS.flush();
267  return result;
268 }
269 
270 namespace {
271 
272 /// The select instruction visitor plays three roles specified
273 /// by the mode. In \c VM_counting mode, it simply counts the number of
274 /// select instructions. In \c VM_instrument mode, it inserts code to count
275 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
276 /// it reads the profile data and annotate the select instruction with metadata.
277 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
278 class PGOUseFunc;
279 
280 /// Instruction Visitor class to visit select instructions.
281 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
282  Function &F;
283  unsigned NSIs = 0; // Number of select instructions instrumented.
284  VisitMode Mode = VM_counting; // Visiting mode.
285  unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
286  unsigned TotalNumCtrs = 0; // Total number of counters
287  GlobalVariable *FuncNameVar = nullptr;
288  uint64_t FuncHash = 0;
289  PGOUseFunc *UseFunc = nullptr;
290 
291  SelectInstVisitor(Function &Func) : F(Func) {}
292 
293  void countSelects(Function &Func) {
294  NSIs = 0;
295  Mode = VM_counting;
296  visit(Func);
297  }
298 
299  // Visit the IR stream and instrument all select instructions. \p
300  // Ind is a pointer to the counter index variable; \p TotalNC
301  // is the total number of counters; \p FNV is the pointer to the
302  // PGO function name var; \p FHash is the function hash.
303  void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
304  GlobalVariable *FNV, uint64_t FHash) {
305  Mode = VM_instrument;
306  CurCtrIdx = Ind;
307  TotalNumCtrs = TotalNC;
308  FuncHash = FHash;
309  FuncNameVar = FNV;
310  visit(Func);
311  }
312 
313  // Visit the IR stream and annotate all select instructions.
314  void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
315  Mode = VM_annotate;
316  UseFunc = UF;
317  CurCtrIdx = Ind;
318  visit(Func);
319  }
320 
321  void instrumentOneSelectInst(SelectInst &SI);
322  void annotateOneSelectInst(SelectInst &SI);
323 
324  // Visit \p SI instruction and perform tasks according to visit mode.
325  void visitSelectInst(SelectInst &SI);
326 
327  // Return the number of select instructions. This needs be called after
328  // countSelects().
329  unsigned getNumOfSelectInsts() const { return NSIs; }
330 };
331 
332 /// Instruction Visitor class to visit memory intrinsic calls.
333 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
334  Function &F;
335  unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
336  VisitMode Mode = VM_counting; // Visiting mode.
337  unsigned CurCtrId = 0; // Current counter index.
338  unsigned TotalNumCtrs = 0; // Total number of counters
339  GlobalVariable *FuncNameVar = nullptr;
340  uint64_t FuncHash = 0;
341  PGOUseFunc *UseFunc = nullptr;
342  std::vector<Instruction *> Candidates;
343 
344  MemIntrinsicVisitor(Function &Func) : F(Func) {}
345 
346  void countMemIntrinsics(Function &Func) {
347  NMemIs = 0;
348  Mode = VM_counting;
349  visit(Func);
350  }
351 
352  void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
353  GlobalVariable *FNV, uint64_t FHash) {
354  Mode = VM_instrument;
355  TotalNumCtrs = TotalNC;
356  FuncHash = FHash;
357  FuncNameVar = FNV;
358  visit(Func);
359  }
360 
361  std::vector<Instruction *> findMemIntrinsics(Function &Func) {
362  Candidates.clear();
363  Mode = VM_annotate;
364  visit(Func);
365  return Candidates;
366  }
367 
368  // Visit the IR stream and annotate all mem intrinsic call instructions.
369  void instrumentOneMemIntrinsic(MemIntrinsic &MI);
370 
371  // Visit \p MI instruction and perform tasks according to visit mode.
372  void visitMemIntrinsic(MemIntrinsic &SI);
373 
374  unsigned getNumOfMemIntrinsics() const { return NMemIs; }
375 };
376 
377 class PGOInstrumentationGenLegacyPass : public ModulePass {
378 public:
379  static char ID;
380 
381  PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
384  }
385 
386  StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
387 
388 private:
389  bool runOnModule(Module &M) override;
390 
391  void getAnalysisUsage(AnalysisUsage &AU) const override {
393  }
394 };
395 
396 class PGOInstrumentationUseLegacyPass : public ModulePass {
397 public:
398  static char ID;
399 
400  // Provide the profile filename as the parameter.
401  PGOInstrumentationUseLegacyPass(std::string Filename = "")
402  : ModulePass(ID), ProfileFileName(std::move(Filename)) {
403  if (!PGOTestProfileFile.empty())
404  ProfileFileName = PGOTestProfileFile;
407  }
408 
409  StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
410 
411 private:
412  std::string ProfileFileName;
413 
414  bool runOnModule(Module &M) override;
415 
416  void getAnalysisUsage(AnalysisUsage &AU) const override {
418  }
419 };
420 
421 } // end anonymous namespace
422 
424 
425 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
426  "PGO instrumentation.", false, false)
429 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
430  "PGO instrumentation.", false, false)
431 
433  return new PGOInstrumentationGenLegacyPass();
434 }
435 
437 
438 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
439  "Read PGO instrumentation profile.", false, false)
442 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
443  "Read PGO instrumentation profile.", false, false)
444 
446  return new PGOInstrumentationUseLegacyPass(Filename.str());
447 }
448 
449 namespace {
450 
451 /// \brief An MST based instrumentation for PGO
452 ///
453 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
454 /// in the function level.
455 struct PGOEdge {
456  // This class implements the CFG edges. Note the CFG can be a multi-graph.
457  // So there might be multiple edges with same SrcBB and DestBB.
458  const BasicBlock *SrcBB;
459  const BasicBlock *DestBB;
460  uint64_t Weight;
461  bool InMST = false;
462  bool Removed = false;
463  bool IsCritical = false;
464 
465  PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
466  : SrcBB(Src), DestBB(Dest), Weight(W) {}
467 
468  // Return the information string of an edge.
469  const std::string infoString() const {
470  return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
471  (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
472  }
473 };
474 
475 // This class stores the auxiliary information for each BB.
476 struct BBInfo {
477  BBInfo *Group;
478  uint32_t Index;
479  uint32_t Rank = 0;
480 
481  BBInfo(unsigned IX) : Group(this), Index(IX) {}
482 
483  // Return the information string of this object.
484  const std::string infoString() const {
485  return (Twine("Index=") + Twine(Index)).str();
486  }
487 };
488 
489 // This class implements the CFG edges. Note the CFG can be a multi-graph.
490 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
491 private:
492  Function &F;
493 
494  // A map that stores the Comdat group in function F.
495  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
496 
497  void computeCFGHash();
498  void renameComdatFunction();
499 
500 public:
501  std::vector<std::vector<Instruction *>> ValueSites;
502  SelectInstVisitor SIVisitor;
503  MemIntrinsicVisitor MIVisitor;
504  std::string FuncName;
505  GlobalVariable *FuncNameVar;
506 
507  // CFG hash value for this function.
508  uint64_t FunctionHash = 0;
509 
510  // The Minimum Spanning Tree of function CFG.
512 
513  // Give an edge, find the BB that will be instrumented.
514  // Return nullptr if there is no BB to be instrumented.
515  BasicBlock *getInstrBB(Edge *E);
516 
517  // Return the auxiliary BB information.
518  BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
519 
520  // Return the auxiliary BB information if available.
521  BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
522 
523  // Dump edges and BB information.
524  void dumpInfo(std::string Str = "") const {
525  MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
526  Twine(FunctionHash) + "\t" + Str);
527  }
528 
529  FuncPGOInstrumentation(
530  Function &Func,
531  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
532  bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
533  BlockFrequencyInfo *BFI = nullptr)
534  : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
535  SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI) {
536  // This should be done before CFG hash computation.
537  SIVisitor.countSelects(Func);
538  MIVisitor.countMemIntrinsics(Func);
539  NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
540  NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
541  ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
542  ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
543 
544  FuncName = getPGOFuncName(F);
545  computeCFGHash();
546  if (!ComdatMembers.empty())
547  renameComdatFunction();
548  DEBUG(dumpInfo("after CFGMST"));
549 
550  NumOfPGOBB += MST.BBInfos.size();
551  for (auto &E : MST.AllEdges) {
552  if (E->Removed)
553  continue;
554  NumOfPGOEdge++;
555  if (!E->InMST)
556  NumOfPGOInstrument++;
557  }
558 
559  if (CreateGlobalVar)
560  FuncNameVar = createPGOFuncNameVar(F, FuncName);
561  }
562 
563  // Return the number of profile counters needed for the function.
564  unsigned getNumCounters() {
565  unsigned NumCounters = 0;
566  for (auto &E : this->MST.AllEdges) {
567  if (!E->InMST && !E->Removed)
568  NumCounters++;
569  }
570  return NumCounters + SIVisitor.getNumOfSelectInsts();
571  }
572 };
573 
574 } // end anonymous namespace
575 
576 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
577 // value of each BB in the CFG. The higher 32 bits record the number of edges.
578 template <class Edge, class BBInfo>
579 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
580  std::vector<char> Indexes;
581  JamCRC JC;
582  for (auto &BB : F) {
583  const TerminatorInst *TI = BB.getTerminator();
584  for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
585  BasicBlock *Succ = TI->getSuccessor(I);
586  auto BI = findBBInfo(Succ);
587  if (BI == nullptr)
588  continue;
589  uint32_t Index = BI->Index;
590  for (int J = 0; J < 4; J++)
591  Indexes.push_back((char)(Index >> (J * 8)));
592  }
593  }
594  JC.update(Indexes);
595  FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
596  (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
597  (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
598  DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
599  << " CRC = " << JC.getCRC()
600  << ", Selects = " << SIVisitor.getNumOfSelectInsts()
601  << ", Edges = " << MST.AllEdges.size()
602  << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
603  << ", Hash = " << FunctionHash << "\n";);
604 }
605 
606 // Check if we can safely rename this Comdat function.
607 static bool canRenameComdat(
608  Function &F,
609  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
610  if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
611  return false;
612 
613  // FIXME: Current only handle those Comdat groups that only containing one
614  // function and function aliases.
615  // (1) For a Comdat group containing multiple functions, we need to have a
616  // unique postfix based on the hashes for each function. There is a
617  // non-trivial code refactoring to do this efficiently.
618  // (2) Variables can not be renamed, so we can not rename Comdat function in a
619  // group including global vars.
620  Comdat *C = F.getComdat();
621  for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
622  if (dyn_cast<GlobalAlias>(CM.second))
623  continue;
624  Function *FM = dyn_cast<Function>(CM.second);
625  if (FM != &F)
626  return false;
627  }
628  return true;
629 }
630 
631 // Append the CFGHash to the Comdat function name.
632 template <class Edge, class BBInfo>
633 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
634  if (!canRenameComdat(F, ComdatMembers))
635  return;
636  std::string OrigName = F.getName().str();
637  std::string NewFuncName =
638  Twine(F.getName() + "." + Twine(FunctionHash)).str();
639  F.setName(Twine(NewFuncName));
641  FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
642  Comdat *NewComdat;
643  Module *M = F.getParent();
644  // For AvailableExternallyLinkage functions, change the linkage to
645  // LinkOnceODR and put them into comdat. This is because after renaming, there
646  // is no backup external copy available for the function.
647  if (!F.hasComdat()) {
649  NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
651  F.setComdat(NewComdat);
652  return;
653  }
654 
655  // This function belongs to a single function Comdat group.
656  Comdat *OrigComdat = F.getComdat();
657  std::string NewComdatName =
658  Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
659  NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
660  NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
661 
662  for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
663  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
664  // For aliases, change the name directly.
665  assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
666  std::string OrigGAName = GA->getName().str();
667  GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
669  continue;
670  }
671  // Must be a function.
672  Function *CF = dyn_cast<Function>(CM.second);
673  assert(CF);
674  CF->setComdat(NewComdat);
675  }
676 }
677 
678 // Given a CFG E to be instrumented, find which BB to place the instrumented
679 // code. The function will split the critical edge if necessary.
680 template <class Edge, class BBInfo>
681 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
682  if (E->InMST || E->Removed)
683  return nullptr;
684 
685  BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
686  BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
687  // For a fake edge, instrument the real BB.
688  if (SrcBB == nullptr)
689  return DestBB;
690  if (DestBB == nullptr)
691  return SrcBB;
692 
693  // Instrument the SrcBB if it has a single successor,
694  // otherwise, the DestBB if this is not a critical edge.
695  TerminatorInst *TI = SrcBB->getTerminator();
696  if (TI->getNumSuccessors() <= 1)
697  return SrcBB;
698  if (!E->IsCritical)
699  return DestBB;
700 
701  // For a critical edge, we have to split. Instrument the newly
702  // created BB.
703  NumOfPGOSplit++;
704  DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
705  << getBBInfo(DestBB).Index << "\n");
706  unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
707  BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
708  assert(InstrBB && "Critical edge is not split");
709 
710  E->Removed = true;
711  return InstrBB;
712 }
713 
714 // Visit all edge and instrument the edges not in MST, and do value profiling.
715 // Critical edges will be split.
716 static void instrumentOneFunc(
718  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
719  FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
720  BFI);
721  unsigned NumCounters = FuncInfo.getNumCounters();
722 
723  uint32_t I = 0;
724  Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
725  for (auto &E : FuncInfo.MST.AllEdges) {
726  BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
727  if (!InstrBB)
728  continue;
729 
730  IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
731  assert(Builder.GetInsertPoint() != InstrBB->end() &&
732  "Cannot get the Instrumentation point");
733  Builder.CreateCall(
734  Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
735  {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
736  Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
737  Builder.getInt32(I++)});
738  }
739 
740  // Now instrument select instructions:
741  FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
742  FuncInfo.FunctionHash);
743  assert(I == NumCounters);
744 
746  return;
747 
748  unsigned NumIndirectCallSites = 0;
749  for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
750  CallSite CS(I);
751  Value *Callee = CS.getCalledValue();
752  DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
753  << NumIndirectCallSites << "\n");
754  IRBuilder<> Builder(I);
755  assert(Builder.GetInsertPoint() != I->getParent()->end() &&
756  "Cannot get the Instrumentation point");
757  Builder.CreateCall(
758  Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
759  {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
760  Builder.getInt64(FuncInfo.FunctionHash),
761  Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
762  Builder.getInt32(IPVK_IndirectCallTarget),
763  Builder.getInt32(NumIndirectCallSites++)});
764  }
765  NumOfPGOICall += NumIndirectCallSites;
766 
767  // Now instrument memop intrinsic calls.
768  FuncInfo.MIVisitor.instrumentMemIntrinsics(
769  F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
770 }
771 
772 namespace {
773 
774 // This class represents a CFG edge in profile use compilation.
775 struct PGOUseEdge : public PGOEdge {
776  bool CountValid = false;
777  uint64_t CountValue = 0;
778 
779  PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
780  : PGOEdge(Src, Dest, W) {}
781 
782  // Set edge count value
783  void setEdgeCount(uint64_t Value) {
784  CountValue = Value;
785  CountValid = true;
786  }
787 
788  // Return the information string for this object.
789  const std::string infoString() const {
790  if (!CountValid)
791  return PGOEdge::infoString();
792  return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
793  .str();
794  }
795 };
796 
797 using DirectEdges = SmallVector<PGOUseEdge *, 2>;
798 
799 // This class stores the auxiliary information for each BB.
800 struct UseBBInfo : public BBInfo {
801  uint64_t CountValue = 0;
802  bool CountValid;
803  int32_t UnknownCountInEdge = 0;
804  int32_t UnknownCountOutEdge = 0;
805  DirectEdges InEdges;
806  DirectEdges OutEdges;
807 
808  UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
809 
810  UseBBInfo(unsigned IX, uint64_t C)
811  : BBInfo(IX), CountValue(C), CountValid(true) {}
812 
813  // Set the profile count value for this BB.
814  void setBBInfoCount(uint64_t Value) {
815  CountValue = Value;
816  CountValid = true;
817  }
818 
819  // Return the information string of this object.
820  const std::string infoString() const {
821  if (!CountValid)
822  return BBInfo::infoString();
823  return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
824  }
825 };
826 
827 } // end anonymous namespace
828 
829 // Sum up the count values for all the edges.
830 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
831  uint64_t Total = 0;
832  for (auto &E : Edges) {
833  if (E->Removed)
834  continue;
835  Total += E->CountValue;
836  }
837  return Total;
838 }
839 
840 namespace {
841 
842 class PGOUseFunc {
843 public:
844  PGOUseFunc(Function &Func, Module *Modu,
845  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
846  BranchProbabilityInfo *BPI = nullptr,
847  BlockFrequencyInfo *BFIin = nullptr)
848  : F(Func), M(Modu), BFI(BFIin),
849  FuncInfo(Func, ComdatMembers, false, BPI, BFIin),
850  FreqAttr(FFA_Normal) {}
851 
852  // Read counts for the instrumented BB from profile.
853  bool readCounters(IndexedInstrProfReader *PGOReader);
854 
855  // Populate the counts for all BBs.
856  void populateCounters();
857 
858  // Set the branch weights based on the count values.
859  void setBranchWeights();
860 
861  // Annotate the value profile call sites all all value kind.
862  void annotateValueSites();
863 
864  // Annotate the value profile call sites for one value kind.
865  void annotateValueSites(uint32_t Kind);
866 
867  // Annotate the irreducible loop header weights.
868  void annotateIrrLoopHeaderWeights();
869 
870  // The hotness of the function from the profile count.
871  enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
872 
873  // Return the function hotness from the profile.
874  FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
875 
876  // Return the function hash.
877  uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
878 
879  // Return the profile record for this function;
880  InstrProfRecord &getProfileRecord() { return ProfileRecord; }
881 
882  // Return the auxiliary BB information.
883  UseBBInfo &getBBInfo(const BasicBlock *BB) const {
884  return FuncInfo.getBBInfo(BB);
885  }
886 
887  // Return the auxiliary BB information if available.
888  UseBBInfo *findBBInfo(const BasicBlock *BB) const {
889  return FuncInfo.findBBInfo(BB);
890  }
891 
892  Function &getFunc() const { return F; }
893 
894  void dumpInfo(std::string Str = "") const {
895  FuncInfo.dumpInfo(Str);
896  }
897 
898 private:
899  Function &F;
900  Module *M;
902 
903  // This member stores the shared information with class PGOGenFunc.
904  FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
905 
906  // The maximum count value in the profile. This is only used in PGO use
907  // compilation.
908  uint64_t ProgramMaxCount;
909 
910  // Position of counter that remains to be read.
911  uint32_t CountPosition = 0;
912 
913  // Total size of the profile count for this function.
914  uint32_t ProfileCountSize = 0;
915 
916  // ProfileRecord for this function.
917  InstrProfRecord ProfileRecord;
918 
919  // Function hotness info derived from profile.
920  FuncFreqAttr FreqAttr;
921 
922  // Find the Instrumented BB and set the value.
923  void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
924 
925  // Set the edge counter value for the unknown edge -- there should be only
926  // one unknown edge.
927  void setEdgeCount(DirectEdges &Edges, uint64_t Value);
928 
929  // Return FuncName string;
930  const std::string getFuncName() const { return FuncInfo.FuncName; }
931 
932  // Set the hot/cold inline hints based on the count values.
933  // FIXME: This function should be removed once the functionality in
934  // the inliner is implemented.
935  void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
936  if (ProgramMaxCount == 0)
937  return;
938  // Threshold of the hot functions.
939  const BranchProbability HotFunctionThreshold(1, 100);
940  // Threshold of the cold functions.
941  const BranchProbability ColdFunctionThreshold(2, 10000);
942  if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
943  FreqAttr = FFA_Hot;
944  else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
945  FreqAttr = FFA_Cold;
946  }
947 };
948 
949 } // end anonymous namespace
950 
951 // Visit all the edges and assign the count value for the instrumented
952 // edges and the BB.
953 void PGOUseFunc::setInstrumentedCounts(
954  const std::vector<uint64_t> &CountFromProfile) {
955  assert(FuncInfo.getNumCounters() == CountFromProfile.size());
956  // Use a worklist as we will update the vector during the iteration.
957  std::vector<PGOUseEdge *> WorkList;
958  for (auto &E : FuncInfo.MST.AllEdges)
959  WorkList.push_back(E.get());
960 
961  uint32_t I = 0;
962  for (auto &E : WorkList) {
963  BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
964  if (!InstrBB)
965  continue;
966  uint64_t CountValue = CountFromProfile[I++];
967  if (!E->Removed) {
968  getBBInfo(InstrBB).setBBInfoCount(CountValue);
969  E->setEdgeCount(CountValue);
970  continue;
971  }
972 
973  // Need to add two new edges.
974  BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
975  BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
976  // Add new edge of SrcBB->InstrBB.
977  PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
978  NewEdge.setEdgeCount(CountValue);
979  // Add new edge of InstrBB->DestBB.
980  PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
981  NewEdge1.setEdgeCount(CountValue);
982  NewEdge1.InMST = true;
983  getBBInfo(InstrBB).setBBInfoCount(CountValue);
984  }
985  ProfileCountSize = CountFromProfile.size();
986  CountPosition = I;
987 }
988 
989 // Set the count value for the unknown edge. There should be one and only one
990 // unknown edge in Edges vector.
991 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
992  for (auto &E : Edges) {
993  if (E->CountValid)
994  continue;
995  E->setEdgeCount(Value);
996 
997  getBBInfo(E->SrcBB).UnknownCountOutEdge--;
998  getBBInfo(E->DestBB).UnknownCountInEdge--;
999  return;
1000  }
1001  llvm_unreachable("Cannot find the unknown count edge");
1002 }
1003 
1004 // Read the profile from ProfileFileName and assign the value to the
1005 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1006 // Return true if the profile are successfully read, and false on errors.
1007 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
1008  auto &Ctx = M->getContext();
1009  Expected<InstrProfRecord> Result =
1010  PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
1011  if (Error E = Result.takeError()) {
1012  handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1013  auto Err = IPE.get();
1014  bool SkipWarning = false;
1015  if (Err == instrprof_error::unknown_function) {
1016  NumOfPGOMissing++;
1017  SkipWarning = !PGOWarnMissing;
1018  } else if (Err == instrprof_error::hash_mismatch ||
1019  Err == instrprof_error::malformed) {
1020  NumOfPGOMismatch++;
1021  SkipWarning =
1024  (F.hasComdat() ||
1025  F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
1026  }
1027 
1028  if (SkipWarning)
1029  return;
1030 
1031  std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1032  Ctx.diagnose(
1033  DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1034  });
1035  return false;
1036  }
1037  ProfileRecord = std::move(Result.get());
1038  std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1039 
1040  NumOfPGOFunc++;
1041  DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1042  uint64_t ValueSum = 0;
1043  for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1044  DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1045  ValueSum += CountFromProfile[I];
1046  }
1047 
1048  DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1049 
1050  getBBInfo(nullptr).UnknownCountOutEdge = 2;
1051  getBBInfo(nullptr).UnknownCountInEdge = 2;
1052 
1053  setInstrumentedCounts(CountFromProfile);
1054  ProgramMaxCount = PGOReader->getMaximumFunctionCount();
1055  return true;
1056 }
1057 
1058 // Populate the counters from instrumented BBs to all BBs.
1059 // In the end of this operation, all BBs should have a valid count value.
1060 void PGOUseFunc::populateCounters() {
1061  // First set up Count variable for all BBs.
1062  for (auto &E : FuncInfo.MST.AllEdges) {
1063  if (E->Removed)
1064  continue;
1065 
1066  const BasicBlock *SrcBB = E->SrcBB;
1067  const BasicBlock *DestBB = E->DestBB;
1068  UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1069  UseBBInfo &DestInfo = getBBInfo(DestBB);
1070  SrcInfo.OutEdges.push_back(E.get());
1071  DestInfo.InEdges.push_back(E.get());
1072  SrcInfo.UnknownCountOutEdge++;
1073  DestInfo.UnknownCountInEdge++;
1074 
1075  if (!E->CountValid)
1076  continue;
1077  DestInfo.UnknownCountInEdge--;
1078  SrcInfo.UnknownCountOutEdge--;
1079  }
1080 
1081  bool Changes = true;
1082  unsigned NumPasses = 0;
1083  while (Changes) {
1084  NumPasses++;
1085  Changes = false;
1086 
1087  // For efficient traversal, it's better to start from the end as most
1088  // of the instrumented edges are at the end.
1089  for (auto &BB : reverse(F)) {
1090  UseBBInfo *Count = findBBInfo(&BB);
1091  if (Count == nullptr)
1092  continue;
1093  if (!Count->CountValid) {
1094  if (Count->UnknownCountOutEdge == 0) {
1095  Count->CountValue = sumEdgeCount(Count->OutEdges);
1096  Count->CountValid = true;
1097  Changes = true;
1098  } else if (Count->UnknownCountInEdge == 0) {
1099  Count->CountValue = sumEdgeCount(Count->InEdges);
1100  Count->CountValid = true;
1101  Changes = true;
1102  }
1103  }
1104  if (Count->CountValid) {
1105  if (Count->UnknownCountOutEdge == 1) {
1106  uint64_t Total = 0;
1107  uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1108  // If the one of the successor block can early terminate (no-return),
1109  // we can end up with situation where out edge sum count is larger as
1110  // the source BB's count is collected by a post-dominated block.
1111  if (Count->CountValue > OutSum)
1112  Total = Count->CountValue - OutSum;
1113  setEdgeCount(Count->OutEdges, Total);
1114  Changes = true;
1115  }
1116  if (Count->UnknownCountInEdge == 1) {
1117  uint64_t Total = 0;
1118  uint64_t InSum = sumEdgeCount(Count->InEdges);
1119  if (Count->CountValue > InSum)
1120  Total = Count->CountValue - InSum;
1121  setEdgeCount(Count->InEdges, Total);
1122  Changes = true;
1123  }
1124  }
1125  }
1126  }
1127 
1128  DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1129 #ifndef NDEBUG
1130  // Assert every BB has a valid counter.
1131  for (auto &BB : F) {
1132  auto BI = findBBInfo(&BB);
1133  if (BI == nullptr)
1134  continue;
1135  assert(BI->CountValid && "BB count is not valid");
1136  }
1137 #endif
1138  uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1139  F.setEntryCount(FuncEntryCount);
1140  uint64_t FuncMaxCount = FuncEntryCount;
1141  for (auto &BB : F) {
1142  auto BI = findBBInfo(&BB);
1143  if (BI == nullptr)
1144  continue;
1145  FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1146  }
1147  markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1148 
1149  // Now annotate select instructions
1150  FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1151  assert(CountPosition == ProfileCountSize);
1152 
1153  DEBUG(FuncInfo.dumpInfo("after reading profile."));
1154 }
1155 
1156 // Assign the scaled count values to the BB with multiple out edges.
1158  // Generate MD_prof metadata for every branch instruction.
1159  DEBUG(dbgs() << "\nSetting branch weights.\n");
1160  for (auto &BB : F) {
1161  TerminatorInst *TI = BB.getTerminator();
1162  if (TI->getNumSuccessors() < 2)
1163  continue;
1164  if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1165  isa<IndirectBrInst>(TI)))
1166  continue;
1167  if (getBBInfo(&BB).CountValue == 0)
1168  continue;
1169 
1170  // We have a non-zero Branch BB.
1171  const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1172  unsigned Size = BBCountInfo.OutEdges.size();
1173  SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1174  uint64_t MaxCount = 0;
1175  for (unsigned s = 0; s < Size; s++) {
1176  const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1177  const BasicBlock *SrcBB = E->SrcBB;
1178  const BasicBlock *DestBB = E->DestBB;
1179  if (DestBB == nullptr)
1180  continue;
1181  unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1182  uint64_t EdgeCount = E->CountValue;
1183  if (EdgeCount > MaxCount)
1184  MaxCount = EdgeCount;
1185  EdgeCounts[SuccNum] = EdgeCount;
1186  }
1187  setProfMetadata(M, TI, EdgeCounts, MaxCount);
1188  }
1189 }
1190 
1191 static bool isIndirectBrTarget(BasicBlock *BB) {
1192  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1193  if (isa<IndirectBrInst>((*PI)->getTerminator()))
1194  return true;
1195  }
1196  return false;
1197 }
1198 
1199 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1200  DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1201  // Find irr loop headers
1202  for (auto &BB : F) {
1203  // As a heuristic also annotate indrectbr targets as they have a high chance
1204  // to become an irreducible loop header after the indirectbr tail
1205  // duplication.
1206  if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1207  TerminatorInst *TI = BB.getTerminator();
1208  const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1209  setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1210  }
1211  }
1212 }
1213 
1214 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1215  Module *M = F.getParent();
1216  IRBuilder<> Builder(&SI);
1217  Type *Int64Ty = Builder.getInt64Ty();
1218  Type *I8PtrTy = Builder.getInt8PtrTy();
1219  auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1220  Builder.CreateCall(
1221  Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1222  {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1223  Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1224  Builder.getInt32(*CurCtrIdx), Step});
1225  ++(*CurCtrIdx);
1226 }
1227 
1228 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1229  std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1230  assert(*CurCtrIdx < CountFromProfile.size() &&
1231  "Out of bound access of counters");
1232  uint64_t SCounts[2];
1233  SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1234  ++(*CurCtrIdx);
1235  uint64_t TotalCount = 0;
1236  auto BI = UseFunc->findBBInfo(SI.getParent());
1237  if (BI != nullptr)
1238  TotalCount = BI->CountValue;
1239  // False Count
1240  SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1241  uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1242  if (MaxCount)
1243  setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1244 }
1245 
1246 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1247  if (!PGOInstrSelect)
1248  return;
1249  // FIXME: do not handle this yet.
1250  if (SI.getCondition()->getType()->isVectorTy())
1251  return;
1252 
1253  switch (Mode) {
1254  case VM_counting:
1255  NSIs++;
1256  return;
1257  case VM_instrument:
1258  instrumentOneSelectInst(SI);
1259  return;
1260  case VM_annotate:
1261  annotateOneSelectInst(SI);
1262  return;
1263  }
1264 
1265  llvm_unreachable("Unknown visiting mode");
1266 }
1267 
1268 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1269  Module *M = F.getParent();
1270  IRBuilder<> Builder(&MI);
1271  Type *Int64Ty = Builder.getInt64Ty();
1272  Type *I8PtrTy = Builder.getInt8PtrTy();
1273  Value *Length = MI.getLength();
1274  assert(!dyn_cast<ConstantInt>(Length));
1275  Builder.CreateCall(
1276  Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1277  {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1278  Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
1279  Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1280  ++CurCtrId;
1281 }
1282 
1283 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1284  if (!PGOInstrMemOP)
1285  return;
1286  Value *Length = MI.getLength();
1287  // Not instrument constant length calls.
1288  if (dyn_cast<ConstantInt>(Length))
1289  return;
1290 
1291  switch (Mode) {
1292  case VM_counting:
1293  NMemIs++;
1294  return;
1295  case VM_instrument:
1296  instrumentOneMemIntrinsic(MI);
1297  return;
1298  case VM_annotate:
1299  Candidates.push_back(&MI);
1300  return;
1301  }
1302  llvm_unreachable("Unknown visiting mode");
1303 }
1304 
1305 // Traverse all valuesites and annotate the instructions for all value kind.
1306 void PGOUseFunc::annotateValueSites() {
1308  return;
1309 
1310  // Create the PGOFuncName meta data.
1311  createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1312 
1313  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1314  annotateValueSites(Kind);
1315 }
1316 
1317 // Annotate the instructions for a specific value kind.
1318 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1319  unsigned ValueSiteIndex = 0;
1320  auto &ValueSites = FuncInfo.ValueSites[Kind];
1321  unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1322  if (NumValueSites != ValueSites.size()) {
1323  auto &Ctx = M->getContext();
1324  Ctx.diagnose(DiagnosticInfoPGOProfile(
1325  M->getName().data(),
1326  Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1327  " in " + F.getName().str(),
1328  DS_Warning));
1329  return;
1330  }
1331 
1332  for (auto &I : ValueSites) {
1333  DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1334  << "): Index = " << ValueSiteIndex << " out of "
1335  << NumValueSites << "\n");
1336  annotateValueSite(*M, *I, ProfileRecord,
1337  static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1338  Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1339  : MaxNumAnnotations);
1340  ValueSiteIndex++;
1341  }
1342 }
1343 
1344 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1345 // aware this is an ir_level profile so it can set the version flag.
1347  Type *IntTy64 = Type::getInt64Ty(M.getContext());
1348  uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1349  auto IRLevelVersionVariable = new GlobalVariable(
1350  M, IntTy64, true, GlobalVariable::ExternalLinkage,
1351  Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
1352  INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1353  IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1354  Triple TT(M.getTargetTriple());
1355  if (!TT.supportsCOMDAT())
1356  IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
1357  else
1358  IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
1359  StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1360 }
1361 
1362 // Collect the set of members for each Comdat in module M and store
1363 // in ComdatMembers.
1365  Module &M,
1366  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1367  if (!DoComdatRenaming)
1368  return;
1369  for (Function &F : M)
1370  if (Comdat *C = F.getComdat())
1371  ComdatMembers.insert(std::make_pair(C, &F));
1372  for (GlobalVariable &GV : M.globals())
1373  if (Comdat *C = GV.getComdat())
1374  ComdatMembers.insert(std::make_pair(C, &GV));
1375  for (GlobalAlias &GA : M.aliases())
1376  if (Comdat *C = GA.getComdat())
1377  ComdatMembers.insert(std::make_pair(C, &GA));
1378 }
1379 
1381  Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1382  function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1384  std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1385  collectComdatMembers(M, ComdatMembers);
1386 
1387  for (auto &F : M) {
1388  if (F.isDeclaration())
1389  continue;
1390  auto *BPI = LookupBPI(F);
1391  auto *BFI = LookupBFI(F);
1392  instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
1393  }
1394  return true;
1395 }
1396 
1397 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1398  if (skipModule(M))
1399  return false;
1400 
1401  auto LookupBPI = [this](Function &F) {
1402  return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1403  };
1404  auto LookupBFI = [this](Function &F) {
1405  return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1406  };
1407  return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1408 }
1409 
1411  ModuleAnalysisManager &AM) {
1412  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1413  auto LookupBPI = [&FAM](Function &F) {
1414  return &FAM.getResult<BranchProbabilityAnalysis>(F);
1415  };
1416 
1417  auto LookupBFI = [&FAM](Function &F) {
1418  return &FAM.getResult<BlockFrequencyAnalysis>(F);
1419  };
1420 
1421  if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1422  return PreservedAnalyses::all();
1423 
1424  return PreservedAnalyses::none();
1425 }
1426 
1428  Module &M, StringRef ProfileFileName,
1430  function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1431  DEBUG(dbgs() << "Read in profile counters: ");
1432  auto &Ctx = M.getContext();
1433  // Read the counter array from file.
1434  auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
1435  if (Error E = ReaderOrErr.takeError()) {
1436  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1437  Ctx.diagnose(
1438  DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1439  });
1440  return false;
1441  }
1442 
1443  std::unique_ptr<IndexedInstrProfReader> PGOReader =
1444  std::move(ReaderOrErr.get());
1445  if (!PGOReader) {
1446  Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1447  StringRef("Cannot get PGOReader")));
1448  return false;
1449  }
1450  // TODO: might need to change the warning once the clang option is finalized.
1451  if (!PGOReader->isIRLevelProfile()) {
1452  Ctx.diagnose(DiagnosticInfoPGOProfile(
1453  ProfileFileName.data(), "Not an IR level instrumentation profile"));
1454  return false;
1455  }
1456 
1457  std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1458  collectComdatMembers(M, ComdatMembers);
1459  std::vector<Function *> HotFunctions;
1460  std::vector<Function *> ColdFunctions;
1461  for (auto &F : M) {
1462  if (F.isDeclaration())
1463  continue;
1464  auto *BPI = LookupBPI(F);
1465  auto *BFI = LookupBFI(F);
1466  PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
1467  if (!Func.readCounters(PGOReader.get()))
1468  continue;
1469  Func.populateCounters();
1470  Func.setBranchWeights();
1471  Func.annotateValueSites();
1472  Func.annotateIrrLoopHeaderWeights();
1473  PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1474  if (FreqAttr == PGOUseFunc::FFA_Cold)
1475  ColdFunctions.push_back(&F);
1476  else if (FreqAttr == PGOUseFunc::FFA_Hot)
1477  HotFunctions.push_back(&F);
1478  if (PGOViewCounts != PGOVCT_None &&
1479  (ViewBlockFreqFuncName.empty() ||
1480  F.getName().equals(ViewBlockFreqFuncName))) {
1481  LoopInfo LI{DominatorTree(F)};
1482  std::unique_ptr<BranchProbabilityInfo> NewBPI =
1483  llvm::make_unique<BranchProbabilityInfo>(F, LI);
1484  std::unique_ptr<BlockFrequencyInfo> NewBFI =
1485  llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1486  if (PGOViewCounts == PGOVCT_Graph)
1487  NewBFI->view();
1488  else if (PGOViewCounts == PGOVCT_Text) {
1489  dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1490  NewBFI->print(dbgs());
1491  }
1492  }
1493  if (PGOViewRawCounts != PGOVCT_None &&
1494  (ViewBlockFreqFuncName.empty() ||
1495  F.getName().equals(ViewBlockFreqFuncName))) {
1497  if (ViewBlockFreqFuncName.empty())
1498  WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1499  else
1500  ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1501  else if (PGOViewRawCounts == PGOVCT_Text) {
1502  dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1503  Func.dumpInfo();
1504  }
1505  }
1506  }
1507  M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1508  // Set function hotness attribute from the profile.
1509  // We have to apply these attributes at the end because their presence
1510  // can affect the BranchProbabilityInfo of any callers, resulting in an
1511  // inconsistent MST between prof-gen and prof-use.
1512  for (auto &F : HotFunctions) {
1513  F->addFnAttr(Attribute::InlineHint);
1514  DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1515  << "\n");
1516  }
1517  for (auto &F : ColdFunctions) {
1518  F->addFnAttr(Attribute::Cold);
1519  DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1520  }
1521  return true;
1522 }
1523 
1525  : ProfileFileName(std::move(Filename)) {
1526  if (!PGOTestProfileFile.empty())
1527  ProfileFileName = PGOTestProfileFile;
1528 }
1529 
1531  ModuleAnalysisManager &AM) {
1532 
1533  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1534  auto LookupBPI = [&FAM](Function &F) {
1535  return &FAM.getResult<BranchProbabilityAnalysis>(F);
1536  };
1537 
1538  auto LookupBFI = [&FAM](Function &F) {
1539  return &FAM.getResult<BlockFrequencyAnalysis>(F);
1540  };
1541 
1542  if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1543  return PreservedAnalyses::all();
1544 
1545  return PreservedAnalyses::none();
1546 }
1547 
1548 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1549  if (skipModule(M))
1550  return false;
1551 
1552  auto LookupBPI = [this](Function &F) {
1553  return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1554  };
1555  auto LookupBFI = [this](Function &F) {
1556  return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1557  };
1558 
1559  return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
1560 }
1561 
1562 static std::string getSimpleNodeName(const BasicBlock *Node) {
1563  if (!Node->getName().empty())
1564  return Node->getName();
1565 
1566  std::string SimpleNodeName;
1567  raw_string_ostream OS(SimpleNodeName);
1568  Node->printAsOperand(OS, false);
1569  return OS.str();
1570 }
1571 
1573  ArrayRef<uint64_t> EdgeCounts,
1574  uint64_t MaxCount) {
1575  MDBuilder MDB(M->getContext());
1576  assert(MaxCount > 0 && "Bad max count");
1577  uint64_t Scale = calculateCountScale(MaxCount);
1578  SmallVector<unsigned, 4> Weights;
1579  for (const auto &ECI : EdgeCounts)
1580  Weights.push_back(scaleBranchCount(ECI, Scale));
1581 
1582  DEBUG(dbgs() << "Weight is: ";
1583  for (const auto &W : Weights) { dbgs() << W << " "; }
1584  dbgs() << "\n";);
1585  TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1586  if (EmitBranchProbability) {
1587  std::string BrCondStr = getBranchCondString(TI);
1588  if (BrCondStr.empty())
1589  return;
1590 
1591  unsigned WSum =
1592  std::accumulate(Weights.begin(), Weights.end(), 0,
1593  [](unsigned w1, unsigned w2) { return w1 + w2; });
1594  uint64_t TotalCount =
1595  std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1596  [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1597  BranchProbability BP(Weights[0], WSum);
1598  std::string BranchProbStr;
1599  raw_string_ostream OS(BranchProbStr);
1600  OS << BP;
1601  OS << " (total count : " << TotalCount << ")";
1602  OS.flush();
1603  Function *F = TI->getParent()->getParent();
1605  ORE.emit([&]() {
1606  return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1607  << BrCondStr << " is true with probability : " << BranchProbStr;
1608  });
1609  }
1610 }
1611 
1612 namespace llvm {
1613 
1614 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1615  MDBuilder MDB(M->getContext());
1617  MDB.createIrrLoopHeaderWeight(Count));
1618 }
1619 
1620 template <> struct GraphTraits<PGOUseFunc *> {
1621  using NodeRef = const BasicBlock *;
1624 
1625  static NodeRef getEntryNode(const PGOUseFunc *G) {
1626  return &G->getFunc().front();
1627  }
1628 
1630  return succ_begin(N);
1631  }
1632 
1633  static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1634 
1635  static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1636  return nodes_iterator(G->getFunc().begin());
1637  }
1638 
1639  static nodes_iterator nodes_end(const PGOUseFunc *G) {
1640  return nodes_iterator(G->getFunc().end());
1641  }
1642 };
1643 
1644 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1645  explicit DOTGraphTraits(bool isSimple = false)
1647 
1648  static std::string getGraphName(const PGOUseFunc *G) {
1649  return G->getFunc().getName();
1650  }
1651 
1652  std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1653  std::string Result;
1654  raw_string_ostream OS(Result);
1655 
1656  OS << getSimpleNodeName(Node) << ":\\l";
1657  UseBBInfo *BI = Graph->findBBInfo(Node);
1658  OS << "Count : ";
1659  if (BI && BI->CountValid)
1660  OS << BI->CountValue << "\\l";
1661  else
1662  OS << "Unknown\\l";
1663 
1664  if (!PGOInstrSelect)
1665  return Result;
1666 
1667  for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1668  auto *I = &*BI;
1669  if (!isa<SelectInst>(I))
1670  continue;
1671  // Display scaled counts for SELECT instruction:
1672  OS << "SELECT : { T = ";
1673  uint64_t TC, FC;
1674  bool HasProf = I->extractProfMetadata(TC, FC);
1675  if (!HasProf)
1676  OS << "Unknown, F = Unknown }\\l";
1677  else
1678  OS << TC << ", F = " << FC << " }\\l";
1679  }
1680  return Result;
1681  }
1682 };
1683 
1684 } // end namespace llvm
uint64_t CallInst * C
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge *> Edges)
void push_back(const T &Elt)
Definition: SmallVector.h:212
uint32_t getCRC() const
Definition: JamCRC.h:42
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
void setProfMetadata(Module *M, Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
ModulePass * createPGOInstrumentationGenLegacyPass()
static cl::opt< bool > NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on " "warnings about profile cfg mismatch."))
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Base class for instruction visitors.
Definition: InstVisitor.h:81
SI Whole Quad Mode
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1395
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static cl::opt< bool > PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, cl::desc("Use this option to turn on/off " "warnings about missing profile data for " "functions."))
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static ChildIteratorType child_begin(const NodeRef N)
std::vector< std::unique_ptr< Edge > > AllEdges
Definition: CFGMST.h:44
Diagnostic information for the PGO profiler.
Available for inspection, not emission.
Definition: GlobalValue.h:50
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:971
pgo instr gen
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", "PGO instrumentation.", false, false) INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:55
Externally visible function.
Definition: GlobalValue.h:49
static cl::opt< bool > PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off " "memory intrinsic size profiling."))
uint64_t getMaximumFunctionCount()
Return the maximum of all known function counts.
STATISTIC(NumFunctions, "Total number of functions")
F(f)
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:227
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
Value * getLength() const
Base class for error info classes.
Definition: Error.h:47
An union-find based Minimum Spanning Tree for CFG.
Definition: CFGMST.h:38
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Definition: BitVector.h:920
This class represents the LLVM &#39;select&#39; instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
PGOInstrumentationUse(std::string Filename="")
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:353
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:668
This file contains the simple types necessary to represent the attributes associated with functions a...
Legacy analysis pass which computes BlockFrequencyInfo.
static std::string getGraphName(const PGOUseFunc *G)
VisitMode
The select instruction visitor plays three roles specified by the mode.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
This file implements a class to represent arbitrary precision integral constant values and operations...
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:103
static bool isSimple(Instruction *I)
Analysis pass which computes BranchProbabilityInfo.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:232
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:100
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:201
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static cl::opt< bool > DisableValueProfiling("disable-vp", cl::init(false), cl::Hidden, cl::desc("Disable Value Profiling"))
static NodeRef getEntryNode(const PGOUseFunc *G)
static bool isIndirectBrTarget(BasicBlock *BB)
static void createIRLevelProfileFlagVariable(Module &M)
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
static void setBranchWeights(SwitchInst *SI, ArrayRef< uint32_t > Weights)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Definition: GraphWriter.h:309
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
void initializePGOInstrumentationGenLegacyPassPass(PassRegistry &)
static bool InstrumentAllFunctions(Module &M, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition: Constants.h:209
static bool canRenameComdat(Function &F, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1387
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
static nodes_iterator nodes_end(const PGOUseFunc *G)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:140
amdgpu Simplify well known AMD library false Value * Callee
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:980
instrprof_error get() const
Definition: InstrProf.h:320
Legacy analysis pass which computes BranchProbabilityInfo.
Value * getOperand(unsigned i) const
Definition: User.h:154
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
static ChildIteratorType child_end(const NodeRef N)
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:106
static cl::opt< unsigned > MaxNumMemOPAnnotations("memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of preicise value annotations for a single memop" "intrinsic"))
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:209
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1678
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
StringRef getName() const
Definition: Comdat.cpp:24
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:200
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Conditional or Unconditional Branch instruction.
#define DEBUG_TYPE
void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:626
static StringRef getPredicateName(Predicate P)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Diagnostic information for applied optimization remarks.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
Represent the analysis usage information of a pass.
static cl::opt< PGOViewCountsType > PGOViewRawCounts("pgo-view-raw-counts", cl::Hidden, cl::desc("A boolean option to show CFG dag or text " "with raw profile counts from " "profile data. See also option " "-pgo-view-counts. To limit graph " "display to only one function, use " "filtering option -view-bfi-func-name."), cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), clEnumValN(PGOVCT_Graph, "graph", "show a graph."), clEnumValN(PGOVCT_Text, "text", "show in text.")))
static cl::opt< bool > DoComdatRenaming("do-comdat-renaming", cl::init(false), cl::Hidden, cl::desc("Append function hash to the name of COMDAT function to avoid " "function hash mismatch due to the preinliner"))
ModulePass * createPGOInstrumentationUseLegacyPass(StringRef Filename=StringRef(""))
This instruction compares its operands according to the predicate given to the constructor.
static std::string getBranchCondString(Instruction *TI)
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:313
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run &#39;dot&#39;, run gv on the postscript file, then cleanup.
Definition: GraphWriter.h:348
static cl::opt< bool > NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), cl::Hidden, cl::desc("The option is used to turn on/off " "warnings about hash mismatch for comdat " "functions."))
void initializePGOInstrumentationUseLegacyPassPass(PassRegistry &)
DenseMap< const BasicBlock *, std::unique_ptr< BBInfo > > BBInfos
Definition: CFGMST.h:47
const Value * getCondition() const
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:467
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:811
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function&#39;s raw name.
Definition: InstrProf.cpp:912
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:386
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:3573
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:478
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1214
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:244
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to &#39;dot...
BBInfo * findBBInfo(const BasicBlock *BB) const
Definition: CFGMST.h:85
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Definition: Error.h:889
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:43
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
static nodes_iterator nodes_begin(const PGOUseFunc *G)
static cl::opt< bool > PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off SELECT " "instruction instrumentation. "))
iterator end()
Definition: BasicBlock.h:254
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
pgo instr PGO instrumentation
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:308
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
uint64_t scale(uint64_t Num) const
Scale a large integer.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:517
bool isConditional() const
void dumpEdges(raw_ostream &OS, const Twine &Message) const
Definition: CFGMST.h:176
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Class for arbitrary precision integers.
Definition: APInt.h:69
static cl::opt< std::string > PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile data file. This is" "mainly for test purpose."))
BBInfo & getBBInfo(const BasicBlock *BB) const
Definition: CFGMST.h:78
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:601
const Comdat * getComdat() const
Definition: GlobalObject.h:101
pgo instr Read PGO instrumentation profile
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:927
Analysis providing branch probability information.
unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition: CFG.cpp:72
Profiling information for a single function.
Definition: InstrProf.h:592
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
static bool annotateAllFunctions(Module &M, StringRef ProfileFileName, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI)
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:3468
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:253
static cl::opt< bool > EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, cl::desc("When this option is on, the annotated " "branch probability will be emitted as " " optimization remarks: -Rpass-analysis=" "pgo-instr-use"))
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:331
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:193
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
static cl::opt< unsigned > MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of annotations for a single indirect " "call callsite"))
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
std::vector< Instruction * > findIndirectCallSites(Function &F)
cl::opt< PGOViewCountsType > PGOViewCounts
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1440
TerminatorInst::SuccIterator< const TerminatorInst *, const BasicBlock > succ_const_iterator
Definition: CFG.h:124
const unsigned Kind
static void instrumentOneFunc(Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:462
LLVM Value Representation.
Definition: Value.h:73
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void update(ArrayRef< char > Data)
Definition: JamCRC.cpp:92
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:123
#define DEBUG(X)
Definition: Debug.h:118
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
IRTranslator LLVM IR MI
cl::opt< std::string > ViewBlockFreqFuncName
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Reader for the indexed binary instrprof format.
A container for analyses that lazily runs them and caches their results.
static void collectComdatMembers(Module &M, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
pgo instr use
This header defines various interfaces for pass management in LLVM.
static std::string getSimpleNodeName(const BasicBlock *Node)
The optimization diagnostic interface.
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:400
const BasicBlock * getParent() const
Definition: Instruction.h:66
SelectionKind getSelectionKind() const
Definition: Comdat.h:42
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1663
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:946