1 //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===// 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 // Loops should be simplified before this analysis. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 15 #include "llvm/ADT/SCCIterator.h" 16 #include "llvm/Support/raw_ostream.h" 17 18 using namespace llvm; 19 using namespace llvm::bfi_detail; 20 21 #define DEBUG_TYPE "block-freq" 22 23 ScaledNumber<uint64_t> BlockMass::toScaled() const { 24 if (isFull()) 25 return ScaledNumber<uint64_t>(1, 0); 26 return ScaledNumber<uint64_t>(getMass() + 1, -64); 27 } 28 29 void BlockMass::dump() const { print(dbgs()); } 30 31 static char getHexDigit(int N) { 32 assert(N < 16); 33 if (N < 10) 34 return '0' + N; 35 return 'a' + N - 10; 36 } 37 raw_ostream &BlockMass::print(raw_ostream &OS) const { 38 for (int Digits = 0; Digits < 16; ++Digits) 39 OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf); 40 return OS; 41 } 42 43 namespace { 44 45 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode; 46 typedef BlockFrequencyInfoImplBase::Distribution Distribution; 47 typedef BlockFrequencyInfoImplBase::Distribution::WeightList WeightList; 48 typedef BlockFrequencyInfoImplBase::Scaled64 Scaled64; 49 typedef BlockFrequencyInfoImplBase::LoopData LoopData; 50 typedef BlockFrequencyInfoImplBase::Weight Weight; 51 typedef BlockFrequencyInfoImplBase::FrequencyData FrequencyData; 52 53 /// \brief Dithering mass distributer. 54 /// 55 /// This class splits up a single mass into portions by weight, dithering to 56 /// spread out error. No mass is lost. The dithering precision depends on the 57 /// precision of the product of \a BlockMass and \a BranchProbability. 58 /// 59 /// The distribution algorithm follows. 60 /// 61 /// 1. Initialize by saving the sum of the weights in \a RemWeight and the 62 /// mass to distribute in \a RemMass. 63 /// 64 /// 2. For each portion: 65 /// 66 /// 1. Construct a branch probability, P, as the portion's weight divided 67 /// by the current value of \a RemWeight. 68 /// 2. Calculate the portion's mass as \a RemMass times P. 69 /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting 70 /// the current portion's weight and mass. 71 struct DitheringDistributer { 72 uint32_t RemWeight; 73 BlockMass RemMass; 74 75 DitheringDistributer(Distribution &Dist, const BlockMass &Mass); 76 77 BlockMass takeMass(uint32_t Weight); 78 }; 79 80 } // end namespace 81 82 DitheringDistributer::DitheringDistributer(Distribution &Dist, 83 const BlockMass &Mass) { 84 Dist.normalize(); 85 RemWeight = Dist.Total; 86 RemMass = Mass; 87 } 88 89 BlockMass DitheringDistributer::takeMass(uint32_t Weight) { 90 assert(Weight && "invalid weight"); 91 assert(Weight <= RemWeight); 92 BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight); 93 94 // Decrement totals (dither). 95 RemWeight -= Weight; 96 RemMass -= Mass; 97 return Mass; 98 } 99 100 void Distribution::add(const BlockNode &Node, uint64_t Amount, 101 Weight::DistType Type) { 102 assert(Amount && "invalid weight of 0"); 103 uint64_t NewTotal = Total + Amount; 104 105 // Check for overflow. It should be impossible to overflow twice. 106 bool IsOverflow = NewTotal < Total; 107 assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow"); 108 DidOverflow |= IsOverflow; 109 110 // Update the total. 111 Total = NewTotal; 112 113 // Save the weight. 114 Weights.push_back(Weight(Type, Node, Amount)); 115 } 116 117 static void combineWeight(Weight &W, const Weight &OtherW) { 118 assert(OtherW.TargetNode.isValid()); 119 if (!W.Amount) { 120 W = OtherW; 121 return; 122 } 123 assert(W.Type == OtherW.Type); 124 assert(W.TargetNode == OtherW.TargetNode); 125 assert(W.Amount < W.Amount + OtherW.Amount && "Unexpected overflow"); 126 W.Amount += OtherW.Amount; 127 } 128 static void combineWeightsBySorting(WeightList &Weights) { 129 // Sort so edges to the same node are adjacent. 130 std::sort(Weights.begin(), Weights.end(), 131 [](const Weight &L, 132 const Weight &R) { return L.TargetNode < R.TargetNode; }); 133 134 // Combine adjacent edges. 135 WeightList::iterator O = Weights.begin(); 136 for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E; 137 ++O, (I = L)) { 138 *O = *I; 139 140 // Find the adjacent weights to the same node. 141 for (++L; L != E && I->TargetNode == L->TargetNode; ++L) 142 combineWeight(*O, *L); 143 } 144 145 // Erase extra entries. 146 Weights.erase(O, Weights.end()); 147 return; 148 } 149 static void combineWeightsByHashing(WeightList &Weights) { 150 // Collect weights into a DenseMap. 151 typedef DenseMap<BlockNode::IndexType, Weight> HashTable; 152 HashTable Combined(NextPowerOf2(2 * Weights.size())); 153 for (const Weight &W : Weights) 154 combineWeight(Combined[W.TargetNode.Index], W); 155 156 // Check whether anything changed. 157 if (Weights.size() == Combined.size()) 158 return; 159 160 // Fill in the new weights. 161 Weights.clear(); 162 Weights.reserve(Combined.size()); 163 for (const auto &I : Combined) 164 Weights.push_back(I.second); 165 } 166 static void combineWeights(WeightList &Weights) { 167 // Use a hash table for many successors to keep this linear. 168 if (Weights.size() > 128) { 169 combineWeightsByHashing(Weights); 170 return; 171 } 172 173 combineWeightsBySorting(Weights); 174 } 175 static uint64_t shiftRightAndRound(uint64_t N, int Shift) { 176 assert(Shift >= 0); 177 assert(Shift < 64); 178 if (!Shift) 179 return N; 180 return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1)); 181 } 182 void Distribution::normalize() { 183 // Early exit for termination nodes. 184 if (Weights.empty()) 185 return; 186 187 // Only bother if there are multiple successors. 188 if (Weights.size() > 1) 189 combineWeights(Weights); 190 191 // Early exit when combined into a single successor. 192 if (Weights.size() == 1) { 193 Total = 1; 194 Weights.front().Amount = 1; 195 return; 196 } 197 198 // Determine how much to shift right so that the total fits into 32-bits. 199 // 200 // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1 201 // for each weight can cause a 32-bit overflow. 202 int Shift = 0; 203 if (DidOverflow) 204 Shift = 33; 205 else if (Total > UINT32_MAX) 206 Shift = 33 - countLeadingZeros(Total); 207 208 // Early exit if nothing needs to be scaled. 209 if (!Shift) 210 return; 211 212 // Recompute the total through accumulation (rather than shifting it) so that 213 // it's accurate after shifting. 214 Total = 0; 215 216 // Sum the weights to each node and shift right if necessary. 217 for (Weight &W : Weights) { 218 // Scale down below UINT32_MAX. Since Shift is larger than necessary, we 219 // can round here without concern about overflow. 220 assert(W.TargetNode.isValid()); 221 W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift)); 222 assert(W.Amount <= UINT32_MAX); 223 224 // Update the total. 225 Total += W.Amount; 226 } 227 assert(Total <= UINT32_MAX); 228 } 229 230 void BlockFrequencyInfoImplBase::clear() { 231 // Swap with a default-constructed std::vector, since std::vector<>::clear() 232 // does not actually clear heap storage. 233 std::vector<FrequencyData>().swap(Freqs); 234 std::vector<WorkingData>().swap(Working); 235 Loops.clear(); 236 } 237 238 /// \brief Clear all memory not needed downstream. 239 /// 240 /// Releases all memory not used downstream. In particular, saves Freqs. 241 static void cleanup(BlockFrequencyInfoImplBase &BFI) { 242 std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs)); 243 BFI.clear(); 244 BFI.Freqs = std::move(SavedFreqs); 245 } 246 247 bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist, 248 const LoopData *OuterLoop, 249 const BlockNode &Pred, 250 const BlockNode &Succ, 251 uint64_t Weight) { 252 if (!Weight) 253 Weight = 1; 254 255 auto isLoopHeader = [&OuterLoop](const BlockNode &Node) { 256 return OuterLoop && OuterLoop->isHeader(Node); 257 }; 258 259 BlockNode Resolved = Working[Succ.Index].getResolvedNode(); 260 261 #ifndef NDEBUG 262 auto debugSuccessor = [&](const char *Type) { 263 dbgs() << " =>" 264 << " [" << Type << "] weight = " << Weight; 265 if (!isLoopHeader(Resolved)) 266 dbgs() << ", succ = " << getBlockName(Succ); 267 if (Resolved != Succ) 268 dbgs() << ", resolved = " << getBlockName(Resolved); 269 dbgs() << "\n"; 270 }; 271 (void)debugSuccessor; 272 #endif 273 274 if (isLoopHeader(Resolved)) { 275 DEBUG(debugSuccessor("backedge")); 276 Dist.addBackedge(OuterLoop->getHeader(), Weight); 277 return true; 278 } 279 280 if (Working[Resolved.Index].getContainingLoop() != OuterLoop) { 281 DEBUG(debugSuccessor(" exit ")); 282 Dist.addExit(Resolved, Weight); 283 return true; 284 } 285 286 if (Resolved < Pred) { 287 if (!isLoopHeader(Pred)) { 288 // If OuterLoop is an irreducible loop, we can't actually handle this. 289 assert((!OuterLoop || !OuterLoop->isIrreducible()) && 290 "unhandled irreducible control flow"); 291 292 // Irreducible backedge. Abort. 293 DEBUG(debugSuccessor("abort!!!")); 294 return false; 295 } 296 297 // If "Pred" is a loop header, then this isn't really a backedge; rather, 298 // OuterLoop must be irreducible. These false backedges can come only from 299 // secondary loop headers. 300 assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) && 301 "unhandled irreducible control flow"); 302 } 303 304 DEBUG(debugSuccessor(" local ")); 305 Dist.addLocal(Resolved, Weight); 306 return true; 307 } 308 309 bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist( 310 const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) { 311 // Copy the exit map into Dist. 312 for (const auto &I : Loop.Exits) 313 if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first, 314 I.second.getMass())) 315 // Irreducible backedge. 316 return false; 317 318 return true; 319 } 320 321 /// \brief Get the maximum allowed loop scale. 322 /// 323 /// Gives the maximum number of estimated iterations allowed for a loop. Very 324 /// large numbers cause problems downstream (even within 64-bits). 325 static Scaled64 getMaxLoopScale() { return Scaled64(1, 12); } 326 327 /// \brief Compute the loop scale for a loop. 328 void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) { 329 // Compute loop scale. 330 DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n"); 331 332 // LoopScale == 1 / ExitMass 333 // ExitMass == HeadMass - BackedgeMass 334 BlockMass ExitMass = BlockMass::getFull() - Loop.BackedgeMass; 335 336 // Block scale stores the inverse of the scale. 337 Loop.Scale = ExitMass.toScaled().inverse(); 338 339 DEBUG(dbgs() << " - exit-mass = " << ExitMass << " (" << BlockMass::getFull() 340 << " - " << Loop.BackedgeMass << ")\n" 341 << " - scale = " << Loop.Scale << "\n"); 342 343 if (Loop.Scale > getMaxLoopScale()) { 344 Loop.Scale = getMaxLoopScale(); 345 DEBUG(dbgs() << " - reduced-to-max-scale: " << getMaxLoopScale() << "\n"); 346 } 347 } 348 349 /// \brief Package up a loop. 350 void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) { 351 DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n"); 352 353 // Clear the subloop exits to prevent quadratic memory usage. 354 for (const BlockNode &M : Loop.Nodes) { 355 if (auto *Loop = Working[M.Index].getPackagedLoop()) 356 Loop->Exits.clear(); 357 DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n"); 358 } 359 Loop.IsPackaged = true; 360 } 361 362 void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source, 363 LoopData *OuterLoop, 364 Distribution &Dist) { 365 BlockMass Mass = Working[Source.Index].getMass(); 366 DEBUG(dbgs() << " => mass: " << Mass << "\n"); 367 368 // Distribute mass to successors as laid out in Dist. 369 DitheringDistributer D(Dist, Mass); 370 371 #ifndef NDEBUG 372 auto debugAssign = [&](const BlockNode &T, const BlockMass &M, 373 const char *Desc) { 374 dbgs() << " => assign " << M << " (" << D.RemMass << ")"; 375 if (Desc) 376 dbgs() << " [" << Desc << "]"; 377 if (T.isValid()) 378 dbgs() << " to " << getBlockName(T); 379 dbgs() << "\n"; 380 }; 381 (void)debugAssign; 382 #endif 383 384 for (const Weight &W : Dist.Weights) { 385 // Check for a local edge (non-backedge and non-exit). 386 BlockMass Taken = D.takeMass(W.Amount); 387 if (W.Type == Weight::Local) { 388 Working[W.TargetNode.Index].getMass() += Taken; 389 DEBUG(debugAssign(W.TargetNode, Taken, nullptr)); 390 continue; 391 } 392 393 // Backedges and exits only make sense if we're processing a loop. 394 assert(OuterLoop && "backedge or exit outside of loop"); 395 396 // Check for a backedge. 397 if (W.Type == Weight::Backedge) { 398 OuterLoop->BackedgeMass += Taken; 399 DEBUG(debugAssign(BlockNode(), Taken, "back")); 400 continue; 401 } 402 403 // This must be an exit. 404 assert(W.Type == Weight::Exit); 405 OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken)); 406 DEBUG(debugAssign(W.TargetNode, Taken, "exit")); 407 } 408 } 409 410 static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI, 411 const Scaled64 &Min, const Scaled64 &Max) { 412 // Scale the Factor to a size that creates integers. Ideally, integers would 413 // be scaled so that Max == UINT64_MAX so that they can be best 414 // differentiated. However, the register allocator currently deals poorly 415 // with large numbers. Instead, push Min up a little from 1 to give some 416 // room to differentiate small, unequal numbers. 417 // 418 // TODO: fix issues downstream so that ScalingFactor can be 419 // Scaled64(1,64)/Max. 420 Scaled64 ScalingFactor = Min.inverse(); 421 if ((Max / Min).lg() < 60) 422 ScalingFactor <<= 3; 423 424 // Translate the floats to integers. 425 DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max 426 << ", factor = " << ScalingFactor << "\n"); 427 for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) { 428 Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor; 429 BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>()); 430 DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = " 431 << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled 432 << ", int = " << BFI.Freqs[Index].Integer << "\n"); 433 } 434 } 435 436 /// \brief Unwrap a loop package. 437 /// 438 /// Visits all the members of a loop, adjusting their BlockData according to 439 /// the loop's pseudo-node. 440 static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) { 441 DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop) 442 << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale 443 << "\n"); 444 Loop.Scale *= Loop.Mass.toScaled(); 445 Loop.IsPackaged = false; 446 DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n"); 447 448 // Propagate the head scale through the loop. Since members are visited in 449 // RPO, the head scale will be updated by the loop scale first, and then the 450 // final head scale will be used for updated the rest of the members. 451 for (const BlockNode &N : Loop.Nodes) { 452 const auto &Working = BFI.Working[N.Index]; 453 Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale 454 : BFI.Freqs[N.Index].Scaled; 455 Scaled64 New = Loop.Scale * F; 456 DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => " << New 457 << "\n"); 458 F = New; 459 } 460 } 461 462 void BlockFrequencyInfoImplBase::unwrapLoops() { 463 // Set initial frequencies from loop-local masses. 464 for (size_t Index = 0; Index < Working.size(); ++Index) 465 Freqs[Index].Scaled = Working[Index].Mass.toScaled(); 466 467 for (LoopData &Loop : Loops) 468 unwrapLoop(*this, Loop); 469 } 470 471 void BlockFrequencyInfoImplBase::finalizeMetrics() { 472 // Unwrap loop packages in reverse post-order, tracking min and max 473 // frequencies. 474 auto Min = Scaled64::getLargest(); 475 auto Max = Scaled64::getZero(); 476 for (size_t Index = 0; Index < Working.size(); ++Index) { 477 // Update min/max scale. 478 Min = std::min(Min, Freqs[Index].Scaled); 479 Max = std::max(Max, Freqs[Index].Scaled); 480 } 481 482 // Convert to integers. 483 convertFloatingToInteger(*this, Min, Max); 484 485 // Clean up data structures. 486 cleanup(*this); 487 488 // Print out the final stats. 489 DEBUG(dump()); 490 } 491 492 BlockFrequency 493 BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const { 494 if (!Node.isValid()) 495 return 0; 496 return Freqs[Node.Index].Integer; 497 } 498 Scaled64 499 BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const { 500 if (!Node.isValid()) 501 return Scaled64::getZero(); 502 return Freqs[Node.Index].Scaled; 503 } 504 505 std::string 506 BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const { 507 return std::string(); 508 } 509 std::string 510 BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const { 511 return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*"); 512 } 513 514 raw_ostream & 515 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS, 516 const BlockNode &Node) const { 517 return OS << getFloatingBlockFreq(Node); 518 } 519 520 raw_ostream & 521 BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS, 522 const BlockFrequency &Freq) const { 523 Scaled64 Block(Freq.getFrequency(), 0); 524 Scaled64 Entry(getEntryFreq(), 0); 525 526 return OS << Block / Entry; 527 } 528 529 void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) { 530 Start = OuterLoop.getHeader(); 531 Nodes.reserve(OuterLoop.Nodes.size()); 532 for (auto N : OuterLoop.Nodes) 533 addNode(N); 534 indexNodes(); 535 } 536 void IrreducibleGraph::addNodesInFunction() { 537 Start = 0; 538 for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index) 539 if (!BFI.Working[Index].isPackaged()) 540 addNode(Index); 541 indexNodes(); 542 } 543 void IrreducibleGraph::indexNodes() { 544 for (auto &I : Nodes) 545 Lookup[I.Node.Index] = &I; 546 } 547 void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ, 548 const BFIBase::LoopData *OuterLoop) { 549 if (OuterLoop && OuterLoop->isHeader(Succ)) 550 return; 551 auto L = Lookup.find(Succ.Index); 552 if (L == Lookup.end()) 553 return; 554 IrrNode &SuccIrr = *L->second; 555 Irr.Edges.push_back(&SuccIrr); 556 SuccIrr.Edges.push_front(&Irr); 557 ++SuccIrr.NumIn; 558 } 559 560 namespace llvm { 561 template <> struct GraphTraits<IrreducibleGraph> { 562 typedef bfi_detail::IrreducibleGraph GraphT; 563 564 typedef const GraphT::IrrNode NodeType; 565 typedef GraphT::IrrNode::iterator ChildIteratorType; 566 567 static const NodeType *getEntryNode(const GraphT &G) { 568 return G.StartIrr; 569 } 570 static ChildIteratorType child_begin(NodeType *N) { return N->succ_begin(); } 571 static ChildIteratorType child_end(NodeType *N) { return N->succ_end(); } 572 }; 573 } 574 575 /// \brief Find extra irreducible headers. 576 /// 577 /// Find entry blocks and other blocks with backedges, which exist when \c G 578 /// contains irreducible sub-SCCs. 579 static void findIrreducibleHeaders( 580 const BlockFrequencyInfoImplBase &BFI, 581 const IrreducibleGraph &G, 582 const std::vector<const IrreducibleGraph::IrrNode *> &SCC, 583 LoopData::NodeList &Headers, LoopData::NodeList &Others) { 584 // Map from nodes in the SCC to whether it's an entry block. 585 SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC; 586 587 // InSCC also acts the set of nodes in the graph. Seed it. 588 for (const auto *I : SCC) 589 InSCC[I] = false; 590 591 for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) { 592 auto &Irr = *I->first; 593 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) { 594 if (InSCC.count(P)) 595 continue; 596 597 // This is an entry block. 598 I->second = true; 599 Headers.push_back(Irr.Node); 600 DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node) << "\n"); 601 break; 602 } 603 } 604 assert(Headers.size() >= 2 && 605 "Expected irreducible CFG; -loop-info is likely invalid"); 606 if (Headers.size() == InSCC.size()) { 607 // Every block is a header. 608 std::sort(Headers.begin(), Headers.end()); 609 return; 610 } 611 612 // Look for extra headers from irreducible sub-SCCs. 613 for (const auto &I : InSCC) { 614 // Entry blocks are already headers. 615 if (I.second) 616 continue; 617 618 auto &Irr = *I.first; 619 for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) { 620 // Skip forward edges. 621 if (P->Node < Irr.Node) 622 continue; 623 624 // Skip predecessors from entry blocks. These can have inverted 625 // ordering. 626 if (InSCC.lookup(P)) 627 continue; 628 629 // Store the extra header. 630 Headers.push_back(Irr.Node); 631 DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node) << "\n"); 632 break; 633 } 634 if (Headers.back() == Irr.Node) 635 // Added this as a header. 636 continue; 637 638 // This is not a header. 639 Others.push_back(Irr.Node); 640 DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n"); 641 } 642 std::sort(Headers.begin(), Headers.end()); 643 std::sort(Others.begin(), Others.end()); 644 } 645 646 static void createIrreducibleLoop( 647 BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G, 648 LoopData *OuterLoop, std::list<LoopData>::iterator Insert, 649 const std::vector<const IrreducibleGraph::IrrNode *> &SCC) { 650 // Translate the SCC into RPO. 651 DEBUG(dbgs() << " - found-scc\n"); 652 653 LoopData::NodeList Headers; 654 LoopData::NodeList Others; 655 findIrreducibleHeaders(BFI, G, SCC, Headers, Others); 656 657 auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(), 658 Headers.end(), Others.begin(), Others.end()); 659 660 // Update loop hierarchy. 661 for (const auto &N : Loop->Nodes) 662 if (BFI.Working[N.Index].isLoopHeader()) 663 BFI.Working[N.Index].Loop->Parent = &*Loop; 664 else 665 BFI.Working[N.Index].Loop = &*Loop; 666 } 667 668 iterator_range<std::list<LoopData>::iterator> 669 BlockFrequencyInfoImplBase::analyzeIrreducible( 670 const IrreducibleGraph &G, LoopData *OuterLoop, 671 std::list<LoopData>::iterator Insert) { 672 assert((OuterLoop == nullptr) == (Insert == Loops.begin())); 673 auto Prev = OuterLoop ? std::prev(Insert) : Loops.end(); 674 675 for (auto I = scc_begin(G); !I.isAtEnd(); ++I) { 676 if (I->size() < 2) 677 continue; 678 679 // Translate the SCC into RPO. 680 createIrreducibleLoop(*this, G, OuterLoop, Insert, *I); 681 } 682 683 if (OuterLoop) 684 return make_range(std::next(Prev), Insert); 685 return make_range(Loops.begin(), Insert); 686 } 687 688 void 689 BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) { 690 OuterLoop.Exits.clear(); 691 OuterLoop.BackedgeMass = BlockMass::getEmpty(); 692 auto O = OuterLoop.Nodes.begin() + 1; 693 for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I) 694 if (!Working[I->Index].isPackaged()) 695 *O++ = *I; 696 OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end()); 697 } 698