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 51 #include "llvm/Transforms/PGOInstrumentation.h" 52 #include "CFGMST.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/SmallVector.h" 55 #include "llvm/ADT/Statistic.h" 56 #include "llvm/ADT/Triple.h" 57 #include "llvm/Analysis/BlockFrequencyInfo.h" 58 #include "llvm/Analysis/BranchProbabilityInfo.h" 59 #include "llvm/Analysis/CFG.h" 60 #include "llvm/Analysis/IndirectCallSiteVisitor.h" 61 #include "llvm/Analysis/LoopInfo.h" 62 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 63 #include "llvm/IR/CallSite.h" 64 #include "llvm/IR/DiagnosticInfo.h" 65 #include "llvm/IR/Dominators.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/InstIterator.h" 69 #include "llvm/IR/Instructions.h" 70 #include "llvm/IR/IntrinsicInst.h" 71 #include "llvm/IR/MDBuilder.h" 72 #include "llvm/IR/Module.h" 73 #include "llvm/Pass.h" 74 #include "llvm/ProfileData/InstrProfReader.h" 75 #include "llvm/ProfileData/ProfileCommon.h" 76 #include "llvm/Support/BranchProbability.h" 77 #include "llvm/Support/DOTGraphTraits.h" 78 #include "llvm/Support/Debug.h" 79 #include "llvm/Support/GraphWriter.h" 80 #include "llvm/Support/JamCRC.h" 81 #include "llvm/Transforms/Instrumentation.h" 82 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 83 #include <algorithm> 84 #include <string> 85 #include <unordered_map> 86 #include <utility> 87 #include <vector> 88 89 using namespace llvm; 90 91 #define DEBUG_TYPE "pgo-instrumentation" 92 93 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); 94 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented."); 95 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented."); 96 STATISTIC(NumOfPGOEdge, "Number of edges."); 97 STATISTIC(NumOfPGOBB, "Number of basic-blocks."); 98 STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); 99 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); 100 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); 101 STATISTIC(NumOfPGOMissing, "Number of functions without profile."); 102 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); 103 104 // Command line option to specify the file to read profile from. This is 105 // mainly used for testing. 106 static cl::opt<std::string> 107 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, 108 cl::value_desc("filename"), 109 cl::desc("Specify the path of profile data file. This is" 110 "mainly for test purpose.")); 111 112 // Command line option to disable value profiling. The default is false: 113 // i.e. value profiling is enabled by default. This is for debug purpose. 114 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), 115 cl::Hidden, 116 cl::desc("Disable Value Profiling")); 117 118 // Command line option to set the maximum number of VP annotations to write to 119 // the metadata for a single indirect call callsite. 120 static cl::opt<unsigned> MaxNumAnnotations( 121 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, 122 cl::desc("Max number of annotations for a single indirect " 123 "call callsite")); 124 125 // Command line option to set the maximum number of value annotations 126 // to write to the metadata for a single memop intrinsic. 127 static cl::opt<unsigned> MaxNumMemOPAnnotations( 128 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, 129 cl::desc("Max number of preicise value annotations for a single memop" 130 "intrinsic")); 131 132 // Command line option to control appending FunctionHash to the name of a COMDAT 133 // function. This is to avoid the hash mismatch caused by the preinliner. 134 static cl::opt<bool> DoComdatRenaming( 135 "do-comdat-renaming", cl::init(false), cl::Hidden, 136 cl::desc("Append function hash to the name of COMDAT function to avoid " 137 "function hash mismatch due to the preinliner")); 138 139 // Command line option to enable/disable the warning about missing profile 140 // information. 141 static cl::opt<bool> 142 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, 143 cl::desc("Use this option to turn on/off " 144 "warnings about missing profile data for " 145 "functions.")); 146 147 // Command line option to enable/disable the warning about a hash mismatch in 148 // the profile data. 149 static cl::opt<bool> 150 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, 151 cl::desc("Use this option to turn off/on " 152 "warnings about profile cfg mismatch.")); 153 154 // Command line option to enable/disable the warning about a hash mismatch in 155 // the profile data for Comdat functions, which often turns out to be false 156 // positive due to the pre-instrumentation inline. 157 static cl::opt<bool> 158 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), 159 cl::Hidden, 160 cl::desc("The option is used to turn on/off " 161 "warnings about hash mismatch for comdat " 162 "functions.")); 163 164 // Command line option to enable/disable select instruction instrumentation. 165 static cl::opt<bool> 166 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, 167 cl::desc("Use this option to turn on/off SELECT " 168 "instruction instrumentation. ")); 169 170 // Command line option to turn on CFG dot or text dump of raw profile counts 171 static cl::opt<PGOViewCountsType> PGOViewRawCounts( 172 "pgo-view-raw-counts", cl::Hidden, 173 cl::desc("A boolean option to show CFG dag or text " 174 "with raw profile counts from " 175 "profile data. See also option " 176 "-pgo-view-counts. To limit graph " 177 "display to only one function, use " 178 "filtering option -view-bfi-func-name."), 179 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), 180 clEnumValN(PGOVCT_Graph, "graph", "show a graph."), 181 clEnumValN(PGOVCT_Text, "text", "show in text."))); 182 183 // Command line option to enable/disable memop intrinsic call.size profiling. 184 static cl::opt<bool> 185 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, 186 cl::desc("Use this option to turn on/off " 187 "memory intrinsic size profiling.")); 188 189 // Emit branch probability as optimization remarks. 190 static cl::opt<bool> 191 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, 192 cl::desc("When this option is on, the annotated " 193 "branch probability will be emitted as " 194 " optimization remarks: -Rpass-analysis=" 195 "pgo-instr-use")); 196 197 // Command line option to turn on CFG dot dump after profile annotation. 198 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts 199 extern cl::opt<PGOViewCountsType> PGOViewCounts; 200 201 // Command line option to specify the name of the function for CFG dump 202 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 203 extern cl::opt<std::string> ViewBlockFreqFuncName; 204 205 namespace { 206 207 // Return a string describing the branch condition that can be 208 // used in static branch probability heuristics: 209 std::string getBranchCondString(Instruction *TI) { 210 BranchInst *BI = dyn_cast<BranchInst>(TI); 211 if (!BI || !BI->isConditional()) 212 return std::string(); 213 214 Value *Cond = BI->getCondition(); 215 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 216 if (!CI) 217 return std::string(); 218 219 std::string result; 220 raw_string_ostream OS(result); 221 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_"; 222 CI->getOperand(0)->getType()->print(OS, true); 223 224 Value *RHS = CI->getOperand(1); 225 ConstantInt *CV = dyn_cast<ConstantInt>(RHS); 226 if (CV) { 227 if (CV->isZero()) 228 OS << "_Zero"; 229 else if (CV->isOne()) 230 OS << "_One"; 231 else if (CV->isMinusOne()) 232 OS << "_MinusOne"; 233 else 234 OS << "_Const"; 235 } 236 OS.flush(); 237 return result; 238 } 239 240 /// The select instruction visitor plays three roles specified 241 /// by the mode. In \c VM_counting mode, it simply counts the number of 242 /// select instructions. In \c VM_instrument mode, it inserts code to count 243 /// the number times TrueValue of select is taken. In \c VM_annotate mode, 244 /// it reads the profile data and annotate the select instruction with metadata. 245 enum VisitMode { VM_counting, VM_instrument, VM_annotate }; 246 class PGOUseFunc; 247 248 /// Instruction Visitor class to visit select instructions. 249 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> { 250 Function &F; 251 unsigned NSIs = 0; // Number of select instructions instrumented. 252 VisitMode Mode = VM_counting; // Visiting mode. 253 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index. 254 unsigned TotalNumCtrs = 0; // Total number of counters 255 GlobalVariable *FuncNameVar = nullptr; 256 uint64_t FuncHash = 0; 257 PGOUseFunc *UseFunc = nullptr; 258 259 SelectInstVisitor(Function &Func) : F(Func) {} 260 261 void countSelects(Function &Func) { 262 NSIs = 0; 263 Mode = VM_counting; 264 visit(Func); 265 } 266 // Visit the IR stream and instrument all select instructions. \p 267 // Ind is a pointer to the counter index variable; \p TotalNC 268 // is the total number of counters; \p FNV is the pointer to the 269 // PGO function name var; \p FHash is the function hash. 270 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC, 271 GlobalVariable *FNV, uint64_t FHash) { 272 Mode = VM_instrument; 273 CurCtrIdx = Ind; 274 TotalNumCtrs = TotalNC; 275 FuncHash = FHash; 276 FuncNameVar = FNV; 277 visit(Func); 278 } 279 280 // Visit the IR stream and annotate all select instructions. 281 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) { 282 Mode = VM_annotate; 283 UseFunc = UF; 284 CurCtrIdx = Ind; 285 visit(Func); 286 } 287 288 void instrumentOneSelectInst(SelectInst &SI); 289 void annotateOneSelectInst(SelectInst &SI); 290 // Visit \p SI instruction and perform tasks according to visit mode. 291 void visitSelectInst(SelectInst &SI); 292 // Return the number of select instructions. This needs be called after 293 // countSelects(). 294 unsigned getNumOfSelectInsts() const { return NSIs; } 295 }; 296 297 /// Instruction Visitor class to visit memory intrinsic calls. 298 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> { 299 Function &F; 300 unsigned NMemIs = 0; // Number of memIntrinsics instrumented. 301 VisitMode Mode = VM_counting; // Visiting mode. 302 unsigned CurCtrId = 0; // Current counter index. 303 unsigned TotalNumCtrs = 0; // Total number of counters 304 GlobalVariable *FuncNameVar = nullptr; 305 uint64_t FuncHash = 0; 306 PGOUseFunc *UseFunc = nullptr; 307 std::vector<Instruction *> Candidates; 308 309 MemIntrinsicVisitor(Function &Func) : F(Func) {} 310 311 void countMemIntrinsics(Function &Func) { 312 NMemIs = 0; 313 Mode = VM_counting; 314 visit(Func); 315 } 316 317 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC, 318 GlobalVariable *FNV, uint64_t FHash) { 319 Mode = VM_instrument; 320 TotalNumCtrs = TotalNC; 321 FuncHash = FHash; 322 FuncNameVar = FNV; 323 visit(Func); 324 } 325 326 std::vector<Instruction *> findMemIntrinsics(Function &Func) { 327 Candidates.clear(); 328 Mode = VM_annotate; 329 visit(Func); 330 return Candidates; 331 } 332 333 // Visit the IR stream and annotate all mem intrinsic call instructions. 334 void instrumentOneMemIntrinsic(MemIntrinsic &MI); 335 // Visit \p MI instruction and perform tasks according to visit mode. 336 void visitMemIntrinsic(MemIntrinsic &SI); 337 unsigned getNumOfMemIntrinsics() const { return NMemIs; } 338 }; 339 340 class PGOInstrumentationGenLegacyPass : public ModulePass { 341 public: 342 static char ID; 343 344 PGOInstrumentationGenLegacyPass() : ModulePass(ID) { 345 initializePGOInstrumentationGenLegacyPassPass( 346 *PassRegistry::getPassRegistry()); 347 } 348 349 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; } 350 351 private: 352 bool runOnModule(Module &M) override; 353 354 void getAnalysisUsage(AnalysisUsage &AU) const override { 355 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 356 } 357 }; 358 359 class PGOInstrumentationUseLegacyPass : public ModulePass { 360 public: 361 static char ID; 362 363 // Provide the profile filename as the parameter. 364 PGOInstrumentationUseLegacyPass(std::string Filename = "") 365 : ModulePass(ID), ProfileFileName(std::move(Filename)) { 366 if (!PGOTestProfileFile.empty()) 367 ProfileFileName = PGOTestProfileFile; 368 initializePGOInstrumentationUseLegacyPassPass( 369 *PassRegistry::getPassRegistry()); 370 } 371 372 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; } 373 374 private: 375 std::string ProfileFileName; 376 377 bool runOnModule(Module &M) override; 378 void getAnalysisUsage(AnalysisUsage &AU) const override { 379 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 380 } 381 }; 382 383 } // end anonymous namespace 384 385 char PGOInstrumentationGenLegacyPass::ID = 0; 386 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", 387 "PGO instrumentation.", false, false) 388 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 389 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 390 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", 391 "PGO instrumentation.", false, false) 392 393 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() { 394 return new PGOInstrumentationGenLegacyPass(); 395 } 396 397 char PGOInstrumentationUseLegacyPass::ID = 0; 398 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use", 399 "Read PGO instrumentation profile.", false, false) 400 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 401 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 402 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use", 403 "Read PGO instrumentation profile.", false, false) 404 405 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) { 406 return new PGOInstrumentationUseLegacyPass(Filename.str()); 407 } 408 409 namespace { 410 /// \brief An MST based instrumentation for PGO 411 /// 412 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO 413 /// in the function level. 414 struct PGOEdge { 415 // This class implements the CFG edges. Note the CFG can be a multi-graph. 416 // So there might be multiple edges with same SrcBB and DestBB. 417 const BasicBlock *SrcBB; 418 const BasicBlock *DestBB; 419 uint64_t Weight; 420 bool InMST; 421 bool Removed; 422 bool IsCritical; 423 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) 424 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), 425 IsCritical(false) {} 426 // Return the information string of an edge. 427 const std::string infoString() const { 428 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + 429 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); 430 } 431 }; 432 433 // This class stores the auxiliary information for each BB. 434 struct BBInfo { 435 BBInfo *Group; 436 uint32_t Index; 437 uint32_t Rank; 438 439 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} 440 441 // Return the information string of this object. 442 const std::string infoString() const { 443 return (Twine("Index=") + Twine(Index)).str(); 444 } 445 }; 446 447 // This class implements the CFG edges. Note the CFG can be a multi-graph. 448 template <class Edge, class BBInfo> class FuncPGOInstrumentation { 449 private: 450 Function &F; 451 void computeCFGHash(); 452 void renameComdatFunction(); 453 // A map that stores the Comdat group in function F. 454 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers; 455 456 public: 457 std::vector<std::vector<Instruction *>> ValueSites; 458 SelectInstVisitor SIVisitor; 459 MemIntrinsicVisitor MIVisitor; 460 std::string FuncName; 461 GlobalVariable *FuncNameVar; 462 // CFG hash value for this function. 463 uint64_t FunctionHash; 464 465 // The Minimum Spanning Tree of function CFG. 466 CFGMST<Edge, BBInfo> MST; 467 468 // Give an edge, find the BB that will be instrumented. 469 // Return nullptr if there is no BB to be instrumented. 470 BasicBlock *getInstrBB(Edge *E); 471 472 // Return the auxiliary BB information. 473 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } 474 475 // Return the auxiliary BB information if available. 476 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); } 477 478 // Dump edges and BB information. 479 void dumpInfo(std::string Str = "") const { 480 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + 481 Twine(FunctionHash) + "\t" + Str); 482 } 483 484 FuncPGOInstrumentation( 485 Function &Func, 486 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 487 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr, 488 BlockFrequencyInfo *BFI = nullptr) 489 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1), 490 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) { 491 492 // This should be done before CFG hash computation. 493 SIVisitor.countSelects(Func); 494 MIVisitor.countMemIntrinsics(Func); 495 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts(); 496 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics(); 497 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func); 498 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func); 499 500 FuncName = getPGOFuncName(F); 501 computeCFGHash(); 502 if (ComdatMembers.size()) 503 renameComdatFunction(); 504 DEBUG(dumpInfo("after CFGMST")); 505 506 NumOfPGOBB += MST.BBInfos.size(); 507 for (auto &E : MST.AllEdges) { 508 if (E->Removed) 509 continue; 510 NumOfPGOEdge++; 511 if (!E->InMST) 512 NumOfPGOInstrument++; 513 } 514 515 if (CreateGlobalVar) 516 FuncNameVar = createPGOFuncNameVar(F, FuncName); 517 } 518 519 // Return the number of profile counters needed for the function. 520 unsigned getNumCounters() { 521 unsigned NumCounters = 0; 522 for (auto &E : this->MST.AllEdges) { 523 if (!E->InMST && !E->Removed) 524 NumCounters++; 525 } 526 return NumCounters + SIVisitor.getNumOfSelectInsts(); 527 } 528 }; 529 530 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index 531 // value of each BB in the CFG. The higher 32 bits record the number of edges. 532 template <class Edge, class BBInfo> 533 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { 534 std::vector<char> Indexes; 535 JamCRC JC; 536 for (auto &BB : F) { 537 const TerminatorInst *TI = BB.getTerminator(); 538 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { 539 BasicBlock *Succ = TI->getSuccessor(I); 540 auto BI = findBBInfo(Succ); 541 if (BI == nullptr) 542 continue; 543 uint32_t Index = BI->Index; 544 for (int J = 0; J < 4; J++) 545 Indexes.push_back((char)(Index >> (J * 8))); 546 } 547 } 548 JC.update(Indexes); 549 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 | 550 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 | 551 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); 552 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n" 553 << " CRC = " << JC.getCRC() 554 << ", Selects = " << SIVisitor.getNumOfSelectInsts() 555 << ", Edges = " << MST.AllEdges.size() 556 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size() 557 << ", Hash = " << FunctionHash << "\n";); 558 } 559 560 // Check if we can safely rename this Comdat function. 561 static bool canRenameComdat( 562 Function &F, 563 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 564 if (!DoComdatRenaming || !canRenameComdatFunc(F, true)) 565 return false; 566 567 // FIXME: Current only handle those Comdat groups that only containing one 568 // function and function aliases. 569 // (1) For a Comdat group containing multiple functions, we need to have a 570 // unique postfix based on the hashes for each function. There is a 571 // non-trivial code refactoring to do this efficiently. 572 // (2) Variables can not be renamed, so we can not rename Comdat function in a 573 // group including global vars. 574 Comdat *C = F.getComdat(); 575 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) { 576 if (dyn_cast<GlobalAlias>(CM.second)) 577 continue; 578 Function *FM = dyn_cast<Function>(CM.second); 579 if (FM != &F) 580 return false; 581 } 582 return true; 583 } 584 585 // Append the CFGHash to the Comdat function name. 586 template <class Edge, class BBInfo> 587 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() { 588 if (!canRenameComdat(F, ComdatMembers)) 589 return; 590 std::string OrigName = F.getName().str(); 591 std::string NewFuncName = 592 Twine(F.getName() + "." + Twine(FunctionHash)).str(); 593 F.setName(Twine(NewFuncName)); 594 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F); 595 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str(); 596 Comdat *NewComdat; 597 Module *M = F.getParent(); 598 // For AvailableExternallyLinkage functions, change the linkage to 599 // LinkOnceODR and put them into comdat. This is because after renaming, there 600 // is no backup external copy available for the function. 601 if (!F.hasComdat()) { 602 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); 603 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName)); 604 F.setLinkage(GlobalValue::LinkOnceODRLinkage); 605 F.setComdat(NewComdat); 606 return; 607 } 608 609 // This function belongs to a single function Comdat group. 610 Comdat *OrigComdat = F.getComdat(); 611 std::string NewComdatName = 612 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str(); 613 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName)); 614 NewComdat->setSelectionKind(OrigComdat->getSelectionKind()); 615 616 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) { 617 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) { 618 // For aliases, change the name directly. 619 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F); 620 std::string OrigGAName = GA->getName().str(); 621 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash))); 622 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA); 623 continue; 624 } 625 // Must be a function. 626 Function *CF = dyn_cast<Function>(CM.second); 627 assert(CF); 628 CF->setComdat(NewComdat); 629 } 630 } 631 632 // Given a CFG E to be instrumented, find which BB to place the instrumented 633 // code. The function will split the critical edge if necessary. 634 template <class Edge, class BBInfo> 635 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { 636 if (E->InMST || E->Removed) 637 return nullptr; 638 639 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); 640 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); 641 // For a fake edge, instrument the real BB. 642 if (SrcBB == nullptr) 643 return DestBB; 644 if (DestBB == nullptr) 645 return SrcBB; 646 647 // Instrument the SrcBB if it has a single successor, 648 // otherwise, the DestBB if this is not a critical edge. 649 TerminatorInst *TI = SrcBB->getTerminator(); 650 if (TI->getNumSuccessors() <= 1) 651 return SrcBB; 652 if (!E->IsCritical) 653 return DestBB; 654 655 // For a critical edge, we have to split. Instrument the newly 656 // created BB. 657 NumOfPGOSplit++; 658 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " 659 << getBBInfo(DestBB).Index << "\n"); 660 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 661 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); 662 assert(InstrBB && "Critical edge is not split"); 663 664 E->Removed = true; 665 return InstrBB; 666 } 667 668 // Visit all edge and instrument the edges not in MST, and do value profiling. 669 // Critical edges will be split. 670 static void instrumentOneFunc( 671 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, 672 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 673 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI, 674 BFI); 675 unsigned NumCounters = FuncInfo.getNumCounters(); 676 677 uint32_t I = 0; 678 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); 679 for (auto &E : FuncInfo.MST.AllEdges) { 680 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); 681 if (!InstrBB) 682 continue; 683 684 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); 685 assert(Builder.GetInsertPoint() != InstrBB->end() && 686 "Cannot get the Instrumentation point"); 687 Builder.CreateCall( 688 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), 689 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), 690 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), 691 Builder.getInt32(I++)}); 692 } 693 694 // Now instrument select instructions: 695 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar, 696 FuncInfo.FunctionHash); 697 assert(I == NumCounters); 698 699 if (DisableValueProfiling) 700 return; 701 702 unsigned NumIndirectCallSites = 0; 703 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) { 704 CallSite CS(I); 705 Value *Callee = CS.getCalledValue(); 706 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " 707 << NumIndirectCallSites << "\n"); 708 IRBuilder<> Builder(I); 709 assert(Builder.GetInsertPoint() != I->getParent()->end() && 710 "Cannot get the Instrumentation point"); 711 Builder.CreateCall( 712 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), 713 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), 714 Builder.getInt64(FuncInfo.FunctionHash), 715 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), 716 Builder.getInt32(IPVK_IndirectCallTarget), 717 Builder.getInt32(NumIndirectCallSites++)}); 718 } 719 NumOfPGOICall += NumIndirectCallSites; 720 721 // Now instrument memop intrinsic calls. 722 FuncInfo.MIVisitor.instrumentMemIntrinsics( 723 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash); 724 } 725 726 // This class represents a CFG edge in profile use compilation. 727 struct PGOUseEdge : public PGOEdge { 728 bool CountValid; 729 uint64_t CountValue; 730 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) 731 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} 732 733 // Set edge count value 734 void setEdgeCount(uint64_t Value) { 735 CountValue = Value; 736 CountValid = true; 737 } 738 739 // Return the information string for this object. 740 const std::string infoString() const { 741 if (!CountValid) 742 return PGOEdge::infoString(); 743 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) 744 .str(); 745 } 746 }; 747 748 typedef SmallVector<PGOUseEdge *, 2> DirectEdges; 749 750 // This class stores the auxiliary information for each BB. 751 struct UseBBInfo : public BBInfo { 752 uint64_t CountValue; 753 bool CountValid; 754 int32_t UnknownCountInEdge; 755 int32_t UnknownCountOutEdge; 756 DirectEdges InEdges; 757 DirectEdges OutEdges; 758 UseBBInfo(unsigned IX) 759 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), 760 UnknownCountOutEdge(0) {} 761 UseBBInfo(unsigned IX, uint64_t C) 762 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), 763 UnknownCountOutEdge(0) {} 764 765 // Set the profile count value for this BB. 766 void setBBInfoCount(uint64_t Value) { 767 CountValue = Value; 768 CountValid = true; 769 } 770 771 // Return the information string of this object. 772 const std::string infoString() const { 773 if (!CountValid) 774 return BBInfo::infoString(); 775 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); 776 } 777 }; 778 779 // Sum up the count values for all the edges. 780 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { 781 uint64_t Total = 0; 782 for (auto &E : Edges) { 783 if (E->Removed) 784 continue; 785 Total += E->CountValue; 786 } 787 return Total; 788 } 789 790 class PGOUseFunc { 791 public: 792 PGOUseFunc(Function &Func, Module *Modu, 793 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 794 BranchProbabilityInfo *BPI = nullptr, 795 BlockFrequencyInfo *BFI = nullptr) 796 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI), 797 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {} 798 799 // Read counts for the instrumented BB from profile. 800 bool readCounters(IndexedInstrProfReader *PGOReader); 801 802 // Populate the counts for all BBs. 803 void populateCounters(); 804 805 // Set the branch weights based on the count values. 806 void setBranchWeights(); 807 808 // Annotate the value profile call sites all all value kind. 809 void annotateValueSites(); 810 811 // Annotate the value profile call sites for one value kind. 812 void annotateValueSites(uint32_t Kind); 813 814 // The hotness of the function from the profile count. 815 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; 816 817 // Return the function hotness from the profile. 818 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } 819 820 // Return the function hash. 821 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; } 822 // Return the profile record for this function; 823 InstrProfRecord &getProfileRecord() { return ProfileRecord; } 824 825 // Return the auxiliary BB information. 826 UseBBInfo &getBBInfo(const BasicBlock *BB) const { 827 return FuncInfo.getBBInfo(BB); 828 } 829 830 // Return the auxiliary BB information if available. 831 UseBBInfo *findBBInfo(const BasicBlock *BB) const { 832 return FuncInfo.findBBInfo(BB); 833 } 834 835 Function &getFunc() const { return F; } 836 837 void dumpInfo(std::string Str = "") const { 838 FuncInfo.dumpInfo(Str); 839 } 840 841 private: 842 Function &F; 843 Module *M; 844 // This member stores the shared information with class PGOGenFunc. 845 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; 846 847 // The maximum count value in the profile. This is only used in PGO use 848 // compilation. 849 uint64_t ProgramMaxCount; 850 851 // Position of counter that remains to be read. 852 uint32_t CountPosition; 853 854 // Total size of the profile count for this function. 855 uint32_t ProfileCountSize; 856 857 // ProfileRecord for this function. 858 InstrProfRecord ProfileRecord; 859 860 // Function hotness info derived from profile. 861 FuncFreqAttr FreqAttr; 862 863 // Find the Instrumented BB and set the value. 864 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); 865 866 // Set the edge counter value for the unknown edge -- there should be only 867 // one unknown edge. 868 void setEdgeCount(DirectEdges &Edges, uint64_t Value); 869 870 // Return FuncName string; 871 const std::string getFuncName() const { return FuncInfo.FuncName; } 872 873 // Set the hot/cold inline hints based on the count values. 874 // FIXME: This function should be removed once the functionality in 875 // the inliner is implemented. 876 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { 877 if (ProgramMaxCount == 0) 878 return; 879 // Threshold of the hot functions. 880 const BranchProbability HotFunctionThreshold(1, 100); 881 // Threshold of the cold functions. 882 const BranchProbability ColdFunctionThreshold(2, 10000); 883 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) 884 FreqAttr = FFA_Hot; 885 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) 886 FreqAttr = FFA_Cold; 887 } 888 }; 889 890 // Visit all the edges and assign the count value for the instrumented 891 // edges and the BB. 892 void PGOUseFunc::setInstrumentedCounts( 893 const std::vector<uint64_t> &CountFromProfile) { 894 895 assert(FuncInfo.getNumCounters() == CountFromProfile.size()); 896 // Use a worklist as we will update the vector during the iteration. 897 std::vector<PGOUseEdge *> WorkList; 898 for (auto &E : FuncInfo.MST.AllEdges) 899 WorkList.push_back(E.get()); 900 901 uint32_t I = 0; 902 for (auto &E : WorkList) { 903 BasicBlock *InstrBB = FuncInfo.getInstrBB(E); 904 if (!InstrBB) 905 continue; 906 uint64_t CountValue = CountFromProfile[I++]; 907 if (!E->Removed) { 908 getBBInfo(InstrBB).setBBInfoCount(CountValue); 909 E->setEdgeCount(CountValue); 910 continue; 911 } 912 913 // Need to add two new edges. 914 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); 915 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); 916 // Add new edge of SrcBB->InstrBB. 917 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); 918 NewEdge.setEdgeCount(CountValue); 919 // Add new edge of InstrBB->DestBB. 920 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); 921 NewEdge1.setEdgeCount(CountValue); 922 NewEdge1.InMST = true; 923 getBBInfo(InstrBB).setBBInfoCount(CountValue); 924 } 925 ProfileCountSize = CountFromProfile.size(); 926 CountPosition = I; 927 } 928 929 // Set the count value for the unknown edge. There should be one and only one 930 // unknown edge in Edges vector. 931 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { 932 for (auto &E : Edges) { 933 if (E->CountValid) 934 continue; 935 E->setEdgeCount(Value); 936 937 getBBInfo(E->SrcBB).UnknownCountOutEdge--; 938 getBBInfo(E->DestBB).UnknownCountInEdge--; 939 return; 940 } 941 llvm_unreachable("Cannot find the unknown count edge"); 942 } 943 944 // Read the profile from ProfileFileName and assign the value to the 945 // instrumented BB and the edges. This function also updates ProgramMaxCount. 946 // Return true if the profile are successfully read, and false on errors. 947 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { 948 auto &Ctx = M->getContext(); 949 Expected<InstrProfRecord> Result = 950 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); 951 if (Error E = Result.takeError()) { 952 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { 953 auto Err = IPE.get(); 954 bool SkipWarning = false; 955 if (Err == instrprof_error::unknown_function) { 956 NumOfPGOMissing++; 957 SkipWarning = !PGOWarnMissing; 958 } else if (Err == instrprof_error::hash_mismatch || 959 Err == instrprof_error::malformed) { 960 NumOfPGOMismatch++; 961 SkipWarning = 962 NoPGOWarnMismatch || 963 (NoPGOWarnMismatchComdat && 964 (F.hasComdat() || 965 F.getLinkage() == GlobalValue::AvailableExternallyLinkage)); 966 } 967 968 if (SkipWarning) 969 return; 970 971 std::string Msg = IPE.message() + std::string(" ") + F.getName().str(); 972 Ctx.diagnose( 973 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); 974 }); 975 return false; 976 } 977 ProfileRecord = std::move(Result.get()); 978 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; 979 980 NumOfPGOFunc++; 981 DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); 982 uint64_t ValueSum = 0; 983 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { 984 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); 985 ValueSum += CountFromProfile[I]; 986 } 987 988 DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); 989 990 getBBInfo(nullptr).UnknownCountOutEdge = 2; 991 getBBInfo(nullptr).UnknownCountInEdge = 2; 992 993 setInstrumentedCounts(CountFromProfile); 994 ProgramMaxCount = PGOReader->getMaximumFunctionCount(); 995 return true; 996 } 997 998 // Populate the counters from instrumented BBs to all BBs. 999 // In the end of this operation, all BBs should have a valid count value. 1000 void PGOUseFunc::populateCounters() { 1001 // First set up Count variable for all BBs. 1002 for (auto &E : FuncInfo.MST.AllEdges) { 1003 if (E->Removed) 1004 continue; 1005 1006 const BasicBlock *SrcBB = E->SrcBB; 1007 const BasicBlock *DestBB = E->DestBB; 1008 UseBBInfo &SrcInfo = getBBInfo(SrcBB); 1009 UseBBInfo &DestInfo = getBBInfo(DestBB); 1010 SrcInfo.OutEdges.push_back(E.get()); 1011 DestInfo.InEdges.push_back(E.get()); 1012 SrcInfo.UnknownCountOutEdge++; 1013 DestInfo.UnknownCountInEdge++; 1014 1015 if (!E->CountValid) 1016 continue; 1017 DestInfo.UnknownCountInEdge--; 1018 SrcInfo.UnknownCountOutEdge--; 1019 } 1020 1021 bool Changes = true; 1022 unsigned NumPasses = 0; 1023 while (Changes) { 1024 NumPasses++; 1025 Changes = false; 1026 1027 // For efficient traversal, it's better to start from the end as most 1028 // of the instrumented edges are at the end. 1029 for (auto &BB : reverse(F)) { 1030 UseBBInfo *Count = findBBInfo(&BB); 1031 if (Count == nullptr) 1032 continue; 1033 if (!Count->CountValid) { 1034 if (Count->UnknownCountOutEdge == 0) { 1035 Count->CountValue = sumEdgeCount(Count->OutEdges); 1036 Count->CountValid = true; 1037 Changes = true; 1038 } else if (Count->UnknownCountInEdge == 0) { 1039 Count->CountValue = sumEdgeCount(Count->InEdges); 1040 Count->CountValid = true; 1041 Changes = true; 1042 } 1043 } 1044 if (Count->CountValid) { 1045 if (Count->UnknownCountOutEdge == 1) { 1046 uint64_t Total = 0; 1047 uint64_t OutSum = sumEdgeCount(Count->OutEdges); 1048 // If the one of the successor block can early terminate (no-return), 1049 // we can end up with situation where out edge sum count is larger as 1050 // the source BB's count is collected by a post-dominated block. 1051 if (Count->CountValue > OutSum) 1052 Total = Count->CountValue - OutSum; 1053 setEdgeCount(Count->OutEdges, Total); 1054 Changes = true; 1055 } 1056 if (Count->UnknownCountInEdge == 1) { 1057 uint64_t Total = 0; 1058 uint64_t InSum = sumEdgeCount(Count->InEdges); 1059 if (Count->CountValue > InSum) 1060 Total = Count->CountValue - InSum; 1061 setEdgeCount(Count->InEdges, Total); 1062 Changes = true; 1063 } 1064 } 1065 } 1066 } 1067 1068 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); 1069 #ifndef NDEBUG 1070 // Assert every BB has a valid counter. 1071 for (auto &BB : F) { 1072 auto BI = findBBInfo(&BB); 1073 if (BI == nullptr) 1074 continue; 1075 assert(BI->CountValid && "BB count is not valid"); 1076 } 1077 #endif 1078 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; 1079 F.setEntryCount(FuncEntryCount); 1080 uint64_t FuncMaxCount = FuncEntryCount; 1081 for (auto &BB : F) { 1082 auto BI = findBBInfo(&BB); 1083 if (BI == nullptr) 1084 continue; 1085 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue); 1086 } 1087 markFunctionAttributes(FuncEntryCount, FuncMaxCount); 1088 1089 // Now annotate select instructions 1090 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition); 1091 assert(CountPosition == ProfileCountSize); 1092 1093 DEBUG(FuncInfo.dumpInfo("after reading profile.")); 1094 } 1095 1096 // Assign the scaled count values to the BB with multiple out edges. 1097 void PGOUseFunc::setBranchWeights() { 1098 // Generate MD_prof metadata for every branch instruction. 1099 DEBUG(dbgs() << "\nSetting branch weights.\n"); 1100 for (auto &BB : F) { 1101 TerminatorInst *TI = BB.getTerminator(); 1102 if (TI->getNumSuccessors() < 2) 1103 continue; 1104 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || 1105 isa<IndirectBrInst>(TI))) 1106 continue; 1107 if (getBBInfo(&BB).CountValue == 0) 1108 continue; 1109 1110 // We have a non-zero Branch BB. 1111 const UseBBInfo &BBCountInfo = getBBInfo(&BB); 1112 unsigned Size = BBCountInfo.OutEdges.size(); 1113 SmallVector<uint64_t, 2> EdgeCounts(Size, 0); 1114 uint64_t MaxCount = 0; 1115 for (unsigned s = 0; s < Size; s++) { 1116 const PGOUseEdge *E = BBCountInfo.OutEdges[s]; 1117 const BasicBlock *SrcBB = E->SrcBB; 1118 const BasicBlock *DestBB = E->DestBB; 1119 if (DestBB == nullptr) 1120 continue; 1121 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 1122 uint64_t EdgeCount = E->CountValue; 1123 if (EdgeCount > MaxCount) 1124 MaxCount = EdgeCount; 1125 EdgeCounts[SuccNum] = EdgeCount; 1126 } 1127 setProfMetadata(M, TI, EdgeCounts, MaxCount); 1128 } 1129 } 1130 1131 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) { 1132 Module *M = F.getParent(); 1133 IRBuilder<> Builder(&SI); 1134 Type *Int64Ty = Builder.getInt64Ty(); 1135 Type *I8PtrTy = Builder.getInt8PtrTy(); 1136 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty); 1137 Builder.CreateCall( 1138 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step), 1139 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), 1140 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs), 1141 Builder.getInt32(*CurCtrIdx), Step}); 1142 ++(*CurCtrIdx); 1143 } 1144 1145 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) { 1146 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts; 1147 assert(*CurCtrIdx < CountFromProfile.size() && 1148 "Out of bound access of counters"); 1149 uint64_t SCounts[2]; 1150 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count 1151 ++(*CurCtrIdx); 1152 uint64_t TotalCount = 0; 1153 auto BI = UseFunc->findBBInfo(SI.getParent()); 1154 if (BI != nullptr) 1155 TotalCount = BI->CountValue; 1156 // False Count 1157 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0); 1158 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]); 1159 if (MaxCount) 1160 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount); 1161 } 1162 1163 void SelectInstVisitor::visitSelectInst(SelectInst &SI) { 1164 if (!PGOInstrSelect) 1165 return; 1166 // FIXME: do not handle this yet. 1167 if (SI.getCondition()->getType()->isVectorTy()) 1168 return; 1169 1170 switch (Mode) { 1171 case VM_counting: 1172 NSIs++; 1173 return; 1174 case VM_instrument: 1175 instrumentOneSelectInst(SI); 1176 return; 1177 case VM_annotate: 1178 annotateOneSelectInst(SI); 1179 return; 1180 } 1181 1182 llvm_unreachable("Unknown visiting mode"); 1183 } 1184 1185 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) { 1186 Module *M = F.getParent(); 1187 IRBuilder<> Builder(&MI); 1188 Type *Int64Ty = Builder.getInt64Ty(); 1189 Type *I8PtrTy = Builder.getInt8PtrTy(); 1190 Value *Length = MI.getLength(); 1191 assert(!dyn_cast<ConstantInt>(Length)); 1192 Builder.CreateCall( 1193 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), 1194 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), 1195 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty), 1196 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)}); 1197 ++CurCtrId; 1198 } 1199 1200 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) { 1201 if (!PGOInstrMemOP) 1202 return; 1203 Value *Length = MI.getLength(); 1204 // Not instrument constant length calls. 1205 if (dyn_cast<ConstantInt>(Length)) 1206 return; 1207 1208 switch (Mode) { 1209 case VM_counting: 1210 NMemIs++; 1211 return; 1212 case VM_instrument: 1213 instrumentOneMemIntrinsic(MI); 1214 return; 1215 case VM_annotate: 1216 Candidates.push_back(&MI); 1217 return; 1218 } 1219 llvm_unreachable("Unknown visiting mode"); 1220 } 1221 1222 // Traverse all valuesites and annotate the instructions for all value kind. 1223 void PGOUseFunc::annotateValueSites() { 1224 if (DisableValueProfiling) 1225 return; 1226 1227 // Create the PGOFuncName meta data. 1228 createPGOFuncNameMetadata(F, FuncInfo.FuncName); 1229 1230 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 1231 annotateValueSites(Kind); 1232 } 1233 1234 // Annotate the instructions for a specific value kind. 1235 void PGOUseFunc::annotateValueSites(uint32_t Kind) { 1236 unsigned ValueSiteIndex = 0; 1237 auto &ValueSites = FuncInfo.ValueSites[Kind]; 1238 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind); 1239 if (NumValueSites != ValueSites.size()) { 1240 auto &Ctx = M->getContext(); 1241 Ctx.diagnose(DiagnosticInfoPGOProfile( 1242 M->getName().data(), 1243 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) + 1244 " in " + F.getName().str(), 1245 DS_Warning)); 1246 return; 1247 } 1248 1249 for (auto &I : ValueSites) { 1250 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind 1251 << "): Index = " << ValueSiteIndex << " out of " 1252 << NumValueSites << "\n"); 1253 annotateValueSite(*M, *I, ProfileRecord, 1254 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex, 1255 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations 1256 : MaxNumAnnotations); 1257 ValueSiteIndex++; 1258 } 1259 } 1260 } // end anonymous namespace 1261 1262 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime 1263 // aware this is an ir_level profile so it can set the version flag. 1264 static void createIRLevelProfileFlagVariable(Module &M) { 1265 Type *IntTy64 = Type::getInt64Ty(M.getContext()); 1266 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); 1267 auto IRLevelVersionVariable = new GlobalVariable( 1268 M, IntTy64, true, GlobalVariable::ExternalLinkage, 1269 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), 1270 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); 1271 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); 1272 Triple TT(M.getTargetTriple()); 1273 if (!TT.supportsCOMDAT()) 1274 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage); 1275 else 1276 IRLevelVersionVariable->setComdat(M.getOrInsertComdat( 1277 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)))); 1278 } 1279 1280 // Collect the set of members for each Comdat in module M and store 1281 // in ComdatMembers. 1282 static void collectComdatMembers( 1283 Module &M, 1284 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 1285 if (!DoComdatRenaming) 1286 return; 1287 for (Function &F : M) 1288 if (Comdat *C = F.getComdat()) 1289 ComdatMembers.insert(std::make_pair(C, &F)); 1290 for (GlobalVariable &GV : M.globals()) 1291 if (Comdat *C = GV.getComdat()) 1292 ComdatMembers.insert(std::make_pair(C, &GV)); 1293 for (GlobalAlias &GA : M.aliases()) 1294 if (Comdat *C = GA.getComdat()) 1295 ComdatMembers.insert(std::make_pair(C, &GA)); 1296 } 1297 1298 static bool InstrumentAllFunctions( 1299 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1300 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { 1301 createIRLevelProfileFlagVariable(M); 1302 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1303 collectComdatMembers(M, ComdatMembers); 1304 1305 for (auto &F : M) { 1306 if (F.isDeclaration()) 1307 continue; 1308 auto *BPI = LookupBPI(F); 1309 auto *BFI = LookupBFI(F); 1310 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers); 1311 } 1312 return true; 1313 } 1314 1315 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) { 1316 if (skipModule(M)) 1317 return false; 1318 1319 auto LookupBPI = [this](Function &F) { 1320 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); 1321 }; 1322 auto LookupBFI = [this](Function &F) { 1323 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 1324 }; 1325 return InstrumentAllFunctions(M, LookupBPI, LookupBFI); 1326 } 1327 1328 PreservedAnalyses PGOInstrumentationGen::run(Module &M, 1329 ModuleAnalysisManager &AM) { 1330 1331 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1332 auto LookupBPI = [&FAM](Function &F) { 1333 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1334 }; 1335 1336 auto LookupBFI = [&FAM](Function &F) { 1337 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1338 }; 1339 1340 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI)) 1341 return PreservedAnalyses::all(); 1342 1343 return PreservedAnalyses::none(); 1344 } 1345 1346 static bool annotateAllFunctions( 1347 Module &M, StringRef ProfileFileName, 1348 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1349 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { 1350 DEBUG(dbgs() << "Read in profile counters: "); 1351 auto &Ctx = M.getContext(); 1352 // Read the counter array from file. 1353 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); 1354 if (Error E = ReaderOrErr.takeError()) { 1355 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 1356 Ctx.diagnose( 1357 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message())); 1358 }); 1359 return false; 1360 } 1361 1362 std::unique_ptr<IndexedInstrProfReader> PGOReader = 1363 std::move(ReaderOrErr.get()); 1364 if (!PGOReader) { 1365 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), 1366 StringRef("Cannot get PGOReader"))); 1367 return false; 1368 } 1369 // TODO: might need to change the warning once the clang option is finalized. 1370 if (!PGOReader->isIRLevelProfile()) { 1371 Ctx.diagnose(DiagnosticInfoPGOProfile( 1372 ProfileFileName.data(), "Not an IR level instrumentation profile")); 1373 return false; 1374 } 1375 1376 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1377 collectComdatMembers(M, ComdatMembers); 1378 std::vector<Function *> HotFunctions; 1379 std::vector<Function *> ColdFunctions; 1380 for (auto &F : M) { 1381 if (F.isDeclaration()) 1382 continue; 1383 auto *BPI = LookupBPI(F); 1384 auto *BFI = LookupBFI(F); 1385 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI); 1386 if (!Func.readCounters(PGOReader.get())) 1387 continue; 1388 Func.populateCounters(); 1389 Func.setBranchWeights(); 1390 Func.annotateValueSites(); 1391 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); 1392 if (FreqAttr == PGOUseFunc::FFA_Cold) 1393 ColdFunctions.push_back(&F); 1394 else if (FreqAttr == PGOUseFunc::FFA_Hot) 1395 HotFunctions.push_back(&F); 1396 if (PGOViewCounts != PGOVCT_None && 1397 (ViewBlockFreqFuncName.empty() || 1398 F.getName().equals(ViewBlockFreqFuncName))) { 1399 LoopInfo LI{DominatorTree(F)}; 1400 std::unique_ptr<BranchProbabilityInfo> NewBPI = 1401 llvm::make_unique<BranchProbabilityInfo>(F, LI); 1402 std::unique_ptr<BlockFrequencyInfo> NewBFI = 1403 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI); 1404 if (PGOViewCounts == PGOVCT_Graph) 1405 NewBFI->view(); 1406 else if (PGOViewCounts == PGOVCT_Text) { 1407 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n"; 1408 NewBFI->print(dbgs()); 1409 } 1410 } 1411 if (PGOViewRawCounts != PGOVCT_None && 1412 (ViewBlockFreqFuncName.empty() || 1413 F.getName().equals(ViewBlockFreqFuncName))) { 1414 if (PGOViewRawCounts == PGOVCT_Graph) 1415 if (ViewBlockFreqFuncName.empty()) 1416 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1417 else 1418 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1419 else if (PGOViewRawCounts == PGOVCT_Text) { 1420 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n"; 1421 Func.dumpInfo(); 1422 } 1423 } 1424 } 1425 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext())); 1426 // Set function hotness attribute from the profile. 1427 // We have to apply these attributes at the end because their presence 1428 // can affect the BranchProbabilityInfo of any callers, resulting in an 1429 // inconsistent MST between prof-gen and prof-use. 1430 for (auto &F : HotFunctions) { 1431 F->addFnAttr(llvm::Attribute::InlineHint); 1432 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() 1433 << "\n"); 1434 } 1435 for (auto &F : ColdFunctions) { 1436 F->addFnAttr(llvm::Attribute::Cold); 1437 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); 1438 } 1439 return true; 1440 } 1441 1442 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename) 1443 : ProfileFileName(std::move(Filename)) { 1444 if (!PGOTestProfileFile.empty()) 1445 ProfileFileName = PGOTestProfileFile; 1446 } 1447 1448 PreservedAnalyses PGOInstrumentationUse::run(Module &M, 1449 ModuleAnalysisManager &AM) { 1450 1451 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1452 auto LookupBPI = [&FAM](Function &F) { 1453 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1454 }; 1455 1456 auto LookupBFI = [&FAM](Function &F) { 1457 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1458 }; 1459 1460 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI)) 1461 return PreservedAnalyses::all(); 1462 1463 return PreservedAnalyses::none(); 1464 } 1465 1466 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) { 1467 if (skipModule(M)) 1468 return false; 1469 1470 auto LookupBPI = [this](Function &F) { 1471 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); 1472 }; 1473 auto LookupBFI = [this](Function &F) { 1474 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 1475 }; 1476 1477 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI); 1478 } 1479 1480 namespace llvm { 1481 void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts, 1482 uint64_t MaxCount) { 1483 MDBuilder MDB(M->getContext()); 1484 assert(MaxCount > 0 && "Bad max count"); 1485 uint64_t Scale = calculateCountScale(MaxCount); 1486 SmallVector<unsigned, 4> Weights; 1487 for (const auto &ECI : EdgeCounts) 1488 Weights.push_back(scaleBranchCount(ECI, Scale)); 1489 1490 DEBUG(dbgs() << "Weight is: "; 1491 for (const auto &W : Weights) { dbgs() << W << " "; } 1492 dbgs() << "\n";); 1493 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1494 if (EmitBranchProbability) { 1495 std::string BrCondStr = getBranchCondString(TI); 1496 if (BrCondStr.empty()) 1497 return; 1498 1499 unsigned WSum = 1500 std::accumulate(Weights.begin(), Weights.end(), 0, 1501 [](unsigned w1, unsigned w2) { return w1 + w2; }); 1502 uint64_t TotalCount = 1503 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0, 1504 [](uint64_t c1, uint64_t c2) { return c1 + c2; }); 1505 BranchProbability BP(Weights[0], WSum); 1506 std::string BranchProbStr; 1507 raw_string_ostream OS(BranchProbStr); 1508 OS << BP; 1509 OS << " (total count : " << TotalCount << ")"; 1510 OS.flush(); 1511 Function *F = TI->getParent()->getParent(); 1512 OptimizationRemarkEmitter ORE(F); 1513 ORE.emit(OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI) 1514 << BrCondStr << " is true with probability : " << BranchProbStr); 1515 } 1516 } 1517 1518 template <> struct GraphTraits<PGOUseFunc *> { 1519 typedef const BasicBlock *NodeRef; 1520 typedef succ_const_iterator ChildIteratorType; 1521 typedef pointer_iterator<Function::const_iterator> nodes_iterator; 1522 1523 static NodeRef getEntryNode(const PGOUseFunc *G) { 1524 return &G->getFunc().front(); 1525 } 1526 static ChildIteratorType child_begin(const NodeRef N) { 1527 return succ_begin(N); 1528 } 1529 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); } 1530 static nodes_iterator nodes_begin(const PGOUseFunc *G) { 1531 return nodes_iterator(G->getFunc().begin()); 1532 } 1533 static nodes_iterator nodes_end(const PGOUseFunc *G) { 1534 return nodes_iterator(G->getFunc().end()); 1535 } 1536 }; 1537 1538 static std::string getSimpleNodeName(const BasicBlock *Node) { 1539 if (!Node->getName().empty()) 1540 return Node->getName(); 1541 1542 std::string SimpleNodeName; 1543 raw_string_ostream OS(SimpleNodeName); 1544 Node->printAsOperand(OS, false); 1545 return OS.str(); 1546 } 1547 1548 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits { 1549 explicit DOTGraphTraits(bool isSimple = false) 1550 : DefaultDOTGraphTraits(isSimple) {} 1551 1552 static std::string getGraphName(const PGOUseFunc *G) { 1553 return G->getFunc().getName(); 1554 } 1555 1556 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) { 1557 std::string Result; 1558 raw_string_ostream OS(Result); 1559 1560 OS << getSimpleNodeName(Node) << ":\\l"; 1561 UseBBInfo *BI = Graph->findBBInfo(Node); 1562 OS << "Count : "; 1563 if (BI && BI->CountValid) 1564 OS << BI->CountValue << "\\l"; 1565 else 1566 OS << "Unknown\\l"; 1567 1568 if (!PGOInstrSelect) 1569 return Result; 1570 1571 for (auto BI = Node->begin(); BI != Node->end(); ++BI) { 1572 auto *I = &*BI; 1573 if (!isa<SelectInst>(I)) 1574 continue; 1575 // Display scaled counts for SELECT instruction: 1576 OS << "SELECT : { T = "; 1577 uint64_t TC, FC; 1578 bool HasProf = I->extractProfMetadata(TC, FC); 1579 if (!HasProf) 1580 OS << "Unknown, F = Unknown }\\l"; 1581 else 1582 OS << TC << ", F = " << FC << " }\\l"; 1583 } 1584 return Result; 1585 } 1586 }; 1587 } // namespace llvm 1588