xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/BranchFolding.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass forwards branches to unconditional branches to make them branch
100b57cec5SDimitry Andric // directly to the target block.  This pass often results in dead MBB's, which
110b57cec5SDimitry Andric // it then removes.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // Note that this pass must be run after register allocation, it cannot handle
140b57cec5SDimitry Andric // SSA form. It also must handle virtual registers for targets that emit virtual
150b57cec5SDimitry Andric // ISA (e.g. NVPTX).
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #include "BranchFolding.h"
200b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
25480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
2781ad6265SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
38480093f4SDimitry Andric #include "llvm/CodeGen/MachineSizeOpts.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
440b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
450b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
460b57cec5SDimitry Andric #include "llvm/IR/Function.h"
47480093f4SDimitry Andric #include "llvm/InitializePasses.h"
480b57cec5SDimitry Andric #include "llvm/MC/LaneBitmask.h"
490b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
500b57cec5SDimitry Andric #include "llvm/Pass.h"
510b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h"
520b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
530b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
540b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
550b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
560b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
570b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
580b57cec5SDimitry Andric #include <cassert>
590b57cec5SDimitry Andric #include <cstddef>
600b57cec5SDimitry Andric #include <iterator>
610b57cec5SDimitry Andric #include <numeric>
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric using namespace llvm;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric #define DEBUG_TYPE "branch-folder"
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
680b57cec5SDimitry Andric STATISTIC(NumBranchOpts, "Number of branches optimized");
690b57cec5SDimitry Andric STATISTIC(NumTailMerge , "Number of block tails merged");
700b57cec5SDimitry Andric STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
710b57cec5SDimitry Andric STATISTIC(NumTailCalls,  "Number of tail calls optimized");
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
740b57cec5SDimitry Andric                               cl::init(cl::BOU_UNSET), cl::Hidden);
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric // Throttle for huge numbers of predecessors (compile speed problems)
770b57cec5SDimitry Andric static cl::opt<unsigned>
780b57cec5SDimitry Andric TailMergeThreshold("tail-merge-threshold",
790b57cec5SDimitry Andric           cl::desc("Max number of predecessors to consider tail merging"),
800b57cec5SDimitry Andric           cl::init(150), cl::Hidden);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // Heuristic for tail merging (and, inversely, tail duplication).
830b57cec5SDimitry Andric static cl::opt<unsigned>
840b57cec5SDimitry Andric TailMergeSize("tail-merge-size",
850b57cec5SDimitry Andric               cl::desc("Min number of instructions to consider tail merging"),
860b57cec5SDimitry Andric               cl::init(3), cl::Hidden);
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric namespace {
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   /// BranchFolderPass - Wrap branch folder in a machine function pass.
910b57cec5SDimitry Andric   class BranchFolderPass : public MachineFunctionPass {
920b57cec5SDimitry Andric   public:
930b57cec5SDimitry Andric     static char ID;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
100*0fca6ea1SDimitry Andric       AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
101*0fca6ea1SDimitry Andric       AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
102480093f4SDimitry Andric       AU.addRequired<ProfileSummaryInfoWrapperPass>();
1030b57cec5SDimitry Andric       AU.addRequired<TargetPassConfig>();
1040b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
1050b57cec5SDimitry Andric     }
10681ad6265SDimitry Andric 
10781ad6265SDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
10881ad6265SDimitry Andric       return MachineFunctionProperties().set(
10981ad6265SDimitry Andric           MachineFunctionProperties::Property::NoPHIs);
11081ad6265SDimitry Andric     }
1110b57cec5SDimitry Andric   };
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric } // end anonymous namespace
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric char BranchFolderPass::ID = 0;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric char &llvm::BranchFolderPassID = BranchFolderPass::ID;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,
1200b57cec5SDimitry Andric                 "Control Flow Optimizer", false, false)
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
1230b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
1240b57cec5SDimitry Andric     return false;
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1270b57cec5SDimitry Andric   // TailMerge can create jump into if branches that make CFG irreducible for
1280b57cec5SDimitry Andric   // HW that requires structurized CFG.
1290b57cec5SDimitry Andric   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
1300b57cec5SDimitry Andric                          PassConfig->getEnableTailMerge();
1315ffd83dbSDimitry Andric   MBFIWrapper MBBFreqInfo(
132*0fca6ea1SDimitry Andric       getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
133*0fca6ea1SDimitry Andric   BranchFolder Folder(
134*0fca6ea1SDimitry Andric       EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
135*0fca6ea1SDimitry Andric       getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(),
136480093f4SDimitry Andric       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
1375ffd83dbSDimitry Andric   return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
1385ffd83dbSDimitry Andric                                  MF.getSubtarget().getRegisterInfo());
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric 
141e8d8bef9SDimitry Andric BranchFolder::BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist,
1420b57cec5SDimitry Andric                            MBFIWrapper &FreqInfo,
1430b57cec5SDimitry Andric                            const MachineBranchProbabilityInfo &ProbInfo,
144e8d8bef9SDimitry Andric                            ProfileSummaryInfo *PSI, unsigned MinTailLength)
1450b57cec5SDimitry Andric     : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
146480093f4SDimitry Andric       MBBFreqInfo(FreqInfo), MBPI(ProbInfo), PSI(PSI) {
1470b57cec5SDimitry Andric   switch (FlagEnableTailMerge) {
148e8d8bef9SDimitry Andric   case cl::BOU_UNSET:
149e8d8bef9SDimitry Andric     EnableTailMerge = DefaultEnableTailMerge;
150e8d8bef9SDimitry Andric     break;
1510b57cec5SDimitry Andric   case cl::BOU_TRUE: EnableTailMerge = true; break;
1520b57cec5SDimitry Andric   case cl::BOU_FALSE: EnableTailMerge = false; break;
1530b57cec5SDimitry Andric   }
1540b57cec5SDimitry Andric }
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
1570b57cec5SDimitry Andric   assert(MBB->pred_empty() && "MBB must be dead!");
1580b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   MachineFunction *MF = MBB->getParent();
1610b57cec5SDimitry Andric   // drop all successors.
1620b57cec5SDimitry Andric   while (!MBB->succ_empty())
1630b57cec5SDimitry Andric     MBB->removeSuccessor(MBB->succ_end()-1);
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   // Avoid matching if this pointer gets reused.
1660b57cec5SDimitry Andric   TriedMerging.erase(MBB);
1670b57cec5SDimitry Andric 
1688bcb0991SDimitry Andric   // Update call site info.
169fe6060f1SDimitry Andric   for (const MachineInstr &MI : *MBB)
1705ffd83dbSDimitry Andric     if (MI.shouldUpdateCallSiteInfo())
1718bcb0991SDimitry Andric       MF->eraseCallSiteInfo(&MI);
172fe6060f1SDimitry Andric 
1730b57cec5SDimitry Andric   // Remove the block.
1740b57cec5SDimitry Andric   MF->erase(MBB);
1750b57cec5SDimitry Andric   EHScopeMembership.erase(MBB);
1760b57cec5SDimitry Andric   if (MLI)
1770b57cec5SDimitry Andric     MLI->removeBlock(MBB);
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric bool BranchFolder::OptimizeFunction(MachineFunction &MF,
1810b57cec5SDimitry Andric                                     const TargetInstrInfo *tii,
1820b57cec5SDimitry Andric                                     const TargetRegisterInfo *tri,
1830b57cec5SDimitry Andric                                     MachineLoopInfo *mli, bool AfterPlacement) {
1840b57cec5SDimitry Andric   if (!tii) return false;
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   TriedMerging.clear();
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
1890b57cec5SDimitry Andric   AfterBlockPlacement = AfterPlacement;
1900b57cec5SDimitry Andric   TII = tii;
1910b57cec5SDimitry Andric   TRI = tri;
1920b57cec5SDimitry Andric   MLI = mli;
1930b57cec5SDimitry Andric   this->MRI = &MRI;
1940b57cec5SDimitry Andric 
195*0fca6ea1SDimitry Andric   if (MinCommonTailLength == 0) {
196*0fca6ea1SDimitry Andric     MinCommonTailLength = TailMergeSize.getNumOccurrences() > 0
197*0fca6ea1SDimitry Andric                               ? TailMergeSize
198*0fca6ea1SDimitry Andric                               : TII->getTailMergeSize(MF);
199*0fca6ea1SDimitry Andric   }
200*0fca6ea1SDimitry Andric 
2010b57cec5SDimitry Andric   UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
2020b57cec5SDimitry Andric   if (!UpdateLiveIns)
2030b57cec5SDimitry Andric     MRI.invalidateLiveness();
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   bool MadeChange = false;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // Recalculate EH scope membership.
2080b57cec5SDimitry Andric   EHScopeMembership = getEHScopeMembership(MF);
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   bool MadeChangeThisIteration = true;
2110b57cec5SDimitry Andric   while (MadeChangeThisIteration) {
2120b57cec5SDimitry Andric     MadeChangeThisIteration    = TailMergeBlocks(MF);
2130b57cec5SDimitry Andric     // No need to clean up if tail merging does not change anything after the
2140b57cec5SDimitry Andric     // block placement.
2150b57cec5SDimitry Andric     if (!AfterBlockPlacement || MadeChangeThisIteration)
2160b57cec5SDimitry Andric       MadeChangeThisIteration |= OptimizeBranches(MF);
2170b57cec5SDimitry Andric     if (EnableHoistCommonCode)
2180b57cec5SDimitry Andric       MadeChangeThisIteration |= HoistCommonCode(MF);
2190b57cec5SDimitry Andric     MadeChange |= MadeChangeThisIteration;
2200b57cec5SDimitry Andric   }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   // See if any jump tables have become dead as the code generator
2230b57cec5SDimitry Andric   // did its thing.
2240b57cec5SDimitry Andric   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
2250b57cec5SDimitry Andric   if (!JTI)
2260b57cec5SDimitry Andric     return MadeChange;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   // Walk the function to find jump tables that are live.
2290b57cec5SDimitry Andric   BitVector JTIsLive(JTI->getJumpTables().size());
2300b57cec5SDimitry Andric   for (const MachineBasicBlock &BB : MF) {
2310b57cec5SDimitry Andric     for (const MachineInstr &I : BB)
2320b57cec5SDimitry Andric       for (const MachineOperand &Op : I.operands()) {
2330b57cec5SDimitry Andric         if (!Op.isJTI()) continue;
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric         // Remember that this JT is live.
2360b57cec5SDimitry Andric         JTIsLive.set(Op.getIndex());
2370b57cec5SDimitry Andric       }
2380b57cec5SDimitry Andric   }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   // Finally, remove dead jump tables.  This happens when the
2410b57cec5SDimitry Andric   // indirect jump was unreachable (and thus deleted).
2420b57cec5SDimitry Andric   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
2430b57cec5SDimitry Andric     if (!JTIsLive.test(i)) {
2440b57cec5SDimitry Andric       JTI->RemoveJumpTable(i);
2450b57cec5SDimitry Andric       MadeChange = true;
2460b57cec5SDimitry Andric     }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   return MadeChange;
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2520b57cec5SDimitry Andric //  Tail Merging of Blocks
2530b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric /// HashMachineInstr - Compute a hash value for MI and its operands.
2560b57cec5SDimitry Andric static unsigned HashMachineInstr(const MachineInstr &MI) {
2570b57cec5SDimitry Andric   unsigned Hash = MI.getOpcode();
2580b57cec5SDimitry Andric   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2590b57cec5SDimitry Andric     const MachineOperand &Op = MI.getOperand(i);
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric     // Merge in bits from the operand if easy. We can't use MachineOperand's
2620b57cec5SDimitry Andric     // hash_code here because it's not deterministic and we sort by hash value
2630b57cec5SDimitry Andric     // later.
2640b57cec5SDimitry Andric     unsigned OperandHash = 0;
2650b57cec5SDimitry Andric     switch (Op.getType()) {
2660b57cec5SDimitry Andric     case MachineOperand::MO_Register:
2670b57cec5SDimitry Andric       OperandHash = Op.getReg();
2680b57cec5SDimitry Andric       break;
2690b57cec5SDimitry Andric     case MachineOperand::MO_Immediate:
2700b57cec5SDimitry Andric       OperandHash = Op.getImm();
2710b57cec5SDimitry Andric       break;
2720b57cec5SDimitry Andric     case MachineOperand::MO_MachineBasicBlock:
2730b57cec5SDimitry Andric       OperandHash = Op.getMBB()->getNumber();
2740b57cec5SDimitry Andric       break;
2750b57cec5SDimitry Andric     case MachineOperand::MO_FrameIndex:
2760b57cec5SDimitry Andric     case MachineOperand::MO_ConstantPoolIndex:
2770b57cec5SDimitry Andric     case MachineOperand::MO_JumpTableIndex:
2780b57cec5SDimitry Andric       OperandHash = Op.getIndex();
2790b57cec5SDimitry Andric       break;
2800b57cec5SDimitry Andric     case MachineOperand::MO_GlobalAddress:
2810b57cec5SDimitry Andric     case MachineOperand::MO_ExternalSymbol:
2820b57cec5SDimitry Andric       // Global address / external symbol are too hard, don't bother, but do
2830b57cec5SDimitry Andric       // pull in the offset.
2840b57cec5SDimitry Andric       OperandHash = Op.getOffset();
2850b57cec5SDimitry Andric       break;
2860b57cec5SDimitry Andric     default:
2870b57cec5SDimitry Andric       break;
2880b57cec5SDimitry Andric     }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric     Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
2910b57cec5SDimitry Andric   }
2920b57cec5SDimitry Andric   return Hash;
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric /// HashEndOfMBB - Hash the last instruction in the MBB.
2960b57cec5SDimitry Andric static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
297fe6060f1SDimitry Andric   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(false);
2980b57cec5SDimitry Andric   if (I == MBB.end())
2990b57cec5SDimitry Andric     return 0;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   return HashMachineInstr(*I);
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric /// Whether MI should be counted as an instruction when calculating common tail.
3050b57cec5SDimitry Andric static bool countsAsInstruction(const MachineInstr &MI) {
3060b57cec5SDimitry Andric   return !(MI.isDebugInstr() || MI.isCFIInstruction());
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric 
309480093f4SDimitry Andric /// Iterate backwards from the given iterator \p I, towards the beginning of the
310480093f4SDimitry Andric /// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator
311480093f4SDimitry Andric /// pointing to that MI. If no such MI is found, return the end iterator.
312480093f4SDimitry Andric static MachineBasicBlock::iterator
313480093f4SDimitry Andric skipBackwardPastNonInstructions(MachineBasicBlock::iterator I,
314480093f4SDimitry Andric                                 MachineBasicBlock *MBB) {
315480093f4SDimitry Andric   while (I != MBB->begin()) {
316480093f4SDimitry Andric     --I;
317480093f4SDimitry Andric     if (countsAsInstruction(*I))
318480093f4SDimitry Andric       return I;
319480093f4SDimitry Andric   }
320480093f4SDimitry Andric   return MBB->end();
321480093f4SDimitry Andric }
322480093f4SDimitry Andric 
323480093f4SDimitry Andric /// Given two machine basic blocks, return the number of instructions they
324480093f4SDimitry Andric /// actually have in common together at their end. If a common tail is found (at
325480093f4SDimitry Andric /// least by one instruction), then iterators for the first shared instruction
326480093f4SDimitry Andric /// in each block are returned as well.
327480093f4SDimitry Andric ///
328480093f4SDimitry Andric /// Non-instructions according to countsAsInstruction are ignored.
3290b57cec5SDimitry Andric static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
3300b57cec5SDimitry Andric                                         MachineBasicBlock *MBB2,
3310b57cec5SDimitry Andric                                         MachineBasicBlock::iterator &I1,
3320b57cec5SDimitry Andric                                         MachineBasicBlock::iterator &I2) {
333480093f4SDimitry Andric   MachineBasicBlock::iterator MBBI1 = MBB1->end();
334480093f4SDimitry Andric   MachineBasicBlock::iterator MBBI2 = MBB2->end();
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   unsigned TailLen = 0;
337480093f4SDimitry Andric   while (true) {
338480093f4SDimitry Andric     MBBI1 = skipBackwardPastNonInstructions(MBBI1, MBB1);
339480093f4SDimitry Andric     MBBI2 = skipBackwardPastNonInstructions(MBBI2, MBB2);
340480093f4SDimitry Andric     if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end())
341480093f4SDimitry Andric       break;
342480093f4SDimitry Andric     if (!MBBI1->isIdenticalTo(*MBBI2) ||
3430b57cec5SDimitry Andric         // FIXME: This check is dubious. It's used to get around a problem where
3440b57cec5SDimitry Andric         // people incorrectly expect inline asm directives to remain in the same
3450b57cec5SDimitry Andric         // relative order. This is untenable because normal compiler
3460b57cec5SDimitry Andric         // optimizations (like this one) may reorder and/or merge these
3470b57cec5SDimitry Andric         // directives.
348480093f4SDimitry Andric         MBBI1->isInlineAsm()) {
3490b57cec5SDimitry Andric       break;
3500b57cec5SDimitry Andric     }
3515ffd83dbSDimitry Andric     if (MBBI1->getFlag(MachineInstr::NoMerge) ||
3525ffd83dbSDimitry Andric         MBBI2->getFlag(MachineInstr::NoMerge))
3535ffd83dbSDimitry Andric       break;
3540b57cec5SDimitry Andric     ++TailLen;
355480093f4SDimitry Andric     I1 = MBBI1;
356480093f4SDimitry Andric     I2 = MBBI2;
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   return TailLen;
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
3630b57cec5SDimitry Andric                                            MachineBasicBlock &NewDest) {
3640b57cec5SDimitry Andric   if (UpdateLiveIns) {
3650b57cec5SDimitry Andric     // OldInst should always point to an instruction.
3660b57cec5SDimitry Andric     MachineBasicBlock &OldMBB = *OldInst->getParent();
3670b57cec5SDimitry Andric     LiveRegs.clear();
3680b57cec5SDimitry Andric     LiveRegs.addLiveOuts(OldMBB);
3690b57cec5SDimitry Andric     // Move backward to the place where will insert the jump.
3700b57cec5SDimitry Andric     MachineBasicBlock::iterator I = OldMBB.end();
3710b57cec5SDimitry Andric     do {
3720b57cec5SDimitry Andric       --I;
3730b57cec5SDimitry Andric       LiveRegs.stepBackward(*I);
3740b57cec5SDimitry Andric     } while (I != OldInst);
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric     // Merging the tails may have switched some undef operand to non-undef ones.
3770b57cec5SDimitry Andric     // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
3780b57cec5SDimitry Andric     // register.
3790b57cec5SDimitry Andric     for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {
3800b57cec5SDimitry Andric       // We computed the liveins with computeLiveIn earlier and should only see
3810b57cec5SDimitry Andric       // full registers:
3820b57cec5SDimitry Andric       assert(P.LaneMask == LaneBitmask::getAll() &&
3830b57cec5SDimitry Andric              "Can only handle full register.");
3840b57cec5SDimitry Andric       MCPhysReg Reg = P.PhysReg;
3850b57cec5SDimitry Andric       if (!LiveRegs.available(*MRI, Reg))
3860b57cec5SDimitry Andric         continue;
3870b57cec5SDimitry Andric       DebugLoc DL;
3880b57cec5SDimitry Andric       BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg);
3890b57cec5SDimitry Andric     }
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   TII->ReplaceTailWithBranchTo(OldInst, &NewDest);
3930b57cec5SDimitry Andric   ++NumTailMerge;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
3970b57cec5SDimitry Andric                                             MachineBasicBlock::iterator BBI1,
3980b57cec5SDimitry Andric                                             const BasicBlock *BB) {
3990b57cec5SDimitry Andric   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
4000b57cec5SDimitry Andric     return nullptr;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   MachineFunction &MF = *CurMBB.getParent();
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   // Create the fall-through block.
4050b57cec5SDimitry Andric   MachineFunction::iterator MBBI = CurMBB.getIterator();
4060b57cec5SDimitry Andric   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
4070b57cec5SDimitry Andric   CurMBB.getParent()->insert(++MBBI, NewMBB);
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // Move all the successors of this block to the specified block.
4100b57cec5SDimitry Andric   NewMBB->transferSuccessors(&CurMBB);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   // Add an edge from CurMBB to NewMBB for the fall-through.
4130b57cec5SDimitry Andric   CurMBB.addSuccessor(NewMBB);
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   // Splice the code over.
4160b57cec5SDimitry Andric   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   // NewMBB belongs to the same loop as CurMBB.
4190b57cec5SDimitry Andric   if (MLI)
4200b57cec5SDimitry Andric     if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
421*0fca6ea1SDimitry Andric       ML->addBasicBlockToLoop(NewMBB, *MLI);
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // NewMBB inherits CurMBB's block frequency.
4240b57cec5SDimitry Andric   MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   if (UpdateLiveIns)
4270b57cec5SDimitry Andric     computeAndAddLiveIns(LiveRegs, *NewMBB);
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   // Add the new block to the EH scope.
4300b57cec5SDimitry Andric   const auto &EHScopeI = EHScopeMembership.find(&CurMBB);
4310b57cec5SDimitry Andric   if (EHScopeI != EHScopeMembership.end()) {
4320b57cec5SDimitry Andric     auto n = EHScopeI->second;
4330b57cec5SDimitry Andric     EHScopeMembership[NewMBB] = n;
4340b57cec5SDimitry Andric   }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   return NewMBB;
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric /// EstimateRuntime - Make a rough estimate for how long it will take to run
4400b57cec5SDimitry Andric /// the specified code.
4410b57cec5SDimitry Andric static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
4420b57cec5SDimitry Andric                                 MachineBasicBlock::iterator E) {
4430b57cec5SDimitry Andric   unsigned Time = 0;
4440b57cec5SDimitry Andric   for (; I != E; ++I) {
4450b57cec5SDimitry Andric     if (!countsAsInstruction(*I))
4460b57cec5SDimitry Andric       continue;
4470b57cec5SDimitry Andric     if (I->isCall())
4480b57cec5SDimitry Andric       Time += 10;
449480093f4SDimitry Andric     else if (I->mayLoadOrStore())
4500b57cec5SDimitry Andric       Time += 2;
4510b57cec5SDimitry Andric     else
4520b57cec5SDimitry Andric       ++Time;
4530b57cec5SDimitry Andric   }
4540b57cec5SDimitry Andric   return Time;
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
4580b57cec5SDimitry Andric // branches temporarily for tail merging).  In the case where CurMBB ends
4590b57cec5SDimitry Andric // with a conditional branch to the next block, optimize by reversing the
4600b57cec5SDimitry Andric // test and conditionally branching to SuccMBB instead.
4610b57cec5SDimitry Andric static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
462*0fca6ea1SDimitry Andric                     const TargetInstrInfo *TII, const DebugLoc &BranchDL) {
4630b57cec5SDimitry Andric   MachineFunction *MF = CurMBB->getParent();
4640b57cec5SDimitry Andric   MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
4650b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
4660b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
4670b57cec5SDimitry Andric   DebugLoc dl = CurMBB->findBranchDebugLoc();
468*0fca6ea1SDimitry Andric   if (!dl)
469*0fca6ea1SDimitry Andric     dl = BranchDL;
4700b57cec5SDimitry Andric   if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
4710b57cec5SDimitry Andric     MachineBasicBlock *NextBB = &*I;
4720b57cec5SDimitry Andric     if (TBB == NextBB && !Cond.empty() && !FBB) {
4730b57cec5SDimitry Andric       if (!TII->reverseBranchCondition(Cond)) {
4740b57cec5SDimitry Andric         TII->removeBranch(*CurMBB);
4750b57cec5SDimitry Andric         TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
4760b57cec5SDimitry Andric         return;
4770b57cec5SDimitry Andric       }
4780b57cec5SDimitry Andric     }
4790b57cec5SDimitry Andric   }
4800b57cec5SDimitry Andric   TII->insertBranch(*CurMBB, SuccBB, nullptr,
4810b57cec5SDimitry Andric                     SmallVector<MachineOperand, 0>(), dl);
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric bool
4850b57cec5SDimitry Andric BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
4860b57cec5SDimitry Andric   if (getHash() < o.getHash())
4870b57cec5SDimitry Andric     return true;
4880b57cec5SDimitry Andric   if (getHash() > o.getHash())
4890b57cec5SDimitry Andric     return false;
4900b57cec5SDimitry Andric   if (getBlock()->getNumber() < o.getBlock()->getNumber())
4910b57cec5SDimitry Andric     return true;
4920b57cec5SDimitry Andric   if (getBlock()->getNumber() > o.getBlock()->getNumber())
4930b57cec5SDimitry Andric     return false;
4940b57cec5SDimitry Andric   return false;
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric /// CountTerminators - Count the number of terminators in the given
4980b57cec5SDimitry Andric /// block and set I to the position of the first non-terminator, if there
4990b57cec5SDimitry Andric /// is one, or MBB->end() otherwise.
5000b57cec5SDimitry Andric static unsigned CountTerminators(MachineBasicBlock *MBB,
5010b57cec5SDimitry Andric                                  MachineBasicBlock::iterator &I) {
5020b57cec5SDimitry Andric   I = MBB->end();
5030b57cec5SDimitry Andric   unsigned NumTerms = 0;
5040b57cec5SDimitry Andric   while (true) {
5050b57cec5SDimitry Andric     if (I == MBB->begin()) {
5060b57cec5SDimitry Andric       I = MBB->end();
5070b57cec5SDimitry Andric       break;
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric     --I;
5100b57cec5SDimitry Andric     if (!I->isTerminator()) break;
5110b57cec5SDimitry Andric     ++NumTerms;
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric   return NumTerms;
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric /// A no successor, non-return block probably ends in unreachable and is cold.
5170b57cec5SDimitry Andric /// Also consider a block that ends in an indirect branch to be a return block,
5180b57cec5SDimitry Andric /// since many targets use plain indirect branches to return.
5190b57cec5SDimitry Andric static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
5200b57cec5SDimitry Andric   if (!MBB->succ_empty())
5210b57cec5SDimitry Andric     return false;
5220b57cec5SDimitry Andric   if (MBB->empty())
5230b57cec5SDimitry Andric     return true;
5240b57cec5SDimitry Andric   return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric /// ProfitableToMerge - Check if two machine basic blocks have a common tail
5280b57cec5SDimitry Andric /// and decide if it would be profitable to merge those tails.  Return the
5290b57cec5SDimitry Andric /// length of the common tail and iterators to the first common instruction
5300b57cec5SDimitry Andric /// in each block.
5310b57cec5SDimitry Andric /// MBB1, MBB2      The blocks to check
5320b57cec5SDimitry Andric /// MinCommonTailLength  Minimum size of tail block to be merged.
5330b57cec5SDimitry Andric /// CommonTailLen   Out parameter to record the size of the shared tail between
5340b57cec5SDimitry Andric ///                 MBB1 and MBB2
5350b57cec5SDimitry Andric /// I1, I2          Iterator references that will be changed to point to the first
5360b57cec5SDimitry Andric ///                 instruction in the common tail shared by MBB1,MBB2
5370b57cec5SDimitry Andric /// SuccBB          A common successor of MBB1, MBB2 which are in a canonical form
5380b57cec5SDimitry Andric ///                 relative to SuccBB
5390b57cec5SDimitry Andric /// PredBB          The layout predecessor of SuccBB, if any.
5400b57cec5SDimitry Andric /// EHScopeMembership  map from block to EH scope #.
5410b57cec5SDimitry Andric /// AfterPlacement  True if we are merging blocks after layout. Stricter
5420b57cec5SDimitry Andric ///                 thresholds apply to prevent undoing tail-duplication.
5430b57cec5SDimitry Andric static bool
5440b57cec5SDimitry Andric ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
5450b57cec5SDimitry Andric                   unsigned MinCommonTailLength, unsigned &CommonTailLen,
5460b57cec5SDimitry Andric                   MachineBasicBlock::iterator &I1,
5470b57cec5SDimitry Andric                   MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
5480b57cec5SDimitry Andric                   MachineBasicBlock *PredBB,
5490b57cec5SDimitry Andric                   DenseMap<const MachineBasicBlock *, int> &EHScopeMembership,
550480093f4SDimitry Andric                   bool AfterPlacement,
5515ffd83dbSDimitry Andric                   MBFIWrapper &MBBFreqInfo,
552480093f4SDimitry Andric                   ProfileSummaryInfo *PSI) {
5530b57cec5SDimitry Andric   // It is never profitable to tail-merge blocks from two different EH scopes.
5540b57cec5SDimitry Andric   if (!EHScopeMembership.empty()) {
5550b57cec5SDimitry Andric     auto EHScope1 = EHScopeMembership.find(MBB1);
5560b57cec5SDimitry Andric     assert(EHScope1 != EHScopeMembership.end());
5570b57cec5SDimitry Andric     auto EHScope2 = EHScopeMembership.find(MBB2);
5580b57cec5SDimitry Andric     assert(EHScope2 != EHScopeMembership.end());
5590b57cec5SDimitry Andric     if (EHScope1->second != EHScope2->second)
5600b57cec5SDimitry Andric       return false;
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
5640b57cec5SDimitry Andric   if (CommonTailLen == 0)
5650b57cec5SDimitry Andric     return false;
5660b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)
5670b57cec5SDimitry Andric                     << " and " << printMBBReference(*MBB2) << " is "
5680b57cec5SDimitry Andric                     << CommonTailLen << '\n');
5690b57cec5SDimitry Andric 
570480093f4SDimitry Andric   // Move the iterators to the beginning of the MBB if we only got debug
571480093f4SDimitry Andric   // instructions before the tail. This is to avoid splitting a block when we
572480093f4SDimitry Andric   // only got debug instructions before the tail (to be invariant on -g).
573fe6060f1SDimitry Andric   if (skipDebugInstructionsForward(MBB1->begin(), MBB1->end(), false) == I1)
574480093f4SDimitry Andric     I1 = MBB1->begin();
575fe6060f1SDimitry Andric   if (skipDebugInstructionsForward(MBB2->begin(), MBB2->end(), false) == I2)
576480093f4SDimitry Andric     I2 = MBB2->begin();
577480093f4SDimitry Andric 
578480093f4SDimitry Andric   bool FullBlockTail1 = I1 == MBB1->begin();
579480093f4SDimitry Andric   bool FullBlockTail2 = I2 == MBB2->begin();
580480093f4SDimitry Andric 
5810b57cec5SDimitry Andric   // It's almost always profitable to merge any number of non-terminator
5820b57cec5SDimitry Andric   // instructions with the block that falls through into the common successor.
5830b57cec5SDimitry Andric   // This is true only for a single successor. For multiple successors, we are
5840b57cec5SDimitry Andric   // trading a conditional branch for an unconditional one.
5850b57cec5SDimitry Andric   // TODO: Re-visit successor size for non-layout tail merging.
5860b57cec5SDimitry Andric   if ((MBB1 == PredBB || MBB2 == PredBB) &&
5870b57cec5SDimitry Andric       (!AfterPlacement || MBB1->succ_size() == 1)) {
5880b57cec5SDimitry Andric     MachineBasicBlock::iterator I;
5890b57cec5SDimitry Andric     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
5900b57cec5SDimitry Andric     if (CommonTailLen > NumTerms)
5910b57cec5SDimitry Andric       return true;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // If these are identical non-return blocks with no successors, merge them.
5950b57cec5SDimitry Andric   // Such blocks are typically cold calls to noreturn functions like abort, and
5960b57cec5SDimitry Andric   // are unlikely to become a fallthrough target after machine block placement.
5970b57cec5SDimitry Andric   // Tail merging these blocks is unlikely to create additional unconditional
5980b57cec5SDimitry Andric   // branches, and will reduce the size of this cold code.
599480093f4SDimitry Andric   if (FullBlockTail1 && FullBlockTail2 &&
6000b57cec5SDimitry Andric       blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
6010b57cec5SDimitry Andric     return true;
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   // If one of the blocks can be completely merged and happens to be in
6040b57cec5SDimitry Andric   // a position where the other could fall through into it, merge any number
6050b57cec5SDimitry Andric   // of instructions, because it can be done without a branch.
6060b57cec5SDimitry Andric   // TODO: If the blocks are not adjacent, move one of them so that they are?
607480093f4SDimitry Andric   if (MBB1->isLayoutSuccessor(MBB2) && FullBlockTail2)
6080b57cec5SDimitry Andric     return true;
609480093f4SDimitry Andric   if (MBB2->isLayoutSuccessor(MBB1) && FullBlockTail1)
6100b57cec5SDimitry Andric     return true;
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   // If both blocks are identical and end in a branch, merge them unless they
6130b57cec5SDimitry Andric   // both have a fallthrough predecessor and successor.
6140b57cec5SDimitry Andric   // We can only do this after block placement because it depends on whether
6150b57cec5SDimitry Andric   // there are fallthroughs, and we don't know until after layout.
616480093f4SDimitry Andric   if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {
6170b57cec5SDimitry Andric     auto BothFallThrough = [](MachineBasicBlock *MBB) {
618349cc55cSDimitry Andric       if (!MBB->succ_empty() && !MBB->canFallThrough())
6190b57cec5SDimitry Andric         return false;
6200b57cec5SDimitry Andric       MachineFunction::iterator I(MBB);
6210b57cec5SDimitry Andric       MachineFunction *MF = MBB->getParent();
6220b57cec5SDimitry Andric       return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
6230b57cec5SDimitry Andric     };
6240b57cec5SDimitry Andric     if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
6250b57cec5SDimitry Andric       return true;
6260b57cec5SDimitry Andric   }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // If both blocks have an unconditional branch temporarily stripped out,
6290b57cec5SDimitry Andric   // count that as an additional common instruction for the following
6300b57cec5SDimitry Andric   // heuristics. This heuristic is only accurate for single-succ blocks, so to
6310b57cec5SDimitry Andric   // make sure that during layout merging and duplicating don't crash, we check
6320b57cec5SDimitry Andric   // for that when merging during layout.
6330b57cec5SDimitry Andric   unsigned EffectiveTailLen = CommonTailLen;
6340b57cec5SDimitry Andric   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
6350b57cec5SDimitry Andric       (MBB1->succ_size() == 1 || !AfterPlacement) &&
6360b57cec5SDimitry Andric       !MBB1->back().isBarrier() &&
6370b57cec5SDimitry Andric       !MBB2->back().isBarrier())
6380b57cec5SDimitry Andric     ++EffectiveTailLen;
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Check if the common tail is long enough to be worthwhile.
6410b57cec5SDimitry Andric   if (EffectiveTailLen >= MinCommonTailLength)
6420b57cec5SDimitry Andric     return true;
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   // If we are optimizing for code size, 2 instructions in common is enough if
6450b57cec5SDimitry Andric   // we don't have to split a block.  At worst we will be introducing 1 new
6460b57cec5SDimitry Andric   // branch instruction, which is likely to be smaller than the 2
6470b57cec5SDimitry Andric   // instructions that would be deleted in the merge.
6480b57cec5SDimitry Andric   MachineFunction *MF = MBB1->getParent();
649480093f4SDimitry Andric   bool OptForSize =
650480093f4SDimitry Andric       MF->getFunction().hasOptSize() ||
6515ffd83dbSDimitry Andric       (llvm::shouldOptimizeForSize(MBB1, PSI, &MBBFreqInfo) &&
6525ffd83dbSDimitry Andric        llvm::shouldOptimizeForSize(MBB2, PSI, &MBBFreqInfo));
653480093f4SDimitry Andric   return EffectiveTailLen >= 2 && OptForSize &&
654480093f4SDimitry Andric          (FullBlockTail1 || FullBlockTail2);
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
6580b57cec5SDimitry Andric                                         unsigned MinCommonTailLength,
6590b57cec5SDimitry Andric                                         MachineBasicBlock *SuccBB,
6600b57cec5SDimitry Andric                                         MachineBasicBlock *PredBB) {
6610b57cec5SDimitry Andric   unsigned maxCommonTailLength = 0U;
6620b57cec5SDimitry Andric   SameTails.clear();
6630b57cec5SDimitry Andric   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
6640b57cec5SDimitry Andric   MPIterator HighestMPIter = std::prev(MergePotentials.end());
6650b57cec5SDimitry Andric   for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
6660b57cec5SDimitry Andric                   B = MergePotentials.begin();
6670b57cec5SDimitry Andric        CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
6680b57cec5SDimitry Andric     for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
6690b57cec5SDimitry Andric       unsigned CommonTailLen;
6700b57cec5SDimitry Andric       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
6710b57cec5SDimitry Andric                             MinCommonTailLength,
6720b57cec5SDimitry Andric                             CommonTailLen, TrialBBI1, TrialBBI2,
6730b57cec5SDimitry Andric                             SuccBB, PredBB,
6740b57cec5SDimitry Andric                             EHScopeMembership,
675480093f4SDimitry Andric                             AfterBlockPlacement, MBBFreqInfo, PSI)) {
6760b57cec5SDimitry Andric         if (CommonTailLen > maxCommonTailLength) {
6770b57cec5SDimitry Andric           SameTails.clear();
6780b57cec5SDimitry Andric           maxCommonTailLength = CommonTailLen;
6790b57cec5SDimitry Andric           HighestMPIter = CurMPIter;
6800b57cec5SDimitry Andric           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
6810b57cec5SDimitry Andric         }
6820b57cec5SDimitry Andric         if (HighestMPIter == CurMPIter &&
6830b57cec5SDimitry Andric             CommonTailLen == maxCommonTailLength)
6840b57cec5SDimitry Andric           SameTails.push_back(SameTailElt(I, TrialBBI2));
6850b57cec5SDimitry Andric       }
6860b57cec5SDimitry Andric       if (I == B)
6870b57cec5SDimitry Andric         break;
6880b57cec5SDimitry Andric     }
6890b57cec5SDimitry Andric   }
6900b57cec5SDimitry Andric   return maxCommonTailLength;
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
6940b57cec5SDimitry Andric                                         MachineBasicBlock *SuccBB,
695*0fca6ea1SDimitry Andric                                         MachineBasicBlock *PredBB,
696*0fca6ea1SDimitry Andric                                         const DebugLoc &BranchDL) {
6970b57cec5SDimitry Andric   MPIterator CurMPIter, B;
6980b57cec5SDimitry Andric   for (CurMPIter = std::prev(MergePotentials.end()),
6990b57cec5SDimitry Andric       B = MergePotentials.begin();
7000b57cec5SDimitry Andric        CurMPIter->getHash() == CurHash; --CurMPIter) {
7010b57cec5SDimitry Andric     // Put the unconditional branch back, if we need one.
7020b57cec5SDimitry Andric     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
7030b57cec5SDimitry Andric     if (SuccBB && CurMBB != PredBB)
704*0fca6ea1SDimitry Andric       FixTail(CurMBB, SuccBB, TII, BranchDL);
7050b57cec5SDimitry Andric     if (CurMPIter == B)
7060b57cec5SDimitry Andric       break;
7070b57cec5SDimitry Andric   }
7080b57cec5SDimitry Andric   if (CurMPIter->getHash() != CurHash)
7090b57cec5SDimitry Andric     CurMPIter++;
7100b57cec5SDimitry Andric   MergePotentials.erase(CurMPIter, MergePotentials.end());
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
7140b57cec5SDimitry Andric                                              MachineBasicBlock *SuccBB,
7150b57cec5SDimitry Andric                                              unsigned maxCommonTailLength,
7160b57cec5SDimitry Andric                                              unsigned &commonTailIndex) {
7170b57cec5SDimitry Andric   commonTailIndex = 0;
7180b57cec5SDimitry Andric   unsigned TimeEstimate = ~0U;
7190b57cec5SDimitry Andric   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
7200b57cec5SDimitry Andric     // Use PredBB if possible; that doesn't require a new branch.
7210b57cec5SDimitry Andric     if (SameTails[i].getBlock() == PredBB) {
7220b57cec5SDimitry Andric       commonTailIndex = i;
7230b57cec5SDimitry Andric       break;
7240b57cec5SDimitry Andric     }
7250b57cec5SDimitry Andric     // Otherwise, make a (fairly bogus) choice based on estimate of
7260b57cec5SDimitry Andric     // how long it will take the various blocks to execute.
7270b57cec5SDimitry Andric     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
7280b57cec5SDimitry Andric                                  SameTails[i].getTailStartPos());
7290b57cec5SDimitry Andric     if (t <= TimeEstimate) {
7300b57cec5SDimitry Andric       TimeEstimate = t;
7310b57cec5SDimitry Andric       commonTailIndex = i;
7320b57cec5SDimitry Andric     }
7330b57cec5SDimitry Andric   }
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   MachineBasicBlock::iterator BBI =
7360b57cec5SDimitry Andric     SameTails[commonTailIndex].getTailStartPos();
7370b57cec5SDimitry Andric   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "
7400b57cec5SDimitry Andric                     << maxCommonTailLength);
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   // If the split block unconditionally falls-thru to SuccBB, it will be
7430b57cec5SDimitry Andric   // merged. In control flow terms it should then take SuccBB's name. e.g. If
7440b57cec5SDimitry Andric   // SuccBB is an inner loop, the common tail is still part of the inner loop.
7450b57cec5SDimitry Andric   const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
7460b57cec5SDimitry Andric     SuccBB->getBasicBlock() : MBB->getBasicBlock();
7470b57cec5SDimitry Andric   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
7480b57cec5SDimitry Andric   if (!newMBB) {
7490b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "... failed!");
7500b57cec5SDimitry Andric     return false;
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   SameTails[commonTailIndex].setBlock(newMBB);
7540b57cec5SDimitry Andric   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   // If we split PredBB, newMBB is the new predecessor.
7570b57cec5SDimitry Andric   if (PredBB == MBB)
7580b57cec5SDimitry Andric     PredBB = newMBB;
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   return true;
7610b57cec5SDimitry Andric }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric static void
7640b57cec5SDimitry Andric mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
7650b57cec5SDimitry Andric                 MachineBasicBlock &MBBCommon) {
7660b57cec5SDimitry Andric   MachineBasicBlock *MBB = MBBIStartPos->getParent();
7670b57cec5SDimitry Andric   // Note CommonTailLen does not necessarily matches the size of
7680b57cec5SDimitry Andric   // the common BB nor all its instructions because of debug
7690b57cec5SDimitry Andric   // instructions differences.
7700b57cec5SDimitry Andric   unsigned CommonTailLen = 0;
7710b57cec5SDimitry Andric   for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
7720b57cec5SDimitry Andric     ++CommonTailLen;
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
7750b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
7760b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
7770b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   while (CommonTailLen--) {
7800b57cec5SDimitry Andric     assert(MBBI != MBBIE && "Reached BB end within common tail length!");
7810b57cec5SDimitry Andric     (void)MBBIE;
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric     if (!countsAsInstruction(*MBBI)) {
7840b57cec5SDimitry Andric       ++MBBI;
7850b57cec5SDimitry Andric       continue;
7860b57cec5SDimitry Andric     }
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric     while ((MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon))
7890b57cec5SDimitry Andric       ++MBBICommon;
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric     assert(MBBICommon != MBBIECommon &&
7920b57cec5SDimitry Andric            "Reached BB end within common tail length!");
7930b57cec5SDimitry Andric     assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     // Merge MMOs from memory operations in the common block.
796480093f4SDimitry Andric     if (MBBICommon->mayLoadOrStore())
7970b57cec5SDimitry Andric       MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI});
7980b57cec5SDimitry Andric     // Drop undef flags if they aren't present in all merged instructions.
7990b57cec5SDimitry Andric     for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
8000b57cec5SDimitry Andric       MachineOperand &MO = MBBICommon->getOperand(I);
8010b57cec5SDimitry Andric       if (MO.isReg() && MO.isUndef()) {
8020b57cec5SDimitry Andric         const MachineOperand &OtherMO = MBBI->getOperand(I);
8030b57cec5SDimitry Andric         if (!OtherMO.isUndef())
8040b57cec5SDimitry Andric           MO.setIsUndef(false);
8050b57cec5SDimitry Andric       }
8060b57cec5SDimitry Andric     }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric     ++MBBI;
8090b57cec5SDimitry Andric     ++MBBICommon;
8100b57cec5SDimitry Andric   }
8110b57cec5SDimitry Andric }
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {
8140b57cec5SDimitry Andric   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
8170b57cec5SDimitry Andric   for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
8180b57cec5SDimitry Andric     if (i != commonTailIndex) {
8190b57cec5SDimitry Andric       NextCommonInsts[i] = SameTails[i].getTailStartPos();
8200b57cec5SDimitry Andric       mergeOperations(SameTails[i].getTailStartPos(), *MBB);
8210b57cec5SDimitry Andric     } else {
8220b57cec5SDimitry Andric       assert(SameTails[i].getTailStartPos() == MBB->begin() &&
8230b57cec5SDimitry Andric           "MBB is not a common tail only block");
8240b57cec5SDimitry Andric     }
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   for (auto &MI : *MBB) {
8280b57cec5SDimitry Andric     if (!countsAsInstruction(MI))
8290b57cec5SDimitry Andric       continue;
8300b57cec5SDimitry Andric     DebugLoc DL = MI.getDebugLoc();
8310b57cec5SDimitry Andric     for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
8320b57cec5SDimitry Andric       if (i == commonTailIndex)
8330b57cec5SDimitry Andric         continue;
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric       auto &Pos = NextCommonInsts[i];
8360b57cec5SDimitry Andric       assert(Pos != SameTails[i].getBlock()->end() &&
8370b57cec5SDimitry Andric           "Reached BB end within common tail");
8380b57cec5SDimitry Andric       while (!countsAsInstruction(*Pos)) {
8390b57cec5SDimitry Andric         ++Pos;
8400b57cec5SDimitry Andric         assert(Pos != SameTails[i].getBlock()->end() &&
8410b57cec5SDimitry Andric             "Reached BB end within common tail");
8420b57cec5SDimitry Andric       }
8430b57cec5SDimitry Andric       assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
8440b57cec5SDimitry Andric       DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc());
8450b57cec5SDimitry Andric       NextCommonInsts[i] = ++Pos;
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric     MI.setDebugLoc(DL);
8480b57cec5SDimitry Andric   }
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   if (UpdateLiveIns) {
8510b57cec5SDimitry Andric     LivePhysRegs NewLiveIns(*TRI);
8520b57cec5SDimitry Andric     computeLiveIns(NewLiveIns, *MBB);
8530b57cec5SDimitry Andric     LiveRegs.init(*TRI);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     // The flag merging may lead to some register uses no longer using the
8560b57cec5SDimitry Andric     // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
8570b57cec5SDimitry Andric     for (MachineBasicBlock *Pred : MBB->predecessors()) {
8580b57cec5SDimitry Andric       LiveRegs.clear();
8590b57cec5SDimitry Andric       LiveRegs.addLiveOuts(*Pred);
8600b57cec5SDimitry Andric       MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();
8615ffd83dbSDimitry Andric       for (Register Reg : NewLiveIns) {
8620b57cec5SDimitry Andric         if (!LiveRegs.available(*MRI, Reg))
8630b57cec5SDimitry Andric           continue;
86406c3fb27SDimitry Andric 
86506c3fb27SDimitry Andric         // Skip the register if we are about to add one of its super registers.
86606c3fb27SDimitry Andric         // TODO: Common this up with the same logic in addLineIns().
86706c3fb27SDimitry Andric         if (any_of(TRI->superregs(Reg), [&](MCPhysReg SReg) {
86806c3fb27SDimitry Andric               return NewLiveIns.contains(SReg) && !MRI->isReserved(SReg);
86906c3fb27SDimitry Andric             }))
87006c3fb27SDimitry Andric           continue;
87106c3fb27SDimitry Andric 
8720b57cec5SDimitry Andric         DebugLoc DL;
8730b57cec5SDimitry Andric         BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF),
8740b57cec5SDimitry Andric                 Reg);
8750b57cec5SDimitry Andric       }
8760b57cec5SDimitry Andric     }
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric     MBB->clearLiveIns();
8790b57cec5SDimitry Andric     addLiveIns(*MBB, NewLiveIns);
8800b57cec5SDimitry Andric   }
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric // See if any of the blocks in MergePotentials (which all have SuccBB as a
8840b57cec5SDimitry Andric // successor, or all have no successor if it is null) can be tail-merged.
8850b57cec5SDimitry Andric // If there is a successor, any blocks in MergePotentials that are not
8860b57cec5SDimitry Andric // tail-merged and are not immediately before Succ must have an unconditional
8870b57cec5SDimitry Andric // branch to Succ added (but the predecessor/successor lists need no
8880b57cec5SDimitry Andric // adjustment). The lone predecessor of Succ that falls through into Succ,
8890b57cec5SDimitry Andric // if any, is given in PredBB.
8900b57cec5SDimitry Andric // MinCommonTailLength - Except for the special cases below, tail-merge if
8910b57cec5SDimitry Andric // there are at least this many instructions in common.
8920b57cec5SDimitry Andric bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
8930b57cec5SDimitry Andric                                       MachineBasicBlock *PredBB,
8940b57cec5SDimitry Andric                                       unsigned MinCommonTailLength) {
8950b57cec5SDimitry Andric   bool MadeChange = false;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   LLVM_DEBUG(
8980b57cec5SDimitry Andric       dbgs() << "\nTryTailMergeBlocks: ";
8990b57cec5SDimitry Andric       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs()
9000b57cec5SDimitry Andric       << printMBBReference(*MergePotentials[i].getBlock())
9010b57cec5SDimitry Andric       << (i == e - 1 ? "" : ", ");
9020b57cec5SDimitry Andric       dbgs() << "\n"; if (SuccBB) {
9030b57cec5SDimitry Andric         dbgs() << "  with successor " << printMBBReference(*SuccBB) << '\n';
9040b57cec5SDimitry Andric         if (PredBB)
9050b57cec5SDimitry Andric           dbgs() << "  which has fall-through from "
9060b57cec5SDimitry Andric                  << printMBBReference(*PredBB) << "\n";
9070b57cec5SDimitry Andric       } dbgs() << "Looking for common tails of at least "
9080b57cec5SDimitry Andric                << MinCommonTailLength << " instruction"
9090b57cec5SDimitry Andric                << (MinCommonTailLength == 1 ? "" : "s") << '\n';);
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   // Sort by hash value so that blocks with identical end sequences sort
9120b57cec5SDimitry Andric   // together.
9130b57cec5SDimitry Andric   array_pod_sort(MergePotentials.begin(), MergePotentials.end());
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   // Walk through equivalence sets looking for actual exact matches.
9160b57cec5SDimitry Andric   while (MergePotentials.size() > 1) {
9170b57cec5SDimitry Andric     unsigned CurHash = MergePotentials.back().getHash();
918*0fca6ea1SDimitry Andric     const DebugLoc &BranchDL = MergePotentials.back().getBranchDebugLoc();
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric     // Build SameTails, identifying the set of blocks with this hash code
9210b57cec5SDimitry Andric     // and with the maximum number of instructions in common.
9220b57cec5SDimitry Andric     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
9230b57cec5SDimitry Andric                                                     MinCommonTailLength,
9240b57cec5SDimitry Andric                                                     SuccBB, PredBB);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric     // If we didn't find any pair that has at least MinCommonTailLength
9270b57cec5SDimitry Andric     // instructions in common, remove all blocks with this hash code and retry.
9280b57cec5SDimitry Andric     if (SameTails.empty()) {
929*0fca6ea1SDimitry Andric       RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
9300b57cec5SDimitry Andric       continue;
9310b57cec5SDimitry Andric     }
9320b57cec5SDimitry Andric 
933e837bb5cSDimitry Andric     // If one of the blocks is the entire common tail (and is not the entry
934e837bb5cSDimitry Andric     // block/an EH pad, which we can't jump to), we can treat all blocks with
935e837bb5cSDimitry Andric     // this same tail at once.  Use PredBB if that is one of the possibilities,
936e837bb5cSDimitry Andric     // as that will not introduce any extra branches.
9370b57cec5SDimitry Andric     MachineBasicBlock *EntryBB =
9380b57cec5SDimitry Andric         &MergePotentials.front().getBlock()->getParent()->front();
9390b57cec5SDimitry Andric     unsigned commonTailIndex = SameTails.size();
9400b57cec5SDimitry Andric     // If there are two blocks, check to see if one can be made to fall through
9410b57cec5SDimitry Andric     // into the other.
9420b57cec5SDimitry Andric     if (SameTails.size() == 2 &&
9430b57cec5SDimitry Andric         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
944e837bb5cSDimitry Andric         SameTails[1].tailIsWholeBlock() && !SameTails[1].getBlock()->isEHPad())
9450b57cec5SDimitry Andric       commonTailIndex = 1;
9460b57cec5SDimitry Andric     else if (SameTails.size() == 2 &&
9470b57cec5SDimitry Andric              SameTails[1].getBlock()->isLayoutSuccessor(
9480b57cec5SDimitry Andric                  SameTails[0].getBlock()) &&
949e837bb5cSDimitry Andric              SameTails[0].tailIsWholeBlock() &&
950e837bb5cSDimitry Andric              !SameTails[0].getBlock()->isEHPad())
9510b57cec5SDimitry Andric       commonTailIndex = 0;
9520b57cec5SDimitry Andric     else {
9530b57cec5SDimitry Andric       // Otherwise just pick one, favoring the fall-through predecessor if
9540b57cec5SDimitry Andric       // there is one.
9550b57cec5SDimitry Andric       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
9560b57cec5SDimitry Andric         MachineBasicBlock *MBB = SameTails[i].getBlock();
957e837bb5cSDimitry Andric         if ((MBB == EntryBB || MBB->isEHPad()) &&
958e837bb5cSDimitry Andric             SameTails[i].tailIsWholeBlock())
9590b57cec5SDimitry Andric           continue;
9600b57cec5SDimitry Andric         if (MBB == PredBB) {
9610b57cec5SDimitry Andric           commonTailIndex = i;
9620b57cec5SDimitry Andric           break;
9630b57cec5SDimitry Andric         }
9640b57cec5SDimitry Andric         if (SameTails[i].tailIsWholeBlock())
9650b57cec5SDimitry Andric           commonTailIndex = i;
9660b57cec5SDimitry Andric       }
9670b57cec5SDimitry Andric     }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric     if (commonTailIndex == SameTails.size() ||
9700b57cec5SDimitry Andric         (SameTails[commonTailIndex].getBlock() == PredBB &&
9710b57cec5SDimitry Andric          !SameTails[commonTailIndex].tailIsWholeBlock())) {
9720b57cec5SDimitry Andric       // None of the blocks consist entirely of the common tail.
9730b57cec5SDimitry Andric       // Split a block so that one does.
9740b57cec5SDimitry Andric       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
9750b57cec5SDimitry Andric                                      maxCommonTailLength, commonTailIndex)) {
976*0fca6ea1SDimitry Andric         RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
9770b57cec5SDimitry Andric         continue;
9780b57cec5SDimitry Andric       }
9790b57cec5SDimitry Andric     }
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric     // Recompute common tail MBB's edge weights and block frequency.
9840b57cec5SDimitry Andric     setCommonTailEdgeWeights(*MBB);
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric     // Merge debug locations, MMOs and undef flags across identical instructions
9870b57cec5SDimitry Andric     // for common tail.
9880b57cec5SDimitry Andric     mergeCommonTails(commonTailIndex);
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     // MBB is common tail.  Adjust all other BB's to jump to this one.
9910b57cec5SDimitry Andric     // Traversal must be forwards so erases work.
9920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)
9930b57cec5SDimitry Andric                       << " for ");
9940b57cec5SDimitry Andric     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
9950b57cec5SDimitry Andric       if (commonTailIndex == i)
9960b57cec5SDimitry Andric         continue;
9970b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())
9980b57cec5SDimitry Andric                         << (i == e - 1 ? "" : ", "));
9990b57cec5SDimitry Andric       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
10000b57cec5SDimitry Andric       replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);
10010b57cec5SDimitry Andric       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
10020b57cec5SDimitry Andric       MergePotentials.erase(SameTails[i].getMPIter());
10030b57cec5SDimitry Andric     }
10040b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
10050b57cec5SDimitry Andric     // We leave commonTailIndex in the worklist in case there are other blocks
10060b57cec5SDimitry Andric     // that match it with a smaller number of instructions.
10070b57cec5SDimitry Andric     MadeChange = true;
10080b57cec5SDimitry Andric   }
10090b57cec5SDimitry Andric   return MadeChange;
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
10130b57cec5SDimitry Andric   bool MadeChange = false;
10140b57cec5SDimitry Andric   if (!EnableTailMerge)
10150b57cec5SDimitry Andric     return MadeChange;
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   // First find blocks with no successors.
10180b57cec5SDimitry Andric   // Block placement may create new tail merging opportunities for these blocks.
10190b57cec5SDimitry Andric   MergePotentials.clear();
10200b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
10210b57cec5SDimitry Andric     if (MergePotentials.size() == TailMergeThreshold)
10220b57cec5SDimitry Andric       break;
10230b57cec5SDimitry Andric     if (!TriedMerging.count(&MBB) && MBB.succ_empty())
1024*0fca6ea1SDimitry Andric       MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB,
1025*0fca6ea1SDimitry Andric                                                    MBB.findBranchDebugLoc()));
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // If this is a large problem, avoid visiting the same basic blocks
10290b57cec5SDimitry Andric   // multiple times.
10300b57cec5SDimitry Andric   if (MergePotentials.size() == TailMergeThreshold)
10314824e7fdSDimitry Andric     for (const MergePotentialsElt &Elt : MergePotentials)
10324824e7fdSDimitry Andric       TriedMerging.insert(Elt.getBlock());
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   // See if we can do any tail merging on those.
10350b57cec5SDimitry Andric   if (MergePotentials.size() >= 2)
10360b57cec5SDimitry Andric     MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // Look at blocks (IBB) with multiple predecessors (PBB).
10390b57cec5SDimitry Andric   // We change each predecessor to a canonical form, by
10400b57cec5SDimitry Andric   // (1) temporarily removing any unconditional branch from the predecessor
10410b57cec5SDimitry Andric   // to IBB, and
10420b57cec5SDimitry Andric   // (2) alter conditional branches so they branch to the other block
10430b57cec5SDimitry Andric   // not IBB; this may require adding back an unconditional branch to IBB
10440b57cec5SDimitry Andric   // later, where there wasn't one coming in.  E.g.
10450b57cec5SDimitry Andric   //   Bcc IBB
10460b57cec5SDimitry Andric   //   fallthrough to QBB
10470b57cec5SDimitry Andric   // here becomes
10480b57cec5SDimitry Andric   //   Bncc QBB
10490b57cec5SDimitry Andric   // with a conceptual B to IBB after that, which never actually exists.
10500b57cec5SDimitry Andric   // With those changes, we see whether the predecessors' tails match,
10510b57cec5SDimitry Andric   // and merge them if so.  We change things out of canonical form and
10520b57cec5SDimitry Andric   // back to the way they were later in the process.  (OptimizeBranches
10530b57cec5SDimitry Andric   // would undo some of this, but we can't use it, because we'd get into
10540b57cec5SDimitry Andric   // a compile-time infinite loop repeatedly doing and undoing the same
10550b57cec5SDimitry Andric   // transformations.)
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
10580b57cec5SDimitry Andric        I != E; ++I) {
10590b57cec5SDimitry Andric     if (I->pred_size() < 2) continue;
10600b57cec5SDimitry Andric     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
10610b57cec5SDimitry Andric     MachineBasicBlock *IBB = &*I;
10620b57cec5SDimitry Andric     MachineBasicBlock *PredBB = &*std::prev(I);
10630b57cec5SDimitry Andric     MergePotentials.clear();
10640b57cec5SDimitry Andric     MachineLoop *ML;
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric     // Bail if merging after placement and IBB is the loop header because
10670b57cec5SDimitry Andric     // -- If merging predecessors that belong to the same loop as IBB, the
10680b57cec5SDimitry Andric     // common tail of merged predecessors may become the loop top if block
10690b57cec5SDimitry Andric     // placement is called again and the predecessors may branch to this common
10700b57cec5SDimitry Andric     // tail and require more branches. This can be relaxed if
10710b57cec5SDimitry Andric     // MachineBlockPlacement::findBestLoopTop is more flexible.
10720b57cec5SDimitry Andric     // --If merging predecessors that do not belong to the same loop as IBB, the
10730b57cec5SDimitry Andric     // loop info of IBB's loop and the other loops may be affected. Calling the
10740b57cec5SDimitry Andric     // block placement again may make big change to the layout and eliminate the
10750b57cec5SDimitry Andric     // reason to do tail merging here.
10760b57cec5SDimitry Andric     if (AfterBlockPlacement && MLI) {
10770b57cec5SDimitry Andric       ML = MLI->getLoopFor(IBB);
10780b57cec5SDimitry Andric       if (ML && IBB == ML->getHeader())
10790b57cec5SDimitry Andric         continue;
10800b57cec5SDimitry Andric     }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric     for (MachineBasicBlock *PBB : I->predecessors()) {
10830b57cec5SDimitry Andric       if (MergePotentials.size() == TailMergeThreshold)
10840b57cec5SDimitry Andric         break;
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric       if (TriedMerging.count(PBB))
10870b57cec5SDimitry Andric         continue;
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric       // Skip blocks that loop to themselves, can't tail merge these.
10900b57cec5SDimitry Andric       if (PBB == IBB)
10910b57cec5SDimitry Andric         continue;
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric       // Visit each predecessor only once.
10940b57cec5SDimitry Andric       if (!UniquePreds.insert(PBB).second)
10950b57cec5SDimitry Andric         continue;
10960b57cec5SDimitry Andric 
10975ffd83dbSDimitry Andric       // Skip blocks which may jump to a landing pad or jump from an asm blob.
10985ffd83dbSDimitry Andric       // Can't tail merge these.
10995ffd83dbSDimitry Andric       if (PBB->hasEHPadSuccessor() || PBB->mayHaveInlineAsmBr())
11000b57cec5SDimitry Andric         continue;
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric       // After block placement, only consider predecessors that belong to the
11030b57cec5SDimitry Andric       // same loop as IBB.  The reason is the same as above when skipping loop
11040b57cec5SDimitry Andric       // header.
11050b57cec5SDimitry Andric       if (AfterBlockPlacement && MLI)
11060b57cec5SDimitry Andric         if (ML != MLI->getLoopFor(PBB))
11070b57cec5SDimitry Andric           continue;
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric       MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
11100b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> Cond;
11110b57cec5SDimitry Andric       if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
11120b57cec5SDimitry Andric         // Failing case: IBB is the target of a cbr, and we cannot reverse the
11130b57cec5SDimitry Andric         // branch.
11140b57cec5SDimitry Andric         SmallVector<MachineOperand, 4> NewCond(Cond);
11150b57cec5SDimitry Andric         if (!Cond.empty() && TBB == IBB) {
11160b57cec5SDimitry Andric           if (TII->reverseBranchCondition(NewCond))
11170b57cec5SDimitry Andric             continue;
11180b57cec5SDimitry Andric           // This is the QBB case described above
11190b57cec5SDimitry Andric           if (!FBB) {
11200b57cec5SDimitry Andric             auto Next = ++PBB->getIterator();
11210b57cec5SDimitry Andric             if (Next != MF.end())
11220b57cec5SDimitry Andric               FBB = &*Next;
11230b57cec5SDimitry Andric           }
11240b57cec5SDimitry Andric         }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric         // Remove the unconditional branch at the end, if any.
11270b57cec5SDimitry Andric         DebugLoc dl = PBB->findBranchDebugLoc();
1128*0fca6ea1SDimitry Andric         if (TBB && (Cond.empty() || FBB)) {
11290b57cec5SDimitry Andric           TII->removeBranch(*PBB);
11300b57cec5SDimitry Andric           if (!Cond.empty())
11310b57cec5SDimitry Andric             // reinsert conditional branch only, for now
11320b57cec5SDimitry Andric             TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
11330b57cec5SDimitry Andric                               NewCond, dl);
11340b57cec5SDimitry Andric         }
11350b57cec5SDimitry Andric 
1136*0fca6ea1SDimitry Andric         MergePotentials.push_back(
1137*0fca6ea1SDimitry Andric             MergePotentialsElt(HashEndOfMBB(*PBB), PBB, dl));
11380b57cec5SDimitry Andric       }
11390b57cec5SDimitry Andric     }
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric     // If this is a large problem, avoid visiting the same basic blocks multiple
11420b57cec5SDimitry Andric     // times.
11430b57cec5SDimitry Andric     if (MergePotentials.size() == TailMergeThreshold)
11440eae32dcSDimitry Andric       for (MergePotentialsElt &Elt : MergePotentials)
11450eae32dcSDimitry Andric         TriedMerging.insert(Elt.getBlock());
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     if (MergePotentials.size() >= 2)
11480b57cec5SDimitry Andric       MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric     // Reinsert an unconditional branch if needed. The 1 below can occur as a
11510b57cec5SDimitry Andric     // result of removing blocks in TryTailMergeBlocks.
11520b57cec5SDimitry Andric     PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
11530b57cec5SDimitry Andric     if (MergePotentials.size() == 1 &&
11540b57cec5SDimitry Andric         MergePotentials.begin()->getBlock() != PredBB)
1155*0fca6ea1SDimitry Andric       FixTail(MergePotentials.begin()->getBlock(), IBB, TII,
1156*0fca6ea1SDimitry Andric               MergePotentials.begin()->getBranchDebugLoc());
11570b57cec5SDimitry Andric   }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   return MadeChange;
11600b57cec5SDimitry Andric }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
11630b57cec5SDimitry Andric   SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
11640b57cec5SDimitry Andric   BlockFrequency AccumulatedMBBFreq;
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   // Aggregate edge frequency of successor edge j:
11670b57cec5SDimitry Andric   //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
11680b57cec5SDimitry Andric   //  where bb is a basic block that is in SameTails.
11690b57cec5SDimitry Andric   for (const auto &Src : SameTails) {
11700b57cec5SDimitry Andric     const MachineBasicBlock *SrcMBB = Src.getBlock();
11710b57cec5SDimitry Andric     BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
11720b57cec5SDimitry Andric     AccumulatedMBBFreq += BlockFreq;
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric     // It is not necessary to recompute edge weights if TailBB has less than two
11750b57cec5SDimitry Andric     // successors.
11760b57cec5SDimitry Andric     if (TailMBB.succ_size() <= 1)
11770b57cec5SDimitry Andric       continue;
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric     auto EdgeFreq = EdgeFreqLs.begin();
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
11820b57cec5SDimitry Andric          SuccI != SuccE; ++SuccI, ++EdgeFreq)
11830b57cec5SDimitry Andric       *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
11840b57cec5SDimitry Andric   }
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric   if (TailMBB.succ_size() <= 1)
11890b57cec5SDimitry Andric     return;
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   auto SumEdgeFreq =
11920b57cec5SDimitry Andric       std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
11930b57cec5SDimitry Andric           .getFrequency();
11940b57cec5SDimitry Andric   auto EdgeFreq = EdgeFreqLs.begin();
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric   if (SumEdgeFreq > 0) {
11970b57cec5SDimitry Andric     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
11980b57cec5SDimitry Andric          SuccI != SuccE; ++SuccI, ++EdgeFreq) {
11990b57cec5SDimitry Andric       auto Prob = BranchProbability::getBranchProbability(
12000b57cec5SDimitry Andric           EdgeFreq->getFrequency(), SumEdgeFreq);
12010b57cec5SDimitry Andric       TailMBB.setSuccProbability(SuccI, Prob);
12020b57cec5SDimitry Andric     }
12030b57cec5SDimitry Andric   }
12040b57cec5SDimitry Andric }
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12070b57cec5SDimitry Andric //  Branch Optimization
12080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
12110b57cec5SDimitry Andric   bool MadeChange = false;
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   // Make sure blocks are numbered in order
12140b57cec5SDimitry Andric   MF.RenumberBlocks();
12150b57cec5SDimitry Andric   // Renumbering blocks alters EH scope membership, recalculate it.
12160b57cec5SDimitry Andric   EHScopeMembership = getEHScopeMembership(MF);
12170b57cec5SDimitry Andric 
1218349cc55cSDimitry Andric   for (MachineBasicBlock &MBB :
1219349cc55cSDimitry Andric        llvm::make_early_inc_range(llvm::drop_begin(MF))) {
1220349cc55cSDimitry Andric     MadeChange |= OptimizeBlock(&MBB);
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     // If it is dead, remove it.
122306c3fb27SDimitry Andric     if (MBB.pred_empty() && !MBB.isMachineBlockAddressTaken()) {
1224349cc55cSDimitry Andric       RemoveDeadBlock(&MBB);
12250b57cec5SDimitry Andric       MadeChange = true;
12260b57cec5SDimitry Andric       ++NumDeadBlocks;
12270b57cec5SDimitry Andric     }
12280b57cec5SDimitry Andric   }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   return MadeChange;
12310b57cec5SDimitry Andric }
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric // Blocks should be considered empty if they contain only debug info;
12340b57cec5SDimitry Andric // else the debug info would affect codegen.
12350b57cec5SDimitry Andric static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1236fe6060f1SDimitry Andric   return MBB->getFirstNonDebugInstr(true) == MBB->end();
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric // Blocks with only debug info and branches should be considered the same
12400b57cec5SDimitry Andric // as blocks with only branches.
12410b57cec5SDimitry Andric static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
12420b57cec5SDimitry Andric   MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
12430b57cec5SDimitry Andric   assert(I != MBB->end() && "empty block!");
12440b57cec5SDimitry Andric   return I->isBranch();
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric /// IsBetterFallthrough - Return true if it would be clearly better to
12480b57cec5SDimitry Andric /// fall-through to MBB1 than to fall through into MBB2.  This has to return
12490b57cec5SDimitry Andric /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
12500b57cec5SDimitry Andric /// result in infinite loops.
12510b57cec5SDimitry Andric static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
12520b57cec5SDimitry Andric                                 MachineBasicBlock *MBB2) {
12538bcb0991SDimitry Andric   assert(MBB1 && MBB2 && "Unknown MachineBasicBlock");
12548bcb0991SDimitry Andric 
12550b57cec5SDimitry Andric   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
12560b57cec5SDimitry Andric   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
12570b57cec5SDimitry Andric   // optimize branches that branch to either a return block or an assert block
12580b57cec5SDimitry Andric   // into a fallthrough to the return.
12590b57cec5SDimitry Andric   MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
12600b57cec5SDimitry Andric   MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
12610b57cec5SDimitry Andric   if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
12620b57cec5SDimitry Andric     return false;
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric   // If there is a clear successor ordering we make sure that one block
12650b57cec5SDimitry Andric   // will fall through to the next
12660b57cec5SDimitry Andric   if (MBB1->isSuccessor(MBB2)) return true;
12670b57cec5SDimitry Andric   if (MBB2->isSuccessor(MBB1)) return false;
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric   return MBB2I->isCall() && !MBB1I->isCall();
12700b57cec5SDimitry Andric }
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
12730b57cec5SDimitry Andric /// instructions on the block.
12740b57cec5SDimitry Andric static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
12750b57cec5SDimitry Andric   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
12760b57cec5SDimitry Andric   if (I != MBB.end() && I->isBranch())
12770b57cec5SDimitry Andric     return I->getDebugLoc();
12780b57cec5SDimitry Andric   return DebugLoc();
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII,
12820b57cec5SDimitry Andric                                        MachineBasicBlock &MBB,
12830b57cec5SDimitry Andric                                        MachineBasicBlock &PredMBB) {
12840b57cec5SDimitry Andric   auto InsertBefore = PredMBB.getFirstTerminator();
12850b57cec5SDimitry Andric   for (MachineInstr &MI : MBB.instrs())
12860b57cec5SDimitry Andric     if (MI.isDebugInstr()) {
12870b57cec5SDimitry Andric       TII->duplicate(PredMBB, InsertBefore, MI);
12880b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
12890b57cec5SDimitry Andric                         << MI);
12900b57cec5SDimitry Andric     }
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII,
12940b57cec5SDimitry Andric                                      MachineBasicBlock &MBB,
12950b57cec5SDimitry Andric                                      MachineBasicBlock &SuccMBB) {
12960b57cec5SDimitry Andric   auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin());
12970b57cec5SDimitry Andric   for (MachineInstr &MI : MBB.instrs())
12980b57cec5SDimitry Andric     if (MI.isDebugInstr()) {
12990b57cec5SDimitry Andric       TII->duplicate(SuccMBB, InsertBefore, MI);
13000b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
13010b57cec5SDimitry Andric                         << MI);
13020b57cec5SDimitry Andric     }
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric // Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
13060b57cec5SDimitry Andric // a basic block is removed we would lose the debug information unless we have
13070b57cec5SDimitry Andric // copied the information to a predecessor/successor.
13080b57cec5SDimitry Andric //
13090b57cec5SDimitry Andric // TODO: This function only handles some simple cases. An alternative would be
13100b57cec5SDimitry Andric // to run a heavier analysis, such as the LiveDebugValues pass, before we do
13110b57cec5SDimitry Andric // branch folding.
13120b57cec5SDimitry Andric static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,
13130b57cec5SDimitry Andric                                            MachineBasicBlock &MBB) {
13140b57cec5SDimitry Andric   assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");
13150b57cec5SDimitry Andric   // If this MBB is the only predecessor of a successor it is legal to copy
13160b57cec5SDimitry Andric   // DBG_VALUE instructions to the beginning of the successor.
13170b57cec5SDimitry Andric   for (MachineBasicBlock *SuccBB : MBB.successors())
13180b57cec5SDimitry Andric     if (SuccBB->pred_size() == 1)
13190b57cec5SDimitry Andric       copyDebugInfoToSuccessor(TII, MBB, *SuccBB);
13200b57cec5SDimitry Andric   // If this MBB is the only successor of a predecessor it is legal to copy the
13210b57cec5SDimitry Andric   // DBG_VALUE instructions to the end of the predecessor (just before the
13220b57cec5SDimitry Andric   // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
13230b57cec5SDimitry Andric   for (MachineBasicBlock *PredBB : MBB.predecessors())
13240b57cec5SDimitry Andric     if (PredBB->succ_size() == 1)
13250b57cec5SDimitry Andric       copyDebugInfoToPredecessor(TII, MBB, *PredBB);
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
13290b57cec5SDimitry Andric   bool MadeChange = false;
13300b57cec5SDimitry Andric   MachineFunction &MF = *MBB->getParent();
13310b57cec5SDimitry Andric ReoptimizeBlock:
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   MachineFunction::iterator FallThrough = MBB->getIterator();
13340b57cec5SDimitry Andric   ++FallThrough;
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   // Make sure MBB and FallThrough belong to the same EH scope.
13370b57cec5SDimitry Andric   bool SameEHScope = true;
13380b57cec5SDimitry Andric   if (!EHScopeMembership.empty() && FallThrough != MF.end()) {
13390b57cec5SDimitry Andric     auto MBBEHScope = EHScopeMembership.find(MBB);
13400b57cec5SDimitry Andric     assert(MBBEHScope != EHScopeMembership.end());
13410b57cec5SDimitry Andric     auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);
13420b57cec5SDimitry Andric     assert(FallThroughEHScope != EHScopeMembership.end());
13430b57cec5SDimitry Andric     SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
13440b57cec5SDimitry Andric   }
13450b57cec5SDimitry Andric 
13465ffd83dbSDimitry Andric   // Analyze the branch in the current block. As a side-effect, this may cause
13475ffd83dbSDimitry Andric   // the block to become empty.
13485ffd83dbSDimitry Andric   MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
13495ffd83dbSDimitry Andric   SmallVector<MachineOperand, 4> CurCond;
13505ffd83dbSDimitry Andric   bool CurUnAnalyzable =
13515ffd83dbSDimitry Andric       TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
13525ffd83dbSDimitry Andric 
13530b57cec5SDimitry Andric   // If this block is empty, make everyone use its fall-through, not the block
13540b57cec5SDimitry Andric   // explicitly.  Landing pads should not do this since the landing-pad table
13550b57cec5SDimitry Andric   // points to this block.  Blocks with their addresses taken shouldn't be
13560b57cec5SDimitry Andric   // optimized away.
13570b57cec5SDimitry Andric   if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
13580b57cec5SDimitry Andric       SameEHScope) {
13590b57cec5SDimitry Andric     salvageDebugInfoFromEmptyBlock(TII, *MBB);
13600b57cec5SDimitry Andric     // Dead block?  Leave for cleanup later.
13610b57cec5SDimitry Andric     if (MBB->pred_empty()) return MadeChange;
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric     if (FallThrough == MF.end()) {
13640b57cec5SDimitry Andric       // TODO: Simplify preds to not branch here if possible!
13650b57cec5SDimitry Andric     } else if (FallThrough->isEHPad()) {
13660b57cec5SDimitry Andric       // Don't rewrite to a landing pad fallthough.  That could lead to the case
13670b57cec5SDimitry Andric       // where a BB jumps to more than one landing pad.
13680b57cec5SDimitry Andric       // TODO: Is it ever worth rewriting predecessors which don't already
13690b57cec5SDimitry Andric       // jump to a landing pad, and so can safely jump to the fallthrough?
13700b57cec5SDimitry Andric     } else if (MBB->isSuccessor(&*FallThrough)) {
13710b57cec5SDimitry Andric       // Rewrite all predecessors of the old block to go to the fallthrough
13720b57cec5SDimitry Andric       // instead.
13730b57cec5SDimitry Andric       while (!MBB->pred_empty()) {
13740b57cec5SDimitry Andric         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
13750b57cec5SDimitry Andric         Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
13760b57cec5SDimitry Andric       }
1377297eecfbSDimitry Andric       // Add rest successors of MBB to successors of FallThrough. Those
1378297eecfbSDimitry Andric       // successors are not directly reachable via MBB, so it should be
1379297eecfbSDimitry Andric       // landing-pad.
1380297eecfbSDimitry Andric       for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
1381297eecfbSDimitry Andric         if (*SI != &*FallThrough && !FallThrough->isSuccessor(*SI)) {
1382297eecfbSDimitry Andric           assert((*SI)->isEHPad() && "Bad CFG");
1383297eecfbSDimitry Andric           FallThrough->copySuccessor(MBB, SI);
1384297eecfbSDimitry Andric         }
13850b57cec5SDimitry Andric       // If MBB was the target of a jump table, update jump tables to go to the
13860b57cec5SDimitry Andric       // fallthrough instead.
13870b57cec5SDimitry Andric       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
13880b57cec5SDimitry Andric         MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
13890b57cec5SDimitry Andric       MadeChange = true;
13900b57cec5SDimitry Andric     }
13910b57cec5SDimitry Andric     return MadeChange;
13920b57cec5SDimitry Andric   }
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric   // Check to see if we can simplify the terminator of the block before this
13950b57cec5SDimitry Andric   // one.
13960b57cec5SDimitry Andric   MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
13990b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> PriorCond;
14000b57cec5SDimitry Andric   bool PriorUnAnalyzable =
14010b57cec5SDimitry Andric       TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
14020b57cec5SDimitry Andric   if (!PriorUnAnalyzable) {
14030b57cec5SDimitry Andric     // If the previous branch is conditional and both conditions go to the same
14040b57cec5SDimitry Andric     // destination, remove the branch, replacing it with an unconditional one or
14050b57cec5SDimitry Andric     // a fall-through.
14060b57cec5SDimitry Andric     if (PriorTBB && PriorTBB == PriorFBB) {
14070b57cec5SDimitry Andric       DebugLoc dl = getBranchDebugLoc(PrevBB);
14080b57cec5SDimitry Andric       TII->removeBranch(PrevBB);
14090b57cec5SDimitry Andric       PriorCond.clear();
14100b57cec5SDimitry Andric       if (PriorTBB != MBB)
14110b57cec5SDimitry Andric         TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
14120b57cec5SDimitry Andric       MadeChange = true;
14130b57cec5SDimitry Andric       ++NumBranchOpts;
14140b57cec5SDimitry Andric       goto ReoptimizeBlock;
14150b57cec5SDimitry Andric     }
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric     // If the previous block unconditionally falls through to this block and
14180b57cec5SDimitry Andric     // this block has no other predecessors, move the contents of this block
14190b57cec5SDimitry Andric     // into the prior block. This doesn't usually happen when SimplifyCFG
14200b57cec5SDimitry Andric     // has been used, but it can happen if tail merging splits a fall-through
14210b57cec5SDimitry Andric     // predecessor of a block.
14220b57cec5SDimitry Andric     // This has to check PrevBB->succ_size() because EH edges are ignored by
14235ffd83dbSDimitry Andric     // analyzeBranch.
14240b57cec5SDimitry Andric     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
14257a6dacacSDimitry Andric         PrevBB.succ_size() == 1 && PrevBB.isSuccessor(MBB) &&
14260b57cec5SDimitry Andric         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
14270b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
14280b57cec5SDimitry Andric                         << "From MBB: " << *MBB);
14290b57cec5SDimitry Andric       // Remove redundant DBG_VALUEs first.
1430e8d8bef9SDimitry Andric       if (!PrevBB.empty()) {
14310b57cec5SDimitry Andric         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
14320b57cec5SDimitry Andric         --PrevBBIter;
14330b57cec5SDimitry Andric         MachineBasicBlock::iterator MBBIter = MBB->begin();
14340b57cec5SDimitry Andric         // Check if DBG_VALUE at the end of PrevBB is identical to the
14350b57cec5SDimitry Andric         // DBG_VALUE at the beginning of MBB.
14360b57cec5SDimitry Andric         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
14370b57cec5SDimitry Andric                && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {
14380b57cec5SDimitry Andric           if (!MBBIter->isIdenticalTo(*PrevBBIter))
14390b57cec5SDimitry Andric             break;
14400b57cec5SDimitry Andric           MachineInstr &DuplicateDbg = *MBBIter;
14410b57cec5SDimitry Andric           ++MBBIter; -- PrevBBIter;
14420b57cec5SDimitry Andric           DuplicateDbg.eraseFromParent();
14430b57cec5SDimitry Andric         }
14440b57cec5SDimitry Andric       }
14450b57cec5SDimitry Andric       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
14460b57cec5SDimitry Andric       PrevBB.removeSuccessor(PrevBB.succ_begin());
14470b57cec5SDimitry Andric       assert(PrevBB.succ_empty());
14480b57cec5SDimitry Andric       PrevBB.transferSuccessors(MBB);
14490b57cec5SDimitry Andric       MadeChange = true;
14500b57cec5SDimitry Andric       return MadeChange;
14510b57cec5SDimitry Andric     }
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric     // If the previous branch *only* branches to *this* block (conditional or
14540b57cec5SDimitry Andric     // not) remove the branch.
14550b57cec5SDimitry Andric     if (PriorTBB == MBB && !PriorFBB) {
14560b57cec5SDimitry Andric       TII->removeBranch(PrevBB);
14570b57cec5SDimitry Andric       MadeChange = true;
14580b57cec5SDimitry Andric       ++NumBranchOpts;
14590b57cec5SDimitry Andric       goto ReoptimizeBlock;
14600b57cec5SDimitry Andric     }
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric     // If the prior block branches somewhere else on the condition and here if
14630b57cec5SDimitry Andric     // the condition is false, remove the uncond second branch.
14640b57cec5SDimitry Andric     if (PriorFBB == MBB) {
14650b57cec5SDimitry Andric       DebugLoc dl = getBranchDebugLoc(PrevBB);
14660b57cec5SDimitry Andric       TII->removeBranch(PrevBB);
14670b57cec5SDimitry Andric       TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
14680b57cec5SDimitry Andric       MadeChange = true;
14690b57cec5SDimitry Andric       ++NumBranchOpts;
14700b57cec5SDimitry Andric       goto ReoptimizeBlock;
14710b57cec5SDimitry Andric     }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric     // If the prior block branches here on true and somewhere else on false, and
14740b57cec5SDimitry Andric     // if the branch condition is reversible, reverse the branch to create a
14750b57cec5SDimitry Andric     // fall-through.
14760b57cec5SDimitry Andric     if (PriorTBB == MBB) {
14770b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
14780b57cec5SDimitry Andric       if (!TII->reverseBranchCondition(NewPriorCond)) {
14790b57cec5SDimitry Andric         DebugLoc dl = getBranchDebugLoc(PrevBB);
14800b57cec5SDimitry Andric         TII->removeBranch(PrevBB);
14810b57cec5SDimitry Andric         TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
14820b57cec5SDimitry Andric         MadeChange = true;
14830b57cec5SDimitry Andric         ++NumBranchOpts;
14840b57cec5SDimitry Andric         goto ReoptimizeBlock;
14850b57cec5SDimitry Andric       }
14860b57cec5SDimitry Andric     }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // If this block has no successors (e.g. it is a return block or ends with
14890b57cec5SDimitry Andric     // a call to a no-return function like abort or __cxa_throw) and if the pred
14900b57cec5SDimitry Andric     // falls through into this block, and if it would otherwise fall through
14910b57cec5SDimitry Andric     // into the block after this, move this block to the end of the function.
14920b57cec5SDimitry Andric     //
14930b57cec5SDimitry Andric     // We consider it more likely that execution will stay in the function (e.g.
14940b57cec5SDimitry Andric     // due to loops) than it is to exit it.  This asserts in loops etc, moving
14950b57cec5SDimitry Andric     // the assert condition out of the loop body.
14960b57cec5SDimitry Andric     if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
14970b57cec5SDimitry Andric         MachineFunction::iterator(PriorTBB) == FallThrough &&
14980b57cec5SDimitry Andric         !MBB->canFallThrough()) {
14990b57cec5SDimitry Andric       bool DoTransform = true;
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric       // We have to be careful that the succs of PredBB aren't both no-successor
15020b57cec5SDimitry Andric       // blocks.  If neither have successors and if PredBB is the second from
15030b57cec5SDimitry Andric       // last block in the function, we'd just keep swapping the two blocks for
15040b57cec5SDimitry Andric       // last.  Only do the swap if one is clearly better to fall through than
15050b57cec5SDimitry Andric       // the other.
15060b57cec5SDimitry Andric       if (FallThrough == --MF.end() &&
15070b57cec5SDimitry Andric           !IsBetterFallthrough(PriorTBB, MBB))
15080b57cec5SDimitry Andric         DoTransform = false;
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric       if (DoTransform) {
15110b57cec5SDimitry Andric         // Reverse the branch so we will fall through on the previous true cond.
15120b57cec5SDimitry Andric         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
15130b57cec5SDimitry Andric         if (!TII->reverseBranchCondition(NewPriorCond)) {
15140b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
15150b57cec5SDimitry Andric                             << "To make fallthrough to: " << *PriorTBB << "\n");
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric           DebugLoc dl = getBranchDebugLoc(PrevBB);
15180b57cec5SDimitry Andric           TII->removeBranch(PrevBB);
15190b57cec5SDimitry Andric           TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric           // Move this block to the end of the function.
15220b57cec5SDimitry Andric           MBB->moveAfter(&MF.back());
15230b57cec5SDimitry Andric           MadeChange = true;
15240b57cec5SDimitry Andric           ++NumBranchOpts;
15250b57cec5SDimitry Andric           return MadeChange;
15260b57cec5SDimitry Andric         }
15270b57cec5SDimitry Andric       }
15280b57cec5SDimitry Andric     }
15290b57cec5SDimitry Andric   }
15300b57cec5SDimitry Andric 
153106c3fb27SDimitry Andric   if (!IsEmptyBlock(MBB)) {
15320b57cec5SDimitry Andric     MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
15330b57cec5SDimitry Andric     if (TII->isUnconditionalTailCall(TailCall)) {
153406c3fb27SDimitry Andric       SmallVector<MachineBasicBlock *> PredsChanged;
153506c3fb27SDimitry Andric       for (auto &Pred : MBB->predecessors()) {
15360b57cec5SDimitry Andric         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
15370b57cec5SDimitry Andric         SmallVector<MachineOperand, 4> PredCond;
15380b57cec5SDimitry Andric         bool PredAnalyzable =
15390b57cec5SDimitry Andric             !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
15400b57cec5SDimitry Andric 
154106c3fb27SDimitry Andric         // Only eliminate if MBB == TBB (Taken Basic Block)
15420b57cec5SDimitry Andric         if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB &&
15430b57cec5SDimitry Andric             PredTBB != PredFBB) {
154406c3fb27SDimitry Andric           // The predecessor has a conditional branch to this block which
154506c3fb27SDimitry Andric           // consists of only a tail call. Try to fold the tail call into the
154606c3fb27SDimitry Andric           // conditional branch.
15470b57cec5SDimitry Andric           if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
15480b57cec5SDimitry Andric             // TODO: It would be nice if analyzeBranch() could provide a pointer
15490b57cec5SDimitry Andric             // to the branch instruction so replaceBranchWithTailCall() doesn't
15500b57cec5SDimitry Andric             // have to search for it.
15510b57cec5SDimitry Andric             TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
155206c3fb27SDimitry Andric             PredsChanged.push_back(Pred);
15530b57cec5SDimitry Andric           }
15540b57cec5SDimitry Andric         }
15550b57cec5SDimitry Andric         // If the predecessor is falling through to this block, we could reverse
15560b57cec5SDimitry Andric         // the branch condition and fold the tail call into that. However, after
15570b57cec5SDimitry Andric         // that we might have to re-arrange the CFG to fall through to the other
15580b57cec5SDimitry Andric         // block and there is a high risk of regressing code size rather than
15590b57cec5SDimitry Andric         // improving it.
15600b57cec5SDimitry Andric       }
156106c3fb27SDimitry Andric       if (!PredsChanged.empty()) {
156206c3fb27SDimitry Andric         NumTailCalls += PredsChanged.size();
156306c3fb27SDimitry Andric         for (auto &Pred : PredsChanged)
156406c3fb27SDimitry Andric           Pred->removeSuccessor(MBB);
156506c3fb27SDimitry Andric 
156606c3fb27SDimitry Andric         return true;
156706c3fb27SDimitry Andric       }
156806c3fb27SDimitry Andric     }
15690b57cec5SDimitry Andric   }
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   if (!CurUnAnalyzable) {
15720b57cec5SDimitry Andric     // If this is a two-way branch, and the FBB branches to this block, reverse
15730b57cec5SDimitry Andric     // the condition so the single-basic-block loop is faster.  Instead of:
15740b57cec5SDimitry Andric     //    Loop: xxx; jcc Out; jmp Loop
15750b57cec5SDimitry Andric     // we want:
15760b57cec5SDimitry Andric     //    Loop: xxx; jncc Loop; jmp Out
15770b57cec5SDimitry Andric     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
15780b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> NewCond(CurCond);
15790b57cec5SDimitry Andric       if (!TII->reverseBranchCondition(NewCond)) {
15800b57cec5SDimitry Andric         DebugLoc dl = getBranchDebugLoc(*MBB);
15810b57cec5SDimitry Andric         TII->removeBranch(*MBB);
15820b57cec5SDimitry Andric         TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
15830b57cec5SDimitry Andric         MadeChange = true;
15840b57cec5SDimitry Andric         ++NumBranchOpts;
15850b57cec5SDimitry Andric         goto ReoptimizeBlock;
15860b57cec5SDimitry Andric       }
15870b57cec5SDimitry Andric     }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric     // If this branch is the only thing in its block, see if we can forward
15900b57cec5SDimitry Andric     // other blocks across it.
15910b57cec5SDimitry Andric     if (CurTBB && CurCond.empty() && !CurFBB &&
15920b57cec5SDimitry Andric         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
15930b57cec5SDimitry Andric         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
15940b57cec5SDimitry Andric       DebugLoc dl = getBranchDebugLoc(*MBB);
15950b57cec5SDimitry Andric       // This block may contain just an unconditional branch.  Because there can
15960b57cec5SDimitry Andric       // be 'non-branch terminators' in the block, try removing the branch and
15970b57cec5SDimitry Andric       // then seeing if the block is empty.
15980b57cec5SDimitry Andric       TII->removeBranch(*MBB);
15990b57cec5SDimitry Andric       // If the only things remaining in the block are debug info, remove these
16000b57cec5SDimitry Andric       // as well, so this will behave the same as an empty block in non-debug
16010b57cec5SDimitry Andric       // mode.
16020b57cec5SDimitry Andric       if (IsEmptyBlock(MBB)) {
16030b57cec5SDimitry Andric         // Make the block empty, losing the debug info (we could probably
16040b57cec5SDimitry Andric         // improve this in some cases.)
16050b57cec5SDimitry Andric         MBB->erase(MBB->begin(), MBB->end());
16060b57cec5SDimitry Andric       }
16070b57cec5SDimitry Andric       // If this block is just an unconditional branch to CurTBB, we can
16080b57cec5SDimitry Andric       // usually completely eliminate the block.  The only case we cannot
16090b57cec5SDimitry Andric       // completely eliminate the block is when the block before this one
16100b57cec5SDimitry Andric       // falls through into MBB and we can't understand the prior block's branch
16110b57cec5SDimitry Andric       // condition.
16120b57cec5SDimitry Andric       if (MBB->empty()) {
16130b57cec5SDimitry Andric         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
16140b57cec5SDimitry Andric         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
16150b57cec5SDimitry Andric             !PrevBB.isSuccessor(MBB)) {
16160b57cec5SDimitry Andric           // If the prior block falls through into us, turn it into an
16170b57cec5SDimitry Andric           // explicit branch to us to make updates simpler.
16180b57cec5SDimitry Andric           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
16190b57cec5SDimitry Andric               PriorTBB != MBB && PriorFBB != MBB) {
16200b57cec5SDimitry Andric             if (!PriorTBB) {
16210b57cec5SDimitry Andric               assert(PriorCond.empty() && !PriorFBB &&
16220b57cec5SDimitry Andric                      "Bad branch analysis");
16230b57cec5SDimitry Andric               PriorTBB = MBB;
16240b57cec5SDimitry Andric             } else {
16250b57cec5SDimitry Andric               assert(!PriorFBB && "Machine CFG out of date!");
16260b57cec5SDimitry Andric               PriorFBB = MBB;
16270b57cec5SDimitry Andric             }
16280b57cec5SDimitry Andric             DebugLoc pdl = getBranchDebugLoc(PrevBB);
16290b57cec5SDimitry Andric             TII->removeBranch(PrevBB);
16300b57cec5SDimitry Andric             TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
16310b57cec5SDimitry Andric           }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric           // Iterate through all the predecessors, revectoring each in-turn.
16340b57cec5SDimitry Andric           size_t PI = 0;
16350b57cec5SDimitry Andric           bool DidChange = false;
16360b57cec5SDimitry Andric           bool HasBranchToSelf = false;
16370b57cec5SDimitry Andric           while(PI != MBB->pred_size()) {
16380b57cec5SDimitry Andric             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
16390b57cec5SDimitry Andric             if (PMBB == MBB) {
16400b57cec5SDimitry Andric               // If this block has an uncond branch to itself, leave it.
16410b57cec5SDimitry Andric               ++PI;
16420b57cec5SDimitry Andric               HasBranchToSelf = true;
16430b57cec5SDimitry Andric             } else {
16440b57cec5SDimitry Andric               DidChange = true;
16450b57cec5SDimitry Andric               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1646297eecfbSDimitry Andric               // Add rest successors of MBB to successors of CurTBB. Those
1647297eecfbSDimitry Andric               // successors are not directly reachable via MBB, so it should be
1648297eecfbSDimitry Andric               // landing-pad.
1649297eecfbSDimitry Andric               for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE;
1650297eecfbSDimitry Andric                    ++SI)
1651297eecfbSDimitry Andric                 if (*SI != CurTBB && !CurTBB->isSuccessor(*SI)) {
1652297eecfbSDimitry Andric                   assert((*SI)->isEHPad() && "Bad CFG");
1653297eecfbSDimitry Andric                   CurTBB->copySuccessor(MBB, SI);
1654297eecfbSDimitry Andric                 }
16550b57cec5SDimitry Andric               // If this change resulted in PMBB ending in a conditional
16560b57cec5SDimitry Andric               // branch where both conditions go to the same destination,
16575ffd83dbSDimitry Andric               // change this to an unconditional branch.
16580b57cec5SDimitry Andric               MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
16590b57cec5SDimitry Andric               SmallVector<MachineOperand, 4> NewCurCond;
16600b57cec5SDimitry Andric               bool NewCurUnAnalyzable = TII->analyzeBranch(
16610b57cec5SDimitry Andric                   *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
16620b57cec5SDimitry Andric               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
16630b57cec5SDimitry Andric                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
16640b57cec5SDimitry Andric                 TII->removeBranch(*PMBB);
16650b57cec5SDimitry Andric                 NewCurCond.clear();
16660b57cec5SDimitry Andric                 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
16670b57cec5SDimitry Andric                 MadeChange = true;
16680b57cec5SDimitry Andric                 ++NumBranchOpts;
16690b57cec5SDimitry Andric               }
16700b57cec5SDimitry Andric             }
16710b57cec5SDimitry Andric           }
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric           // Change any jumptables to go to the new MBB.
16740b57cec5SDimitry Andric           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
16750b57cec5SDimitry Andric             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
16760b57cec5SDimitry Andric           if (DidChange) {
16770b57cec5SDimitry Andric             ++NumBranchOpts;
16780b57cec5SDimitry Andric             MadeChange = true;
16790b57cec5SDimitry Andric             if (!HasBranchToSelf) return MadeChange;
16800b57cec5SDimitry Andric           }
16810b57cec5SDimitry Andric         }
16820b57cec5SDimitry Andric       }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric       // Add the branch back if the block is more than just an uncond branch.
16850b57cec5SDimitry Andric       TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
16860b57cec5SDimitry Andric     }
16870b57cec5SDimitry Andric   }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   // If the prior block doesn't fall through into this block, and if this
16900b57cec5SDimitry Andric   // block doesn't fall through into some other block, see if we can find a
16910b57cec5SDimitry Andric   // place to move this block where a fall-through will happen.
16920b57cec5SDimitry Andric   if (!PrevBB.canFallThrough()) {
16930b57cec5SDimitry Andric     // Now we know that there was no fall-through into this block, check to
16940b57cec5SDimitry Andric     // see if it has a fall-through into its successor.
16950b57cec5SDimitry Andric     bool CurFallsThru = MBB->canFallThrough();
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric     if (!MBB->isEHPad()) {
16980b57cec5SDimitry Andric       // Check all the predecessors of this block.  If one of them has no fall
16995ffd83dbSDimitry Andric       // throughs, and analyzeBranch thinks it _could_ fallthrough to this
17005ffd83dbSDimitry Andric       // block, move this block right after it.
17010b57cec5SDimitry Andric       for (MachineBasicBlock *PredBB : MBB->predecessors()) {
17020b57cec5SDimitry Andric         // Analyze the branch at the end of the pred.
17030b57cec5SDimitry Andric         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
17040b57cec5SDimitry Andric         SmallVector<MachineOperand, 4> PredCond;
17050b57cec5SDimitry Andric         if (PredBB != MBB && !PredBB->canFallThrough() &&
17060b57cec5SDimitry Andric             !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
17075ffd83dbSDimitry Andric             (PredTBB == MBB || PredFBB == MBB) &&
17080b57cec5SDimitry Andric             (!CurFallsThru || !CurTBB || !CurFBB) &&
17090b57cec5SDimitry Andric             (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
17100b57cec5SDimitry Andric           // If the current block doesn't fall through, just move it.
17110b57cec5SDimitry Andric           // If the current block can fall through and does not end with a
17120b57cec5SDimitry Andric           // conditional branch, we need to append an unconditional jump to
17130b57cec5SDimitry Andric           // the (current) next block.  To avoid a possible compile-time
17140b57cec5SDimitry Andric           // infinite loop, move blocks only backward in this case.
17150b57cec5SDimitry Andric           // Also, if there are already 2 branches here, we cannot add a third;
17160b57cec5SDimitry Andric           // this means we have the case
17170b57cec5SDimitry Andric           // Bcc next
17180b57cec5SDimitry Andric           // B elsewhere
17190b57cec5SDimitry Andric           // next:
17200b57cec5SDimitry Andric           if (CurFallsThru) {
17210b57cec5SDimitry Andric             MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
17220b57cec5SDimitry Andric             CurCond.clear();
17230b57cec5SDimitry Andric             TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
17240b57cec5SDimitry Andric           }
17250b57cec5SDimitry Andric           MBB->moveAfter(PredBB);
17260b57cec5SDimitry Andric           MadeChange = true;
17270b57cec5SDimitry Andric           goto ReoptimizeBlock;
17280b57cec5SDimitry Andric         }
17290b57cec5SDimitry Andric       }
17300b57cec5SDimitry Andric     }
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric     if (!CurFallsThru) {
17335ffd83dbSDimitry Andric       // Check analyzable branch-successors to see if we can move this block
17345ffd83dbSDimitry Andric       // before one.
17355ffd83dbSDimitry Andric       if (!CurUnAnalyzable) {
17365ffd83dbSDimitry Andric         for (MachineBasicBlock *SuccBB : {CurFBB, CurTBB}) {
17375ffd83dbSDimitry Andric           if (!SuccBB)
17385ffd83dbSDimitry Andric             continue;
17390b57cec5SDimitry Andric           // Analyze the branch at the end of the block before the succ.
17400b57cec5SDimitry Andric           MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
17410b57cec5SDimitry Andric 
17425ffd83dbSDimitry Andric           // If this block doesn't already fall-through to that successor, and
17435ffd83dbSDimitry Andric           // if the succ doesn't already have a block that can fall through into
17445ffd83dbSDimitry Andric           // it, we can arrange for the fallthrough to happen.
17450b57cec5SDimitry Andric           if (SuccBB != MBB && &*SuccPrev != MBB &&
17465ffd83dbSDimitry Andric               !SuccPrev->canFallThrough()) {
17470b57cec5SDimitry Andric             MBB->moveBefore(SuccBB);
17480b57cec5SDimitry Andric             MadeChange = true;
17490b57cec5SDimitry Andric             goto ReoptimizeBlock;
17500b57cec5SDimitry Andric           }
17510b57cec5SDimitry Andric         }
17525ffd83dbSDimitry Andric       }
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric       // Okay, there is no really great place to put this block.  If, however,
17550b57cec5SDimitry Andric       // the block before this one would be a fall-through if this block were
17560b57cec5SDimitry Andric       // removed, move this block to the end of the function. There is no real
17570b57cec5SDimitry Andric       // advantage in "falling through" to an EH block, so we don't want to
17580b57cec5SDimitry Andric       // perform this transformation for that case.
17590b57cec5SDimitry Andric       //
17600b57cec5SDimitry Andric       // Also, Windows EH introduced the possibility of an arbitrary number of
17610b57cec5SDimitry Andric       // successors to a given block.  The analyzeBranch call does not consider
17620b57cec5SDimitry Andric       // exception handling and so we can get in a state where a block
17630b57cec5SDimitry Andric       // containing a call is followed by multiple EH blocks that would be
17640b57cec5SDimitry Andric       // rotated infinitely at the end of the function if the transformation
17650b57cec5SDimitry Andric       // below were performed for EH "FallThrough" blocks.  Therefore, even if
17660b57cec5SDimitry Andric       // that appears not to be happening anymore, we should assume that it is
17670b57cec5SDimitry Andric       // possible and not remove the "!FallThrough()->isEHPad" condition below.
17680b57cec5SDimitry Andric       MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
17690b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> PrevCond;
17700b57cec5SDimitry Andric       if (FallThrough != MF.end() &&
17710b57cec5SDimitry Andric           !FallThrough->isEHPad() &&
17720b57cec5SDimitry Andric           !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
17730b57cec5SDimitry Andric           PrevBB.isSuccessor(&*FallThrough)) {
17740b57cec5SDimitry Andric         MBB->moveAfter(&MF.back());
17750b57cec5SDimitry Andric         MadeChange = true;
17760b57cec5SDimitry Andric         return MadeChange;
17770b57cec5SDimitry Andric       }
17780b57cec5SDimitry Andric     }
17790b57cec5SDimitry Andric   }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   return MadeChange;
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17850b57cec5SDimitry Andric //  Hoist Common Code
17860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
17890b57cec5SDimitry Andric   bool MadeChange = false;
1790349cc55cSDimitry Andric   for (MachineBasicBlock &MBB : llvm::make_early_inc_range(MF))
1791349cc55cSDimitry Andric     MadeChange |= HoistCommonCodeInSuccs(&MBB);
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   return MadeChange;
17940b57cec5SDimitry Andric }
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
17970b57cec5SDimitry Andric /// its 'true' successor.
17980b57cec5SDimitry Andric static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
17990b57cec5SDimitry Andric                                          MachineBasicBlock *TrueBB) {
18000b57cec5SDimitry Andric   for (MachineBasicBlock *SuccBB : BB->successors())
18010b57cec5SDimitry Andric     if (SuccBB != TrueBB)
18020b57cec5SDimitry Andric       return SuccBB;
18030b57cec5SDimitry Andric   return nullptr;
18040b57cec5SDimitry Andric }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric template <class Container>
18075ffd83dbSDimitry Andric static void addRegAndItsAliases(Register Reg, const TargetRegisterInfo *TRI,
18080b57cec5SDimitry Andric                                 Container &Set) {
18095ffd83dbSDimitry Andric   if (Reg.isPhysical()) {
18100b57cec5SDimitry Andric     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
18110b57cec5SDimitry Andric       Set.insert(*AI);
18120b57cec5SDimitry Andric   } else {
18130b57cec5SDimitry Andric     Set.insert(Reg);
18140b57cec5SDimitry Andric   }
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric /// findHoistingInsertPosAndDeps - Find the location to move common instructions
18180b57cec5SDimitry Andric /// in successors to. The location is usually just before the terminator,
18190b57cec5SDimitry Andric /// however if the terminator is a conditional branch and its previous
18200b57cec5SDimitry Andric /// instruction is the flag setting instruction, the previous instruction is
18210b57cec5SDimitry Andric /// the preferred location. This function also gathers uses and defs of the
18220b57cec5SDimitry Andric /// instructions from the insertion point to the end of the block. The data is
18230b57cec5SDimitry Andric /// used by HoistCommonCodeInSuccs to ensure safety.
18240b57cec5SDimitry Andric static
18250b57cec5SDimitry Andric MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
18260b57cec5SDimitry Andric                                                   const TargetInstrInfo *TII,
18270b57cec5SDimitry Andric                                                   const TargetRegisterInfo *TRI,
18285ffd83dbSDimitry Andric                                                   SmallSet<Register, 4> &Uses,
18295ffd83dbSDimitry Andric                                                   SmallSet<Register, 4> &Defs) {
18300b57cec5SDimitry Andric   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
18310b57cec5SDimitry Andric   if (!TII->isUnpredicatedTerminator(*Loc))
18320b57cec5SDimitry Andric     return MBB->end();
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   for (const MachineOperand &MO : Loc->operands()) {
18350b57cec5SDimitry Andric     if (!MO.isReg())
18360b57cec5SDimitry Andric       continue;
18378bcb0991SDimitry Andric     Register Reg = MO.getReg();
18380b57cec5SDimitry Andric     if (!Reg)
18390b57cec5SDimitry Andric       continue;
18400b57cec5SDimitry Andric     if (MO.isUse()) {
18410b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, Uses);
18420b57cec5SDimitry Andric     } else {
18430b57cec5SDimitry Andric       if (!MO.isDead())
18440b57cec5SDimitry Andric         // Don't try to hoist code in the rare case the terminator defines a
18450b57cec5SDimitry Andric         // register that is later used.
18460b57cec5SDimitry Andric         return MBB->end();
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric       // If the terminator defines a register, make sure we don't hoist
18490b57cec5SDimitry Andric       // the instruction whose def might be clobbered by the terminator.
18500b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, Defs);
18510b57cec5SDimitry Andric     }
18520b57cec5SDimitry Andric   }
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   if (Uses.empty())
18550b57cec5SDimitry Andric     return Loc;
18560b57cec5SDimitry Andric   // If the terminator is the only instruction in the block and Uses is not
18570b57cec5SDimitry Andric   // empty (or we would have returned above), we can still safely hoist
18580b57cec5SDimitry Andric   // instructions just before the terminator as long as the Defs/Uses are not
18590b57cec5SDimitry Andric   // violated (which is checked in HoistCommonCodeInSuccs).
18600b57cec5SDimitry Andric   if (Loc == MBB->begin())
18610b57cec5SDimitry Andric     return Loc;
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric   // The terminator is probably a conditional branch, try not to separate the
18640b57cec5SDimitry Andric   // branch from condition setting instruction.
18655ffd83dbSDimitry Andric   MachineBasicBlock::iterator PI = prev_nodbg(Loc, MBB->begin());
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric   bool IsDef = false;
18680b57cec5SDimitry Andric   for (const MachineOperand &MO : PI->operands()) {
18690b57cec5SDimitry Andric     // If PI has a regmask operand, it is probably a call. Separate away.
18700b57cec5SDimitry Andric     if (MO.isRegMask())
18710b57cec5SDimitry Andric       return Loc;
18720b57cec5SDimitry Andric     if (!MO.isReg() || MO.isUse())
18730b57cec5SDimitry Andric       continue;
18748bcb0991SDimitry Andric     Register Reg = MO.getReg();
18750b57cec5SDimitry Andric     if (!Reg)
18760b57cec5SDimitry Andric       continue;
18770b57cec5SDimitry Andric     if (Uses.count(Reg)) {
18780b57cec5SDimitry Andric       IsDef = true;
18790b57cec5SDimitry Andric       break;
18800b57cec5SDimitry Andric     }
18810b57cec5SDimitry Andric   }
18820b57cec5SDimitry Andric   if (!IsDef)
18830b57cec5SDimitry Andric     // The condition setting instruction is not just before the conditional
18840b57cec5SDimitry Andric     // branch.
18850b57cec5SDimitry Andric     return Loc;
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric   // Be conservative, don't insert instruction above something that may have
18880b57cec5SDimitry Andric   // side-effects. And since it's potentially bad to separate flag setting
18890b57cec5SDimitry Andric   // instruction from the conditional branch, just abort the optimization
18900b57cec5SDimitry Andric   // completely.
18910b57cec5SDimitry Andric   // Also avoid moving code above predicated instruction since it's hard to
18920b57cec5SDimitry Andric   // reason about register liveness with predicated instruction.
18930b57cec5SDimitry Andric   bool DontMoveAcrossStore = true;
18940b57cec5SDimitry Andric   if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
18950b57cec5SDimitry Andric     return MBB->end();
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric   // Find out what registers are live. Note this routine is ignoring other live
18980b57cec5SDimitry Andric   // registers which are only used by instructions in successor blocks.
18990b57cec5SDimitry Andric   for (const MachineOperand &MO : PI->operands()) {
19000b57cec5SDimitry Andric     if (!MO.isReg())
19010b57cec5SDimitry Andric       continue;
19028bcb0991SDimitry Andric     Register Reg = MO.getReg();
19030b57cec5SDimitry Andric     if (!Reg)
19040b57cec5SDimitry Andric       continue;
19050b57cec5SDimitry Andric     if (MO.isUse()) {
19060b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, Uses);
19070b57cec5SDimitry Andric     } else {
19080b57cec5SDimitry Andric       if (Uses.erase(Reg)) {
1909bdd1243dSDimitry Andric         if (Reg.isPhysical()) {
191006c3fb27SDimitry Andric           for (MCPhysReg SubReg : TRI->subregs(Reg))
191106c3fb27SDimitry Andric             Uses.erase(SubReg); // Use sub-registers to be conservative
19120b57cec5SDimitry Andric         }
19130b57cec5SDimitry Andric       }
19140b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, Defs);
19150b57cec5SDimitry Andric     }
19160b57cec5SDimitry Andric   }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric   return PI;
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
19220b57cec5SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
19230b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
19240b57cec5SDimitry Andric   if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
19250b57cec5SDimitry Andric     return false;
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   if (!FBB) FBB = findFalseBlock(MBB, TBB);
19280b57cec5SDimitry Andric   if (!FBB)
19290b57cec5SDimitry Andric     // Malformed bcc? True and false blocks are the same?
19300b57cec5SDimitry Andric     return false;
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric   // Restrict the optimization to cases where MBB is the only predecessor,
19330b57cec5SDimitry Andric   // it is an obvious win.
19340b57cec5SDimitry Andric   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
19350b57cec5SDimitry Andric     return false;
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   // Find a suitable position to hoist the common instructions to. Also figure
19380b57cec5SDimitry Andric   // out which registers are used or defined by instructions from the insertion
19390b57cec5SDimitry Andric   // point to the end of the block.
19405ffd83dbSDimitry Andric   SmallSet<Register, 4> Uses, Defs;
19410b57cec5SDimitry Andric   MachineBasicBlock::iterator Loc =
19420b57cec5SDimitry Andric     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
19430b57cec5SDimitry Andric   if (Loc == MBB->end())
19440b57cec5SDimitry Andric     return false;
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric   bool HasDups = false;
19475ffd83dbSDimitry Andric   SmallSet<Register, 4> ActiveDefsSet, AllDefsSet;
19480b57cec5SDimitry Andric   MachineBasicBlock::iterator TIB = TBB->begin();
19490b57cec5SDimitry Andric   MachineBasicBlock::iterator FIB = FBB->begin();
19500b57cec5SDimitry Andric   MachineBasicBlock::iterator TIE = TBB->end();
19510b57cec5SDimitry Andric   MachineBasicBlock::iterator FIE = FBB->end();
19520b57cec5SDimitry Andric   while (TIB != TIE && FIB != FIE) {
19530b57cec5SDimitry Andric     // Skip dbg_value instructions. These do not count.
1954fe6060f1SDimitry Andric     TIB = skipDebugInstructionsForward(TIB, TIE, false);
1955fe6060f1SDimitry Andric     FIB = skipDebugInstructionsForward(FIB, FIE, false);
19560b57cec5SDimitry Andric     if (TIB == TIE || FIB == FIE)
19570b57cec5SDimitry Andric       break;
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric     if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
19600b57cec5SDimitry Andric       break;
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric     if (TII->isPredicated(*TIB))
19630b57cec5SDimitry Andric       // Hard to reason about register liveness with predicated instruction.
19640b57cec5SDimitry Andric       break;
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric     bool IsSafe = true;
19670b57cec5SDimitry Andric     for (MachineOperand &MO : TIB->operands()) {
19680b57cec5SDimitry Andric       // Don't attempt to hoist instructions with register masks.
19690b57cec5SDimitry Andric       if (MO.isRegMask()) {
19700b57cec5SDimitry Andric         IsSafe = false;
19710b57cec5SDimitry Andric         break;
19720b57cec5SDimitry Andric       }
19730b57cec5SDimitry Andric       if (!MO.isReg())
19740b57cec5SDimitry Andric         continue;
19758bcb0991SDimitry Andric       Register Reg = MO.getReg();
19760b57cec5SDimitry Andric       if (!Reg)
19770b57cec5SDimitry Andric         continue;
19780b57cec5SDimitry Andric       if (MO.isDef()) {
19790b57cec5SDimitry Andric         if (Uses.count(Reg)) {
19800b57cec5SDimitry Andric           // Avoid clobbering a register that's used by the instruction at
19810b57cec5SDimitry Andric           // the point of insertion.
19820b57cec5SDimitry Andric           IsSafe = false;
19830b57cec5SDimitry Andric           break;
19840b57cec5SDimitry Andric         }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric         if (Defs.count(Reg) && !MO.isDead()) {
19870b57cec5SDimitry Andric           // Don't hoist the instruction if the def would be clobber by the
19880b57cec5SDimitry Andric           // instruction at the point insertion. FIXME: This is overly
19890b57cec5SDimitry Andric           // conservative. It should be possible to hoist the instructions
19900b57cec5SDimitry Andric           // in BB2 in the following example:
19910b57cec5SDimitry Andric           // BB1:
19920b57cec5SDimitry Andric           // r1, eflag = op1 r2, r3
19930b57cec5SDimitry Andric           // brcc eflag
19940b57cec5SDimitry Andric           //
19950b57cec5SDimitry Andric           // BB2:
19960b57cec5SDimitry Andric           // r1 = op2, ...
19970b57cec5SDimitry Andric           //    = op3, killed r1
19980b57cec5SDimitry Andric           IsSafe = false;
19990b57cec5SDimitry Andric           break;
20000b57cec5SDimitry Andric         }
20010b57cec5SDimitry Andric       } else if (!ActiveDefsSet.count(Reg)) {
20020b57cec5SDimitry Andric         if (Defs.count(Reg)) {
20030b57cec5SDimitry Andric           // Use is defined by the instruction at the point of insertion.
20040b57cec5SDimitry Andric           IsSafe = false;
20050b57cec5SDimitry Andric           break;
20060b57cec5SDimitry Andric         }
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric         if (MO.isKill() && Uses.count(Reg))
20090b57cec5SDimitry Andric           // Kills a register that's read by the instruction at the point of
20100b57cec5SDimitry Andric           // insertion. Remove the kill marker.
20110b57cec5SDimitry Andric           MO.setIsKill(false);
20120b57cec5SDimitry Andric       }
20130b57cec5SDimitry Andric     }
20140b57cec5SDimitry Andric     if (!IsSafe)
20150b57cec5SDimitry Andric       break;
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric     bool DontMoveAcrossStore = true;
20180b57cec5SDimitry Andric     if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
20190b57cec5SDimitry Andric       break;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric     // Remove kills from ActiveDefsSet, these registers had short live ranges.
202206c3fb27SDimitry Andric     for (const MachineOperand &MO : TIB->all_uses()) {
202306c3fb27SDimitry Andric       if (!MO.isKill())
20240b57cec5SDimitry Andric         continue;
20258bcb0991SDimitry Andric       Register Reg = MO.getReg();
20260b57cec5SDimitry Andric       if (!Reg)
20270b57cec5SDimitry Andric         continue;
20280b57cec5SDimitry Andric       if (!AllDefsSet.count(Reg)) {
20290b57cec5SDimitry Andric         continue;
20300b57cec5SDimitry Andric       }
20315ffd83dbSDimitry Andric       if (Reg.isPhysical()) {
20320b57cec5SDimitry Andric         for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
20330b57cec5SDimitry Andric           ActiveDefsSet.erase(*AI);
20340b57cec5SDimitry Andric       } else {
20350b57cec5SDimitry Andric         ActiveDefsSet.erase(Reg);
20360b57cec5SDimitry Andric       }
20370b57cec5SDimitry Andric     }
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric     // Track local defs so we can update liveins.
204006c3fb27SDimitry Andric     for (const MachineOperand &MO : TIB->all_defs()) {
204106c3fb27SDimitry Andric       if (MO.isDead())
20420b57cec5SDimitry Andric         continue;
20438bcb0991SDimitry Andric       Register Reg = MO.getReg();
20445ffd83dbSDimitry Andric       if (!Reg || Reg.isVirtual())
20450b57cec5SDimitry Andric         continue;
20460b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
20470b57cec5SDimitry Andric       addRegAndItsAliases(Reg, TRI, AllDefsSet);
20480b57cec5SDimitry Andric     }
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric     HasDups = true;
20510b57cec5SDimitry Andric     ++TIB;
20520b57cec5SDimitry Andric     ++FIB;
20530b57cec5SDimitry Andric   }
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric   if (!HasDups)
20560b57cec5SDimitry Andric     return false;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   MBB->splice(Loc, TBB, TBB->begin(), TIB);
20590b57cec5SDimitry Andric   FBB->erase(FBB->begin(), FIB);
20600b57cec5SDimitry Andric 
2061*0fca6ea1SDimitry Andric   if (UpdateLiveIns)
2062*0fca6ea1SDimitry Andric     fullyRecomputeLiveIns({TBB, FBB});
20630b57cec5SDimitry Andric 
20640b57cec5SDimitry Andric   ++NumHoist;
20650b57cec5SDimitry Andric   return true;
20660b57cec5SDimitry Andric }
2067