1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===// 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 the SampleProfileLoader transformation. This pass 11 // reads a profile file generated by a sampling profiler (e.g. Linux Perf - 12 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the 13 // profile information in the given profile. 14 // 15 // This pass generates branch weight annotations on the IR: 16 // 17 // - prof: Represents branch weights. This annotation is added to branches 18 // to indicate the weights of each edge coming out of the branch. 19 // The weight of each edge is the weight of the target block for 20 // that edge. The weight of a block B is computed as the maximum 21 // number of samples found in B. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #include "llvm/ADT/DenseMap.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/Analysis/LoopInfo.h" 30 #include "llvm/Analysis/PostDominators.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/InstIterator.h" 37 #include "llvm/IR/Instructions.h" 38 #include "llvm/IR/LLVMContext.h" 39 #include "llvm/IR/MDBuilder.h" 40 #include "llvm/IR/Metadata.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/Pass.h" 43 #include "llvm/ProfileData/SampleProfReader.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Debug.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Transforms/IPO.h" 48 #include <cctype> 49 50 using namespace llvm; 51 using namespace sampleprof; 52 53 #define DEBUG_TYPE "sample-profile" 54 55 // Command line option to specify the file to read samples from. This is 56 // mainly used for debugging. 57 static cl::opt<std::string> SampleProfileFile( 58 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 59 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 60 static cl::opt<unsigned> SampleProfileMaxPropagateIterations( 61 "sample-profile-max-propagate-iterations", cl::init(100), 62 cl::desc("Maximum number of iterations to go through when propagating " 63 "sample block/edge weights through the CFG.")); 64 65 namespace { 66 typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap; 67 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap; 68 typedef std::pair<BasicBlock *, BasicBlock *> Edge; 69 typedef DenseMap<Edge, unsigned> EdgeWeightMap; 70 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap; 71 72 /// \brief Sample profile pass. 73 /// 74 /// This pass reads profile data from the file specified by 75 /// -sample-profile-file and annotates every affected function with the 76 /// profile information found in that file. 77 class SampleProfileLoader : public ModulePass { 78 public: 79 // Class identification, replacement for typeinfo 80 static char ID; 81 82 SampleProfileLoader(StringRef Name = SampleProfileFile) 83 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(), 84 Samples(nullptr), Filename(Name), ProfileIsValid(false) { 85 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry()); 86 } 87 88 bool doInitialization(Module &M) override; 89 90 void dump() { Reader->dump(); } 91 92 const char *getPassName() const override { return "Sample profile pass"; } 93 94 bool runOnModule(Module &M) override; 95 96 void getAnalysisUsage(AnalysisUsage &AU) const override { 97 AU.setPreservesCFG(); 98 } 99 100 protected: 101 bool runOnFunction(Function &F); 102 unsigned getFunctionLoc(Function &F); 103 bool emitAnnotations(Function &F); 104 unsigned getInstWeight(Instruction &I); 105 unsigned getBlockWeight(BasicBlock *BB); 106 void printEdgeWeight(raw_ostream &OS, Edge E); 107 void printBlockWeight(raw_ostream &OS, BasicBlock *BB); 108 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB); 109 bool computeBlockWeights(Function &F); 110 void findEquivalenceClasses(Function &F); 111 void findEquivalencesFor(BasicBlock *BB1, 112 SmallVector<BasicBlock *, 8> Descendants, 113 DominatorTreeBase<BasicBlock> *DomTree); 114 void propagateWeights(Function &F); 115 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); 116 void buildEdges(Function &F); 117 bool propagateThroughEdges(Function &F); 118 void computeDominanceAndLoopInfo(Function &F); 119 120 /// \brief Line number for the function header. Used to compute absolute 121 /// line numbers from the relative line numbers found in the profile. 122 unsigned HeaderLineno; 123 124 /// \brief Map basic blocks to their computed weights. 125 /// 126 /// The weight of a basic block is defined to be the maximum 127 /// of all the instruction weights in that block. 128 BlockWeightMap BlockWeights; 129 130 /// \brief Map edges to their computed weights. 131 /// 132 /// Edge weights are computed by propagating basic block weights in 133 /// SampleProfile::propagateWeights. 134 EdgeWeightMap EdgeWeights; 135 136 /// \brief Set of visited blocks during propagation. 137 SmallPtrSet<BasicBlock *, 128> VisitedBlocks; 138 139 /// \brief Set of visited edges during propagation. 140 SmallSet<Edge, 128> VisitedEdges; 141 142 /// \brief Equivalence classes for block weights. 143 /// 144 /// Two blocks BB1 and BB2 are in the same equivalence class if they 145 /// dominate and post-dominate each other, and they are in the same loop 146 /// nest. When this happens, the two blocks are guaranteed to execute 147 /// the same number of times. 148 EquivalenceClassMap EquivalenceClass; 149 150 /// \brief Dominance, post-dominance and loop information. 151 std::unique_ptr<DominatorTree> DT; 152 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT; 153 std::unique_ptr<LoopInfo> LI; 154 155 /// \brief Predecessors for each basic block in the CFG. 156 BlockEdgeMap Predecessors; 157 158 /// \brief Successors for each basic block in the CFG. 159 BlockEdgeMap Successors; 160 161 /// \brief Profile reader object. 162 std::unique_ptr<SampleProfileReader> Reader; 163 164 /// \brief Samples collected for the body of this function. 165 FunctionSamples *Samples; 166 167 /// \brief Name of the profile file to load. 168 StringRef Filename; 169 170 /// \brief Flag indicating whether the profile input loaded successfully. 171 bool ProfileIsValid; 172 }; 173 } 174 175 /// \brief Print the weight of edge \p E on stream \p OS. 176 /// 177 /// \param OS Stream to emit the output to. 178 /// \param E Edge to print. 179 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { 180 OS << "weight[" << E.first->getName() << "->" << E.second->getName() 181 << "]: " << EdgeWeights[E] << "\n"; 182 } 183 184 /// \brief Print the equivalence class of block \p BB on stream \p OS. 185 /// 186 /// \param OS Stream to emit the output to. 187 /// \param BB Block to print. 188 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, 189 BasicBlock *BB) { 190 BasicBlock *Equiv = EquivalenceClass[BB]; 191 OS << "equivalence[" << BB->getName() 192 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; 193 } 194 195 /// \brief Print the weight of block \p BB on stream \p OS. 196 /// 197 /// \param OS Stream to emit the output to. 198 /// \param BB Block to print. 199 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, BasicBlock *BB) { 200 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n"; 201 } 202 203 /// \brief Get the weight for an instruction. 204 /// 205 /// The "weight" of an instruction \p Inst is the number of samples 206 /// collected on that instruction at runtime. To retrieve it, we 207 /// need to compute the line number of \p Inst relative to the start of its 208 /// function. We use HeaderLineno to compute the offset. We then 209 /// look up the samples collected for \p Inst using BodySamples. 210 /// 211 /// \param Inst Instruction to query. 212 /// 213 /// \returns The profiled weight of I. 214 unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) { 215 DebugLoc DLoc = Inst.getDebugLoc(); 216 if (!DLoc) 217 return 0; 218 219 unsigned Lineno = DLoc.getLine(); 220 if (Lineno < HeaderLineno) 221 return 0; 222 223 const DILocation *DIL = DLoc; 224 int LOffset = Lineno - HeaderLineno; 225 unsigned Discriminator = DIL->getDiscriminator(); 226 unsigned Weight = Samples->samplesAt(LOffset, Discriminator); 227 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst 228 << " (line offset: " << LOffset << "." << Discriminator 229 << " - weight: " << Weight << ")\n"); 230 return Weight; 231 } 232 233 /// \brief Compute the weight of a basic block. 234 /// 235 /// The weight of basic block \p BB is the maximum weight of all the 236 /// instructions in BB. The weight of \p BB is computed and cached in 237 /// the BlockWeights map. 238 /// 239 /// \param BB The basic block to query. 240 /// 241 /// \returns The computed weight of BB. 242 unsigned SampleProfileLoader::getBlockWeight(BasicBlock *BB) { 243 // If we've computed BB's weight before, return it. 244 std::pair<BlockWeightMap::iterator, bool> Entry = 245 BlockWeights.insert(std::make_pair(BB, 0)); 246 if (!Entry.second) 247 return Entry.first->second; 248 249 // Otherwise, compute and cache BB's weight. 250 unsigned Weight = 0; 251 for (auto &I : BB->getInstList()) { 252 unsigned InstWeight = getInstWeight(I); 253 if (InstWeight > Weight) 254 Weight = InstWeight; 255 } 256 Entry.first->second = Weight; 257 return Weight; 258 } 259 260 /// \brief Compute and store the weights of every basic block. 261 /// 262 /// This populates the BlockWeights map by computing 263 /// the weights of every basic block in the CFG. 264 /// 265 /// \param F The function to query. 266 bool SampleProfileLoader::computeBlockWeights(Function &F) { 267 bool Changed = false; 268 DEBUG(dbgs() << "Block weights\n"); 269 for (auto &BB : F) { 270 unsigned Weight = getBlockWeight(&BB); 271 Changed |= (Weight > 0); 272 DEBUG(printBlockWeight(dbgs(), &BB)); 273 } 274 275 return Changed; 276 } 277 278 /// \brief Find equivalence classes for the given block. 279 /// 280 /// This finds all the blocks that are guaranteed to execute the same 281 /// number of times as \p BB1. To do this, it traverses all the 282 /// descendants of \p BB1 in the dominator or post-dominator tree. 283 /// 284 /// A block BB2 will be in the same equivalence class as \p BB1 if 285 /// the following holds: 286 /// 287 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 288 /// is a descendant of \p BB1 in the dominator tree, then BB2 should 289 /// dominate BB1 in the post-dominator tree. 290 /// 291 /// 2- Both BB2 and \p BB1 must be in the same loop. 292 /// 293 /// For every block BB2 that meets those two requirements, we set BB2's 294 /// equivalence class to \p BB1. 295 /// 296 /// \param BB1 Block to check. 297 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. 298 /// \param DomTree Opposite dominator tree. If \p Descendants is filled 299 /// with blocks from \p BB1's dominator tree, then 300 /// this is the post-dominator tree, and vice versa. 301 void SampleProfileLoader::findEquivalencesFor( 302 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants, 303 DominatorTreeBase<BasicBlock> *DomTree) { 304 for (auto *BB2 : Descendants) { 305 bool IsDomParent = DomTree->dominates(BB2, BB1); 306 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); 307 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent && 308 IsInSameLoop) { 309 EquivalenceClass[BB2] = BB1; 310 311 // If BB2 is heavier than BB1, make BB2 have the same weight 312 // as BB1. 313 // 314 // Note that we don't worry about the opposite situation here 315 // (when BB2 is lighter than BB1). We will deal with this 316 // during the propagation phase. Right now, we just want to 317 // make sure that BB1 has the largest weight of all the 318 // members of its equivalence set. 319 unsigned &BB1Weight = BlockWeights[BB1]; 320 unsigned &BB2Weight = BlockWeights[BB2]; 321 BB1Weight = std::max(BB1Weight, BB2Weight); 322 } 323 } 324 } 325 326 /// \brief Find equivalence classes. 327 /// 328 /// Since samples may be missing from blocks, we can fill in the gaps by setting 329 /// the weights of all the blocks in the same equivalence class to the same 330 /// weight. To compute the concept of equivalence, we use dominance and loop 331 /// information. Two blocks B1 and B2 are in the same equivalence class if B1 332 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 333 /// 334 /// \param F The function to query. 335 void SampleProfileLoader::findEquivalenceClasses(Function &F) { 336 SmallVector<BasicBlock *, 8> DominatedBBs; 337 DEBUG(dbgs() << "\nBlock equivalence classes\n"); 338 // Find equivalence sets based on dominance and post-dominance information. 339 for (auto &BB : F) { 340 BasicBlock *BB1 = &BB; 341 342 // Compute BB1's equivalence class once. 343 if (EquivalenceClass.count(BB1)) { 344 DEBUG(printBlockEquivalence(dbgs(), BB1)); 345 continue; 346 } 347 348 // By default, blocks are in their own equivalence class. 349 EquivalenceClass[BB1] = BB1; 350 351 // Traverse all the blocks dominated by BB1. We are looking for 352 // every basic block BB2 such that: 353 // 354 // 1- BB1 dominates BB2. 355 // 2- BB2 post-dominates BB1. 356 // 3- BB1 and BB2 are in the same loop nest. 357 // 358 // If all those conditions hold, it means that BB2 is executed 359 // as many times as BB1, so they are placed in the same equivalence 360 // class by making BB2's equivalence class be BB1. 361 DominatedBBs.clear(); 362 DT->getDescendants(BB1, DominatedBBs); 363 findEquivalencesFor(BB1, DominatedBBs, PDT.get()); 364 365 // Repeat the same logic for all the blocks post-dominated by BB1. 366 // We are looking for every basic block BB2 such that: 367 // 368 // 1- BB1 post-dominates BB2. 369 // 2- BB2 dominates BB1. 370 // 3- BB1 and BB2 are in the same loop nest. 371 // 372 // If all those conditions hold, BB2's equivalence class is BB1. 373 DominatedBBs.clear(); 374 PDT->getDescendants(BB1, DominatedBBs); 375 findEquivalencesFor(BB1, DominatedBBs, DT.get()); 376 377 DEBUG(printBlockEquivalence(dbgs(), BB1)); 378 } 379 380 // Assign weights to equivalence classes. 381 // 382 // All the basic blocks in the same equivalence class will execute 383 // the same number of times. Since we know that the head block in 384 // each equivalence class has the largest weight, assign that weight 385 // to all the blocks in that equivalence class. 386 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n"); 387 for (auto &BI : F) { 388 BasicBlock *BB = &BI; 389 BasicBlock *EquivBB = EquivalenceClass[BB]; 390 if (BB != EquivBB) 391 BlockWeights[BB] = BlockWeights[EquivBB]; 392 DEBUG(printBlockWeight(dbgs(), BB)); 393 } 394 } 395 396 /// \brief Visit the given edge to decide if it has a valid weight. 397 /// 398 /// If \p E has not been visited before, we copy to \p UnknownEdge 399 /// and increment the count of unknown edges. 400 /// 401 /// \param E Edge to visit. 402 /// \param NumUnknownEdges Current number of unknown edges. 403 /// \param UnknownEdge Set if E has not been visited before. 404 /// 405 /// \returns E's weight, if known. Otherwise, return 0. 406 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, 407 Edge *UnknownEdge) { 408 if (!VisitedEdges.count(E)) { 409 (*NumUnknownEdges)++; 410 *UnknownEdge = E; 411 return 0; 412 } 413 414 return EdgeWeights[E]; 415 } 416 417 /// \brief Propagate weights through incoming/outgoing edges. 418 /// 419 /// If the weight of a basic block is known, and there is only one edge 420 /// with an unknown weight, we can calculate the weight of that edge. 421 /// 422 /// Similarly, if all the edges have a known count, we can calculate the 423 /// count of the basic block, if needed. 424 /// 425 /// \param F Function to process. 426 /// 427 /// \returns True if new weights were assigned to edges or blocks. 428 bool SampleProfileLoader::propagateThroughEdges(Function &F) { 429 bool Changed = false; 430 DEBUG(dbgs() << "\nPropagation through edges\n"); 431 for (auto &BI : F) { 432 BasicBlock *BB = &BI; 433 434 // Visit all the predecessor and successor edges to determine 435 // which ones have a weight assigned already. Note that it doesn't 436 // matter that we only keep track of a single unknown edge. The 437 // only case we are interested in handling is when only a single 438 // edge is unknown (see setEdgeOrBlockWeight). 439 for (unsigned i = 0; i < 2; i++) { 440 unsigned TotalWeight = 0; 441 unsigned NumUnknownEdges = 0; 442 Edge UnknownEdge, SelfReferentialEdge; 443 444 if (i == 0) { 445 // First, visit all predecessor edges. 446 for (auto *Pred : Predecessors[BB]) { 447 Edge E = std::make_pair(Pred, BB); 448 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 449 if (E.first == E.second) 450 SelfReferentialEdge = E; 451 } 452 } else { 453 // On the second round, visit all successor edges. 454 for (auto *Succ : Successors[BB]) { 455 Edge E = std::make_pair(BB, Succ); 456 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); 457 } 458 } 459 460 // After visiting all the edges, there are three cases that we 461 // can handle immediately: 462 // 463 // - All the edge weights are known (i.e., NumUnknownEdges == 0). 464 // In this case, we simply check that the sum of all the edges 465 // is the same as BB's weight. If not, we change BB's weight 466 // to match. Additionally, if BB had not been visited before, 467 // we mark it visited. 468 // 469 // - Only one edge is unknown and BB has already been visited. 470 // In this case, we can compute the weight of the edge by 471 // subtracting the total block weight from all the known 472 // edge weights. If the edges weight more than BB, then the 473 // edge of the last remaining edge is set to zero. 474 // 475 // - There exists a self-referential edge and the weight of BB is 476 // known. In this case, this edge can be based on BB's weight. 477 // We add up all the other known edges and set the weight on 478 // the self-referential edge as we did in the previous case. 479 // 480 // In any other case, we must continue iterating. Eventually, 481 // all edges will get a weight, or iteration will stop when 482 // it reaches SampleProfileMaxPropagateIterations. 483 if (NumUnknownEdges <= 1) { 484 unsigned &BBWeight = BlockWeights[BB]; 485 if (NumUnknownEdges == 0) { 486 // If we already know the weight of all edges, the weight of the 487 // basic block can be computed. It should be no larger than the sum 488 // of all edge weights. 489 if (TotalWeight > BBWeight) { 490 BBWeight = TotalWeight; 491 Changed = true; 492 DEBUG(dbgs() << "All edge weights for " << BB->getName() 493 << " known. Set weight for block: "; 494 printBlockWeight(dbgs(), BB);); 495 } 496 if (VisitedBlocks.insert(BB).second) 497 Changed = true; 498 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) { 499 // If there is a single unknown edge and the block has been 500 // visited, then we can compute E's weight. 501 if (BBWeight >= TotalWeight) 502 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; 503 else 504 EdgeWeights[UnknownEdge] = 0; 505 VisitedEdges.insert(UnknownEdge); 506 Changed = true; 507 DEBUG(dbgs() << "Set weight for edge: "; 508 printEdgeWeight(dbgs(), UnknownEdge)); 509 } 510 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) { 511 unsigned &BBWeight = BlockWeights[BB]; 512 // We have a self-referential edge and the weight of BB is known. 513 if (BBWeight >= TotalWeight) 514 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; 515 else 516 EdgeWeights[SelfReferentialEdge] = 0; 517 VisitedEdges.insert(SelfReferentialEdge); 518 Changed = true; 519 DEBUG(dbgs() << "Set self-referential edge weight to: "; 520 printEdgeWeight(dbgs(), SelfReferentialEdge)); 521 } 522 } 523 } 524 525 return Changed; 526 } 527 528 /// \brief Build in/out edge lists for each basic block in the CFG. 529 /// 530 /// We are interested in unique edges. If a block B1 has multiple 531 /// edges to another block B2, we only add a single B1->B2 edge. 532 void SampleProfileLoader::buildEdges(Function &F) { 533 for (auto &BI : F) { 534 BasicBlock *B1 = &BI; 535 536 // Add predecessors for B1. 537 SmallPtrSet<BasicBlock *, 16> Visited; 538 if (!Predecessors[B1].empty()) 539 llvm_unreachable("Found a stale predecessors list in a basic block."); 540 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { 541 BasicBlock *B2 = *PI; 542 if (Visited.insert(B2).second) 543 Predecessors[B1].push_back(B2); 544 } 545 546 // Add successors for B1. 547 Visited.clear(); 548 if (!Successors[B1].empty()) 549 llvm_unreachable("Found a stale successors list in a basic block."); 550 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { 551 BasicBlock *B2 = *SI; 552 if (Visited.insert(B2).second) 553 Successors[B1].push_back(B2); 554 } 555 } 556 } 557 558 /// \brief Propagate weights into edges 559 /// 560 /// The following rules are applied to every block BB in the CFG: 561 /// 562 /// - If BB has a single predecessor/successor, then the weight 563 /// of that edge is the weight of the block. 564 /// 565 /// - If all incoming or outgoing edges are known except one, and the 566 /// weight of the block is already known, the weight of the unknown 567 /// edge will be the weight of the block minus the sum of all the known 568 /// edges. If the sum of all the known edges is larger than BB's weight, 569 /// we set the unknown edge weight to zero. 570 /// 571 /// - If there is a self-referential edge, and the weight of the block is 572 /// known, the weight for that edge is set to the weight of the block 573 /// minus the weight of the other incoming edges to that block (if 574 /// known). 575 void SampleProfileLoader::propagateWeights(Function &F) { 576 bool Changed = true; 577 unsigned i = 0; 578 579 // Add an entry count to the function using the samples gathered 580 // at the function entry. 581 F.setEntryCount(Samples->getHeadSamples()); 582 583 // Before propagation starts, build, for each block, a list of 584 // unique predecessors and successors. This is necessary to handle 585 // identical edges in multiway branches. Since we visit all blocks and all 586 // edges of the CFG, it is cleaner to build these lists once at the start 587 // of the pass. 588 buildEdges(F); 589 590 // Propagate until we converge or we go past the iteration limit. 591 while (Changed && i++ < SampleProfileMaxPropagateIterations) { 592 Changed = propagateThroughEdges(F); 593 } 594 595 // Generate MD_prof metadata for every branch instruction using the 596 // edge weights computed during propagation. 597 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 598 MDBuilder MDB(F.getContext()); 599 for (auto &BI : F) { 600 BasicBlock *BB = &BI; 601 TerminatorInst *TI = BB->getTerminator(); 602 if (TI->getNumSuccessors() == 1) 603 continue; 604 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 605 continue; 606 607 DEBUG(dbgs() << "\nGetting weights for branch at line " 608 << TI->getDebugLoc().getLine() << ".\n"); 609 SmallVector<unsigned, 4> Weights; 610 bool AllWeightsZero = true; 611 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 612 BasicBlock *Succ = TI->getSuccessor(I); 613 Edge E = std::make_pair(BB, Succ); 614 unsigned Weight = EdgeWeights[E]; 615 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 616 Weights.push_back(Weight); 617 if (Weight != 0) 618 AllWeightsZero = false; 619 } 620 621 // Only set weights if there is at least one non-zero weight. 622 // In any other case, let the analyzer set weights. 623 if (!AllWeightsZero) { 624 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 625 TI->setMetadata(llvm::LLVMContext::MD_prof, 626 MDB.createBranchWeights(Weights)); 627 } else { 628 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 629 } 630 } 631 } 632 633 /// \brief Get the line number for the function header. 634 /// 635 /// This looks up function \p F in the current compilation unit and 636 /// retrieves the line number where the function is defined. This is 637 /// line 0 for all the samples read from the profile file. Every line 638 /// number is relative to this line. 639 /// 640 /// \param F Function object to query. 641 /// 642 /// \returns the line number where \p F is defined. If it returns 0, 643 /// it means that there is no debug information available for \p F. 644 unsigned SampleProfileLoader::getFunctionLoc(Function &F) { 645 if (DISubprogram *S = getDISubprogram(&F)) 646 return S->getLine(); 647 648 // If could not find the start of \p F, emit a diagnostic to inform the user 649 // about the missed opportunity. 650 F.getContext().diagnose(DiagnosticInfoSampleProfile( 651 "No debug information found in function " + F.getName() + 652 ": Function profile not used", 653 DS_Warning)); 654 return 0; 655 } 656 657 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { 658 DT.reset(new DominatorTree); 659 DT->recalculate(F); 660 661 PDT.reset(new DominatorTreeBase<BasicBlock>(true)); 662 PDT->recalculate(F); 663 664 LI.reset(new LoopInfo); 665 LI->analyze(*DT); 666 } 667 668 /// \brief Generate branch weight metadata for all branches in \p F. 669 /// 670 /// Branch weights are computed out of instruction samples using a 671 /// propagation heuristic. Propagation proceeds in 3 phases: 672 /// 673 /// 1- Assignment of block weights. All the basic blocks in the function 674 /// are initial assigned the same weight as their most frequently 675 /// executed instruction. 676 /// 677 /// 2- Creation of equivalence classes. Since samples may be missing from 678 /// blocks, we can fill in the gaps by setting the weights of all the 679 /// blocks in the same equivalence class to the same weight. To compute 680 /// the concept of equivalence, we use dominance and loop information. 681 /// Two blocks B1 and B2 are in the same equivalence class if B1 682 /// dominates B2, B2 post-dominates B1 and both are in the same loop. 683 /// 684 /// 3- Propagation of block weights into edges. This uses a simple 685 /// propagation heuristic. The following rules are applied to every 686 /// block BB in the CFG: 687 /// 688 /// - If BB has a single predecessor/successor, then the weight 689 /// of that edge is the weight of the block. 690 /// 691 /// - If all the edges are known except one, and the weight of the 692 /// block is already known, the weight of the unknown edge will 693 /// be the weight of the block minus the sum of all the known 694 /// edges. If the sum of all the known edges is larger than BB's weight, 695 /// we set the unknown edge weight to zero. 696 /// 697 /// - If there is a self-referential edge, and the weight of the block is 698 /// known, the weight for that edge is set to the weight of the block 699 /// minus the weight of the other incoming edges to that block (if 700 /// known). 701 /// 702 /// Since this propagation is not guaranteed to finalize for every CFG, we 703 /// only allow it to proceed for a limited number of iterations (controlled 704 /// by -sample-profile-max-propagate-iterations). 705 /// 706 /// FIXME: Try to replace this propagation heuristic with a scheme 707 /// that is guaranteed to finalize. A work-list approach similar to 708 /// the standard value propagation algorithm used by SSA-CCP might 709 /// work here. 710 /// 711 /// Once all the branch weights are computed, we emit the MD_prof 712 /// metadata on BB using the computed values for each of its branches. 713 /// 714 /// \param F The function to query. 715 /// 716 /// \returns true if \p F was modified. Returns false, otherwise. 717 bool SampleProfileLoader::emitAnnotations(Function &F) { 718 bool Changed = false; 719 720 // Initialize invariants used during computation and propagation. 721 HeaderLineno = getFunctionLoc(F); 722 if (HeaderLineno == 0) 723 return false; 724 725 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName() 726 << ": " << HeaderLineno << "\n"); 727 728 // Compute basic block weights. 729 Changed |= computeBlockWeights(F); 730 731 if (Changed) { 732 // Compute dominance and loop info needed for propagation. 733 computeDominanceAndLoopInfo(F); 734 735 // Find equivalence classes. 736 findEquivalenceClasses(F); 737 738 // Propagate weights to all edges. 739 propagateWeights(F); 740 } 741 742 return Changed; 743 } 744 745 char SampleProfileLoader::ID = 0; 746 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile", 747 "Sample Profile loader", false, false) 748 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators) 749 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile", 750 "Sample Profile loader", false, false) 751 752 bool SampleProfileLoader::doInitialization(Module &M) { 753 auto &Ctx = M.getContext(); 754 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx); 755 if (std::error_code EC = ReaderOrErr.getError()) { 756 std::string Msg = "Could not open profile: " + EC.message(); 757 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg)); 758 return false; 759 } 760 Reader = std::move(ReaderOrErr.get()); 761 ProfileIsValid = (Reader->read() == sampleprof_error::success); 762 return true; 763 } 764 765 ModulePass *llvm::createSampleProfileLoaderPass() { 766 return new SampleProfileLoader(SampleProfileFile); 767 } 768 769 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 770 return new SampleProfileLoader(Name); 771 } 772 773 bool SampleProfileLoader::runOnModule(Module &M) { 774 bool retval = false; 775 for (auto &F : M) 776 if (!F.isDeclaration()) 777 retval |= runOnFunction(F); 778 return retval; 779 } 780 781 bool SampleProfileLoader::runOnFunction(Function &F) { 782 if (!ProfileIsValid) 783 return false; 784 785 Samples = Reader->getSamplesFor(F); 786 if (!Samples->empty()) 787 return emitAnnotations(F); 788 return false; 789 } 790