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