2169 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This pass forwards branches to unconditional branches to make them branch10// directly to the target block. This pass often results in dead MBB's, which11// it then removes.12//13// Note that this pass must be run after register allocation, it cannot handle14// SSA form. It also must handle virtual registers for targets that emit virtual15// 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/BranchFoldingPass.h"28#include "llvm/CodeGen/MBFIWrapper.h"29#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"30#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"31#include "llvm/CodeGen/MachineFunction.h"32#include "llvm/CodeGen/MachineFunctionPass.h"33#include "llvm/CodeGen/MachineInstr.h"34#include "llvm/CodeGen/MachineInstrBuilder.h"35#include "llvm/CodeGen/MachineJumpTableInfo.h"36#include "llvm/CodeGen/MachineLoopInfo.h"37#include "llvm/CodeGen/MachineOperand.h"38#include "llvm/CodeGen/MachineRegisterInfo.h"39#include "llvm/CodeGen/MachineSizeOpts.h"40#include "llvm/CodeGen/TargetInstrInfo.h"41#include "llvm/CodeGen/TargetOpcodes.h"42#include "llvm/CodeGen/TargetPassConfig.h"43#include "llvm/CodeGen/TargetRegisterInfo.h"44#include "llvm/CodeGen/TargetSubtargetInfo.h"45#include "llvm/Config/llvm-config.h"46#include "llvm/IR/DebugInfoMetadata.h"47#include "llvm/IR/DebugLoc.h"48#include "llvm/IR/Function.h"49#include "llvm/InitializePasses.h"50#include "llvm/MC/LaneBitmask.h"51#include "llvm/MC/MCRegisterInfo.h"52#include "llvm/Pass.h"53#include "llvm/Support/BlockFrequency.h"54#include "llvm/Support/BranchProbability.h"55#include "llvm/Support/CommandLine.h"56#include "llvm/Support/Debug.h"57#include "llvm/Support/ErrorHandling.h"58#include "llvm/Support/raw_ostream.h"59#include "llvm/Target/TargetMachine.h"60#include <cassert>61#include <cstddef>62#include <iterator>63#include <numeric>64 65using namespace llvm;66 67#define DEBUG_TYPE "branch-folder"68 69STATISTIC(NumDeadBlocks, "Number of dead blocks removed");70STATISTIC(NumBranchOpts, "Number of branches optimized");71STATISTIC(NumTailMerge , "Number of block tails merged");72STATISTIC(NumHoist , "Number of times common instructions are hoisted");73STATISTIC(NumTailCalls, "Number of tail calls optimized");74 75static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",76 cl::init(cl::BOU_UNSET), cl::Hidden);77 78// Throttle for huge numbers of predecessors (compile speed problems)79static cl::opt<unsigned>80TailMergeThreshold("tail-merge-threshold",81 cl::desc("Max number of predecessors to consider tail merging"),82 cl::init(150), cl::Hidden);83 84// Heuristic for tail merging (and, inversely, tail duplication).85static cl::opt<unsigned>86TailMergeSize("tail-merge-size",87 cl::desc("Min number of instructions to consider tail merging"),88 cl::init(3), cl::Hidden);89 90namespace {91 92 /// BranchFolderPass - Wrap branch folder in a machine function pass.93class BranchFolderLegacy : public MachineFunctionPass {94public:95 static char ID;96 97 explicit BranchFolderLegacy() : MachineFunctionPass(ID) {}98 99 bool runOnMachineFunction(MachineFunction &MF) override;100 101 void getAnalysisUsage(AnalysisUsage &AU) const override {102 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();103 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();104 AU.addRequired<ProfileSummaryInfoWrapperPass>();105 AU.addRequired<TargetPassConfig>();106 MachineFunctionPass::getAnalysisUsage(AU);107 }108 109 MachineFunctionProperties getRequiredProperties() const override {110 return MachineFunctionProperties().setNoPHIs();111 }112};113 114} // end anonymous namespace115 116char BranchFolderLegacy::ID = 0;117 118char &llvm::BranchFolderPassID = BranchFolderLegacy::ID;119 120INITIALIZE_PASS(BranchFolderLegacy, DEBUG_TYPE, "Control Flow Optimizer", false,121 false)122 123PreservedAnalyses BranchFolderPass::run(MachineFunction &MF,124 MachineFunctionAnalysisManager &MFAM) {125 MFPropsModifier _(*this, MF);126 bool EnableTailMerge =127 !MF.getTarget().requiresStructuredCFG() && this->EnableTailMerge;128 129 auto &MBPI = MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);130 auto *PSI = MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(MF)131 .getCachedResult<ProfileSummaryAnalysis>(132 *MF.getFunction().getParent());133 if (!PSI)134 report_fatal_error(135 "ProfileSummaryAnalysis is required for BranchFoldingPass", false);136 137 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);138 MBFIWrapper MBBFreqInfo(MBFI);139 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo, MBPI,140 PSI);141 if (!Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),142 MF.getSubtarget().getRegisterInfo()))143 return PreservedAnalyses::all();144 return getMachineFunctionPassPreservedAnalyses();145}146 147bool BranchFolderLegacy::runOnMachineFunction(MachineFunction &MF) {148 if (skipFunction(MF.getFunction()))149 return false;150 151 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();152 // TailMerge can create jump into if branches that make CFG irreducible for153 // HW that requires structurized CFG.154 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&155 PassConfig->getEnableTailMerge();156 MBFIWrapper MBBFreqInfo(157 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());158 BranchFolder Folder(159 EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,160 getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(),161 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());162 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),163 MF.getSubtarget().getRegisterInfo());164}165 166BranchFolder::BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist,167 MBFIWrapper &FreqInfo,168 const MachineBranchProbabilityInfo &ProbInfo,169 ProfileSummaryInfo *PSI, unsigned MinTailLength)170 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),171 MBBFreqInfo(FreqInfo), MBPI(ProbInfo), PSI(PSI) {172 switch (FlagEnableTailMerge) {173 case cl::BOU_UNSET:174 EnableTailMerge = DefaultEnableTailMerge;175 break;176 case cl::BOU_TRUE: EnableTailMerge = true; break;177 case cl::BOU_FALSE: EnableTailMerge = false; break;178 }179}180 181void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {182 assert(MBB->pred_empty() && "MBB must be dead!");183 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);184 185 MachineFunction *MF = MBB->getParent();186 // drop all successors.187 while (!MBB->succ_empty())188 MBB->removeSuccessor(MBB->succ_end()-1);189 190 // Avoid matching if this pointer gets reused.191 TriedMerging.erase(MBB);192 193 // Update call info.194 for (const MachineInstr &MI : *MBB)195 if (MI.shouldUpdateAdditionalCallInfo())196 MF->eraseAdditionalCallInfo(&MI);197 198 // Remove the block.199 MF->erase(MBB);200 EHScopeMembership.erase(MBB);201 if (MLI)202 MLI->removeBlock(MBB);203}204 205bool BranchFolder::OptimizeFunction(MachineFunction &MF,206 const TargetInstrInfo *tii,207 const TargetRegisterInfo *tri,208 MachineLoopInfo *mli, bool AfterPlacement) {209 if (!tii) return false;210 211 TriedMerging.clear();212 213 MachineRegisterInfo &MRI = MF.getRegInfo();214 AfterBlockPlacement = AfterPlacement;215 TII = tii;216 TRI = tri;217 MLI = mli;218 this->MRI = &MRI;219 220 if (MinCommonTailLength == 0) {221 MinCommonTailLength = TailMergeSize.getNumOccurrences() > 0222 ? TailMergeSize223 : TII->getTailMergeSize(MF);224 }225 226 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);227 if (!UpdateLiveIns)228 MRI.invalidateLiveness();229 230 bool MadeChange = false;231 232 // Recalculate EH scope membership.233 EHScopeMembership = getEHScopeMembership(MF);234 235 bool MadeChangeThisIteration = true;236 while (MadeChangeThisIteration) {237 MadeChangeThisIteration = TailMergeBlocks(MF);238 // No need to clean up if tail merging does not change anything after the239 // block placement.240 if (!AfterBlockPlacement || MadeChangeThisIteration)241 MadeChangeThisIteration |= OptimizeBranches(MF);242 if (EnableHoistCommonCode)243 MadeChangeThisIteration |= HoistCommonCode(MF);244 MadeChange |= MadeChangeThisIteration;245 }246 247 // See if any jump tables have become dead as the code generator248 // did its thing.249 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();250 if (!JTI)251 return MadeChange;252 253 // Walk the function to find jump tables that are live.254 BitVector JTIsLive(JTI->getJumpTables().size());255 for (const MachineBasicBlock &BB : MF) {256 for (const MachineInstr &I : BB)257 for (const MachineOperand &Op : I.operands()) {258 if (!Op.isJTI()) continue;259 260 // Remember that this JT is live.261 JTIsLive.set(Op.getIndex());262 }263 }264 265 // Finally, remove dead jump tables. This happens when the266 // indirect jump was unreachable (and thus deleted).267 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)268 if (!JTIsLive.test(i)) {269 JTI->RemoveJumpTable(i);270 MadeChange = true;271 }272 273 return MadeChange;274}275 276//===----------------------------------------------------------------------===//277// Tail Merging of Blocks278//===----------------------------------------------------------------------===//279 280/// HashMachineInstr - Compute a hash value for MI and its operands.281static unsigned HashMachineInstr(const MachineInstr &MI) {282 unsigned Hash = MI.getOpcode();283 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {284 const MachineOperand &Op = MI.getOperand(i);285 286 // Merge in bits from the operand if easy. We can't use MachineOperand's287 // hash_code here because it's not deterministic and we sort by hash value288 // later.289 unsigned OperandHash = 0;290 switch (Op.getType()) {291 case MachineOperand::MO_Register:292 OperandHash = Op.getReg().id();293 break;294 case MachineOperand::MO_Immediate:295 OperandHash = Op.getImm();296 break;297 case MachineOperand::MO_MachineBasicBlock:298 OperandHash = Op.getMBB()->getNumber();299 break;300 case MachineOperand::MO_FrameIndex:301 case MachineOperand::MO_ConstantPoolIndex:302 case MachineOperand::MO_JumpTableIndex:303 OperandHash = Op.getIndex();304 break;305 case MachineOperand::MO_GlobalAddress:306 case MachineOperand::MO_ExternalSymbol:307 // Global address / external symbol are too hard, don't bother, but do308 // pull in the offset.309 OperandHash = Op.getOffset();310 break;311 default:312 break;313 }314 315 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);316 }317 return Hash;318}319 320/// HashEndOfMBB - Hash the last instruction in the MBB.321static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {322 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(false);323 if (I == MBB.end())324 return 0;325 326 return HashMachineInstr(*I);327}328 329/// Whether MI should be counted as an instruction when calculating common tail.330static bool countsAsInstruction(const MachineInstr &MI) {331 return !(MI.isDebugInstr() || MI.isCFIInstruction());332}333 334/// Iterate backwards from the given iterator \p I, towards the beginning of the335/// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator336/// pointing to that MI. If no such MI is found, return the end iterator.337static MachineBasicBlock::iterator338skipBackwardPastNonInstructions(MachineBasicBlock::iterator I,339 MachineBasicBlock *MBB) {340 while (I != MBB->begin()) {341 --I;342 if (countsAsInstruction(*I))343 return I;344 }345 return MBB->end();346}347 348/// Given two machine basic blocks, return the number of instructions they349/// actually have in common together at their end. If a common tail is found (at350/// least by one instruction), then iterators for the first shared instruction351/// in each block are returned as well.352///353/// Non-instructions according to countsAsInstruction are ignored.354static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,355 MachineBasicBlock *MBB2,356 MachineBasicBlock::iterator &I1,357 MachineBasicBlock::iterator &I2) {358 MachineBasicBlock::iterator MBBI1 = MBB1->end();359 MachineBasicBlock::iterator MBBI2 = MBB2->end();360 361 unsigned TailLen = 0;362 while (true) {363 MBBI1 = skipBackwardPastNonInstructions(MBBI1, MBB1);364 MBBI2 = skipBackwardPastNonInstructions(MBBI2, MBB2);365 if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end())366 break;367 if (!MBBI1->isIdenticalTo(*MBBI2) ||368 // FIXME: This check is dubious. It's used to get around a problem where369 // people incorrectly expect inline asm directives to remain in the same370 // relative order. This is untenable because normal compiler371 // optimizations (like this one) may reorder and/or merge these372 // directives.373 MBBI1->isInlineAsm()) {374 break;375 }376 if (MBBI1->getFlag(MachineInstr::NoMerge) ||377 MBBI2->getFlag(MachineInstr::NoMerge))378 break;379 ++TailLen;380 I1 = MBBI1;381 I2 = MBBI2;382 }383 384 return TailLen;385}386 387void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,388 MachineBasicBlock &NewDest) {389 if (UpdateLiveIns) {390 // OldInst should always point to an instruction.391 MachineBasicBlock &OldMBB = *OldInst->getParent();392 LiveRegs.clear();393 LiveRegs.addLiveOuts(OldMBB);394 // Move backward to the place where will insert the jump.395 MachineBasicBlock::iterator I = OldMBB.end();396 do {397 --I;398 LiveRegs.stepBackward(*I);399 } while (I != OldInst);400 401 // Merging the tails may have switched some undef operand to non-undef ones.402 // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the403 // register.404 for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {405 // We computed the liveins with computeLiveIn earlier and should only see406 // full registers:407 assert(P.LaneMask == LaneBitmask::getAll() &&408 "Can only handle full register.");409 MCRegister Reg = P.PhysReg;410 if (!LiveRegs.available(*MRI, Reg))411 continue;412 DebugLoc DL;413 BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg);414 }415 }416 417 TII->ReplaceTailWithBranchTo(OldInst, &NewDest);418 ++NumTailMerge;419}420 421MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,422 MachineBasicBlock::iterator BBI1,423 const BasicBlock *BB) {424 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))425 return nullptr;426 427 MachineFunction &MF = *CurMBB.getParent();428 429 // Create the fall-through block.430 MachineFunction::iterator MBBI = CurMBB.getIterator();431 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);432 CurMBB.getParent()->insert(++MBBI, NewMBB);433 434 // Move all the successors of this block to the specified block.435 NewMBB->transferSuccessors(&CurMBB);436 437 // Add an edge from CurMBB to NewMBB for the fall-through.438 CurMBB.addSuccessor(NewMBB);439 440 // Splice the code over.441 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());442 443 // NewMBB belongs to the same loop as CurMBB.444 if (MLI)445 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))446 ML->addBasicBlockToLoop(NewMBB, *MLI);447 448 // NewMBB inherits CurMBB's block frequency.449 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));450 451 if (UpdateLiveIns)452 computeAndAddLiveIns(LiveRegs, *NewMBB);453 454 // Add the new block to the EH scope.455 const auto &EHScopeI = EHScopeMembership.find(&CurMBB);456 if (EHScopeI != EHScopeMembership.end()) {457 auto n = EHScopeI->second;458 EHScopeMembership[NewMBB] = n;459 }460 461 return NewMBB;462}463 464/// EstimateRuntime - Make a rough estimate for how long it will take to run465/// the specified code.466static unsigned EstimateRuntime(MachineBasicBlock::iterator I,467 MachineBasicBlock::iterator E) {468 unsigned Time = 0;469 for (; I != E; ++I) {470 if (!countsAsInstruction(*I))471 continue;472 if (I->isCall())473 Time += 10;474 else if (I->mayLoadOrStore())475 Time += 2;476 else477 ++Time;478 }479 return Time;480}481 482// CurMBB needs to add an unconditional branch to SuccMBB (we removed these483// branches temporarily for tail merging). In the case where CurMBB ends484// with a conditional branch to the next block, optimize by reversing the485// test and conditionally branching to SuccMBB instead.486static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,487 const TargetInstrInfo *TII, const DebugLoc &BranchDL) {488 MachineFunction *MF = CurMBB->getParent();489 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));490 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;491 SmallVector<MachineOperand, 4> Cond;492 DebugLoc dl = CurMBB->findBranchDebugLoc();493 if (!dl)494 dl = BranchDL;495 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {496 MachineBasicBlock *NextBB = &*I;497 if (TBB == NextBB && !Cond.empty() && !FBB) {498 if (!TII->reverseBranchCondition(Cond)) {499 TII->removeBranch(*CurMBB);500 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);501 return;502 }503 }504 }505 TII->insertBranch(*CurMBB, SuccBB, nullptr,506 SmallVector<MachineOperand, 0>(), dl);507}508 509bool510BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {511 if (getHash() < o.getHash())512 return true;513 if (getHash() > o.getHash())514 return false;515 if (getBlock()->getNumber() < o.getBlock()->getNumber())516 return true;517 if (getBlock()->getNumber() > o.getBlock()->getNumber())518 return false;519 return false;520}521 522/// CountTerminators - Count the number of terminators in the given523/// block and set I to the position of the first non-terminator, if there524/// is one, or MBB->end() otherwise.525static unsigned CountTerminators(MachineBasicBlock *MBB,526 MachineBasicBlock::iterator &I) {527 I = MBB->end();528 unsigned NumTerms = 0;529 while (true) {530 if (I == MBB->begin()) {531 I = MBB->end();532 break;533 }534 --I;535 if (!I->isTerminator()) break;536 ++NumTerms;537 }538 return NumTerms;539}540 541/// A no successor, non-return block probably ends in unreachable and is cold.542/// Also consider a block that ends in an indirect branch to be a return block,543/// since many targets use plain indirect branches to return.544static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {545 if (!MBB->succ_empty())546 return false;547 if (MBB->empty())548 return true;549 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());550}551 552/// ProfitableToMerge - Check if two machine basic blocks have a common tail553/// and decide if it would be profitable to merge those tails. Return the554/// length of the common tail and iterators to the first common instruction555/// in each block.556/// MBB1, MBB2 The blocks to check557/// MinCommonTailLength Minimum size of tail block to be merged.558/// CommonTailLen Out parameter to record the size of the shared tail between559/// MBB1 and MBB2560/// I1, I2 Iterator references that will be changed to point to the first561/// instruction in the common tail shared by MBB1,MBB2562/// SuccBB A common successor of MBB1, MBB2 which are in a canonical form563/// relative to SuccBB564/// PredBB The layout predecessor of SuccBB, if any.565/// EHScopeMembership map from block to EH scope #.566/// AfterPlacement True if we are merging blocks after layout. Stricter567/// thresholds apply to prevent undoing tail-duplication.568static bool569ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,570 unsigned MinCommonTailLength, unsigned &CommonTailLen,571 MachineBasicBlock::iterator &I1,572 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,573 MachineBasicBlock *PredBB,574 DenseMap<const MachineBasicBlock *, int> &EHScopeMembership,575 bool AfterPlacement,576 MBFIWrapper &MBBFreqInfo,577 ProfileSummaryInfo *PSI) {578 // It is never profitable to tail-merge blocks from two different EH scopes.579 if (!EHScopeMembership.empty()) {580 auto EHScope1 = EHScopeMembership.find(MBB1);581 assert(EHScope1 != EHScopeMembership.end());582 auto EHScope2 = EHScopeMembership.find(MBB2);583 assert(EHScope2 != EHScopeMembership.end());584 if (EHScope1->second != EHScope2->second)585 return false;586 }587 588 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);589 if (CommonTailLen == 0)590 return false;591 LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)592 << " and " << printMBBReference(*MBB2) << " is "593 << CommonTailLen << '\n');594 595 // Move the iterators to the beginning of the MBB if we only got debug596 // instructions before the tail. This is to avoid splitting a block when we597 // only got debug instructions before the tail (to be invariant on -g).598 if (skipDebugInstructionsForward(MBB1->begin(), MBB1->end(), false) == I1)599 I1 = MBB1->begin();600 if (skipDebugInstructionsForward(MBB2->begin(), MBB2->end(), false) == I2)601 I2 = MBB2->begin();602 603 bool FullBlockTail1 = I1 == MBB1->begin();604 bool FullBlockTail2 = I2 == MBB2->begin();605 606 // It's almost always profitable to merge any number of non-terminator607 // instructions with the block that falls through into the common successor.608 // This is true only for a single successor. For multiple successors, we are609 // trading a conditional branch for an unconditional one.610 // TODO: Re-visit successor size for non-layout tail merging.611 if ((MBB1 == PredBB || MBB2 == PredBB) &&612 (!AfterPlacement || MBB1->succ_size() == 1)) {613 MachineBasicBlock::iterator I;614 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);615 if (CommonTailLen > NumTerms)616 return true;617 }618 619 // If these are identical non-return blocks with no successors, merge them.620 // Such blocks are typically cold calls to noreturn functions like abort, and621 // are unlikely to become a fallthrough target after machine block placement.622 // Tail merging these blocks is unlikely to create additional unconditional623 // branches, and will reduce the size of this cold code.624 if (FullBlockTail1 && FullBlockTail2 &&625 blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))626 return true;627 628 // If one of the blocks can be completely merged and happens to be in629 // a position where the other could fall through into it, merge any number630 // of instructions, because it can be done without a branch.631 // TODO: If the blocks are not adjacent, move one of them so that they are?632 if (MBB1->isLayoutSuccessor(MBB2) && FullBlockTail2)633 return true;634 if (MBB2->isLayoutSuccessor(MBB1) && FullBlockTail1)635 return true;636 637 // If both blocks are identical and end in a branch, merge them unless they638 // both have a fallthrough predecessor and successor.639 // We can only do this after block placement because it depends on whether640 // there are fallthroughs, and we don't know until after layout.641 if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {642 auto BothFallThrough = [](MachineBasicBlock *MBB) {643 if (!MBB->succ_empty() && !MBB->canFallThrough())644 return false;645 MachineFunction::iterator I(MBB);646 MachineFunction *MF = MBB->getParent();647 return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();648 };649 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))650 return true;651 }652 653 // If both blocks have an unconditional branch temporarily stripped out,654 // count that as an additional common instruction for the following655 // heuristics. This heuristic is only accurate for single-succ blocks, so to656 // make sure that during layout merging and duplicating don't crash, we check657 // for that when merging during layout.658 unsigned EffectiveTailLen = CommonTailLen;659 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&660 (MBB1->succ_size() == 1 || !AfterPlacement) &&661 !MBB1->back().isBarrier() &&662 !MBB2->back().isBarrier())663 ++EffectiveTailLen;664 665 // Check if the common tail is long enough to be worthwhile.666 if (EffectiveTailLen >= MinCommonTailLength)667 return true;668 669 // If we are optimizing for code size, 2 instructions in common is enough if670 // we don't have to split a block. At worst we will be introducing 1 new671 // branch instruction, which is likely to be smaller than the 2672 // instructions that would be deleted in the merge.673 bool OptForSize = llvm::shouldOptimizeForSize(MBB1, PSI, &MBBFreqInfo) &&674 llvm::shouldOptimizeForSize(MBB2, PSI, &MBBFreqInfo);675 return EffectiveTailLen >= 2 && OptForSize &&676 (FullBlockTail1 || FullBlockTail2);677}678 679unsigned BranchFolder::ComputeSameTails(unsigned CurHash,680 unsigned MinCommonTailLength,681 MachineBasicBlock *SuccBB,682 MachineBasicBlock *PredBB) {683 unsigned maxCommonTailLength = 0U;684 SameTails.clear();685 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;686 MPIterator HighestMPIter = std::prev(MergePotentials.end());687 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),688 B = MergePotentials.begin();689 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {690 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {691 unsigned CommonTailLen;692 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),693 MinCommonTailLength,694 CommonTailLen, TrialBBI1, TrialBBI2,695 SuccBB, PredBB,696 EHScopeMembership,697 AfterBlockPlacement, MBBFreqInfo, PSI)) {698 if (CommonTailLen > maxCommonTailLength) {699 SameTails.clear();700 maxCommonTailLength = CommonTailLen;701 HighestMPIter = CurMPIter;702 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));703 }704 if (HighestMPIter == CurMPIter &&705 CommonTailLen == maxCommonTailLength)706 SameTails.push_back(SameTailElt(I, TrialBBI2));707 }708 if (I == B)709 break;710 }711 }712 return maxCommonTailLength;713}714 715void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,716 MachineBasicBlock *SuccBB,717 MachineBasicBlock *PredBB,718 const DebugLoc &BranchDL) {719 MPIterator CurMPIter, B;720 for (CurMPIter = std::prev(MergePotentials.end()),721 B = MergePotentials.begin();722 CurMPIter->getHash() == CurHash; --CurMPIter) {723 // Put the unconditional branch back, if we need one.724 MachineBasicBlock *CurMBB = CurMPIter->getBlock();725 if (SuccBB && CurMBB != PredBB)726 FixTail(CurMBB, SuccBB, TII, BranchDL);727 if (CurMPIter == B)728 break;729 }730 if (CurMPIter->getHash() != CurHash)731 CurMPIter++;732 MergePotentials.erase(CurMPIter, MergePotentials.end());733}734 735bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,736 MachineBasicBlock *SuccBB,737 unsigned maxCommonTailLength,738 unsigned &commonTailIndex) {739 commonTailIndex = 0;740 unsigned TimeEstimate = ~0U;741 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {742 // Use PredBB if possible; that doesn't require a new branch.743 if (SameTails[i].getBlock() == PredBB) {744 commonTailIndex = i;745 break;746 }747 // Otherwise, make a (fairly bogus) choice based on estimate of748 // how long it will take the various blocks to execute.749 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),750 SameTails[i].getTailStartPos());751 if (t <= TimeEstimate) {752 TimeEstimate = t;753 commonTailIndex = i;754 }755 }756 757 MachineBasicBlock::iterator BBI =758 SameTails[commonTailIndex].getTailStartPos();759 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();760 761 LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "762 << maxCommonTailLength);763 764 // If the split block unconditionally falls-thru to SuccBB, it will be765 // merged. In control flow terms it should then take SuccBB's name. e.g. If766 // SuccBB is an inner loop, the common tail is still part of the inner loop.767 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?768 SuccBB->getBasicBlock() : MBB->getBasicBlock();769 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);770 if (!newMBB) {771 LLVM_DEBUG(dbgs() << "... failed!");772 return false;773 }774 775 SameTails[commonTailIndex].setBlock(newMBB);776 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());777 778 // If we split PredBB, newMBB is the new predecessor.779 if (PredBB == MBB)780 PredBB = newMBB;781 782 return true;783}784 785static void786mergeOperations(MachineBasicBlock::iterator MBBIStartPos,787 MachineBasicBlock &MBBCommon) {788 MachineBasicBlock *MBB = MBBIStartPos->getParent();789 // Note CommonTailLen does not necessarily matches the size of790 // the common BB nor all its instructions because of debug791 // instructions differences.792 unsigned CommonTailLen = 0;793 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)794 ++CommonTailLen;795 796 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();797 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();798 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();799 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();800 801 while (CommonTailLen--) {802 assert(MBBI != MBBIE && "Reached BB end within common tail length!");803 (void)MBBIE;804 805 if (!countsAsInstruction(*MBBI)) {806 ++MBBI;807 continue;808 }809 810 while ((MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon))811 ++MBBICommon;812 813 assert(MBBICommon != MBBIECommon &&814 "Reached BB end within common tail length!");815 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");816 817 // Merge MMOs from memory operations in the common block.818 if (MBBICommon->mayLoadOrStore())819 MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI});820 // Drop undef flags if they aren't present in all merged instructions.821 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {822 MachineOperand &MO = MBBICommon->getOperand(I);823 if (MO.isReg() && MO.isUndef()) {824 const MachineOperand &OtherMO = MBBI->getOperand(I);825 if (!OtherMO.isUndef())826 MO.setIsUndef(false);827 }828 }829 830 ++MBBI;831 ++MBBICommon;832 }833}834 835void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {836 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();837 838 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());839 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {840 if (i != commonTailIndex) {841 NextCommonInsts[i] = SameTails[i].getTailStartPos();842 mergeOperations(SameTails[i].getTailStartPos(), *MBB);843 } else {844 assert(SameTails[i].getTailStartPos() == MBB->begin() &&845 "MBB is not a common tail only block");846 }847 }848 849 for (auto &MI : *MBB) {850 if (!countsAsInstruction(MI))851 continue;852 DebugLoc DL = MI.getDebugLoc();853 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {854 if (i == commonTailIndex)855 continue;856 857 auto &Pos = NextCommonInsts[i];858 assert(Pos != SameTails[i].getBlock()->end() &&859 "Reached BB end within common tail");860 while (!countsAsInstruction(*Pos)) {861 ++Pos;862 assert(Pos != SameTails[i].getBlock()->end() &&863 "Reached BB end within common tail");864 }865 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");866 DL = DebugLoc::getMergedLocation(DL, Pos->getDebugLoc());867 NextCommonInsts[i] = ++Pos;868 }869 MI.setDebugLoc(DL);870 }871 872 if (UpdateLiveIns) {873 LivePhysRegs NewLiveIns(*TRI);874 computeLiveIns(NewLiveIns, *MBB);875 LiveRegs.init(*TRI);876 877 // The flag merging may lead to some register uses no longer using the878 // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.879 for (MachineBasicBlock *Pred : MBB->predecessors()) {880 LiveRegs.clear();881 LiveRegs.addLiveOuts(*Pred);882 MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();883 for (Register Reg : NewLiveIns) {884 if (!LiveRegs.available(*MRI, Reg))885 continue;886 887 // Skip the register if we are about to add one of its super registers.888 // TODO: Common this up with the same logic in addLineIns().889 if (any_of(TRI->superregs(Reg), [&](MCPhysReg SReg) {890 return NewLiveIns.contains(SReg) && !MRI->isReserved(SReg);891 }))892 continue;893 894 DebugLoc DL;895 BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF),896 Reg);897 }898 }899 900 MBB->clearLiveIns();901 addLiveIns(*MBB, NewLiveIns);902 }903}904 905// See if any of the blocks in MergePotentials (which all have SuccBB as a906// successor, or all have no successor if it is null) can be tail-merged.907// If there is a successor, any blocks in MergePotentials that are not908// tail-merged and are not immediately before Succ must have an unconditional909// branch to Succ added (but the predecessor/successor lists need no910// adjustment). The lone predecessor of Succ that falls through into Succ,911// if any, is given in PredBB.912// MinCommonTailLength - Except for the special cases below, tail-merge if913// there are at least this many instructions in common.914bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,915 MachineBasicBlock *PredBB,916 unsigned MinCommonTailLength) {917 bool MadeChange = false;918 919 LLVM_DEBUG({920 dbgs() << "\nTryTailMergeBlocks: ";921 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)922 dbgs() << printMBBReference(*MergePotentials[i].getBlock())923 << (i == e - 1 ? "" : ", ");924 dbgs() << "\n";925 if (SuccBB) {926 dbgs() << " with successor " << printMBBReference(*SuccBB) << '\n';927 if (PredBB)928 dbgs() << " which has fall-through from " << printMBBReference(*PredBB)929 << "\n";930 }931 dbgs() << "Looking for common tails of at least " << MinCommonTailLength932 << " instruction" << (MinCommonTailLength == 1 ? "" : "s") << '\n';933 });934 935 // Sort by hash value so that blocks with identical end sequences sort936 // together.937#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN938 // If origin-tracking is enabled then MergePotentialElt is no longer a POD939 // type, so we need std::sort instead.940 std::sort(MergePotentials.begin(), MergePotentials.end());941#else942 array_pod_sort(MergePotentials.begin(), MergePotentials.end());943#endif944 945 // Walk through equivalence sets looking for actual exact matches.946 while (MergePotentials.size() > 1) {947 unsigned CurHash = MergePotentials.back().getHash();948 const DebugLoc &BranchDL = MergePotentials.back().getBranchDebugLoc();949 950 // Build SameTails, identifying the set of blocks with this hash code951 // and with the maximum number of instructions in common.952 unsigned maxCommonTailLength = ComputeSameTails(CurHash,953 MinCommonTailLength,954 SuccBB, PredBB);955 956 // If we didn't find any pair that has at least MinCommonTailLength957 // instructions in common, remove all blocks with this hash code and retry.958 if (SameTails.empty()) {959 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);960 continue;961 }962 963 // If one of the blocks is the entire common tail (and is not the entry964 // block/an EH pad, which we can't jump to), we can treat all blocks with965 // this same tail at once. Use PredBB if that is one of the possibilities,966 // as that will not introduce any extra branches.967 MachineBasicBlock *EntryBB =968 &MergePotentials.front().getBlock()->getParent()->front();969 unsigned commonTailIndex = SameTails.size();970 // If there are two blocks, check to see if one can be made to fall through971 // into the other.972 if (SameTails.size() == 2 &&973 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&974 SameTails[1].tailIsWholeBlock() && !SameTails[1].getBlock()->isEHPad())975 commonTailIndex = 1;976 else if (SameTails.size() == 2 &&977 SameTails[1].getBlock()->isLayoutSuccessor(978 SameTails[0].getBlock()) &&979 SameTails[0].tailIsWholeBlock() &&980 !SameTails[0].getBlock()->isEHPad())981 commonTailIndex = 0;982 else {983 // Otherwise just pick one, favoring the fall-through predecessor if984 // there is one.985 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {986 MachineBasicBlock *MBB = SameTails[i].getBlock();987 if ((MBB == EntryBB || MBB->isEHPad()) &&988 SameTails[i].tailIsWholeBlock())989 continue;990 if (MBB == PredBB) {991 commonTailIndex = i;992 break;993 }994 if (SameTails[i].tailIsWholeBlock())995 commonTailIndex = i;996 }997 }998 999 if (commonTailIndex == SameTails.size() ||1000 (SameTails[commonTailIndex].getBlock() == PredBB &&1001 !SameTails[commonTailIndex].tailIsWholeBlock())) {1002 // None of the blocks consist entirely of the common tail.1003 // Split a block so that one does.1004 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,1005 maxCommonTailLength, commonTailIndex)) {1006 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);1007 continue;1008 }1009 }1010 1011 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();1012 1013 // Recompute common tail MBB's edge weights and block frequency.1014 setCommonTailEdgeWeights(*MBB);1015 1016 // Merge debug locations, MMOs and undef flags across identical instructions1017 // for common tail.1018 mergeCommonTails(commonTailIndex);1019 1020 // MBB is common tail. Adjust all other BB's to jump to this one.1021 // Traversal must be forwards so erases work.1022 LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)1023 << " for ");1024 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {1025 if (commonTailIndex == i)1026 continue;1027 LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())1028 << (i == e - 1 ? "" : ", "));1029 // Hack the end off BB i, making it jump to BB commonTailIndex instead.1030 replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);1031 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.1032 MergePotentials.erase(SameTails[i].getMPIter());1033 }1034 LLVM_DEBUG(dbgs() << "\n");1035 // We leave commonTailIndex in the worklist in case there are other blocks1036 // that match it with a smaller number of instructions.1037 MadeChange = true;1038 }1039 return MadeChange;1040}1041 1042bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {1043 bool MadeChange = false;1044 if (!EnableTailMerge)1045 return MadeChange;1046 1047 // First find blocks with no successors.1048 // Block placement may create new tail merging opportunities for these blocks.1049 MergePotentials.clear();1050 for (MachineBasicBlock &MBB : MF) {1051 if (MergePotentials.size() == TailMergeThreshold)1052 break;1053 if (!TriedMerging.count(&MBB) && MBB.succ_empty())1054 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB,1055 MBB.findBranchDebugLoc()));1056 }1057 1058 // If this is a large problem, avoid visiting the same basic blocks1059 // multiple times.1060 if (MergePotentials.size() == TailMergeThreshold)1061 for (const MergePotentialsElt &Elt : MergePotentials)1062 TriedMerging.insert(Elt.getBlock());1063 1064 // See if we can do any tail merging on those.1065 if (MergePotentials.size() >= 2)1066 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);1067 1068 // Look at blocks (IBB) with multiple predecessors (PBB).1069 // We change each predecessor to a canonical form, by1070 // (1) temporarily removing any unconditional branch from the predecessor1071 // to IBB, and1072 // (2) alter conditional branches so they branch to the other block1073 // not IBB; this may require adding back an unconditional branch to IBB1074 // later, where there wasn't one coming in. E.g.1075 // Bcc IBB1076 // fallthrough to QBB1077 // here becomes1078 // Bncc QBB1079 // with a conceptual B to IBB after that, which never actually exists.1080 // With those changes, we see whether the predecessors' tails match,1081 // and merge them if so. We change things out of canonical form and1082 // back to the way they were later in the process. (OptimizeBranches1083 // would undo some of this, but we can't use it, because we'd get into1084 // a compile-time infinite loop repeatedly doing and undoing the same1085 // transformations.)1086 1087 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();1088 I != E; ++I) {1089 if (I->pred_size() < 2) continue;1090 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;1091 MachineBasicBlock *IBB = &*I;1092 MachineBasicBlock *PredBB = &*std::prev(I);1093 MergePotentials.clear();1094 MachineLoop *ML;1095 1096 // Bail if merging after placement and IBB is the loop header because1097 // -- If merging predecessors that belong to the same loop as IBB, the1098 // common tail of merged predecessors may become the loop top if block1099 // placement is called again and the predecessors may branch to this common1100 // tail and require more branches. This can be relaxed if1101 // MachineBlockPlacement::findBestLoopTop is more flexible.1102 // --If merging predecessors that do not belong to the same loop as IBB, the1103 // loop info of IBB's loop and the other loops may be affected. Calling the1104 // block placement again may make big change to the layout and eliminate the1105 // reason to do tail merging here.1106 if (AfterBlockPlacement && MLI) {1107 ML = MLI->getLoopFor(IBB);1108 if (ML && IBB == ML->getHeader())1109 continue;1110 }1111 1112 for (MachineBasicBlock *PBB : I->predecessors()) {1113 if (MergePotentials.size() == TailMergeThreshold)1114 break;1115 1116 if (TriedMerging.count(PBB))1117 continue;1118 1119 // Skip blocks that loop to themselves, can't tail merge these.1120 if (PBB == IBB)1121 continue;1122 1123 // Visit each predecessor only once.1124 if (!UniquePreds.insert(PBB).second)1125 continue;1126 1127 // Skip blocks which may jump to a landing pad or jump from an asm blob.1128 // Can't tail merge these.1129 if (PBB->hasEHPadSuccessor() || PBB->mayHaveInlineAsmBr())1130 continue;1131 1132 // After block placement, only consider predecessors that belong to the1133 // same loop as IBB. The reason is the same as above when skipping loop1134 // header.1135 if (AfterBlockPlacement && MLI)1136 if (ML != MLI->getLoopFor(PBB))1137 continue;1138 1139 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;1140 SmallVector<MachineOperand, 4> Cond;1141 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {1142 // Failing case: IBB is the target of a cbr, and we cannot reverse the1143 // branch.1144 SmallVector<MachineOperand, 4> NewCond(Cond);1145 if (!Cond.empty() && TBB == IBB) {1146 if (TII->reverseBranchCondition(NewCond))1147 continue;1148 // This is the QBB case described above1149 if (!FBB) {1150 auto Next = ++PBB->getIterator();1151 if (Next != MF.end())1152 FBB = &*Next;1153 }1154 }1155 1156 // Remove the unconditional branch at the end, if any.1157 DebugLoc dl = PBB->findBranchDebugLoc();1158 if (TBB && (Cond.empty() || FBB)) {1159 TII->removeBranch(*PBB);1160 if (!Cond.empty())1161 // reinsert conditional branch only, for now1162 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,1163 NewCond, dl);1164 }1165 1166 MergePotentials.push_back(1167 MergePotentialsElt(HashEndOfMBB(*PBB), PBB, dl));1168 }1169 }1170 1171 // If this is a large problem, avoid visiting the same basic blocks multiple1172 // times.1173 if (MergePotentials.size() == TailMergeThreshold)1174 for (MergePotentialsElt &Elt : MergePotentials)1175 TriedMerging.insert(Elt.getBlock());1176 1177 if (MergePotentials.size() >= 2)1178 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);1179 1180 // Reinsert an unconditional branch if needed. The 1 below can occur as a1181 // result of removing blocks in TryTailMergeBlocks.1182 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks1183 if (MergePotentials.size() == 1 &&1184 MergePotentials.begin()->getBlock() != PredBB)1185 FixTail(MergePotentials.begin()->getBlock(), IBB, TII,1186 MergePotentials.begin()->getBranchDebugLoc());1187 }1188 1189 return MadeChange;1190}1191 1192void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {1193 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());1194 BlockFrequency AccumulatedMBBFreq;1195 1196 // Aggregate edge frequency of successor edge j:1197 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),1198 // where bb is a basic block that is in SameTails.1199 for (const auto &Src : SameTails) {1200 const MachineBasicBlock *SrcMBB = Src.getBlock();1201 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);1202 AccumulatedMBBFreq += BlockFreq;1203 1204 // It is not necessary to recompute edge weights if TailBB has less than two1205 // successors.1206 if (TailMBB.succ_size() <= 1)1207 continue;1208 1209 auto EdgeFreq = EdgeFreqLs.begin();1210 1211 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();1212 SuccI != SuccE; ++SuccI, ++EdgeFreq)1213 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);1214 }1215 1216 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);1217 1218 if (TailMBB.succ_size() <= 1)1219 return;1220 1221 auto SumEdgeFreq =1222 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))1223 .getFrequency();1224 auto EdgeFreq = EdgeFreqLs.begin();1225 1226 if (SumEdgeFreq > 0) {1227 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();1228 SuccI != SuccE; ++SuccI, ++EdgeFreq) {1229 auto Prob = BranchProbability::getBranchProbability(1230 EdgeFreq->getFrequency(), SumEdgeFreq);1231 TailMBB.setSuccProbability(SuccI, Prob);1232 }1233 }1234}1235 1236//===----------------------------------------------------------------------===//1237// Branch Optimization1238//===----------------------------------------------------------------------===//1239 1240bool BranchFolder::OptimizeBranches(MachineFunction &MF) {1241 bool MadeChange = false;1242 1243 // Make sure blocks are numbered in order1244 MF.RenumberBlocks();1245 // Renumbering blocks alters EH scope membership, recalculate it.1246 EHScopeMembership = getEHScopeMembership(MF);1247 1248 for (MachineBasicBlock &MBB :1249 llvm::make_early_inc_range(llvm::drop_begin(MF))) {1250 MadeChange |= OptimizeBlock(&MBB);1251 1252 // If it is dead, remove it.1253 if (MBB.pred_empty() && !MBB.isMachineBlockAddressTaken()) {1254 RemoveDeadBlock(&MBB);1255 MadeChange = true;1256 ++NumDeadBlocks;1257 }1258 }1259 1260 return MadeChange;1261}1262 1263// Blocks should be considered empty if they contain only debug info;1264// else the debug info would affect codegen.1265static bool IsEmptyBlock(MachineBasicBlock *MBB) {1266 return MBB->getFirstNonDebugInstr(true) == MBB->end();1267}1268 1269// Blocks with only debug info and branches should be considered the same1270// as blocks with only branches.1271static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {1272 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();1273 assert(I != MBB->end() && "empty block!");1274 return I->isBranch();1275}1276 1277/// IsBetterFallthrough - Return true if it would be clearly better to1278/// fall-through to MBB1 than to fall through into MBB2. This has to return1279/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will1280/// result in infinite loops.1281static bool IsBetterFallthrough(MachineBasicBlock *MBB1,1282 MachineBasicBlock *MBB2) {1283 assert(MBB1 && MBB2 && "Unknown MachineBasicBlock");1284 1285 // Right now, we use a simple heuristic. If MBB2 ends with a call, and1286 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to1287 // optimize branches that branch to either a return block or an assert block1288 // into a fallthrough to the return.1289 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();1290 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();1291 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())1292 return false;1293 1294 // If there is a clear successor ordering we make sure that one block1295 // will fall through to the next1296 if (MBB1->isSuccessor(MBB2)) return true;1297 if (MBB2->isSuccessor(MBB1)) return false;1298 1299 return MBB2I->isCall() && !MBB1I->isCall();1300}1301 1302static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII,1303 MachineBasicBlock &MBB,1304 MachineBasicBlock &PredMBB) {1305 auto InsertBefore = PredMBB.getFirstTerminator();1306 for (MachineInstr &MI : MBB.instrs())1307 if (MI.isDebugInstr()) {1308 TII->duplicate(PredMBB, InsertBefore, MI);1309 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "1310 << MI);1311 }1312}1313 1314static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII,1315 MachineBasicBlock &MBB,1316 MachineBasicBlock &SuccMBB) {1317 auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin());1318 for (MachineInstr &MI : MBB.instrs())1319 if (MI.isDebugInstr()) {1320 TII->duplicate(SuccMBB, InsertBefore, MI);1321 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "1322 << MI);1323 }1324}1325 1326// Try to salvage DBG_VALUE instructions from an otherwise empty block. If such1327// a basic block is removed we would lose the debug information unless we have1328// copied the information to a predecessor/successor.1329//1330// TODO: This function only handles some simple cases. An alternative would be1331// to run a heavier analysis, such as the LiveDebugValues pass, before we do1332// branch folding.1333static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,1334 MachineBasicBlock &MBB) {1335 assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");1336 // If this MBB is the only predecessor of a successor it is legal to copy1337 // DBG_VALUE instructions to the beginning of the successor.1338 for (MachineBasicBlock *SuccBB : MBB.successors())1339 if (SuccBB->pred_size() == 1)1340 copyDebugInfoToSuccessor(TII, MBB, *SuccBB);1341 // If this MBB is the only successor of a predecessor it is legal to copy the1342 // DBG_VALUE instructions to the end of the predecessor (just before the1343 // terminators, assuming that the terminator isn't affecting the DBG_VALUE).1344 for (MachineBasicBlock *PredBB : MBB.predecessors())1345 if (PredBB->succ_size() == 1)1346 copyDebugInfoToPredecessor(TII, MBB, *PredBB);1347}1348 1349bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {1350 bool MadeChange = false;1351 MachineFunction &MF = *MBB->getParent();1352ReoptimizeBlock:1353 1354 MachineFunction::iterator FallThrough = MBB->getIterator();1355 ++FallThrough;1356 1357 // Make sure MBB and FallThrough belong to the same EH scope.1358 bool SameEHScope = true;1359 if (!EHScopeMembership.empty() && FallThrough != MF.end()) {1360 auto MBBEHScope = EHScopeMembership.find(MBB);1361 assert(MBBEHScope != EHScopeMembership.end());1362 auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);1363 assert(FallThroughEHScope != EHScopeMembership.end());1364 SameEHScope = MBBEHScope->second == FallThroughEHScope->second;1365 }1366 1367 // Analyze the branch in the current block. As a side-effect, this may cause1368 // the block to become empty.1369 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;1370 SmallVector<MachineOperand, 4> CurCond;1371 bool CurUnAnalyzable =1372 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);1373 1374 // If this block is empty, make everyone use its fall-through, not the block1375 // explicitly. Landing pads should not do this since the landing-pad table1376 // points to this block. Blocks with their addresses taken shouldn't be1377 // optimized away.1378 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&1379 SameEHScope) {1380 salvageDebugInfoFromEmptyBlock(TII, *MBB);1381 // Dead block? Leave for cleanup later.1382 if (MBB->pred_empty()) return MadeChange;1383 1384 if (FallThrough == MF.end()) {1385 // TODO: Simplify preds to not branch here if possible!1386 } else if (FallThrough->isEHPad()) {1387 // Don't rewrite to a landing pad fallthough. That could lead to the case1388 // where a BB jumps to more than one landing pad.1389 // TODO: Is it ever worth rewriting predecessors which don't already1390 // jump to a landing pad, and so can safely jump to the fallthrough?1391 } else if (MBB->isSuccessor(&*FallThrough)) {1392 // Rewrite all predecessors of the old block to go to the fallthrough1393 // instead.1394 while (!MBB->pred_empty()) {1395 MachineBasicBlock *Pred = *(MBB->pred_end()-1);1396 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);1397 }1398 // Add rest successors of MBB to successors of FallThrough. Those1399 // successors are not directly reachable via MBB, so it should be1400 // landing-pad.1401 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)1402 if (*SI != &*FallThrough && !FallThrough->isSuccessor(*SI)) {1403 assert((*SI)->isEHPad() && "Bad CFG");1404 FallThrough->copySuccessor(MBB, SI);1405 }1406 // If MBB was the target of a jump table, update jump tables to go to the1407 // fallthrough instead.1408 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())1409 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);1410 MadeChange = true;1411 }1412 return MadeChange;1413 }1414 1415 // Check to see if we can simplify the terminator of the block before this1416 // one.1417 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));1418 1419 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;1420 SmallVector<MachineOperand, 4> PriorCond;1421 bool PriorUnAnalyzable =1422 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);1423 if (!PriorUnAnalyzable) {1424 // If the previous branch is conditional and both conditions go to the same1425 // destination, remove the branch, replacing it with an unconditional one or1426 // a fall-through.1427 if (PriorTBB && PriorTBB == PriorFBB) {1428 DebugLoc Dl = PrevBB.findBranchDebugLoc();1429 TII->removeBranch(PrevBB);1430 PriorCond.clear();1431 if (PriorTBB != MBB)1432 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, Dl);1433 MadeChange = true;1434 ++NumBranchOpts;1435 goto ReoptimizeBlock;1436 }1437 1438 // If the previous block unconditionally falls through to this block and1439 // this block has no other predecessors, move the contents of this block1440 // into the prior block. This doesn't usually happen when SimplifyCFG1441 // has been used, but it can happen if tail merging splits a fall-through1442 // predecessor of a block.1443 // This has to check PrevBB->succ_size() because EH edges are ignored by1444 // analyzeBranch.1445 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&1446 PrevBB.succ_size() == 1 && PrevBB.isSuccessor(MBB) &&1447 !MBB->hasAddressTaken() && !MBB->isEHPad()) {1448 LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB1449 << "From MBB: " << *MBB);1450 // Remove redundant DBG_VALUEs first.1451 if (!PrevBB.empty()) {1452 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();1453 --PrevBBIter;1454 MachineBasicBlock::iterator MBBIter = MBB->begin();1455 // Check if DBG_VALUE at the end of PrevBB is identical to the1456 // DBG_VALUE at the beginning of MBB.1457 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()1458 && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {1459 if (!MBBIter->isIdenticalTo(*PrevBBIter))1460 break;1461 MachineInstr &DuplicateDbg = *MBBIter;1462 ++MBBIter; -- PrevBBIter;1463 DuplicateDbg.eraseFromParent();1464 }1465 }1466 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());1467 PrevBB.removeSuccessor(PrevBB.succ_begin());1468 assert(PrevBB.succ_empty());1469 PrevBB.transferSuccessors(MBB);1470 MadeChange = true;1471 return MadeChange;1472 }1473 1474 // If the previous branch *only* branches to *this* block (conditional or1475 // not) remove the branch.1476 if (PriorTBB == MBB && !PriorFBB) {1477 TII->removeBranch(PrevBB);1478 MadeChange = true;1479 ++NumBranchOpts;1480 goto ReoptimizeBlock;1481 }1482 1483 // If the prior block branches somewhere else on the condition and here if1484 // the condition is false, remove the uncond second branch.1485 if (PriorFBB == MBB) {1486 DebugLoc Dl = PrevBB.findBranchDebugLoc();1487 TII->removeBranch(PrevBB);1488 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, Dl);1489 MadeChange = true;1490 ++NumBranchOpts;1491 goto ReoptimizeBlock;1492 }1493 1494 // If the prior block branches here on true and somewhere else on false, and1495 // if the branch condition is reversible, reverse the branch to create a1496 // fall-through.1497 if (PriorTBB == MBB) {1498 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);1499 if (!TII->reverseBranchCondition(NewPriorCond)) {1500 DebugLoc Dl = PrevBB.findBranchDebugLoc();1501 TII->removeBranch(PrevBB);1502 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, Dl);1503 MadeChange = true;1504 ++NumBranchOpts;1505 goto ReoptimizeBlock;1506 }1507 }1508 1509 // If this block has no successors (e.g. it is a return block or ends with1510 // a call to a no-return function like abort or __cxa_throw) and if the pred1511 // falls through into this block, and if it would otherwise fall through1512 // into the block after this, move this block to the end of the function.1513 //1514 // We consider it more likely that execution will stay in the function (e.g.1515 // due to loops) than it is to exit it. This asserts in loops etc, moving1516 // the assert condition out of the loop body.1517 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&1518 MachineFunction::iterator(PriorTBB) == FallThrough &&1519 !MBB->canFallThrough()) {1520 bool DoTransform = true;1521 1522 // We have to be careful that the succs of PredBB aren't both no-successor1523 // blocks. If neither have successors and if PredBB is the second from1524 // last block in the function, we'd just keep swapping the two blocks for1525 // last. Only do the swap if one is clearly better to fall through than1526 // the other.1527 if (FallThrough == --MF.end() &&1528 !IsBetterFallthrough(PriorTBB, MBB))1529 DoTransform = false;1530 1531 if (DoTransform) {1532 // Reverse the branch so we will fall through on the previous true cond.1533 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);1534 if (!TII->reverseBranchCondition(NewPriorCond)) {1535 LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB1536 << "To make fallthrough to: " << *PriorTBB << "\n");1537 1538 DebugLoc Dl = PrevBB.findBranchDebugLoc();1539 TII->removeBranch(PrevBB);1540 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, Dl);1541 1542 // Move this block to the end of the function.1543 MBB->moveAfter(&MF.back());1544 MadeChange = true;1545 ++NumBranchOpts;1546 return MadeChange;1547 }1548 }1549 }1550 }1551 1552 if (!IsEmptyBlock(MBB)) {1553 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();1554 if (TII->isUnconditionalTailCall(TailCall)) {1555 SmallVector<MachineBasicBlock *> PredsChanged;1556 for (auto &Pred : MBB->predecessors()) {1557 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;1558 SmallVector<MachineOperand, 4> PredCond;1559 bool PredAnalyzable =1560 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);1561 1562 // Only eliminate if MBB == TBB (Taken Basic Block)1563 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB &&1564 PredTBB != PredFBB) {1565 // The predecessor has a conditional branch to this block which1566 // consists of only a tail call. Try to fold the tail call into the1567 // conditional branch.1568 if (TII->canMakeTailCallConditional(PredCond, TailCall)) {1569 // TODO: It would be nice if analyzeBranch() could provide a pointer1570 // to the branch instruction so replaceBranchWithTailCall() doesn't1571 // have to search for it.1572 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);1573 PredsChanged.push_back(Pred);1574 }1575 }1576 // If the predecessor is falling through to this block, we could reverse1577 // the branch condition and fold the tail call into that. However, after1578 // that we might have to re-arrange the CFG to fall through to the other1579 // block and there is a high risk of regressing code size rather than1580 // improving it.1581 }1582 if (!PredsChanged.empty()) {1583 NumTailCalls += PredsChanged.size();1584 for (auto &Pred : PredsChanged)1585 Pred->removeSuccessor(MBB);1586 1587 return true;1588 }1589 }1590 }1591 1592 if (!CurUnAnalyzable) {1593 // If this is a two-way branch, and the FBB branches to this block, reverse1594 // the condition so the single-basic-block loop is faster. Instead of:1595 // Loop: xxx; jcc Out; jmp Loop1596 // we want:1597 // Loop: xxx; jncc Loop; jmp Out1598 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {1599 SmallVector<MachineOperand, 4> NewCond(CurCond);1600 if (!TII->reverseBranchCondition(NewCond)) {1601 DebugLoc Dl = MBB->findBranchDebugLoc();1602 TII->removeBranch(*MBB);1603 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, Dl);1604 MadeChange = true;1605 ++NumBranchOpts;1606 goto ReoptimizeBlock;1607 }1608 }1609 1610 // If this branch is the only thing in its block, see if we can forward1611 // other blocks across it.1612 if (CurTBB && CurCond.empty() && !CurFBB &&1613 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&1614 !MBB->hasAddressTaken() && !MBB->isEHPad()) {1615 DebugLoc Dl = MBB->findBranchDebugLoc();1616 // This block may contain just an unconditional branch. Because there can1617 // be 'non-branch terminators' in the block, try removing the branch and1618 // then seeing if the block is empty.1619 TII->removeBranch(*MBB);1620 // If the only things remaining in the block are debug info, remove these1621 // as well, so this will behave the same as an empty block in non-debug1622 // mode.1623 if (IsEmptyBlock(MBB)) {1624 // Make the block empty, losing the debug info (we could probably1625 // improve this in some cases.)1626 MBB->erase(MBB->begin(), MBB->end());1627 }1628 // If this block is just an unconditional branch to CurTBB, we can1629 // usually completely eliminate the block. The only case we cannot1630 // completely eliminate the block is when the block before this one1631 // falls through into MBB and we can't understand the prior block's branch1632 // condition.1633 if (MBB->empty()) {1634 bool PredHasNoFallThrough = !PrevBB.canFallThrough();1635 if (PredHasNoFallThrough || !PriorUnAnalyzable ||1636 !PrevBB.isSuccessor(MBB)) {1637 // If the prior block falls through into us, turn it into an1638 // explicit branch to us to make updates simpler.1639 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&1640 PriorTBB != MBB && PriorFBB != MBB) {1641 if (!PriorTBB) {1642 assert(PriorCond.empty() && !PriorFBB &&1643 "Bad branch analysis");1644 PriorTBB = MBB;1645 } else {1646 assert(!PriorFBB && "Machine CFG out of date!");1647 PriorFBB = MBB;1648 }1649 DebugLoc PrevDl = PrevBB.findBranchDebugLoc();1650 TII->removeBranch(PrevBB);1651 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, PrevDl);1652 }1653 1654 // Iterate through all the predecessors, revectoring each in-turn.1655 size_t PI = 0;1656 bool DidChange = false;1657 bool HasBranchToSelf = false;1658 while(PI != MBB->pred_size()) {1659 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);1660 if (PMBB == MBB) {1661 // If this block has an uncond branch to itself, leave it.1662 ++PI;1663 HasBranchToSelf = true;1664 } else {1665 DidChange = true;1666 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);1667 // Add rest successors of MBB to successors of CurTBB. Those1668 // successors are not directly reachable via MBB, so it should be1669 // landing-pad.1670 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE;1671 ++SI)1672 if (*SI != CurTBB && !CurTBB->isSuccessor(*SI)) {1673 assert((*SI)->isEHPad() && "Bad CFG");1674 CurTBB->copySuccessor(MBB, SI);1675 }1676 // If this change resulted in PMBB ending in a conditional1677 // branch where both conditions go to the same destination,1678 // change this to an unconditional branch.1679 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;1680 SmallVector<MachineOperand, 4> NewCurCond;1681 bool NewCurUnAnalyzable = TII->analyzeBranch(1682 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);1683 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {1684 DebugLoc PrevDl = PMBB->findBranchDebugLoc();1685 TII->removeBranch(*PMBB);1686 NewCurCond.clear();1687 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond,1688 PrevDl);1689 MadeChange = true;1690 ++NumBranchOpts;1691 }1692 }1693 }1694 1695 // Change any jumptables to go to the new MBB.1696 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())1697 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);1698 if (DidChange) {1699 ++NumBranchOpts;1700 MadeChange = true;1701 if (!HasBranchToSelf) return MadeChange;1702 }1703 }1704 }1705 1706 // Add the branch back if the block is more than just an uncond branch.1707 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, Dl);1708 }1709 }1710 1711 // If the prior block doesn't fall through into this block, and if this1712 // block doesn't fall through into some other block, see if we can find a1713 // place to move this block where a fall-through will happen.1714 if (!PrevBB.canFallThrough()) {1715 // Now we know that there was no fall-through into this block, check to1716 // see if it has a fall-through into its successor.1717 bool CurFallsThru = MBB->canFallThrough();1718 1719 if (!MBB->isEHPad()) {1720 // Check all the predecessors of this block. If one of them has no fall1721 // throughs, and analyzeBranch thinks it _could_ fallthrough to this1722 // block, move this block right after it.1723 for (MachineBasicBlock *PredBB : MBB->predecessors()) {1724 // Analyze the branch at the end of the pred.1725 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;1726 SmallVector<MachineOperand, 4> PredCond;1727 if (PredBB != MBB && !PredBB->canFallThrough() &&1728 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&1729 (PredTBB == MBB || PredFBB == MBB) &&1730 (!CurFallsThru || !CurTBB || !CurFBB) &&1731 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {1732 // If the current block doesn't fall through, just move it.1733 // If the current block can fall through and does not end with a1734 // conditional branch, we need to append an unconditional jump to1735 // the (current) next block. To avoid a possible compile-time1736 // infinite loop, move blocks only backward in this case.1737 // Also, if there are already 2 branches here, we cannot add a third;1738 // this means we have the case1739 // Bcc next1740 // B elsewhere1741 // next:1742 if (CurFallsThru) {1743 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());1744 CurCond.clear();1745 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());1746 }1747 MBB->moveAfter(PredBB);1748 MadeChange = true;1749 goto ReoptimizeBlock;1750 }1751 }1752 }1753 1754 if (!CurFallsThru) {1755 // Check analyzable branch-successors to see if we can move this block1756 // before one.1757 if (!CurUnAnalyzable) {1758 for (MachineBasicBlock *SuccBB : {CurFBB, CurTBB}) {1759 if (!SuccBB)1760 continue;1761 // Analyze the branch at the end of the block before the succ.1762 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();1763 1764 // If this block doesn't already fall-through to that successor, and1765 // if the succ doesn't already have a block that can fall through into1766 // it, we can arrange for the fallthrough to happen.1767 if (SuccBB != MBB && &*SuccPrev != MBB &&1768 !SuccPrev->canFallThrough()) {1769 MBB->moveBefore(SuccBB);1770 MadeChange = true;1771 goto ReoptimizeBlock;1772 }1773 }1774 }1775 1776 // Okay, there is no really great place to put this block. If, however,1777 // the block before this one would be a fall-through if this block were1778 // removed, move this block to the end of the function. There is no real1779 // advantage in "falling through" to an EH block, so we don't want to1780 // perform this transformation for that case.1781 //1782 // Also, Windows EH introduced the possibility of an arbitrary number of1783 // successors to a given block. The analyzeBranch call does not consider1784 // exception handling and so we can get in a state where a block1785 // containing a call is followed by multiple EH blocks that would be1786 // rotated infinitely at the end of the function if the transformation1787 // below were performed for EH "FallThrough" blocks. Therefore, even if1788 // that appears not to be happening anymore, we should assume that it is1789 // possible and not remove the "!FallThrough()->isEHPad" condition below.1790 //1791 // Similarly, the analyzeBranch call does not consider callbr, which also1792 // introduces the possibility of infinite rotation, as there may be1793 // multiple successors of PrevBB. Thus we check such case by1794 // FallThrough->isInlineAsmBrIndirectTarget().1795 // NOTE: Checking if PrevBB contains callbr is more precise, but much1796 // more expensive.1797 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;1798 SmallVector<MachineOperand, 4> PrevCond;1799 1800 if (FallThrough != MF.end() && !FallThrough->isEHPad() &&1801 !FallThrough->isInlineAsmBrIndirectTarget() &&1802 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&1803 PrevBB.isSuccessor(&*FallThrough)) {1804 MBB->moveAfter(&MF.back());1805 MadeChange = true;1806 return MadeChange;1807 }1808 }1809 }1810 1811 return MadeChange;1812}1813 1814//===----------------------------------------------------------------------===//1815// Hoist Common Code1816//===----------------------------------------------------------------------===//1817 1818bool BranchFolder::HoistCommonCode(MachineFunction &MF) {1819 bool MadeChange = false;1820 for (MachineBasicBlock &MBB : llvm::make_early_inc_range(MF))1821 MadeChange |= HoistCommonCodeInSuccs(&MBB);1822 1823 return MadeChange;1824}1825 1826/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given1827/// its 'true' successor.1828static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,1829 MachineBasicBlock *TrueBB) {1830 for (MachineBasicBlock *SuccBB : BB->successors())1831 if (SuccBB != TrueBB)1832 return SuccBB;1833 return nullptr;1834}1835 1836template <class Container>1837static void addRegAndItsAliases(Register Reg, const TargetRegisterInfo *TRI,1838 Container &Set) {1839 if (Reg.isPhysical()) {1840 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)1841 Set.insert(*AI);1842 } else {1843 Set.insert(Reg);1844 }1845}1846 1847/// findHoistingInsertPosAndDeps - Find the location to move common instructions1848/// in successors to. The location is usually just before the terminator,1849/// however if the terminator is a conditional branch and its previous1850/// instruction is the flag setting instruction, the previous instruction is1851/// the preferred location. This function also gathers uses and defs of the1852/// instructions from the insertion point to the end of the block. The data is1853/// used by HoistCommonCodeInSuccs to ensure safety.1854static1855MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,1856 const TargetInstrInfo *TII,1857 const TargetRegisterInfo *TRI,1858 SmallSet<Register, 4> &Uses,1859 SmallSet<Register, 4> &Defs) {1860 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();1861 if (!TII->isUnpredicatedTerminator(*Loc))1862 return MBB->end();1863 1864 for (const MachineOperand &MO : Loc->operands()) {1865 if (!MO.isReg())1866 continue;1867 Register Reg = MO.getReg();1868 if (!Reg)1869 continue;1870 if (MO.isUse()) {1871 addRegAndItsAliases(Reg, TRI, Uses);1872 } else {1873 if (!MO.isDead())1874 // Don't try to hoist code in the rare case the terminator defines a1875 // register that is later used.1876 return MBB->end();1877 1878 // If the terminator defines a register, make sure we don't hoist1879 // the instruction whose def might be clobbered by the terminator.1880 addRegAndItsAliases(Reg, TRI, Defs);1881 }1882 }1883 1884 if (Uses.empty())1885 return Loc;1886 // If the terminator is the only instruction in the block and Uses is not1887 // empty (or we would have returned above), we can still safely hoist1888 // instructions just before the terminator as long as the Defs/Uses are not1889 // violated (which is checked in HoistCommonCodeInSuccs).1890 if (Loc == MBB->begin())1891 return Loc;1892 1893 // The terminator is probably a conditional branch, try not to separate the1894 // branch from condition setting instruction.1895 MachineBasicBlock::iterator PI = prev_nodbg(Loc, MBB->begin());1896 1897 bool IsDef = false;1898 for (const MachineOperand &MO : PI->operands()) {1899 // If PI has a regmask operand, it is probably a call. Separate away.1900 if (MO.isRegMask())1901 return Loc;1902 if (!MO.isReg() || MO.isUse())1903 continue;1904 Register Reg = MO.getReg();1905 if (!Reg)1906 continue;1907 if (Uses.count(Reg)) {1908 IsDef = true;1909 break;1910 }1911 }1912 if (!IsDef)1913 // The condition setting instruction is not just before the conditional1914 // branch.1915 return Loc;1916 1917 // Be conservative, don't insert instruction above something that may have1918 // side-effects. And since it's potentially bad to separate flag setting1919 // instruction from the conditional branch, just abort the optimization1920 // completely.1921 // Also avoid moving code above predicated instruction since it's hard to1922 // reason about register liveness with predicated instruction.1923 bool DontMoveAcrossStore = true;1924 if (!PI->isSafeToMove(DontMoveAcrossStore) || TII->isPredicated(*PI))1925 return MBB->end();1926 1927 // Find out what registers are live. Note this routine is ignoring other live1928 // registers which are only used by instructions in successor blocks.1929 for (const MachineOperand &MO : PI->operands()) {1930 if (!MO.isReg())1931 continue;1932 Register Reg = MO.getReg();1933 if (!Reg)1934 continue;1935 if (MO.isUse()) {1936 addRegAndItsAliases(Reg, TRI, Uses);1937 } else {1938 if (Uses.erase(Reg)) {1939 if (Reg.isPhysical()) {1940 for (MCPhysReg SubReg : TRI->subregs(Reg))1941 Uses.erase(SubReg); // Use sub-registers to be conservative1942 }1943 }1944 addRegAndItsAliases(Reg, TRI, Defs);1945 }1946 }1947 1948 return PI;1949}1950 1951bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {1952 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;1953 SmallVector<MachineOperand, 4> Cond;1954 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())1955 return false;1956 1957 if (!FBB) FBB = findFalseBlock(MBB, TBB);1958 if (!FBB)1959 // Malformed bcc? True and false blocks are the same?1960 return false;1961 1962 // Restrict the optimization to cases where MBB is the only predecessor,1963 // it is an obvious win.1964 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)1965 return false;1966 1967 // Find a suitable position to hoist the common instructions to. Also figure1968 // out which registers are used or defined by instructions from the insertion1969 // point to the end of the block.1970 SmallSet<Register, 4> Uses, Defs;1971 MachineBasicBlock::iterator Loc =1972 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);1973 if (Loc == MBB->end())1974 return false;1975 1976 bool HasDups = false;1977 SmallSet<Register, 4> ActiveDefsSet, AllDefsSet;1978 MachineBasicBlock::iterator TIB = TBB->begin();1979 MachineBasicBlock::iterator FIB = FBB->begin();1980 MachineBasicBlock::iterator TIE = TBB->end();1981 MachineBasicBlock::iterator FIE = FBB->end();1982 MachineFunction &MF = *TBB->getParent();1983 while (TIB != TIE && FIB != FIE) {1984 // Skip dbg_value instructions. These do not count.1985 TIB = skipDebugInstructionsForward(TIB, TIE, false);1986 FIB = skipDebugInstructionsForward(FIB, FIE, false);1987 if (TIB == TIE || FIB == FIE)1988 break;1989 1990 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))1991 break;1992 1993 if (TII->isPredicated(*TIB))1994 // Hard to reason about register liveness with predicated instruction.1995 break;1996 1997 if (!TII->isSafeToMove(*TIB, TBB, MF))1998 // Don't hoist the instruction if it isn't safe to move.1999 break;2000 2001 bool IsSafe = true;2002 for (MachineOperand &MO : TIB->operands()) {2003 // Don't attempt to hoist instructions with register masks.2004 if (MO.isRegMask()) {2005 IsSafe = false;2006 break;2007 }2008 if (!MO.isReg())2009 continue;2010 Register Reg = MO.getReg();2011 if (!Reg)2012 continue;2013 if (MO.isDef()) {2014 if (Uses.count(Reg)) {2015 // Avoid clobbering a register that's used by the instruction at2016 // the point of insertion.2017 IsSafe = false;2018 break;2019 }2020 2021 if (Defs.count(Reg) && !MO.isDead()) {2022 // Don't hoist the instruction if the def would be clobber by the2023 // instruction at the point insertion. FIXME: This is overly2024 // conservative. It should be possible to hoist the instructions2025 // in BB2 in the following example:2026 // BB1:2027 // r1, eflag = op1 r2, r32028 // brcc eflag2029 //2030 // BB2:2031 // r1 = op2, ...2032 // = op3, killed r12033 IsSafe = false;2034 break;2035 }2036 } else if (!ActiveDefsSet.count(Reg)) {2037 if (Defs.count(Reg)) {2038 // Use is defined by the instruction at the point of insertion.2039 IsSafe = false;2040 break;2041 }2042 2043 if (MO.isKill() && Uses.count(Reg))2044 // Kills a register that's read by the instruction at the point of2045 // insertion. Remove the kill marker.2046 MO.setIsKill(false);2047 }2048 }2049 if (!IsSafe)2050 break;2051 2052 bool DontMoveAcrossStore = true;2053 if (!TIB->isSafeToMove(DontMoveAcrossStore))2054 break;2055 2056 // Remove kills from ActiveDefsSet, these registers had short live ranges.2057 for (const MachineOperand &MO : TIB->all_uses()) {2058 if (!MO.isKill())2059 continue;2060 Register Reg = MO.getReg();2061 if (!Reg)2062 continue;2063 if (!AllDefsSet.count(Reg)) {2064 continue;2065 }2066 if (Reg.isPhysical()) {2067 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)2068 ActiveDefsSet.erase(*AI);2069 } else {2070 ActiveDefsSet.erase(Reg);2071 }2072 }2073 2074 // Track local defs so we can update liveins.2075 for (const MachineOperand &MO : TIB->all_defs()) {2076 if (MO.isDead())2077 continue;2078 Register Reg = MO.getReg();2079 if (!Reg || Reg.isVirtual())2080 continue;2081 addRegAndItsAliases(Reg, TRI, ActiveDefsSet);2082 addRegAndItsAliases(Reg, TRI, AllDefsSet);2083 }2084 2085 HasDups = true;2086 ++TIB;2087 ++FIB;2088 }2089 2090 if (!HasDups)2091 return false;2092 2093 // Hoist the instructions from [T.begin, TIB) and then delete [F.begin, FIB).2094 // If we're hoisting from a single block then just splice. Else step through2095 // and merge the debug locations.2096 if (TBB == FBB) {2097 MBB->splice(Loc, TBB, TBB->begin(), TIB);2098 } else {2099 // Merge the debug locations, and hoist and kill the debug instructions from2100 // both branches. FIXME: We could probably try harder to preserve some debug2101 // instructions (but at least this isn't producing wrong locations).2102 MachineInstrBuilder MIRBuilder(*MBB->getParent(), Loc);2103 auto HoistAndKillDbgInstr = [MBB, Loc](MachineBasicBlock::iterator DI) {2104 assert(DI->isDebugInstr() && "Expected a debug instruction");2105 if (DI->isDebugRef()) {2106 const TargetInstrInfo *TII =2107 MBB->getParent()->getSubtarget().getInstrInfo();2108 const MCInstrDesc &DBGV = TII->get(TargetOpcode::DBG_VALUE);2109 DI = BuildMI(*MBB->getParent(), DI->getDebugLoc(), DBGV, false, 0,2110 DI->getDebugVariable(), DI->getDebugExpression());2111 MBB->insert(Loc, &*DI);2112 return;2113 }2114 // Deleting a DBG_PHI results in an undef at the referenced DBG_INSTR_REF.2115 if (DI->isDebugPHI()) {2116 DI->eraseFromParent();2117 return;2118 }2119 // Move DBG_LABELs without modifying them. Set DBG_VALUEs undef.2120 if (!DI->isDebugLabel())2121 DI->setDebugValueUndef();2122 DI->moveBefore(&*Loc);2123 };2124 2125 // TIB and FIB point to the end of the regions to hoist/merge in TBB and2126 // FBB.2127 MachineBasicBlock::iterator FE = FIB;2128 MachineBasicBlock::iterator FI = FBB->begin();2129 for (MachineBasicBlock::iterator TI :2130 make_early_inc_range(make_range(TBB->begin(), TIB))) {2131 // Hoist and kill debug instructions from FBB. After this loop FI points2132 // to the next non-debug instruction to hoist (checked in assert after the2133 // TBB debug instruction handling code).2134 while (FI != FE && FI->isDebugInstr())2135 HoistAndKillDbgInstr(FI++);2136 2137 // Kill debug instructions before moving.2138 if (TI->isDebugInstr()) {2139 HoistAndKillDbgInstr(TI);2140 continue;2141 }2142 2143 // FI and TI now point to identical non-debug instructions.2144 assert(FI != FE && "Unexpected end of FBB range");2145 // Pseudo probes are excluded from the range when identifying foldable2146 // instructions, so we don't expect to see one now.2147 assert(!TI->isPseudoProbe() && "Unexpected pseudo probe in range");2148 // NOTE: The loop above checks CheckKillDead but we can't do that here as2149 // it modifies some kill markers after the check.2150 assert(TI->isIdenticalTo(*FI, MachineInstr::CheckDefs) &&2151 "Expected non-debug lockstep");2152 2153 // Merge debug locs on hoisted instructions.2154 TI->setDebugLoc(2155 DILocation::getMergedLocation(TI->getDebugLoc(), FI->getDebugLoc()));2156 TI->moveBefore(&*Loc);2157 ++FI;2158 }2159 }2160 2161 FBB->erase(FBB->begin(), FIB);2162 2163 if (UpdateLiveIns)2164 fullyRecomputeLiveIns({TBB, FBB});2165 2166 ++NumHoist;2167 return true;2168}2169