1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===// 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 pass forwards branches to unconditional branches to make them branch 11 // directly to the target block. This pass often results in dead MBB's, which 12 // it then removes. 13 // 14 // Note that this pass must be run after register allocation, it cannot handle 15 // SSA form. It also must handle virtual registers for targets that emit virtual 16 // ISA (e.g. NVPTX). 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "BranchFolding.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 27 #include "llvm/CodeGen/MachineFunctionPass.h" 28 #include "llvm/CodeGen/MachineJumpTableInfo.h" 29 #include "llvm/CodeGen/MachineMemOperand.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/CodeGen/MachineModuleInfo.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/Passes.h" 34 #include "llvm/CodeGen/TargetPassConfig.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Target/TargetInstrInfo.h" 41 #include "llvm/Target/TargetRegisterInfo.h" 42 #include "llvm/Target/TargetSubtargetInfo.h" 43 #include <algorithm> 44 using namespace llvm; 45 46 #define DEBUG_TYPE "branchfolding" 47 48 STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); 49 STATISTIC(NumBranchOpts, "Number of branches optimized"); 50 STATISTIC(NumTailMerge , "Number of block tails merged"); 51 STATISTIC(NumHoist , "Number of times common instructions are hoisted"); 52 STATISTIC(NumTailCalls, "Number of tail calls optimized"); 53 54 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", 55 cl::init(cl::BOU_UNSET), cl::Hidden); 56 57 // Throttle for huge numbers of predecessors (compile speed problems) 58 static cl::opt<unsigned> 59 TailMergeThreshold("tail-merge-threshold", 60 cl::desc("Max number of predecessors to consider tail merging"), 61 cl::init(150), cl::Hidden); 62 63 // Heuristic for tail merging (and, inversely, tail duplication). 64 // TODO: This should be replaced with a target query. 65 static cl::opt<unsigned> 66 TailMergeSize("tail-merge-size", 67 cl::desc("Min number of instructions to consider tail merging"), 68 cl::init(3), cl::Hidden); 69 70 namespace { 71 /// BranchFolderPass - Wrap branch folder in a machine function pass. 72 class BranchFolderPass : public MachineFunctionPass { 73 public: 74 static char ID; 75 explicit BranchFolderPass(): MachineFunctionPass(ID) {} 76 77 bool runOnMachineFunction(MachineFunction &MF) override; 78 79 void getAnalysisUsage(AnalysisUsage &AU) const override { 80 AU.addRequired<MachineBlockFrequencyInfo>(); 81 AU.addRequired<MachineBranchProbabilityInfo>(); 82 AU.addRequired<TargetPassConfig>(); 83 MachineFunctionPass::getAnalysisUsage(AU); 84 } 85 }; 86 } 87 88 char BranchFolderPass::ID = 0; 89 char &llvm::BranchFolderPassID = BranchFolderPass::ID; 90 91 INITIALIZE_PASS(BranchFolderPass, "branch-folder", 92 "Control Flow Optimizer", false, false) 93 94 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) { 95 if (skipFunction(*MF.getFunction())) 96 return false; 97 98 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 99 // TailMerge can create jump into if branches that make CFG irreducible for 100 // HW that requires structurized CFG. 101 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 102 PassConfig->getEnableTailMerge(); 103 BranchFolder::MBFIWrapper MBBFreqInfo( 104 getAnalysis<MachineBlockFrequencyInfo>()); 105 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo, 106 getAnalysis<MachineBranchProbabilityInfo>()); 107 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(), 108 MF.getSubtarget().getRegisterInfo(), 109 getAnalysisIfAvailable<MachineModuleInfo>()); 110 } 111 112 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist, 113 MBFIWrapper &FreqInfo, 114 const MachineBranchProbabilityInfo &ProbInfo, 115 unsigned MinTailLength) 116 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength), 117 MBBFreqInfo(FreqInfo), MBPI(ProbInfo) { 118 if (MinCommonTailLength == 0) 119 MinCommonTailLength = TailMergeSize; 120 switch (FlagEnableTailMerge) { 121 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break; 122 case cl::BOU_TRUE: EnableTailMerge = true; break; 123 case cl::BOU_FALSE: EnableTailMerge = false; break; 124 } 125 } 126 127 /// RemoveDeadBlock - Remove the specified dead machine basic block from the 128 /// function, updating the CFG. 129 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) { 130 assert(MBB->pred_empty() && "MBB must be dead!"); 131 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); 132 133 MachineFunction *MF = MBB->getParent(); 134 // drop all successors. 135 while (!MBB->succ_empty()) 136 MBB->removeSuccessor(MBB->succ_end()-1); 137 138 // Avoid matching if this pointer gets reused. 139 TriedMerging.erase(MBB); 140 141 // Remove the block. 142 MF->erase(MBB); 143 FuncletMembership.erase(MBB); 144 if (MLI) 145 MLI->removeBlock(MBB); 146 } 147 148 /// OptimizeFunction - Perhaps branch folding, tail merging and other 149 /// CFG optimizations on the given function. Block placement changes the layout 150 /// and may create new tail merging opportunities. 151 bool BranchFolder::OptimizeFunction(MachineFunction &MF, 152 const TargetInstrInfo *tii, 153 const TargetRegisterInfo *tri, 154 MachineModuleInfo *mmi, 155 MachineLoopInfo *mli, bool AfterPlacement) { 156 if (!tii) return false; 157 158 TriedMerging.clear(); 159 160 AfterBlockPlacement = AfterPlacement; 161 TII = tii; 162 TRI = tri; 163 MMI = mmi; 164 MLI = mli; 165 166 MachineRegisterInfo &MRI = MF.getRegInfo(); 167 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF); 168 if (!UpdateLiveIns) 169 MRI.invalidateLiveness(); 170 171 // Fix CFG. The later algorithms expect it to be right. 172 bool MadeChange = false; 173 for (MachineBasicBlock &MBB : MF) { 174 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 175 SmallVector<MachineOperand, 4> Cond; 176 if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true)) 177 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty()); 178 } 179 180 // Recalculate funclet membership. 181 FuncletMembership = getFuncletMembership(MF); 182 183 bool MadeChangeThisIteration = true; 184 while (MadeChangeThisIteration) { 185 MadeChangeThisIteration = TailMergeBlocks(MF); 186 // No need to clean up if tail merging does not change anything after the 187 // block placement. 188 if (!AfterBlockPlacement || MadeChangeThisIteration) 189 MadeChangeThisIteration |= OptimizeBranches(MF); 190 if (EnableHoistCommonCode) 191 MadeChangeThisIteration |= HoistCommonCode(MF); 192 MadeChange |= MadeChangeThisIteration; 193 } 194 195 // See if any jump tables have become dead as the code generator 196 // did its thing. 197 MachineJumpTableInfo *JTI = MF.getJumpTableInfo(); 198 if (!JTI) 199 return MadeChange; 200 201 // Walk the function to find jump tables that are live. 202 BitVector JTIsLive(JTI->getJumpTables().size()); 203 for (const MachineBasicBlock &BB : MF) { 204 for (const MachineInstr &I : BB) 205 for (const MachineOperand &Op : I.operands()) { 206 if (!Op.isJTI()) continue; 207 208 // Remember that this JT is live. 209 JTIsLive.set(Op.getIndex()); 210 } 211 } 212 213 // Finally, remove dead jump tables. This happens when the 214 // indirect jump was unreachable (and thus deleted). 215 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i) 216 if (!JTIsLive.test(i)) { 217 JTI->RemoveJumpTable(i); 218 MadeChange = true; 219 } 220 221 return MadeChange; 222 } 223 224 //===----------------------------------------------------------------------===// 225 // Tail Merging of Blocks 226 //===----------------------------------------------------------------------===// 227 228 /// HashMachineInstr - Compute a hash value for MI and its operands. 229 static unsigned HashMachineInstr(const MachineInstr &MI) { 230 unsigned Hash = MI.getOpcode(); 231 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 232 const MachineOperand &Op = MI.getOperand(i); 233 234 // Merge in bits from the operand if easy. We can't use MachineOperand's 235 // hash_code here because it's not deterministic and we sort by hash value 236 // later. 237 unsigned OperandHash = 0; 238 switch (Op.getType()) { 239 case MachineOperand::MO_Register: 240 OperandHash = Op.getReg(); 241 break; 242 case MachineOperand::MO_Immediate: 243 OperandHash = Op.getImm(); 244 break; 245 case MachineOperand::MO_MachineBasicBlock: 246 OperandHash = Op.getMBB()->getNumber(); 247 break; 248 case MachineOperand::MO_FrameIndex: 249 case MachineOperand::MO_ConstantPoolIndex: 250 case MachineOperand::MO_JumpTableIndex: 251 OperandHash = Op.getIndex(); 252 break; 253 case MachineOperand::MO_GlobalAddress: 254 case MachineOperand::MO_ExternalSymbol: 255 // Global address / external symbol are too hard, don't bother, but do 256 // pull in the offset. 257 OperandHash = Op.getOffset(); 258 break; 259 default: 260 break; 261 } 262 263 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31); 264 } 265 return Hash; 266 } 267 268 /// HashEndOfMBB - Hash the last instruction in the MBB. 269 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) { 270 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(); 271 if (I == MBB.end()) 272 return 0; 273 274 return HashMachineInstr(*I); 275 } 276 277 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number 278 /// of instructions they actually have in common together at their end. Return 279 /// iterators for the first shared instruction in each block. 280 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, 281 MachineBasicBlock *MBB2, 282 MachineBasicBlock::iterator &I1, 283 MachineBasicBlock::iterator &I2) { 284 I1 = MBB1->end(); 285 I2 = MBB2->end(); 286 287 unsigned TailLen = 0; 288 while (I1 != MBB1->begin() && I2 != MBB2->begin()) { 289 --I1; --I2; 290 // Skip debugging pseudos; necessary to avoid changing the code. 291 while (I1->isDebugValue()) { 292 if (I1==MBB1->begin()) { 293 while (I2->isDebugValue()) { 294 if (I2==MBB2->begin()) 295 // I1==DBG at begin; I2==DBG at begin 296 return TailLen; 297 --I2; 298 } 299 ++I2; 300 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin 301 return TailLen; 302 } 303 --I1; 304 } 305 // I1==first (untested) non-DBG preceding known match 306 while (I2->isDebugValue()) { 307 if (I2==MBB2->begin()) { 308 ++I1; 309 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin 310 return TailLen; 311 } 312 --I2; 313 } 314 // I1, I2==first (untested) non-DBGs preceding known match 315 if (!I1->isIdenticalTo(*I2) || 316 // FIXME: This check is dubious. It's used to get around a problem where 317 // people incorrectly expect inline asm directives to remain in the same 318 // relative order. This is untenable because normal compiler 319 // optimizations (like this one) may reorder and/or merge these 320 // directives. 321 I1->isInlineAsm()) { 322 ++I1; ++I2; 323 break; 324 } 325 ++TailLen; 326 } 327 // Back past possible debugging pseudos at beginning of block. This matters 328 // when one block differs from the other only by whether debugging pseudos 329 // are present at the beginning. (This way, the various checks later for 330 // I1==MBB1->begin() work as expected.) 331 if (I1 == MBB1->begin() && I2 != MBB2->begin()) { 332 --I2; 333 while (I2->isDebugValue()) { 334 if (I2 == MBB2->begin()) 335 return TailLen; 336 --I2; 337 } 338 ++I2; 339 } 340 if (I2 == MBB2->begin() && I1 != MBB1->begin()) { 341 --I1; 342 while (I1->isDebugValue()) { 343 if (I1 == MBB1->begin()) 344 return TailLen; 345 --I1; 346 } 347 ++I1; 348 } 349 return TailLen; 350 } 351 352 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything 353 /// after it, replacing it with an unconditional branch to NewDest. 354 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst, 355 MachineBasicBlock *NewDest) { 356 TII->ReplaceTailWithBranchTo(OldInst, NewDest); 357 358 if (UpdateLiveIns) { 359 NewDest->clearLiveIns(); 360 computeLiveIns(LiveRegs, *TRI, *NewDest); 361 } 362 363 ++NumTailMerge; 364 } 365 366 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the 367 /// MBB so that the part before the iterator falls into the part starting at the 368 /// iterator. This returns the new MBB. 369 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB, 370 MachineBasicBlock::iterator BBI1, 371 const BasicBlock *BB) { 372 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1)) 373 return nullptr; 374 375 MachineFunction &MF = *CurMBB.getParent(); 376 377 // Create the fall-through block. 378 MachineFunction::iterator MBBI = CurMBB.getIterator(); 379 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB); 380 CurMBB.getParent()->insert(++MBBI, NewMBB); 381 382 // Move all the successors of this block to the specified block. 383 NewMBB->transferSuccessors(&CurMBB); 384 385 // Add an edge from CurMBB to NewMBB for the fall-through. 386 CurMBB.addSuccessor(NewMBB); 387 388 // Splice the code over. 389 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end()); 390 391 // NewMBB belongs to the same loop as CurMBB. 392 if (MLI) 393 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB)) 394 ML->addBasicBlockToLoop(NewMBB, MLI->getBase()); 395 396 // NewMBB inherits CurMBB's block frequency. 397 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB)); 398 399 if (UpdateLiveIns) 400 computeLiveIns(LiveRegs, *TRI, *NewMBB); 401 402 // Add the new block to the funclet. 403 const auto &FuncletI = FuncletMembership.find(&CurMBB); 404 if (FuncletI != FuncletMembership.end()) { 405 auto n = FuncletI->second; 406 FuncletMembership[NewMBB] = n; 407 } 408 409 return NewMBB; 410 } 411 412 /// EstimateRuntime - Make a rough estimate for how long it will take to run 413 /// the specified code. 414 static unsigned EstimateRuntime(MachineBasicBlock::iterator I, 415 MachineBasicBlock::iterator E) { 416 unsigned Time = 0; 417 for (; I != E; ++I) { 418 if (I->isDebugValue()) 419 continue; 420 if (I->isCall()) 421 Time += 10; 422 else if (I->mayLoad() || I->mayStore()) 423 Time += 2; 424 else 425 ++Time; 426 } 427 return Time; 428 } 429 430 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these 431 // branches temporarily for tail merging). In the case where CurMBB ends 432 // with a conditional branch to the next block, optimize by reversing the 433 // test and conditionally branching to SuccMBB instead. 434 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, 435 const TargetInstrInfo *TII) { 436 MachineFunction *MF = CurMBB->getParent(); 437 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB)); 438 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 439 SmallVector<MachineOperand, 4> Cond; 440 DebugLoc dl; // FIXME: this is nowhere 441 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) { 442 MachineBasicBlock *NextBB = &*I; 443 if (TBB == NextBB && !Cond.empty() && !FBB) { 444 if (!TII->reverseBranchCondition(Cond)) { 445 TII->removeBranch(*CurMBB); 446 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl); 447 return; 448 } 449 } 450 } 451 TII->insertBranch(*CurMBB, SuccBB, nullptr, 452 SmallVector<MachineOperand, 0>(), dl); 453 } 454 455 bool 456 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const { 457 if (getHash() < o.getHash()) 458 return true; 459 if (getHash() > o.getHash()) 460 return false; 461 if (getBlock()->getNumber() < o.getBlock()->getNumber()) 462 return true; 463 if (getBlock()->getNumber() > o.getBlock()->getNumber()) 464 return false; 465 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing 466 // an object with itself. 467 #ifndef _GLIBCXX_DEBUG 468 llvm_unreachable("Predecessor appears twice"); 469 #else 470 return false; 471 #endif 472 } 473 474 BlockFrequency 475 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const { 476 auto I = MergedBBFreq.find(MBB); 477 478 if (I != MergedBBFreq.end()) 479 return I->second; 480 481 return MBFI.getBlockFreq(MBB); 482 } 483 484 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB, 485 BlockFrequency F) { 486 MergedBBFreq[MBB] = F; 487 } 488 489 raw_ostream & 490 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS, 491 const MachineBasicBlock *MBB) const { 492 return MBFI.printBlockFreq(OS, getBlockFreq(MBB)); 493 } 494 495 raw_ostream & 496 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS, 497 const BlockFrequency Freq) const { 498 return MBFI.printBlockFreq(OS, Freq); 499 } 500 501 /// CountTerminators - Count the number of terminators in the given 502 /// block and set I to the position of the first non-terminator, if there 503 /// is one, or MBB->end() otherwise. 504 static unsigned CountTerminators(MachineBasicBlock *MBB, 505 MachineBasicBlock::iterator &I) { 506 I = MBB->end(); 507 unsigned NumTerms = 0; 508 for (;;) { 509 if (I == MBB->begin()) { 510 I = MBB->end(); 511 break; 512 } 513 --I; 514 if (!I->isTerminator()) break; 515 ++NumTerms; 516 } 517 return NumTerms; 518 } 519 520 /// ProfitableToMerge - Check if two machine basic blocks have a common tail 521 /// and decide if it would be profitable to merge those tails. Return the 522 /// length of the common tail and iterators to the first common instruction 523 /// in each block. 524 /// MBB1, MBB2 The blocks to check 525 /// MinCommonTailLength Minimum size of tail block to be merged. 526 /// CommonTailLen Out parameter to record the size of the shared tail between 527 /// MBB1 and MBB2 528 /// I1, I2 Iterator references that will be changed to point to the first 529 /// instruction in the common tail shared by MBB1,MBB2 530 /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form 531 /// relative to SuccBB 532 /// PredBB The layout predecessor of SuccBB, if any. 533 /// FuncletMembership map from block to funclet #. 534 /// AfterPlacement True if we are merging blocks after layout. Stricter 535 /// thresholds apply to prevent undoing tail-duplication. 536 static bool 537 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, 538 unsigned MinCommonTailLength, unsigned &CommonTailLen, 539 MachineBasicBlock::iterator &I1, 540 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, 541 MachineBasicBlock *PredBB, 542 DenseMap<const MachineBasicBlock *, int> &FuncletMembership, 543 bool AfterPlacement) { 544 // It is never profitable to tail-merge blocks from two different funclets. 545 if (!FuncletMembership.empty()) { 546 auto Funclet1 = FuncletMembership.find(MBB1); 547 assert(Funclet1 != FuncletMembership.end()); 548 auto Funclet2 = FuncletMembership.find(MBB2); 549 assert(Funclet2 != FuncletMembership.end()); 550 if (Funclet1->second != Funclet2->second) 551 return false; 552 } 553 554 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2); 555 if (CommonTailLen == 0) 556 return false; 557 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber() 558 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen 559 << '\n'); 560 561 // It's almost always profitable to merge any number of non-terminator 562 // instructions with the block that falls through into the common successor. 563 // This is true only for a single successor. For multiple successors, we are 564 // trading a conditional branch for an unconditional one. 565 // TODO: Re-visit successor size for non-layout tail merging. 566 if ((MBB1 == PredBB || MBB2 == PredBB) && 567 (!AfterPlacement || MBB1->succ_size() == 1)) { 568 MachineBasicBlock::iterator I; 569 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I); 570 if (CommonTailLen > NumTerms) 571 return true; 572 } 573 574 // If one of the blocks can be completely merged and happens to be in 575 // a position where the other could fall through into it, merge any number 576 // of instructions, because it can be done without a branch. 577 // TODO: If the blocks are not adjacent, move one of them so that they are? 578 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin()) 579 return true; 580 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin()) 581 return true; 582 583 // If both blocks have an unconditional branch temporarily stripped out, 584 // count that as an additional common instruction for the following 585 // heuristics. This heuristic is only accurate for single-succ blocks, so to 586 // make sure that during layout merging and duplicating don't crash, we check 587 // for that when merging during layout. 588 unsigned EffectiveTailLen = CommonTailLen; 589 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB && 590 (MBB1->succ_size() == 1 || !AfterPlacement) && 591 !MBB1->back().isBarrier() && 592 !MBB2->back().isBarrier()) 593 ++EffectiveTailLen; 594 595 // Check if the common tail is long enough to be worthwhile. 596 if (EffectiveTailLen >= MinCommonTailLength) 597 return true; 598 599 // If we are optimizing for code size, 2 instructions in common is enough if 600 // we don't have to split a block. At worst we will be introducing 1 new 601 // branch instruction, which is likely to be smaller than the 2 602 // instructions that would be deleted in the merge. 603 MachineFunction *MF = MBB1->getParent(); 604 return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() && 605 (I1 == MBB1->begin() || I2 == MBB2->begin()); 606 } 607 608 /// ComputeSameTails - Look through all the blocks in MergePotentials that have 609 /// hash CurHash (guaranteed to match the last element). Build the vector 610 /// SameTails of all those that have the (same) largest number of instructions 611 /// in common of any pair of these blocks. SameTails entries contain an 612 /// iterator into MergePotentials (from which the MachineBasicBlock can be 613 /// found) and a MachineBasicBlock::iterator into that MBB indicating the 614 /// instruction where the matching code sequence begins. 615 /// Order of elements in SameTails is the reverse of the order in which 616 /// those blocks appear in MergePotentials (where they are not necessarily 617 /// consecutive). 618 unsigned BranchFolder::ComputeSameTails(unsigned CurHash, 619 unsigned MinCommonTailLength, 620 MachineBasicBlock *SuccBB, 621 MachineBasicBlock *PredBB) { 622 unsigned maxCommonTailLength = 0U; 623 SameTails.clear(); 624 MachineBasicBlock::iterator TrialBBI1, TrialBBI2; 625 MPIterator HighestMPIter = std::prev(MergePotentials.end()); 626 for (MPIterator CurMPIter = std::prev(MergePotentials.end()), 627 B = MergePotentials.begin(); 628 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) { 629 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) { 630 unsigned CommonTailLen; 631 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(), 632 MinCommonTailLength, 633 CommonTailLen, TrialBBI1, TrialBBI2, 634 SuccBB, PredBB, 635 FuncletMembership, 636 AfterBlockPlacement)) { 637 if (CommonTailLen > maxCommonTailLength) { 638 SameTails.clear(); 639 maxCommonTailLength = CommonTailLen; 640 HighestMPIter = CurMPIter; 641 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1)); 642 } 643 if (HighestMPIter == CurMPIter && 644 CommonTailLen == maxCommonTailLength) 645 SameTails.push_back(SameTailElt(I, TrialBBI2)); 646 } 647 if (I == B) 648 break; 649 } 650 } 651 return maxCommonTailLength; 652 } 653 654 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from 655 /// MergePotentials, restoring branches at ends of blocks as appropriate. 656 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash, 657 MachineBasicBlock *SuccBB, 658 MachineBasicBlock *PredBB) { 659 MPIterator CurMPIter, B; 660 for (CurMPIter = std::prev(MergePotentials.end()), 661 B = MergePotentials.begin(); 662 CurMPIter->getHash() == CurHash; --CurMPIter) { 663 // Put the unconditional branch back, if we need one. 664 MachineBasicBlock *CurMBB = CurMPIter->getBlock(); 665 if (SuccBB && CurMBB != PredBB) 666 FixTail(CurMBB, SuccBB, TII); 667 if (CurMPIter == B) 668 break; 669 } 670 if (CurMPIter->getHash() != CurHash) 671 CurMPIter++; 672 MergePotentials.erase(CurMPIter, MergePotentials.end()); 673 } 674 675 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist 676 /// only of the common tail. Create a block that does by splitting one. 677 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB, 678 MachineBasicBlock *SuccBB, 679 unsigned maxCommonTailLength, 680 unsigned &commonTailIndex) { 681 commonTailIndex = 0; 682 unsigned TimeEstimate = ~0U; 683 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { 684 // Use PredBB if possible; that doesn't require a new branch. 685 if (SameTails[i].getBlock() == PredBB) { 686 commonTailIndex = i; 687 break; 688 } 689 // Otherwise, make a (fairly bogus) choice based on estimate of 690 // how long it will take the various blocks to execute. 691 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(), 692 SameTails[i].getTailStartPos()); 693 if (t <= TimeEstimate) { 694 TimeEstimate = t; 695 commonTailIndex = i; 696 } 697 } 698 699 MachineBasicBlock::iterator BBI = 700 SameTails[commonTailIndex].getTailStartPos(); 701 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); 702 703 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size " 704 << maxCommonTailLength); 705 706 // If the split block unconditionally falls-thru to SuccBB, it will be 707 // merged. In control flow terms it should then take SuccBB's name. e.g. If 708 // SuccBB is an inner loop, the common tail is still part of the inner loop. 709 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ? 710 SuccBB->getBasicBlock() : MBB->getBasicBlock(); 711 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB); 712 if (!newMBB) { 713 DEBUG(dbgs() << "... failed!"); 714 return false; 715 } 716 717 SameTails[commonTailIndex].setBlock(newMBB); 718 SameTails[commonTailIndex].setTailStartPos(newMBB->begin()); 719 720 // If we split PredBB, newMBB is the new predecessor. 721 if (PredBB == MBB) 722 PredBB = newMBB; 723 724 return true; 725 } 726 727 static void 728 mergeOperations(MachineBasicBlock::iterator MBBIStartPos, 729 MachineBasicBlock &MBBCommon) { 730 MachineBasicBlock *MBB = MBBIStartPos->getParent(); 731 // Note CommonTailLen does not necessarily matches the size of 732 // the common BB nor all its instructions because of debug 733 // instructions differences. 734 unsigned CommonTailLen = 0; 735 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos) 736 ++CommonTailLen; 737 738 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin(); 739 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend(); 740 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin(); 741 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend(); 742 743 while (CommonTailLen--) { 744 assert(MBBI != MBBIE && "Reached BB end within common tail length!"); 745 (void)MBBIE; 746 747 if (MBBI->isDebugValue()) { 748 ++MBBI; 749 continue; 750 } 751 752 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue()) 753 ++MBBICommon; 754 755 assert(MBBICommon != MBBIECommon && 756 "Reached BB end within common tail length!"); 757 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!"); 758 759 // Merge MMOs from memory operations in the common block. 760 if (MBBICommon->mayLoad() || MBBICommon->mayStore()) 761 MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI)); 762 // Drop undef flags if they aren't present in all merged instructions. 763 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) { 764 MachineOperand &MO = MBBICommon->getOperand(I); 765 if (MO.isReg() && MO.isUndef()) { 766 const MachineOperand &OtherMO = MBBI->getOperand(I); 767 if (!OtherMO.isUndef()) 768 MO.setIsUndef(false); 769 } 770 } 771 772 ++MBBI; 773 ++MBBICommon; 774 } 775 } 776 777 // See if any of the blocks in MergePotentials (which all have SuccBB as a 778 // successor, or all have no successor if it is null) can be tail-merged. 779 // If there is a successor, any blocks in MergePotentials that are not 780 // tail-merged and are not immediately before Succ must have an unconditional 781 // branch to Succ added (but the predecessor/successor lists need no 782 // adjustment). The lone predecessor of Succ that falls through into Succ, 783 // if any, is given in PredBB. 784 // MinCommonTailLength - Except for the special cases below, tail-merge if 785 // there are at least this many instructions in common. 786 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB, 787 MachineBasicBlock *PredBB, 788 unsigned MinCommonTailLength) { 789 bool MadeChange = false; 790 791 DEBUG(dbgs() << "\nTryTailMergeBlocks: "; 792 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) 793 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber() 794 << (i == e-1 ? "" : ", "); 795 dbgs() << "\n"; 796 if (SuccBB) { 797 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n'; 798 if (PredBB) 799 dbgs() << " which has fall-through from BB#" 800 << PredBB->getNumber() << "\n"; 801 } 802 dbgs() << "Looking for common tails of at least " 803 << MinCommonTailLength << " instruction" 804 << (MinCommonTailLength == 1 ? "" : "s") << '\n'; 805 ); 806 807 // Sort by hash value so that blocks with identical end sequences sort 808 // together. 809 array_pod_sort(MergePotentials.begin(), MergePotentials.end()); 810 811 // Walk through equivalence sets looking for actual exact matches. 812 while (MergePotentials.size() > 1) { 813 unsigned CurHash = MergePotentials.back().getHash(); 814 815 // Build SameTails, identifying the set of blocks with this hash code 816 // and with the maximum number of instructions in common. 817 unsigned maxCommonTailLength = ComputeSameTails(CurHash, 818 MinCommonTailLength, 819 SuccBB, PredBB); 820 821 // If we didn't find any pair that has at least MinCommonTailLength 822 // instructions in common, remove all blocks with this hash code and retry. 823 if (SameTails.empty()) { 824 RemoveBlocksWithHash(CurHash, SuccBB, PredBB); 825 continue; 826 } 827 828 // If one of the blocks is the entire common tail (and not the entry 829 // block, which we can't jump to), we can treat all blocks with this same 830 // tail at once. Use PredBB if that is one of the possibilities, as that 831 // will not introduce any extra branches. 832 MachineBasicBlock *EntryBB = 833 &MergePotentials.front().getBlock()->getParent()->front(); 834 unsigned commonTailIndex = SameTails.size(); 835 // If there are two blocks, check to see if one can be made to fall through 836 // into the other. 837 if (SameTails.size() == 2 && 838 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) && 839 SameTails[1].tailIsWholeBlock()) 840 commonTailIndex = 1; 841 else if (SameTails.size() == 2 && 842 SameTails[1].getBlock()->isLayoutSuccessor( 843 SameTails[0].getBlock()) && 844 SameTails[0].tailIsWholeBlock()) 845 commonTailIndex = 0; 846 else { 847 // Otherwise just pick one, favoring the fall-through predecessor if 848 // there is one. 849 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) { 850 MachineBasicBlock *MBB = SameTails[i].getBlock(); 851 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock()) 852 continue; 853 if (MBB == PredBB) { 854 commonTailIndex = i; 855 break; 856 } 857 if (SameTails[i].tailIsWholeBlock()) 858 commonTailIndex = i; 859 } 860 } 861 862 if (commonTailIndex == SameTails.size() || 863 (SameTails[commonTailIndex].getBlock() == PredBB && 864 !SameTails[commonTailIndex].tailIsWholeBlock())) { 865 // None of the blocks consist entirely of the common tail. 866 // Split a block so that one does. 867 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB, 868 maxCommonTailLength, commonTailIndex)) { 869 RemoveBlocksWithHash(CurHash, SuccBB, PredBB); 870 continue; 871 } 872 } 873 874 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock(); 875 876 // Recompute common tail MBB's edge weights and block frequency. 877 setCommonTailEdgeWeights(*MBB); 878 879 // Remove the original debug location from the common tail. 880 for (auto &MI : *MBB) 881 if (!MI.isDebugValue()) 882 MI.setDebugLoc(DebugLoc()); 883 884 // MBB is common tail. Adjust all other BB's to jump to this one. 885 // Traversal must be forwards so erases work. 886 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber() 887 << " for "); 888 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) { 889 if (commonTailIndex == i) 890 continue; 891 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber() 892 << (i == e-1 ? "" : ", ")); 893 // Merge operations (MMOs, undef flags) 894 mergeOperations(SameTails[i].getTailStartPos(), *MBB); 895 // Hack the end off BB i, making it jump to BB commonTailIndex instead. 896 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB); 897 // BB i is no longer a predecessor of SuccBB; remove it from the worklist. 898 MergePotentials.erase(SameTails[i].getMPIter()); 899 } 900 DEBUG(dbgs() << "\n"); 901 // We leave commonTailIndex in the worklist in case there are other blocks 902 // that match it with a smaller number of instructions. 903 MadeChange = true; 904 } 905 return MadeChange; 906 } 907 908 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) { 909 bool MadeChange = false; 910 if (!EnableTailMerge) return MadeChange; 911 912 // First find blocks with no successors. 913 // Block placement does not create new tail merging opportunities for these 914 // blocks. 915 if (!AfterBlockPlacement) { 916 MergePotentials.clear(); 917 for (MachineBasicBlock &MBB : MF) { 918 if (MergePotentials.size() == TailMergeThreshold) 919 break; 920 if (!TriedMerging.count(&MBB) && MBB.succ_empty()) 921 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB)); 922 } 923 924 // If this is a large problem, avoid visiting the same basic blocks 925 // multiple times. 926 if (MergePotentials.size() == TailMergeThreshold) 927 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) 928 TriedMerging.insert(MergePotentials[i].getBlock()); 929 930 // See if we can do any tail merging on those. 931 if (MergePotentials.size() >= 2) 932 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength); 933 } 934 935 // Look at blocks (IBB) with multiple predecessors (PBB). 936 // We change each predecessor to a canonical form, by 937 // (1) temporarily removing any unconditional branch from the predecessor 938 // to IBB, and 939 // (2) alter conditional branches so they branch to the other block 940 // not IBB; this may require adding back an unconditional branch to IBB 941 // later, where there wasn't one coming in. E.g. 942 // Bcc IBB 943 // fallthrough to QBB 944 // here becomes 945 // Bncc QBB 946 // with a conceptual B to IBB after that, which never actually exists. 947 // With those changes, we see whether the predecessors' tails match, 948 // and merge them if so. We change things out of canonical form and 949 // back to the way they were later in the process. (OptimizeBranches 950 // would undo some of this, but we can't use it, because we'd get into 951 // a compile-time infinite loop repeatedly doing and undoing the same 952 // transformations.) 953 954 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); 955 I != E; ++I) { 956 if (I->pred_size() < 2) continue; 957 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds; 958 MachineBasicBlock *IBB = &*I; 959 MachineBasicBlock *PredBB = &*std::prev(I); 960 MergePotentials.clear(); 961 MachineLoop *ML; 962 963 // Bail if merging after placement and IBB is the loop header because 964 // -- If merging predecessors that belong to the same loop as IBB, the 965 // common tail of merged predecessors may become the loop top if block 966 // placement is called again and the predecessors may branch to this common 967 // tail and require more branches. This can be relaxed if 968 // MachineBlockPlacement::findBestLoopTop is more flexible. 969 // --If merging predecessors that do not belong to the same loop as IBB, the 970 // loop info of IBB's loop and the other loops may be affected. Calling the 971 // block placement again may make big change to the layout and eliminate the 972 // reason to do tail merging here. 973 if (AfterBlockPlacement && MLI) { 974 ML = MLI->getLoopFor(IBB); 975 if (ML && IBB == ML->getHeader()) 976 continue; 977 } 978 979 for (MachineBasicBlock *PBB : I->predecessors()) { 980 if (MergePotentials.size() == TailMergeThreshold) 981 break; 982 983 if (TriedMerging.count(PBB)) 984 continue; 985 986 // Skip blocks that loop to themselves, can't tail merge these. 987 if (PBB == IBB) 988 continue; 989 990 // Visit each predecessor only once. 991 if (!UniquePreds.insert(PBB).second) 992 continue; 993 994 // Skip blocks which may jump to a landing pad. Can't tail merge these. 995 if (PBB->hasEHPadSuccessor()) 996 continue; 997 998 // After block placement, only consider predecessors that belong to the 999 // same loop as IBB. The reason is the same as above when skipping loop 1000 // header. 1001 if (AfterBlockPlacement && MLI) 1002 if (ML != MLI->getLoopFor(PBB)) 1003 continue; 1004 1005 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1006 SmallVector<MachineOperand, 4> Cond; 1007 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) { 1008 // Failing case: IBB is the target of a cbr, and we cannot reverse the 1009 // branch. 1010 SmallVector<MachineOperand, 4> NewCond(Cond); 1011 if (!Cond.empty() && TBB == IBB) { 1012 if (TII->reverseBranchCondition(NewCond)) 1013 continue; 1014 // This is the QBB case described above 1015 if (!FBB) { 1016 auto Next = ++PBB->getIterator(); 1017 if (Next != MF.end()) 1018 FBB = &*Next; 1019 } 1020 } 1021 1022 // Failing case: the only way IBB can be reached from PBB is via 1023 // exception handling. Happens for landing pads. Would be nice to have 1024 // a bit in the edge so we didn't have to do all this. 1025 if (IBB->isEHPad()) { 1026 MachineFunction::iterator IP = ++PBB->getIterator(); 1027 MachineBasicBlock *PredNextBB = nullptr; 1028 if (IP != MF.end()) 1029 PredNextBB = &*IP; 1030 if (!TBB) { 1031 if (IBB != PredNextBB) // fallthrough 1032 continue; 1033 } else if (FBB) { 1034 if (TBB != IBB && FBB != IBB) // cbr then ubr 1035 continue; 1036 } else if (Cond.empty()) { 1037 if (TBB != IBB) // ubr 1038 continue; 1039 } else { 1040 if (TBB != IBB && IBB != PredNextBB) // cbr 1041 continue; 1042 } 1043 } 1044 1045 // Remove the unconditional branch at the end, if any. 1046 if (TBB && (Cond.empty() || FBB)) { 1047 DebugLoc dl; // FIXME: this is nowhere 1048 TII->removeBranch(*PBB); 1049 if (!Cond.empty()) 1050 // reinsert conditional branch only, for now 1051 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr, 1052 NewCond, dl); 1053 } 1054 1055 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB)); 1056 } 1057 } 1058 1059 // If this is a large problem, avoid visiting the same basic blocks multiple 1060 // times. 1061 if (MergePotentials.size() == TailMergeThreshold) 1062 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) 1063 TriedMerging.insert(MergePotentials[i].getBlock()); 1064 1065 if (MergePotentials.size() >= 2) 1066 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength); 1067 1068 // Reinsert an unconditional branch if needed. The 1 below can occur as a 1069 // result of removing blocks in TryTailMergeBlocks. 1070 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks 1071 if (MergePotentials.size() == 1 && 1072 MergePotentials.begin()->getBlock() != PredBB) 1073 FixTail(MergePotentials.begin()->getBlock(), IBB, TII); 1074 } 1075 1076 return MadeChange; 1077 } 1078 1079 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) { 1080 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size()); 1081 BlockFrequency AccumulatedMBBFreq; 1082 1083 // Aggregate edge frequency of successor edge j: 1084 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)), 1085 // where bb is a basic block that is in SameTails. 1086 for (const auto &Src : SameTails) { 1087 const MachineBasicBlock *SrcMBB = Src.getBlock(); 1088 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB); 1089 AccumulatedMBBFreq += BlockFreq; 1090 1091 // It is not necessary to recompute edge weights if TailBB has less than two 1092 // successors. 1093 if (TailMBB.succ_size() <= 1) 1094 continue; 1095 1096 auto EdgeFreq = EdgeFreqLs.begin(); 1097 1098 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); 1099 SuccI != SuccE; ++SuccI, ++EdgeFreq) 1100 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI); 1101 } 1102 1103 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq); 1104 1105 if (TailMBB.succ_size() <= 1) 1106 return; 1107 1108 auto SumEdgeFreq = 1109 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0)) 1110 .getFrequency(); 1111 auto EdgeFreq = EdgeFreqLs.begin(); 1112 1113 if (SumEdgeFreq > 0) { 1114 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end(); 1115 SuccI != SuccE; ++SuccI, ++EdgeFreq) { 1116 auto Prob = BranchProbability::getBranchProbability( 1117 EdgeFreq->getFrequency(), SumEdgeFreq); 1118 TailMBB.setSuccProbability(SuccI, Prob); 1119 } 1120 } 1121 } 1122 1123 //===----------------------------------------------------------------------===// 1124 // Branch Optimization 1125 //===----------------------------------------------------------------------===// 1126 1127 bool BranchFolder::OptimizeBranches(MachineFunction &MF) { 1128 bool MadeChange = false; 1129 1130 // Make sure blocks are numbered in order 1131 MF.RenumberBlocks(); 1132 // Renumbering blocks alters funclet membership, recalculate it. 1133 FuncletMembership = getFuncletMembership(MF); 1134 1135 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end(); 1136 I != E; ) { 1137 MachineBasicBlock *MBB = &*I++; 1138 MadeChange |= OptimizeBlock(MBB); 1139 1140 // If it is dead, remove it. 1141 if (MBB->pred_empty()) { 1142 RemoveDeadBlock(MBB); 1143 MadeChange = true; 1144 ++NumDeadBlocks; 1145 } 1146 } 1147 1148 return MadeChange; 1149 } 1150 1151 // Blocks should be considered empty if they contain only debug info; 1152 // else the debug info would affect codegen. 1153 static bool IsEmptyBlock(MachineBasicBlock *MBB) { 1154 return MBB->getFirstNonDebugInstr() == MBB->end(); 1155 } 1156 1157 // Blocks with only debug info and branches should be considered the same 1158 // as blocks with only branches. 1159 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) { 1160 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr(); 1161 assert(I != MBB->end() && "empty block!"); 1162 return I->isBranch(); 1163 } 1164 1165 /// IsBetterFallthrough - Return true if it would be clearly better to 1166 /// fall-through to MBB1 than to fall through into MBB2. This has to return 1167 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will 1168 /// result in infinite loops. 1169 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 1170 MachineBasicBlock *MBB2) { 1171 // Right now, we use a simple heuristic. If MBB2 ends with a call, and 1172 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to 1173 // optimize branches that branch to either a return block or an assert block 1174 // into a fallthrough to the return. 1175 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr(); 1176 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr(); 1177 if (MBB1I == MBB1->end() || MBB2I == MBB2->end()) 1178 return false; 1179 1180 // If there is a clear successor ordering we make sure that one block 1181 // will fall through to the next 1182 if (MBB1->isSuccessor(MBB2)) return true; 1183 if (MBB2->isSuccessor(MBB1)) return false; 1184 1185 return MBB2I->isCall() && !MBB1I->isCall(); 1186 } 1187 1188 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch 1189 /// instructions on the block. 1190 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) { 1191 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 1192 if (I != MBB.end() && I->isBranch()) 1193 return I->getDebugLoc(); 1194 return DebugLoc(); 1195 } 1196 1197 /// OptimizeBlock - Analyze and optimize control flow related to the specified 1198 /// block. This is never called on the entry block. 1199 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) { 1200 bool MadeChange = false; 1201 MachineFunction &MF = *MBB->getParent(); 1202 ReoptimizeBlock: 1203 1204 MachineFunction::iterator FallThrough = MBB->getIterator(); 1205 ++FallThrough; 1206 1207 // Make sure MBB and FallThrough belong to the same funclet. 1208 bool SameFunclet = true; 1209 if (!FuncletMembership.empty() && FallThrough != MF.end()) { 1210 auto MBBFunclet = FuncletMembership.find(MBB); 1211 assert(MBBFunclet != FuncletMembership.end()); 1212 auto FallThroughFunclet = FuncletMembership.find(&*FallThrough); 1213 assert(FallThroughFunclet != FuncletMembership.end()); 1214 SameFunclet = MBBFunclet->second == FallThroughFunclet->second; 1215 } 1216 1217 // If this block is empty, make everyone use its fall-through, not the block 1218 // explicitly. Landing pads should not do this since the landing-pad table 1219 // points to this block. Blocks with their addresses taken shouldn't be 1220 // optimized away. 1221 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() && 1222 SameFunclet) { 1223 // Dead block? Leave for cleanup later. 1224 if (MBB->pred_empty()) return MadeChange; 1225 1226 if (FallThrough == MF.end()) { 1227 // TODO: Simplify preds to not branch here if possible! 1228 } else if (FallThrough->isEHPad()) { 1229 // Don't rewrite to a landing pad fallthough. That could lead to the case 1230 // where a BB jumps to more than one landing pad. 1231 // TODO: Is it ever worth rewriting predecessors which don't already 1232 // jump to a landing pad, and so can safely jump to the fallthrough? 1233 } else if (MBB->isSuccessor(&*FallThrough)) { 1234 // Rewrite all predecessors of the old block to go to the fallthrough 1235 // instead. 1236 while (!MBB->pred_empty()) { 1237 MachineBasicBlock *Pred = *(MBB->pred_end()-1); 1238 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough); 1239 } 1240 // If MBB was the target of a jump table, update jump tables to go to the 1241 // fallthrough instead. 1242 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) 1243 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough); 1244 MadeChange = true; 1245 } 1246 return MadeChange; 1247 } 1248 1249 // Check to see if we can simplify the terminator of the block before this 1250 // one. 1251 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB)); 1252 1253 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; 1254 SmallVector<MachineOperand, 4> PriorCond; 1255 bool PriorUnAnalyzable = 1256 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true); 1257 if (!PriorUnAnalyzable) { 1258 // If the CFG for the prior block has extra edges, remove them. 1259 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB, 1260 !PriorCond.empty()); 1261 1262 // If the previous branch is conditional and both conditions go to the same 1263 // destination, remove the branch, replacing it with an unconditional one or 1264 // a fall-through. 1265 if (PriorTBB && PriorTBB == PriorFBB) { 1266 DebugLoc dl = getBranchDebugLoc(PrevBB); 1267 TII->removeBranch(PrevBB); 1268 PriorCond.clear(); 1269 if (PriorTBB != MBB) 1270 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); 1271 MadeChange = true; 1272 ++NumBranchOpts; 1273 goto ReoptimizeBlock; 1274 } 1275 1276 // If the previous block unconditionally falls through to this block and 1277 // this block has no other predecessors, move the contents of this block 1278 // into the prior block. This doesn't usually happen when SimplifyCFG 1279 // has been used, but it can happen if tail merging splits a fall-through 1280 // predecessor of a block. 1281 // This has to check PrevBB->succ_size() because EH edges are ignored by 1282 // AnalyzeBranch. 1283 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 && 1284 PrevBB.succ_size() == 1 && 1285 !MBB->hasAddressTaken() && !MBB->isEHPad()) { 1286 DEBUG(dbgs() << "\nMerging into block: " << PrevBB 1287 << "From MBB: " << *MBB); 1288 // Remove redundant DBG_VALUEs first. 1289 if (PrevBB.begin() != PrevBB.end()) { 1290 MachineBasicBlock::iterator PrevBBIter = PrevBB.end(); 1291 --PrevBBIter; 1292 MachineBasicBlock::iterator MBBIter = MBB->begin(); 1293 // Check if DBG_VALUE at the end of PrevBB is identical to the 1294 // DBG_VALUE at the beginning of MBB. 1295 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end() 1296 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) { 1297 if (!MBBIter->isIdenticalTo(*PrevBBIter)) 1298 break; 1299 MachineInstr &DuplicateDbg = *MBBIter; 1300 ++MBBIter; -- PrevBBIter; 1301 DuplicateDbg.eraseFromParent(); 1302 } 1303 } 1304 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end()); 1305 PrevBB.removeSuccessor(PrevBB.succ_begin()); 1306 assert(PrevBB.succ_empty()); 1307 PrevBB.transferSuccessors(MBB); 1308 MadeChange = true; 1309 return MadeChange; 1310 } 1311 1312 // If the previous branch *only* branches to *this* block (conditional or 1313 // not) remove the branch. 1314 if (PriorTBB == MBB && !PriorFBB) { 1315 TII->removeBranch(PrevBB); 1316 MadeChange = true; 1317 ++NumBranchOpts; 1318 goto ReoptimizeBlock; 1319 } 1320 1321 // If the prior block branches somewhere else on the condition and here if 1322 // the condition is false, remove the uncond second branch. 1323 if (PriorFBB == MBB) { 1324 DebugLoc dl = getBranchDebugLoc(PrevBB); 1325 TII->removeBranch(PrevBB); 1326 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl); 1327 MadeChange = true; 1328 ++NumBranchOpts; 1329 goto ReoptimizeBlock; 1330 } 1331 1332 // If the prior block branches here on true and somewhere else on false, and 1333 // if the branch condition is reversible, reverse the branch to create a 1334 // fall-through. 1335 if (PriorTBB == MBB) { 1336 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); 1337 if (!TII->reverseBranchCondition(NewPriorCond)) { 1338 DebugLoc dl = getBranchDebugLoc(PrevBB); 1339 TII->removeBranch(PrevBB); 1340 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl); 1341 MadeChange = true; 1342 ++NumBranchOpts; 1343 goto ReoptimizeBlock; 1344 } 1345 } 1346 1347 // If this block has no successors (e.g. it is a return block or ends with 1348 // a call to a no-return function like abort or __cxa_throw) and if the pred 1349 // falls through into this block, and if it would otherwise fall through 1350 // into the block after this, move this block to the end of the function. 1351 // 1352 // We consider it more likely that execution will stay in the function (e.g. 1353 // due to loops) than it is to exit it. This asserts in loops etc, moving 1354 // the assert condition out of the loop body. 1355 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB && 1356 MachineFunction::iterator(PriorTBB) == FallThrough && 1357 !MBB->canFallThrough()) { 1358 bool DoTransform = true; 1359 1360 // We have to be careful that the succs of PredBB aren't both no-successor 1361 // blocks. If neither have successors and if PredBB is the second from 1362 // last block in the function, we'd just keep swapping the two blocks for 1363 // last. Only do the swap if one is clearly better to fall through than 1364 // the other. 1365 if (FallThrough == --MF.end() && 1366 !IsBetterFallthrough(PriorTBB, MBB)) 1367 DoTransform = false; 1368 1369 if (DoTransform) { 1370 // Reverse the branch so we will fall through on the previous true cond. 1371 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond); 1372 if (!TII->reverseBranchCondition(NewPriorCond)) { 1373 DEBUG(dbgs() << "\nMoving MBB: " << *MBB 1374 << "To make fallthrough to: " << *PriorTBB << "\n"); 1375 1376 DebugLoc dl = getBranchDebugLoc(PrevBB); 1377 TII->removeBranch(PrevBB); 1378 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl); 1379 1380 // Move this block to the end of the function. 1381 MBB->moveAfter(&MF.back()); 1382 MadeChange = true; 1383 ++NumBranchOpts; 1384 return MadeChange; 1385 } 1386 } 1387 } 1388 } 1389 1390 if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 && 1391 MF.getFunction()->optForSize()) { 1392 // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch 1393 // direction, thereby defeating careful block placement and regressing 1394 // performance. Therefore, only consider this for optsize functions. 1395 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr(); 1396 if (TII->isUnconditionalTailCall(TailCall)) { 1397 MachineBasicBlock *Pred = *MBB->pred_begin(); 1398 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 1399 SmallVector<MachineOperand, 4> PredCond; 1400 bool PredAnalyzable = 1401 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true); 1402 1403 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB) { 1404 // The predecessor has a conditional branch to this block which consists 1405 // of only a tail call. Try to fold the tail call into the conditional 1406 // branch. 1407 if (TII->canMakeTailCallConditional(PredCond, TailCall)) { 1408 // TODO: It would be nice if analyzeBranch() could provide a pointer 1409 // to the branch insturction so replaceBranchWithTailCall() doesn't 1410 // have to search for it. 1411 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall); 1412 ++NumTailCalls; 1413 Pred->removeSuccessor(MBB); 1414 MadeChange = true; 1415 return MadeChange; 1416 } 1417 } 1418 // If the predecessor is falling through to this block, we could reverse 1419 // the branch condition and fold the tail call into that. However, after 1420 // that we might have to re-arrange the CFG to fall through to the other 1421 // block and there is a high risk of regressing code size rather than 1422 // improving it. 1423 } 1424 } 1425 1426 // Analyze the branch in the current block. 1427 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr; 1428 SmallVector<MachineOperand, 4> CurCond; 1429 bool CurUnAnalyzable = 1430 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true); 1431 if (!CurUnAnalyzable) { 1432 // If the CFG for the prior block has extra edges, remove them. 1433 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty()); 1434 1435 // If this is a two-way branch, and the FBB branches to this block, reverse 1436 // the condition so the single-basic-block loop is faster. Instead of: 1437 // Loop: xxx; jcc Out; jmp Loop 1438 // we want: 1439 // Loop: xxx; jncc Loop; jmp Out 1440 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) { 1441 SmallVector<MachineOperand, 4> NewCond(CurCond); 1442 if (!TII->reverseBranchCondition(NewCond)) { 1443 DebugLoc dl = getBranchDebugLoc(*MBB); 1444 TII->removeBranch(*MBB); 1445 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl); 1446 MadeChange = true; 1447 ++NumBranchOpts; 1448 goto ReoptimizeBlock; 1449 } 1450 } 1451 1452 // If this branch is the only thing in its block, see if we can forward 1453 // other blocks across it. 1454 if (CurTBB && CurCond.empty() && !CurFBB && 1455 IsBranchOnlyBlock(MBB) && CurTBB != MBB && 1456 !MBB->hasAddressTaken() && !MBB->isEHPad()) { 1457 DebugLoc dl = getBranchDebugLoc(*MBB); 1458 // This block may contain just an unconditional branch. Because there can 1459 // be 'non-branch terminators' in the block, try removing the branch and 1460 // then seeing if the block is empty. 1461 TII->removeBranch(*MBB); 1462 // If the only things remaining in the block are debug info, remove these 1463 // as well, so this will behave the same as an empty block in non-debug 1464 // mode. 1465 if (IsEmptyBlock(MBB)) { 1466 // Make the block empty, losing the debug info (we could probably 1467 // improve this in some cases.) 1468 MBB->erase(MBB->begin(), MBB->end()); 1469 } 1470 // If this block is just an unconditional branch to CurTBB, we can 1471 // usually completely eliminate the block. The only case we cannot 1472 // completely eliminate the block is when the block before this one 1473 // falls through into MBB and we can't understand the prior block's branch 1474 // condition. 1475 if (MBB->empty()) { 1476 bool PredHasNoFallThrough = !PrevBB.canFallThrough(); 1477 if (PredHasNoFallThrough || !PriorUnAnalyzable || 1478 !PrevBB.isSuccessor(MBB)) { 1479 // If the prior block falls through into us, turn it into an 1480 // explicit branch to us to make updates simpler. 1481 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 1482 PriorTBB != MBB && PriorFBB != MBB) { 1483 if (!PriorTBB) { 1484 assert(PriorCond.empty() && !PriorFBB && 1485 "Bad branch analysis"); 1486 PriorTBB = MBB; 1487 } else { 1488 assert(!PriorFBB && "Machine CFG out of date!"); 1489 PriorFBB = MBB; 1490 } 1491 DebugLoc pdl = getBranchDebugLoc(PrevBB); 1492 TII->removeBranch(PrevBB); 1493 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl); 1494 } 1495 1496 // Iterate through all the predecessors, revectoring each in-turn. 1497 size_t PI = 0; 1498 bool DidChange = false; 1499 bool HasBranchToSelf = false; 1500 while(PI != MBB->pred_size()) { 1501 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI); 1502 if (PMBB == MBB) { 1503 // If this block has an uncond branch to itself, leave it. 1504 ++PI; 1505 HasBranchToSelf = true; 1506 } else { 1507 DidChange = true; 1508 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB); 1509 // If this change resulted in PMBB ending in a conditional 1510 // branch where both conditions go to the same destination, 1511 // change this to an unconditional branch (and fix the CFG). 1512 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr; 1513 SmallVector<MachineOperand, 4> NewCurCond; 1514 bool NewCurUnAnalyzable = TII->analyzeBranch( 1515 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true); 1516 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) { 1517 DebugLoc pdl = getBranchDebugLoc(*PMBB); 1518 TII->removeBranch(*PMBB); 1519 NewCurCond.clear(); 1520 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl); 1521 MadeChange = true; 1522 ++NumBranchOpts; 1523 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false); 1524 } 1525 } 1526 } 1527 1528 // Change any jumptables to go to the new MBB. 1529 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) 1530 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB); 1531 if (DidChange) { 1532 ++NumBranchOpts; 1533 MadeChange = true; 1534 if (!HasBranchToSelf) return MadeChange; 1535 } 1536 } 1537 } 1538 1539 // Add the branch back if the block is more than just an uncond branch. 1540 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl); 1541 } 1542 } 1543 1544 // If the prior block doesn't fall through into this block, and if this 1545 // block doesn't fall through into some other block, see if we can find a 1546 // place to move this block where a fall-through will happen. 1547 if (!PrevBB.canFallThrough()) { 1548 1549 // Now we know that there was no fall-through into this block, check to 1550 // see if it has a fall-through into its successor. 1551 bool CurFallsThru = MBB->canFallThrough(); 1552 1553 if (!MBB->isEHPad()) { 1554 // Check all the predecessors of this block. If one of them has no fall 1555 // throughs, move this block right after it. 1556 for (MachineBasicBlock *PredBB : MBB->predecessors()) { 1557 // Analyze the branch at the end of the pred. 1558 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; 1559 SmallVector<MachineOperand, 4> PredCond; 1560 if (PredBB != MBB && !PredBB->canFallThrough() && 1561 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) && 1562 (!CurFallsThru || !CurTBB || !CurFBB) && 1563 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) { 1564 // If the current block doesn't fall through, just move it. 1565 // If the current block can fall through and does not end with a 1566 // conditional branch, we need to append an unconditional jump to 1567 // the (current) next block. To avoid a possible compile-time 1568 // infinite loop, move blocks only backward in this case. 1569 // Also, if there are already 2 branches here, we cannot add a third; 1570 // this means we have the case 1571 // Bcc next 1572 // B elsewhere 1573 // next: 1574 if (CurFallsThru) { 1575 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator()); 1576 CurCond.clear(); 1577 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc()); 1578 } 1579 MBB->moveAfter(PredBB); 1580 MadeChange = true; 1581 goto ReoptimizeBlock; 1582 } 1583 } 1584 } 1585 1586 if (!CurFallsThru) { 1587 // Check all successors to see if we can move this block before it. 1588 for (MachineBasicBlock *SuccBB : MBB->successors()) { 1589 // Analyze the branch at the end of the block before the succ. 1590 MachineFunction::iterator SuccPrev = --SuccBB->getIterator(); 1591 1592 // If this block doesn't already fall-through to that successor, and if 1593 // the succ doesn't already have a block that can fall through into it, 1594 // and if the successor isn't an EH destination, we can arrange for the 1595 // fallthrough to happen. 1596 if (SuccBB != MBB && &*SuccPrev != MBB && 1597 !SuccPrev->canFallThrough() && !CurUnAnalyzable && 1598 !SuccBB->isEHPad()) { 1599 MBB->moveBefore(SuccBB); 1600 MadeChange = true; 1601 goto ReoptimizeBlock; 1602 } 1603 } 1604 1605 // Okay, there is no really great place to put this block. If, however, 1606 // the block before this one would be a fall-through if this block were 1607 // removed, move this block to the end of the function. There is no real 1608 // advantage in "falling through" to an EH block, so we don't want to 1609 // perform this transformation for that case. 1610 // 1611 // Also, Windows EH introduced the possibility of an arbitrary number of 1612 // successors to a given block. The analyzeBranch call does not consider 1613 // exception handling and so we can get in a state where a block 1614 // containing a call is followed by multiple EH blocks that would be 1615 // rotated infinitely at the end of the function if the transformation 1616 // below were performed for EH "FallThrough" blocks. Therefore, even if 1617 // that appears not to be happening anymore, we should assume that it is 1618 // possible and not remove the "!FallThrough()->isEHPad" condition below. 1619 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr; 1620 SmallVector<MachineOperand, 4> PrevCond; 1621 if (FallThrough != MF.end() && 1622 !FallThrough->isEHPad() && 1623 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) && 1624 PrevBB.isSuccessor(&*FallThrough)) { 1625 MBB->moveAfter(&MF.back()); 1626 MadeChange = true; 1627 return MadeChange; 1628 } 1629 } 1630 } 1631 1632 return MadeChange; 1633 } 1634 1635 //===----------------------------------------------------------------------===// 1636 // Hoist Common Code 1637 //===----------------------------------------------------------------------===// 1638 1639 /// HoistCommonCode - Hoist common instruction sequences at the start of basic 1640 /// blocks to their common predecessor. 1641 bool BranchFolder::HoistCommonCode(MachineFunction &MF) { 1642 bool MadeChange = false; 1643 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) { 1644 MachineBasicBlock *MBB = &*I++; 1645 MadeChange |= HoistCommonCodeInSuccs(MBB); 1646 } 1647 1648 return MadeChange; 1649 } 1650 1651 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given 1652 /// its 'true' successor. 1653 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB, 1654 MachineBasicBlock *TrueBB) { 1655 for (MachineBasicBlock *SuccBB : BB->successors()) 1656 if (SuccBB != TrueBB) 1657 return SuccBB; 1658 return nullptr; 1659 } 1660 1661 template <class Container> 1662 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI, 1663 Container &Set) { 1664 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1665 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 1666 Set.insert(*AI); 1667 } else { 1668 Set.insert(Reg); 1669 } 1670 } 1671 1672 /// findHoistingInsertPosAndDeps - Find the location to move common instructions 1673 /// in successors to. The location is usually just before the terminator, 1674 /// however if the terminator is a conditional branch and its previous 1675 /// instruction is the flag setting instruction, the previous instruction is 1676 /// the preferred location. This function also gathers uses and defs of the 1677 /// instructions from the insertion point to the end of the block. The data is 1678 /// used by HoistCommonCodeInSuccs to ensure safety. 1679 static 1680 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB, 1681 const TargetInstrInfo *TII, 1682 const TargetRegisterInfo *TRI, 1683 SmallSet<unsigned,4> &Uses, 1684 SmallSet<unsigned,4> &Defs) { 1685 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); 1686 if (!TII->isUnpredicatedTerminator(*Loc)) 1687 return MBB->end(); 1688 1689 for (const MachineOperand &MO : Loc->operands()) { 1690 if (!MO.isReg()) 1691 continue; 1692 unsigned Reg = MO.getReg(); 1693 if (!Reg) 1694 continue; 1695 if (MO.isUse()) { 1696 addRegAndItsAliases(Reg, TRI, Uses); 1697 } else { 1698 if (!MO.isDead()) 1699 // Don't try to hoist code in the rare case the terminator defines a 1700 // register that is later used. 1701 return MBB->end(); 1702 1703 // If the terminator defines a register, make sure we don't hoist 1704 // the instruction whose def might be clobbered by the terminator. 1705 addRegAndItsAliases(Reg, TRI, Defs); 1706 } 1707 } 1708 1709 if (Uses.empty()) 1710 return Loc; 1711 if (Loc == MBB->begin()) 1712 return MBB->end(); 1713 1714 // The terminator is probably a conditional branch, try not to separate the 1715 // branch from condition setting instruction. 1716 MachineBasicBlock::iterator PI = 1717 skipDebugInstructionsBackward(std::prev(Loc), MBB->begin()); 1718 1719 bool IsDef = false; 1720 for (const MachineOperand &MO : PI->operands()) { 1721 // If PI has a regmask operand, it is probably a call. Separate away. 1722 if (MO.isRegMask()) 1723 return Loc; 1724 if (!MO.isReg() || MO.isUse()) 1725 continue; 1726 unsigned Reg = MO.getReg(); 1727 if (!Reg) 1728 continue; 1729 if (Uses.count(Reg)) { 1730 IsDef = true; 1731 break; 1732 } 1733 } 1734 if (!IsDef) 1735 // The condition setting instruction is not just before the conditional 1736 // branch. 1737 return Loc; 1738 1739 // Be conservative, don't insert instruction above something that may have 1740 // side-effects. And since it's potentially bad to separate flag setting 1741 // instruction from the conditional branch, just abort the optimization 1742 // completely. 1743 // Also avoid moving code above predicated instruction since it's hard to 1744 // reason about register liveness with predicated instruction. 1745 bool DontMoveAcrossStore = true; 1746 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI)) 1747 return MBB->end(); 1748 1749 1750 // Find out what registers are live. Note this routine is ignoring other live 1751 // registers which are only used by instructions in successor blocks. 1752 for (const MachineOperand &MO : PI->operands()) { 1753 if (!MO.isReg()) 1754 continue; 1755 unsigned Reg = MO.getReg(); 1756 if (!Reg) 1757 continue; 1758 if (MO.isUse()) { 1759 addRegAndItsAliases(Reg, TRI, Uses); 1760 } else { 1761 if (Uses.erase(Reg)) { 1762 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1763 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) 1764 Uses.erase(*SubRegs); // Use sub-registers to be conservative 1765 } 1766 } 1767 addRegAndItsAliases(Reg, TRI, Defs); 1768 } 1769 } 1770 1771 return PI; 1772 } 1773 1774 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction 1775 /// sequence at the start of the function, move the instructions before MBB 1776 /// terminator if it's legal. 1777 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) { 1778 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1779 SmallVector<MachineOperand, 4> Cond; 1780 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty()) 1781 return false; 1782 1783 if (!FBB) FBB = findFalseBlock(MBB, TBB); 1784 if (!FBB) 1785 // Malformed bcc? True and false blocks are the same? 1786 return false; 1787 1788 // Restrict the optimization to cases where MBB is the only predecessor, 1789 // it is an obvious win. 1790 if (TBB->pred_size() > 1 || FBB->pred_size() > 1) 1791 return false; 1792 1793 // Find a suitable position to hoist the common instructions to. Also figure 1794 // out which registers are used or defined by instructions from the insertion 1795 // point to the end of the block. 1796 SmallSet<unsigned, 4> Uses, Defs; 1797 MachineBasicBlock::iterator Loc = 1798 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs); 1799 if (Loc == MBB->end()) 1800 return false; 1801 1802 bool HasDups = false; 1803 SmallVector<unsigned, 4> LocalDefs; 1804 SmallSet<unsigned, 4> LocalDefsSet; 1805 MachineBasicBlock::iterator TIB = TBB->begin(); 1806 MachineBasicBlock::iterator FIB = FBB->begin(); 1807 MachineBasicBlock::iterator TIE = TBB->end(); 1808 MachineBasicBlock::iterator FIE = FBB->end(); 1809 while (TIB != TIE && FIB != FIE) { 1810 // Skip dbg_value instructions. These do not count. 1811 TIB = skipDebugInstructionsForward(TIB, TIE); 1812 FIB = skipDebugInstructionsForward(FIB, FIE); 1813 if (TIB == TIE || FIB == FIE) 1814 break; 1815 1816 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead)) 1817 break; 1818 1819 if (TII->isPredicated(*TIB)) 1820 // Hard to reason about register liveness with predicated instruction. 1821 break; 1822 1823 bool IsSafe = true; 1824 for (MachineOperand &MO : TIB->operands()) { 1825 // Don't attempt to hoist instructions with register masks. 1826 if (MO.isRegMask()) { 1827 IsSafe = false; 1828 break; 1829 } 1830 if (!MO.isReg()) 1831 continue; 1832 unsigned Reg = MO.getReg(); 1833 if (!Reg) 1834 continue; 1835 if (MO.isDef()) { 1836 if (Uses.count(Reg)) { 1837 // Avoid clobbering a register that's used by the instruction at 1838 // the point of insertion. 1839 IsSafe = false; 1840 break; 1841 } 1842 1843 if (Defs.count(Reg) && !MO.isDead()) { 1844 // Don't hoist the instruction if the def would be clobber by the 1845 // instruction at the point insertion. FIXME: This is overly 1846 // conservative. It should be possible to hoist the instructions 1847 // in BB2 in the following example: 1848 // BB1: 1849 // r1, eflag = op1 r2, r3 1850 // brcc eflag 1851 // 1852 // BB2: 1853 // r1 = op2, ... 1854 // = op3, r1<kill> 1855 IsSafe = false; 1856 break; 1857 } 1858 } else if (!LocalDefsSet.count(Reg)) { 1859 if (Defs.count(Reg)) { 1860 // Use is defined by the instruction at the point of insertion. 1861 IsSafe = false; 1862 break; 1863 } 1864 1865 if (MO.isKill() && Uses.count(Reg)) 1866 // Kills a register that's read by the instruction at the point of 1867 // insertion. Remove the kill marker. 1868 MO.setIsKill(false); 1869 } 1870 } 1871 if (!IsSafe) 1872 break; 1873 1874 bool DontMoveAcrossStore = true; 1875 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore)) 1876 break; 1877 1878 // Remove kills from LocalDefsSet, these registers had short live ranges. 1879 for (const MachineOperand &MO : TIB->operands()) { 1880 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 1881 continue; 1882 unsigned Reg = MO.getReg(); 1883 if (!Reg || !LocalDefsSet.count(Reg)) 1884 continue; 1885 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1886 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 1887 LocalDefsSet.erase(*AI); 1888 } else { 1889 LocalDefsSet.erase(Reg); 1890 } 1891 } 1892 1893 // Track local defs so we can update liveins. 1894 for (const MachineOperand &MO : TIB->operands()) { 1895 if (!MO.isReg() || !MO.isDef() || MO.isDead()) 1896 continue; 1897 unsigned Reg = MO.getReg(); 1898 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg)) 1899 continue; 1900 LocalDefs.push_back(Reg); 1901 addRegAndItsAliases(Reg, TRI, LocalDefsSet); 1902 } 1903 1904 HasDups = true; 1905 ++TIB; 1906 ++FIB; 1907 } 1908 1909 if (!HasDups) 1910 return false; 1911 1912 MBB->splice(Loc, TBB, TBB->begin(), TIB); 1913 FBB->erase(FBB->begin(), FIB); 1914 1915 // Update livein's. 1916 bool AddedLiveIns = false; 1917 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) { 1918 unsigned Def = LocalDefs[i]; 1919 if (LocalDefsSet.count(Def)) { 1920 TBB->addLiveIn(Def); 1921 FBB->addLiveIn(Def); 1922 AddedLiveIns = true; 1923 } 1924 } 1925 1926 if (AddedLiveIns) { 1927 TBB->sortUniqueLiveIns(); 1928 FBB->sortUniqueLiveIns(); 1929 } 1930 1931 ++NumHoist; 1932 return true; 1933 } 1934