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