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