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