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