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