1f4a2713aSLionel Sambuc //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This pass forwards branches to unconditional branches to make them branch
11f4a2713aSLionel Sambuc // directly to the target block. This pass often results in dead MBB's, which
12f4a2713aSLionel Sambuc // it then removes.
13f4a2713aSLionel Sambuc //
14f4a2713aSLionel Sambuc // Note that this pass must be run after register allocation, it cannot handle
15f4a2713aSLionel Sambuc // SSA form.
16f4a2713aSLionel Sambuc //
17f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
18f4a2713aSLionel Sambuc
19f4a2713aSLionel Sambuc #include "BranchFolding.h"
20f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
21f4a2713aSLionel Sambuc #include "llvm/ADT/SmallSet.h"
22f4a2713aSLionel Sambuc #include "llvm/ADT/Statistic.h"
23*0a6a1f1dSLionel Sambuc #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24*0a6a1f1dSLionel Sambuc #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineFunctionPass.h"
26f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineJumpTableInfo.h"
27f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineModuleInfo.h"
28f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineRegisterInfo.h"
29f4a2713aSLionel Sambuc #include "llvm/CodeGen/Passes.h"
30f4a2713aSLionel Sambuc #include "llvm/CodeGen/RegisterScavenging.h"
31f4a2713aSLionel Sambuc #include "llvm/IR/Function.h"
32f4a2713aSLionel Sambuc #include "llvm/Support/CommandLine.h"
33f4a2713aSLionel Sambuc #include "llvm/Support/Debug.h"
34f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
35f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
36f4a2713aSLionel Sambuc #include "llvm/Target/TargetInstrInfo.h"
37f4a2713aSLionel Sambuc #include "llvm/Target/TargetRegisterInfo.h"
38*0a6a1f1dSLionel Sambuc #include "llvm/Target/TargetSubtargetInfo.h"
39f4a2713aSLionel Sambuc #include <algorithm>
40f4a2713aSLionel Sambuc using namespace llvm;
41f4a2713aSLionel Sambuc
42*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "branchfolding"
43*0a6a1f1dSLionel Sambuc
44f4a2713aSLionel Sambuc STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
45f4a2713aSLionel Sambuc STATISTIC(NumBranchOpts, "Number of branches optimized");
46f4a2713aSLionel Sambuc STATISTIC(NumTailMerge , "Number of block tails merged");
47f4a2713aSLionel Sambuc STATISTIC(NumHoist , "Number of times common instructions are hoisted");
48f4a2713aSLionel Sambuc
49f4a2713aSLionel Sambuc static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
50f4a2713aSLionel Sambuc cl::init(cl::BOU_UNSET), cl::Hidden);
51f4a2713aSLionel Sambuc
52f4a2713aSLionel Sambuc // Throttle for huge numbers of predecessors (compile speed problems)
53f4a2713aSLionel Sambuc static cl::opt<unsigned>
54f4a2713aSLionel Sambuc TailMergeThreshold("tail-merge-threshold",
55f4a2713aSLionel Sambuc cl::desc("Max number of predecessors to consider tail merging"),
56f4a2713aSLionel Sambuc cl::init(150), cl::Hidden);
57f4a2713aSLionel Sambuc
58f4a2713aSLionel Sambuc // Heuristic for tail merging (and, inversely, tail duplication).
59f4a2713aSLionel Sambuc // TODO: This should be replaced with a target query.
60f4a2713aSLionel Sambuc static cl::opt<unsigned>
61f4a2713aSLionel Sambuc TailMergeSize("tail-merge-size",
62f4a2713aSLionel Sambuc cl::desc("Min number of instructions to consider tail merging"),
63f4a2713aSLionel Sambuc cl::init(3), cl::Hidden);
64f4a2713aSLionel Sambuc
65f4a2713aSLionel Sambuc namespace {
66f4a2713aSLionel Sambuc /// BranchFolderPass - Wrap branch folder in a machine function pass.
67f4a2713aSLionel Sambuc class BranchFolderPass : public MachineFunctionPass {
68f4a2713aSLionel Sambuc public:
69f4a2713aSLionel Sambuc static char ID;
BranchFolderPass()70f4a2713aSLionel Sambuc explicit BranchFolderPass(): MachineFunctionPass(ID) {}
71f4a2713aSLionel Sambuc
72*0a6a1f1dSLionel Sambuc bool runOnMachineFunction(MachineFunction &MF) override;
73f4a2713aSLionel Sambuc
getAnalysisUsage(AnalysisUsage & AU) const74*0a6a1f1dSLionel Sambuc void getAnalysisUsage(AnalysisUsage &AU) const override {
75*0a6a1f1dSLionel Sambuc AU.addRequired<MachineBlockFrequencyInfo>();
76*0a6a1f1dSLionel Sambuc AU.addRequired<MachineBranchProbabilityInfo>();
77f4a2713aSLionel Sambuc AU.addRequired<TargetPassConfig>();
78f4a2713aSLionel Sambuc MachineFunctionPass::getAnalysisUsage(AU);
79f4a2713aSLionel Sambuc }
80f4a2713aSLionel Sambuc };
81f4a2713aSLionel Sambuc }
82f4a2713aSLionel Sambuc
83f4a2713aSLionel Sambuc char BranchFolderPass::ID = 0;
84f4a2713aSLionel Sambuc char &llvm::BranchFolderPassID = BranchFolderPass::ID;
85f4a2713aSLionel Sambuc
86f4a2713aSLionel Sambuc INITIALIZE_PASS(BranchFolderPass, "branch-folder",
87f4a2713aSLionel Sambuc "Control Flow Optimizer", false, false)
88f4a2713aSLionel Sambuc
runOnMachineFunction(MachineFunction & MF)89f4a2713aSLionel Sambuc bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
90*0a6a1f1dSLionel Sambuc if (skipOptnoneFunction(*MF.getFunction()))
91*0a6a1f1dSLionel Sambuc return false;
92*0a6a1f1dSLionel Sambuc
93f4a2713aSLionel Sambuc TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
94*0a6a1f1dSLionel Sambuc // TailMerge can create jump into if branches that make CFG irreducible for
95*0a6a1f1dSLionel Sambuc // HW that requires structurized CFG.
96*0a6a1f1dSLionel Sambuc bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
97*0a6a1f1dSLionel Sambuc PassConfig->getEnableTailMerge();
98*0a6a1f1dSLionel Sambuc BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true,
99*0a6a1f1dSLionel Sambuc getAnalysis<MachineBlockFrequencyInfo>(),
100*0a6a1f1dSLionel Sambuc getAnalysis<MachineBranchProbabilityInfo>());
101*0a6a1f1dSLionel Sambuc return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
102*0a6a1f1dSLionel Sambuc MF.getSubtarget().getRegisterInfo(),
103f4a2713aSLionel Sambuc getAnalysisIfAvailable<MachineModuleInfo>());
104f4a2713aSLionel Sambuc }
105f4a2713aSLionel Sambuc
BranchFolder(bool defaultEnableTailMerge,bool CommonHoist,const MachineBlockFrequencyInfo & FreqInfo,const MachineBranchProbabilityInfo & ProbInfo)106*0a6a1f1dSLionel Sambuc BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
107*0a6a1f1dSLionel Sambuc const MachineBlockFrequencyInfo &FreqInfo,
108*0a6a1f1dSLionel Sambuc const MachineBranchProbabilityInfo &ProbInfo)
109*0a6a1f1dSLionel Sambuc : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo),
110*0a6a1f1dSLionel Sambuc MBPI(ProbInfo) {
111f4a2713aSLionel Sambuc switch (FlagEnableTailMerge) {
112f4a2713aSLionel Sambuc case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
113f4a2713aSLionel Sambuc case cl::BOU_TRUE: EnableTailMerge = true; break;
114f4a2713aSLionel Sambuc case cl::BOU_FALSE: EnableTailMerge = false; break;
115f4a2713aSLionel Sambuc }
116f4a2713aSLionel Sambuc }
117f4a2713aSLionel Sambuc
118f4a2713aSLionel Sambuc /// RemoveDeadBlock - Remove the specified dead machine basic block from the
119f4a2713aSLionel Sambuc /// function, updating the CFG.
RemoveDeadBlock(MachineBasicBlock * MBB)120f4a2713aSLionel Sambuc void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
121f4a2713aSLionel Sambuc assert(MBB->pred_empty() && "MBB must be dead!");
122f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
123f4a2713aSLionel Sambuc
124f4a2713aSLionel Sambuc MachineFunction *MF = MBB->getParent();
125f4a2713aSLionel Sambuc // drop all successors.
126f4a2713aSLionel Sambuc while (!MBB->succ_empty())
127f4a2713aSLionel Sambuc MBB->removeSuccessor(MBB->succ_end()-1);
128f4a2713aSLionel Sambuc
129f4a2713aSLionel Sambuc // Avoid matching if this pointer gets reused.
130f4a2713aSLionel Sambuc TriedMerging.erase(MBB);
131f4a2713aSLionel Sambuc
132f4a2713aSLionel Sambuc // Remove the block.
133f4a2713aSLionel Sambuc MF->erase(MBB);
134f4a2713aSLionel Sambuc }
135f4a2713aSLionel Sambuc
136f4a2713aSLionel Sambuc /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
137f4a2713aSLionel Sambuc /// followed by terminators, and if the implicitly defined registers are not
138f4a2713aSLionel Sambuc /// used by the terminators, remove those implicit_def's. e.g.
139f4a2713aSLionel Sambuc /// BB1:
140f4a2713aSLionel Sambuc /// r0 = implicit_def
141f4a2713aSLionel Sambuc /// r1 = implicit_def
142f4a2713aSLionel Sambuc /// br
143f4a2713aSLionel Sambuc /// This block can be optimized away later if the implicit instructions are
144f4a2713aSLionel Sambuc /// removed.
OptimizeImpDefsBlock(MachineBasicBlock * MBB)145f4a2713aSLionel Sambuc bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
146f4a2713aSLionel Sambuc SmallSet<unsigned, 4> ImpDefRegs;
147f4a2713aSLionel Sambuc MachineBasicBlock::iterator I = MBB->begin();
148f4a2713aSLionel Sambuc while (I != MBB->end()) {
149f4a2713aSLionel Sambuc if (!I->isImplicitDef())
150f4a2713aSLionel Sambuc break;
151f4a2713aSLionel Sambuc unsigned Reg = I->getOperand(0).getReg();
152f4a2713aSLionel Sambuc for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
153f4a2713aSLionel Sambuc SubRegs.isValid(); ++SubRegs)
154f4a2713aSLionel Sambuc ImpDefRegs.insert(*SubRegs);
155f4a2713aSLionel Sambuc ++I;
156f4a2713aSLionel Sambuc }
157f4a2713aSLionel Sambuc if (ImpDefRegs.empty())
158f4a2713aSLionel Sambuc return false;
159f4a2713aSLionel Sambuc
160f4a2713aSLionel Sambuc MachineBasicBlock::iterator FirstTerm = I;
161f4a2713aSLionel Sambuc while (I != MBB->end()) {
162f4a2713aSLionel Sambuc if (!TII->isUnpredicatedTerminator(I))
163f4a2713aSLionel Sambuc return false;
164f4a2713aSLionel Sambuc // See if it uses any of the implicitly defined registers.
165f4a2713aSLionel Sambuc for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
166f4a2713aSLionel Sambuc MachineOperand &MO = I->getOperand(i);
167f4a2713aSLionel Sambuc if (!MO.isReg() || !MO.isUse())
168f4a2713aSLionel Sambuc continue;
169f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
170f4a2713aSLionel Sambuc if (ImpDefRegs.count(Reg))
171f4a2713aSLionel Sambuc return false;
172f4a2713aSLionel Sambuc }
173f4a2713aSLionel Sambuc ++I;
174f4a2713aSLionel Sambuc }
175f4a2713aSLionel Sambuc
176f4a2713aSLionel Sambuc I = MBB->begin();
177f4a2713aSLionel Sambuc while (I != FirstTerm) {
178f4a2713aSLionel Sambuc MachineInstr *ImpDefMI = &*I;
179f4a2713aSLionel Sambuc ++I;
180f4a2713aSLionel Sambuc MBB->erase(ImpDefMI);
181f4a2713aSLionel Sambuc }
182f4a2713aSLionel Sambuc
183f4a2713aSLionel Sambuc return true;
184f4a2713aSLionel Sambuc }
185f4a2713aSLionel Sambuc
186f4a2713aSLionel Sambuc /// OptimizeFunction - Perhaps branch folding, tail merging and other
187f4a2713aSLionel Sambuc /// CFG optimizations on the given function.
OptimizeFunction(MachineFunction & MF,const TargetInstrInfo * tii,const TargetRegisterInfo * tri,MachineModuleInfo * mmi)188f4a2713aSLionel Sambuc bool BranchFolder::OptimizeFunction(MachineFunction &MF,
189f4a2713aSLionel Sambuc const TargetInstrInfo *tii,
190f4a2713aSLionel Sambuc const TargetRegisterInfo *tri,
191f4a2713aSLionel Sambuc MachineModuleInfo *mmi) {
192f4a2713aSLionel Sambuc if (!tii) return false;
193f4a2713aSLionel Sambuc
194f4a2713aSLionel Sambuc TriedMerging.clear();
195f4a2713aSLionel Sambuc
196f4a2713aSLionel Sambuc TII = tii;
197f4a2713aSLionel Sambuc TRI = tri;
198f4a2713aSLionel Sambuc MMI = mmi;
199*0a6a1f1dSLionel Sambuc RS = nullptr;
200f4a2713aSLionel Sambuc
201f4a2713aSLionel Sambuc // Use a RegScavenger to help update liveness when required.
202f4a2713aSLionel Sambuc MachineRegisterInfo &MRI = MF.getRegInfo();
203f4a2713aSLionel Sambuc if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
204f4a2713aSLionel Sambuc RS = new RegScavenger();
205f4a2713aSLionel Sambuc else
206f4a2713aSLionel Sambuc MRI.invalidateLiveness();
207f4a2713aSLionel Sambuc
208f4a2713aSLionel Sambuc // Fix CFG. The later algorithms expect it to be right.
209f4a2713aSLionel Sambuc bool MadeChange = false;
210f4a2713aSLionel Sambuc for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
211*0a6a1f1dSLionel Sambuc MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
212f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> Cond;
213f4a2713aSLionel Sambuc if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
214f4a2713aSLionel Sambuc MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
215f4a2713aSLionel Sambuc MadeChange |= OptimizeImpDefsBlock(MBB);
216f4a2713aSLionel Sambuc }
217f4a2713aSLionel Sambuc
218f4a2713aSLionel Sambuc bool MadeChangeThisIteration = true;
219f4a2713aSLionel Sambuc while (MadeChangeThisIteration) {
220f4a2713aSLionel Sambuc MadeChangeThisIteration = TailMergeBlocks(MF);
221f4a2713aSLionel Sambuc MadeChangeThisIteration |= OptimizeBranches(MF);
222f4a2713aSLionel Sambuc if (EnableHoistCommonCode)
223f4a2713aSLionel Sambuc MadeChangeThisIteration |= HoistCommonCode(MF);
224f4a2713aSLionel Sambuc MadeChange |= MadeChangeThisIteration;
225f4a2713aSLionel Sambuc }
226f4a2713aSLionel Sambuc
227f4a2713aSLionel Sambuc // See if any jump tables have become dead as the code generator
228f4a2713aSLionel Sambuc // did its thing.
229f4a2713aSLionel Sambuc MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
230*0a6a1f1dSLionel Sambuc if (!JTI) {
231f4a2713aSLionel Sambuc delete RS;
232f4a2713aSLionel Sambuc return MadeChange;
233f4a2713aSLionel Sambuc }
234f4a2713aSLionel Sambuc
235f4a2713aSLionel Sambuc // Walk the function to find jump tables that are live.
236f4a2713aSLionel Sambuc BitVector JTIsLive(JTI->getJumpTables().size());
237f4a2713aSLionel Sambuc for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
238f4a2713aSLionel Sambuc BB != E; ++BB) {
239f4a2713aSLionel Sambuc for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
240f4a2713aSLionel Sambuc I != E; ++I)
241f4a2713aSLionel Sambuc for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
242f4a2713aSLionel Sambuc MachineOperand &Op = I->getOperand(op);
243f4a2713aSLionel Sambuc if (!Op.isJTI()) continue;
244f4a2713aSLionel Sambuc
245f4a2713aSLionel Sambuc // Remember that this JT is live.
246f4a2713aSLionel Sambuc JTIsLive.set(Op.getIndex());
247f4a2713aSLionel Sambuc }
248f4a2713aSLionel Sambuc }
249f4a2713aSLionel Sambuc
250f4a2713aSLionel Sambuc // Finally, remove dead jump tables. This happens when the
251f4a2713aSLionel Sambuc // indirect jump was unreachable (and thus deleted).
252f4a2713aSLionel Sambuc for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
253f4a2713aSLionel Sambuc if (!JTIsLive.test(i)) {
254f4a2713aSLionel Sambuc JTI->RemoveJumpTable(i);
255f4a2713aSLionel Sambuc MadeChange = true;
256f4a2713aSLionel Sambuc }
257f4a2713aSLionel Sambuc
258f4a2713aSLionel Sambuc delete RS;
259f4a2713aSLionel Sambuc return MadeChange;
260f4a2713aSLionel Sambuc }
261f4a2713aSLionel Sambuc
262f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
263f4a2713aSLionel Sambuc // Tail Merging of Blocks
264f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
265f4a2713aSLionel Sambuc
266f4a2713aSLionel Sambuc /// HashMachineInstr - Compute a hash value for MI and its operands.
HashMachineInstr(const MachineInstr * MI)267f4a2713aSLionel Sambuc static unsigned HashMachineInstr(const MachineInstr *MI) {
268f4a2713aSLionel Sambuc unsigned Hash = MI->getOpcode();
269f4a2713aSLionel Sambuc for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
270f4a2713aSLionel Sambuc const MachineOperand &Op = MI->getOperand(i);
271f4a2713aSLionel Sambuc
272f4a2713aSLionel Sambuc // Merge in bits from the operand if easy.
273f4a2713aSLionel Sambuc unsigned OperandHash = 0;
274f4a2713aSLionel Sambuc switch (Op.getType()) {
275f4a2713aSLionel Sambuc case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
276f4a2713aSLionel Sambuc case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
277f4a2713aSLionel Sambuc case MachineOperand::MO_MachineBasicBlock:
278f4a2713aSLionel Sambuc OperandHash = Op.getMBB()->getNumber();
279f4a2713aSLionel Sambuc break;
280f4a2713aSLionel Sambuc case MachineOperand::MO_FrameIndex:
281f4a2713aSLionel Sambuc case MachineOperand::MO_ConstantPoolIndex:
282f4a2713aSLionel Sambuc case MachineOperand::MO_JumpTableIndex:
283f4a2713aSLionel Sambuc OperandHash = Op.getIndex();
284f4a2713aSLionel Sambuc break;
285f4a2713aSLionel Sambuc case MachineOperand::MO_GlobalAddress:
286f4a2713aSLionel Sambuc case MachineOperand::MO_ExternalSymbol:
287f4a2713aSLionel Sambuc // Global address / external symbol are too hard, don't bother, but do
288f4a2713aSLionel Sambuc // pull in the offset.
289f4a2713aSLionel Sambuc OperandHash = Op.getOffset();
290f4a2713aSLionel Sambuc break;
291f4a2713aSLionel Sambuc default: break;
292f4a2713aSLionel Sambuc }
293f4a2713aSLionel Sambuc
294f4a2713aSLionel Sambuc Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
295f4a2713aSLionel Sambuc }
296f4a2713aSLionel Sambuc return Hash;
297f4a2713aSLionel Sambuc }
298f4a2713aSLionel Sambuc
299f4a2713aSLionel Sambuc /// HashEndOfMBB - Hash the last instruction in the MBB.
HashEndOfMBB(const MachineBasicBlock * MBB)300f4a2713aSLionel Sambuc static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
301f4a2713aSLionel Sambuc MachineBasicBlock::const_iterator I = MBB->end();
302f4a2713aSLionel Sambuc if (I == MBB->begin())
303f4a2713aSLionel Sambuc return 0; // Empty MBB.
304f4a2713aSLionel Sambuc
305f4a2713aSLionel Sambuc --I;
306f4a2713aSLionel Sambuc // Skip debug info so it will not affect codegen.
307f4a2713aSLionel Sambuc while (I->isDebugValue()) {
308f4a2713aSLionel Sambuc if (I==MBB->begin())
309f4a2713aSLionel Sambuc return 0; // MBB empty except for debug info.
310f4a2713aSLionel Sambuc --I;
311f4a2713aSLionel Sambuc }
312f4a2713aSLionel Sambuc
313f4a2713aSLionel Sambuc return HashMachineInstr(I);
314f4a2713aSLionel Sambuc }
315f4a2713aSLionel Sambuc
316f4a2713aSLionel Sambuc /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
317f4a2713aSLionel Sambuc /// of instructions they actually have in common together at their end. Return
318f4a2713aSLionel Sambuc /// iterators for the first shared instruction in each block.
ComputeCommonTailLength(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2,MachineBasicBlock::iterator & I1,MachineBasicBlock::iterator & I2)319f4a2713aSLionel Sambuc static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
320f4a2713aSLionel Sambuc MachineBasicBlock *MBB2,
321f4a2713aSLionel Sambuc MachineBasicBlock::iterator &I1,
322f4a2713aSLionel Sambuc MachineBasicBlock::iterator &I2) {
323f4a2713aSLionel Sambuc I1 = MBB1->end();
324f4a2713aSLionel Sambuc I2 = MBB2->end();
325f4a2713aSLionel Sambuc
326f4a2713aSLionel Sambuc unsigned TailLen = 0;
327f4a2713aSLionel Sambuc while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
328f4a2713aSLionel Sambuc --I1; --I2;
329f4a2713aSLionel Sambuc // Skip debugging pseudos; necessary to avoid changing the code.
330f4a2713aSLionel Sambuc while (I1->isDebugValue()) {
331f4a2713aSLionel Sambuc if (I1==MBB1->begin()) {
332f4a2713aSLionel Sambuc while (I2->isDebugValue()) {
333f4a2713aSLionel Sambuc if (I2==MBB2->begin())
334f4a2713aSLionel Sambuc // I1==DBG at begin; I2==DBG at begin
335f4a2713aSLionel Sambuc return TailLen;
336f4a2713aSLionel Sambuc --I2;
337f4a2713aSLionel Sambuc }
338f4a2713aSLionel Sambuc ++I2;
339f4a2713aSLionel Sambuc // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
340f4a2713aSLionel Sambuc return TailLen;
341f4a2713aSLionel Sambuc }
342f4a2713aSLionel Sambuc --I1;
343f4a2713aSLionel Sambuc }
344f4a2713aSLionel Sambuc // I1==first (untested) non-DBG preceding known match
345f4a2713aSLionel Sambuc while (I2->isDebugValue()) {
346f4a2713aSLionel Sambuc if (I2==MBB2->begin()) {
347f4a2713aSLionel Sambuc ++I1;
348f4a2713aSLionel Sambuc // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
349f4a2713aSLionel Sambuc return TailLen;
350f4a2713aSLionel Sambuc }
351f4a2713aSLionel Sambuc --I2;
352f4a2713aSLionel Sambuc }
353f4a2713aSLionel Sambuc // I1, I2==first (untested) non-DBGs preceding known match
354f4a2713aSLionel Sambuc if (!I1->isIdenticalTo(I2) ||
355f4a2713aSLionel Sambuc // FIXME: This check is dubious. It's used to get around a problem where
356f4a2713aSLionel Sambuc // people incorrectly expect inline asm directives to remain in the same
357f4a2713aSLionel Sambuc // relative order. This is untenable because normal compiler
358f4a2713aSLionel Sambuc // optimizations (like this one) may reorder and/or merge these
359f4a2713aSLionel Sambuc // directives.
360f4a2713aSLionel Sambuc I1->isInlineAsm()) {
361f4a2713aSLionel Sambuc ++I1; ++I2;
362f4a2713aSLionel Sambuc break;
363f4a2713aSLionel Sambuc }
364f4a2713aSLionel Sambuc ++TailLen;
365f4a2713aSLionel Sambuc }
366f4a2713aSLionel Sambuc // Back past possible debugging pseudos at beginning of block. This matters
367f4a2713aSLionel Sambuc // when one block differs from the other only by whether debugging pseudos
368f4a2713aSLionel Sambuc // are present at the beginning. (This way, the various checks later for
369f4a2713aSLionel Sambuc // I1==MBB1->begin() work as expected.)
370f4a2713aSLionel Sambuc if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
371f4a2713aSLionel Sambuc --I2;
372f4a2713aSLionel Sambuc while (I2->isDebugValue()) {
373f4a2713aSLionel Sambuc if (I2 == MBB2->begin())
374f4a2713aSLionel Sambuc return TailLen;
375f4a2713aSLionel Sambuc --I2;
376f4a2713aSLionel Sambuc }
377f4a2713aSLionel Sambuc ++I2;
378f4a2713aSLionel Sambuc }
379f4a2713aSLionel Sambuc if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
380f4a2713aSLionel Sambuc --I1;
381f4a2713aSLionel Sambuc while (I1->isDebugValue()) {
382f4a2713aSLionel Sambuc if (I1 == MBB1->begin())
383f4a2713aSLionel Sambuc return TailLen;
384f4a2713aSLionel Sambuc --I1;
385f4a2713aSLionel Sambuc }
386f4a2713aSLionel Sambuc ++I1;
387f4a2713aSLionel Sambuc }
388f4a2713aSLionel Sambuc return TailLen;
389f4a2713aSLionel Sambuc }
390f4a2713aSLionel Sambuc
MaintainLiveIns(MachineBasicBlock * CurMBB,MachineBasicBlock * NewMBB)391f4a2713aSLionel Sambuc void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
392f4a2713aSLionel Sambuc MachineBasicBlock *NewMBB) {
393f4a2713aSLionel Sambuc if (RS) {
394f4a2713aSLionel Sambuc RS->enterBasicBlock(CurMBB);
395f4a2713aSLionel Sambuc if (!CurMBB->empty())
396*0a6a1f1dSLionel Sambuc RS->forward(std::prev(CurMBB->end()));
397*0a6a1f1dSLionel Sambuc for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++)
398*0a6a1f1dSLionel Sambuc if (RS->isRegUsed(i, false))
399f4a2713aSLionel Sambuc NewMBB->addLiveIn(i);
400f4a2713aSLionel Sambuc }
401f4a2713aSLionel Sambuc }
402f4a2713aSLionel Sambuc
403f4a2713aSLionel Sambuc /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
404f4a2713aSLionel Sambuc /// after it, replacing it with an unconditional branch to NewDest.
ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,MachineBasicBlock * NewDest)405f4a2713aSLionel Sambuc void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
406f4a2713aSLionel Sambuc MachineBasicBlock *NewDest) {
407f4a2713aSLionel Sambuc MachineBasicBlock *CurMBB = OldInst->getParent();
408f4a2713aSLionel Sambuc
409f4a2713aSLionel Sambuc TII->ReplaceTailWithBranchTo(OldInst, NewDest);
410f4a2713aSLionel Sambuc
411f4a2713aSLionel Sambuc // For targets that use the register scavenger, we must maintain LiveIns.
412f4a2713aSLionel Sambuc MaintainLiveIns(CurMBB, NewDest);
413f4a2713aSLionel Sambuc
414f4a2713aSLionel Sambuc ++NumTailMerge;
415f4a2713aSLionel Sambuc }
416f4a2713aSLionel Sambuc
417f4a2713aSLionel Sambuc /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
418f4a2713aSLionel Sambuc /// MBB so that the part before the iterator falls into the part starting at the
419f4a2713aSLionel Sambuc /// iterator. This returns the new MBB.
SplitMBBAt(MachineBasicBlock & CurMBB,MachineBasicBlock::iterator BBI1,const BasicBlock * BB)420f4a2713aSLionel Sambuc MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
421f4a2713aSLionel Sambuc MachineBasicBlock::iterator BBI1,
422f4a2713aSLionel Sambuc const BasicBlock *BB) {
423f4a2713aSLionel Sambuc if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
424*0a6a1f1dSLionel Sambuc return nullptr;
425f4a2713aSLionel Sambuc
426f4a2713aSLionel Sambuc MachineFunction &MF = *CurMBB.getParent();
427f4a2713aSLionel Sambuc
428f4a2713aSLionel Sambuc // Create the fall-through block.
429f4a2713aSLionel Sambuc MachineFunction::iterator MBBI = &CurMBB;
430f4a2713aSLionel Sambuc MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
431f4a2713aSLionel Sambuc CurMBB.getParent()->insert(++MBBI, NewMBB);
432f4a2713aSLionel Sambuc
433f4a2713aSLionel Sambuc // Move all the successors of this block to the specified block.
434f4a2713aSLionel Sambuc NewMBB->transferSuccessors(&CurMBB);
435f4a2713aSLionel Sambuc
436f4a2713aSLionel Sambuc // Add an edge from CurMBB to NewMBB for the fall-through.
437f4a2713aSLionel Sambuc CurMBB.addSuccessor(NewMBB);
438f4a2713aSLionel Sambuc
439f4a2713aSLionel Sambuc // Splice the code over.
440f4a2713aSLionel Sambuc NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
441f4a2713aSLionel Sambuc
442*0a6a1f1dSLionel Sambuc // NewMBB inherits CurMBB's block frequency.
443*0a6a1f1dSLionel Sambuc MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
444*0a6a1f1dSLionel Sambuc
445f4a2713aSLionel Sambuc // For targets that use the register scavenger, we must maintain LiveIns.
446f4a2713aSLionel Sambuc MaintainLiveIns(&CurMBB, NewMBB);
447f4a2713aSLionel Sambuc
448f4a2713aSLionel Sambuc return NewMBB;
449f4a2713aSLionel Sambuc }
450f4a2713aSLionel Sambuc
451f4a2713aSLionel Sambuc /// EstimateRuntime - Make a rough estimate for how long it will take to run
452f4a2713aSLionel Sambuc /// the specified code.
EstimateRuntime(MachineBasicBlock::iterator I,MachineBasicBlock::iterator E)453f4a2713aSLionel Sambuc static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
454f4a2713aSLionel Sambuc MachineBasicBlock::iterator E) {
455f4a2713aSLionel Sambuc unsigned Time = 0;
456f4a2713aSLionel Sambuc for (; I != E; ++I) {
457f4a2713aSLionel Sambuc if (I->isDebugValue())
458f4a2713aSLionel Sambuc continue;
459f4a2713aSLionel Sambuc if (I->isCall())
460f4a2713aSLionel Sambuc Time += 10;
461f4a2713aSLionel Sambuc else if (I->mayLoad() || I->mayStore())
462f4a2713aSLionel Sambuc Time += 2;
463f4a2713aSLionel Sambuc else
464f4a2713aSLionel Sambuc ++Time;
465f4a2713aSLionel Sambuc }
466f4a2713aSLionel Sambuc return Time;
467f4a2713aSLionel Sambuc }
468f4a2713aSLionel Sambuc
469f4a2713aSLionel Sambuc // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
470f4a2713aSLionel Sambuc // branches temporarily for tail merging). In the case where CurMBB ends
471f4a2713aSLionel Sambuc // with a conditional branch to the next block, optimize by reversing the
472f4a2713aSLionel Sambuc // test and conditionally branching to SuccMBB instead.
FixTail(MachineBasicBlock * CurMBB,MachineBasicBlock * SuccBB,const TargetInstrInfo * TII)473f4a2713aSLionel Sambuc static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
474f4a2713aSLionel Sambuc const TargetInstrInfo *TII) {
475f4a2713aSLionel Sambuc MachineFunction *MF = CurMBB->getParent();
476*0a6a1f1dSLionel Sambuc MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
477*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
478f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> Cond;
479f4a2713aSLionel Sambuc DebugLoc dl; // FIXME: this is nowhere
480f4a2713aSLionel Sambuc if (I != MF->end() &&
481f4a2713aSLionel Sambuc !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
482f4a2713aSLionel Sambuc MachineBasicBlock *NextBB = I;
483f4a2713aSLionel Sambuc if (TBB == NextBB && !Cond.empty() && !FBB) {
484f4a2713aSLionel Sambuc if (!TII->ReverseBranchCondition(Cond)) {
485f4a2713aSLionel Sambuc TII->RemoveBranch(*CurMBB);
486*0a6a1f1dSLionel Sambuc TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
487f4a2713aSLionel Sambuc return;
488f4a2713aSLionel Sambuc }
489f4a2713aSLionel Sambuc }
490f4a2713aSLionel Sambuc }
491*0a6a1f1dSLionel Sambuc TII->InsertBranch(*CurMBB, SuccBB, nullptr,
492f4a2713aSLionel Sambuc SmallVector<MachineOperand, 0>(), dl);
493f4a2713aSLionel Sambuc }
494f4a2713aSLionel Sambuc
495f4a2713aSLionel Sambuc bool
operator <(const MergePotentialsElt & o) const496f4a2713aSLionel Sambuc BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
497f4a2713aSLionel Sambuc if (getHash() < o.getHash())
498f4a2713aSLionel Sambuc return true;
499f4a2713aSLionel Sambuc if (getHash() > o.getHash())
500f4a2713aSLionel Sambuc return false;
501f4a2713aSLionel Sambuc if (getBlock()->getNumber() < o.getBlock()->getNumber())
502f4a2713aSLionel Sambuc return true;
503f4a2713aSLionel Sambuc if (getBlock()->getNumber() > o.getBlock()->getNumber())
504f4a2713aSLionel Sambuc return false;
505f4a2713aSLionel Sambuc // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
506f4a2713aSLionel Sambuc // an object with itself.
507f4a2713aSLionel Sambuc #ifndef _GLIBCXX_DEBUG
508f4a2713aSLionel Sambuc llvm_unreachable("Predecessor appears twice");
509f4a2713aSLionel Sambuc #else
510f4a2713aSLionel Sambuc return false;
511f4a2713aSLionel Sambuc #endif
512f4a2713aSLionel Sambuc }
513f4a2713aSLionel Sambuc
514*0a6a1f1dSLionel Sambuc BlockFrequency
getBlockFreq(const MachineBasicBlock * MBB) const515*0a6a1f1dSLionel Sambuc BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
516*0a6a1f1dSLionel Sambuc auto I = MergedBBFreq.find(MBB);
517*0a6a1f1dSLionel Sambuc
518*0a6a1f1dSLionel Sambuc if (I != MergedBBFreq.end())
519*0a6a1f1dSLionel Sambuc return I->second;
520*0a6a1f1dSLionel Sambuc
521*0a6a1f1dSLionel Sambuc return MBFI.getBlockFreq(MBB);
522*0a6a1f1dSLionel Sambuc }
523*0a6a1f1dSLionel Sambuc
setBlockFreq(const MachineBasicBlock * MBB,BlockFrequency F)524*0a6a1f1dSLionel Sambuc void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
525*0a6a1f1dSLionel Sambuc BlockFrequency F) {
526*0a6a1f1dSLionel Sambuc MergedBBFreq[MBB] = F;
527*0a6a1f1dSLionel Sambuc }
528*0a6a1f1dSLionel Sambuc
529f4a2713aSLionel Sambuc /// CountTerminators - Count the number of terminators in the given
530f4a2713aSLionel Sambuc /// block and set I to the position of the first non-terminator, if there
531f4a2713aSLionel Sambuc /// is one, or MBB->end() otherwise.
CountTerminators(MachineBasicBlock * MBB,MachineBasicBlock::iterator & I)532f4a2713aSLionel Sambuc static unsigned CountTerminators(MachineBasicBlock *MBB,
533f4a2713aSLionel Sambuc MachineBasicBlock::iterator &I) {
534f4a2713aSLionel Sambuc I = MBB->end();
535f4a2713aSLionel Sambuc unsigned NumTerms = 0;
536f4a2713aSLionel Sambuc for (;;) {
537f4a2713aSLionel Sambuc if (I == MBB->begin()) {
538f4a2713aSLionel Sambuc I = MBB->end();
539f4a2713aSLionel Sambuc break;
540f4a2713aSLionel Sambuc }
541f4a2713aSLionel Sambuc --I;
542f4a2713aSLionel Sambuc if (!I->isTerminator()) break;
543f4a2713aSLionel Sambuc ++NumTerms;
544f4a2713aSLionel Sambuc }
545f4a2713aSLionel Sambuc return NumTerms;
546f4a2713aSLionel Sambuc }
547f4a2713aSLionel Sambuc
548f4a2713aSLionel Sambuc /// ProfitableToMerge - Check if two machine basic blocks have a common tail
549f4a2713aSLionel Sambuc /// and decide if it would be profitable to merge those tails. Return the
550f4a2713aSLionel Sambuc /// length of the common tail and iterators to the first common instruction
551f4a2713aSLionel Sambuc /// in each block.
ProfitableToMerge(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2,unsigned minCommonTailLength,unsigned & CommonTailLen,MachineBasicBlock::iterator & I1,MachineBasicBlock::iterator & I2,MachineBasicBlock * SuccBB,MachineBasicBlock * PredBB)552f4a2713aSLionel Sambuc static bool ProfitableToMerge(MachineBasicBlock *MBB1,
553f4a2713aSLionel Sambuc MachineBasicBlock *MBB2,
554f4a2713aSLionel Sambuc unsigned minCommonTailLength,
555f4a2713aSLionel Sambuc unsigned &CommonTailLen,
556f4a2713aSLionel Sambuc MachineBasicBlock::iterator &I1,
557f4a2713aSLionel Sambuc MachineBasicBlock::iterator &I2,
558f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB,
559f4a2713aSLionel Sambuc MachineBasicBlock *PredBB) {
560f4a2713aSLionel Sambuc CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
561f4a2713aSLionel Sambuc if (CommonTailLen == 0)
562f4a2713aSLionel Sambuc return false;
563f4a2713aSLionel Sambuc DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
564f4a2713aSLionel Sambuc << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
565f4a2713aSLionel Sambuc << '\n');
566f4a2713aSLionel Sambuc
567f4a2713aSLionel Sambuc // It's almost always profitable to merge any number of non-terminator
568f4a2713aSLionel Sambuc // instructions with the block that falls through into the common successor.
569f4a2713aSLionel Sambuc if (MBB1 == PredBB || MBB2 == PredBB) {
570f4a2713aSLionel Sambuc MachineBasicBlock::iterator I;
571f4a2713aSLionel Sambuc unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
572f4a2713aSLionel Sambuc if (CommonTailLen > NumTerms)
573f4a2713aSLionel Sambuc return true;
574f4a2713aSLionel Sambuc }
575f4a2713aSLionel Sambuc
576f4a2713aSLionel Sambuc // If one of the blocks can be completely merged and happens to be in
577f4a2713aSLionel Sambuc // a position where the other could fall through into it, merge any number
578f4a2713aSLionel Sambuc // of instructions, because it can be done without a branch.
579f4a2713aSLionel Sambuc // TODO: If the blocks are not adjacent, move one of them so that they are?
580f4a2713aSLionel Sambuc if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
581f4a2713aSLionel Sambuc return true;
582f4a2713aSLionel Sambuc if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
583f4a2713aSLionel Sambuc return true;
584f4a2713aSLionel Sambuc
585f4a2713aSLionel Sambuc // If both blocks have an unconditional branch temporarily stripped out,
586f4a2713aSLionel Sambuc // count that as an additional common instruction for the following
587f4a2713aSLionel Sambuc // heuristics.
588f4a2713aSLionel Sambuc unsigned EffectiveTailLen = CommonTailLen;
589f4a2713aSLionel Sambuc if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
590f4a2713aSLionel Sambuc !MBB1->back().isBarrier() &&
591f4a2713aSLionel Sambuc !MBB2->back().isBarrier())
592f4a2713aSLionel Sambuc ++EffectiveTailLen;
593f4a2713aSLionel Sambuc
594f4a2713aSLionel Sambuc // Check if the common tail is long enough to be worthwhile.
595f4a2713aSLionel Sambuc if (EffectiveTailLen >= minCommonTailLength)
596f4a2713aSLionel Sambuc return true;
597f4a2713aSLionel Sambuc
598f4a2713aSLionel Sambuc // If we are optimizing for code size, 2 instructions in common is enough if
599f4a2713aSLionel Sambuc // we don't have to split a block. At worst we will be introducing 1 new
600f4a2713aSLionel Sambuc // branch instruction, which is likely to be smaller than the 2
601f4a2713aSLionel Sambuc // instructions that would be deleted in the merge.
602f4a2713aSLionel Sambuc MachineFunction *MF = MBB1->getParent();
603f4a2713aSLionel Sambuc if (EffectiveTailLen >= 2 &&
604f4a2713aSLionel Sambuc MF->getFunction()->getAttributes().
605f4a2713aSLionel Sambuc hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize) &&
606f4a2713aSLionel Sambuc (I1 == MBB1->begin() || I2 == MBB2->begin()))
607f4a2713aSLionel Sambuc return true;
608f4a2713aSLionel Sambuc
609f4a2713aSLionel Sambuc return false;
610f4a2713aSLionel Sambuc }
611f4a2713aSLionel Sambuc
612f4a2713aSLionel Sambuc /// ComputeSameTails - Look through all the blocks in MergePotentials that have
613f4a2713aSLionel Sambuc /// hash CurHash (guaranteed to match the last element). Build the vector
614f4a2713aSLionel Sambuc /// SameTails of all those that have the (same) largest number of instructions
615f4a2713aSLionel Sambuc /// in common of any pair of these blocks. SameTails entries contain an
616f4a2713aSLionel Sambuc /// iterator into MergePotentials (from which the MachineBasicBlock can be
617f4a2713aSLionel Sambuc /// found) and a MachineBasicBlock::iterator into that MBB indicating the
618f4a2713aSLionel Sambuc /// instruction where the matching code sequence begins.
619f4a2713aSLionel Sambuc /// Order of elements in SameTails is the reverse of the order in which
620f4a2713aSLionel Sambuc /// those blocks appear in MergePotentials (where they are not necessarily
621f4a2713aSLionel Sambuc /// consecutive).
ComputeSameTails(unsigned CurHash,unsigned minCommonTailLength,MachineBasicBlock * SuccBB,MachineBasicBlock * PredBB)622f4a2713aSLionel Sambuc unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
623f4a2713aSLionel Sambuc unsigned minCommonTailLength,
624f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB,
625f4a2713aSLionel Sambuc MachineBasicBlock *PredBB) {
626f4a2713aSLionel Sambuc unsigned maxCommonTailLength = 0U;
627f4a2713aSLionel Sambuc SameTails.clear();
628f4a2713aSLionel Sambuc MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
629*0a6a1f1dSLionel Sambuc MPIterator HighestMPIter = std::prev(MergePotentials.end());
630*0a6a1f1dSLionel Sambuc for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
631f4a2713aSLionel Sambuc B = MergePotentials.begin();
632*0a6a1f1dSLionel Sambuc CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
633*0a6a1f1dSLionel Sambuc for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
634f4a2713aSLionel Sambuc unsigned CommonTailLen;
635f4a2713aSLionel Sambuc if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
636f4a2713aSLionel Sambuc minCommonTailLength,
637f4a2713aSLionel Sambuc CommonTailLen, TrialBBI1, TrialBBI2,
638f4a2713aSLionel Sambuc SuccBB, PredBB)) {
639f4a2713aSLionel Sambuc if (CommonTailLen > maxCommonTailLength) {
640f4a2713aSLionel Sambuc SameTails.clear();
641f4a2713aSLionel Sambuc maxCommonTailLength = CommonTailLen;
642f4a2713aSLionel Sambuc HighestMPIter = CurMPIter;
643f4a2713aSLionel Sambuc SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
644f4a2713aSLionel Sambuc }
645f4a2713aSLionel Sambuc if (HighestMPIter == CurMPIter &&
646f4a2713aSLionel Sambuc CommonTailLen == maxCommonTailLength)
647f4a2713aSLionel Sambuc SameTails.push_back(SameTailElt(I, TrialBBI2));
648f4a2713aSLionel Sambuc }
649f4a2713aSLionel Sambuc if (I == B)
650f4a2713aSLionel Sambuc break;
651f4a2713aSLionel Sambuc }
652f4a2713aSLionel Sambuc }
653f4a2713aSLionel Sambuc return maxCommonTailLength;
654f4a2713aSLionel Sambuc }
655f4a2713aSLionel Sambuc
656f4a2713aSLionel Sambuc /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
657f4a2713aSLionel Sambuc /// MergePotentials, restoring branches at ends of blocks as appropriate.
RemoveBlocksWithHash(unsigned CurHash,MachineBasicBlock * SuccBB,MachineBasicBlock * PredBB)658f4a2713aSLionel Sambuc void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
659f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB,
660f4a2713aSLionel Sambuc MachineBasicBlock *PredBB) {
661f4a2713aSLionel Sambuc MPIterator CurMPIter, B;
662*0a6a1f1dSLionel Sambuc for (CurMPIter = std::prev(MergePotentials.end()),
663*0a6a1f1dSLionel Sambuc B = MergePotentials.begin();
664*0a6a1f1dSLionel Sambuc CurMPIter->getHash() == CurHash; --CurMPIter) {
665f4a2713aSLionel Sambuc // Put the unconditional branch back, if we need one.
666f4a2713aSLionel Sambuc MachineBasicBlock *CurMBB = CurMPIter->getBlock();
667f4a2713aSLionel Sambuc if (SuccBB && CurMBB != PredBB)
668f4a2713aSLionel Sambuc FixTail(CurMBB, SuccBB, TII);
669f4a2713aSLionel Sambuc if (CurMPIter == B)
670f4a2713aSLionel Sambuc break;
671f4a2713aSLionel Sambuc }
672f4a2713aSLionel Sambuc if (CurMPIter->getHash() != CurHash)
673f4a2713aSLionel Sambuc CurMPIter++;
674f4a2713aSLionel Sambuc MergePotentials.erase(CurMPIter, MergePotentials.end());
675f4a2713aSLionel Sambuc }
676f4a2713aSLionel Sambuc
677f4a2713aSLionel Sambuc /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
678f4a2713aSLionel Sambuc /// only of the common tail. Create a block that does by splitting one.
CreateCommonTailOnlyBlock(MachineBasicBlock * & PredBB,MachineBasicBlock * SuccBB,unsigned maxCommonTailLength,unsigned & commonTailIndex)679f4a2713aSLionel Sambuc bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
680f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB,
681f4a2713aSLionel Sambuc unsigned maxCommonTailLength,
682f4a2713aSLionel Sambuc unsigned &commonTailIndex) {
683f4a2713aSLionel Sambuc commonTailIndex = 0;
684f4a2713aSLionel Sambuc unsigned TimeEstimate = ~0U;
685f4a2713aSLionel Sambuc for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
686f4a2713aSLionel Sambuc // Use PredBB if possible; that doesn't require a new branch.
687f4a2713aSLionel Sambuc if (SameTails[i].getBlock() == PredBB) {
688f4a2713aSLionel Sambuc commonTailIndex = i;
689f4a2713aSLionel Sambuc break;
690f4a2713aSLionel Sambuc }
691f4a2713aSLionel Sambuc // Otherwise, make a (fairly bogus) choice based on estimate of
692f4a2713aSLionel Sambuc // how long it will take the various blocks to execute.
693f4a2713aSLionel Sambuc unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
694f4a2713aSLionel Sambuc SameTails[i].getTailStartPos());
695f4a2713aSLionel Sambuc if (t <= TimeEstimate) {
696f4a2713aSLionel Sambuc TimeEstimate = t;
697f4a2713aSLionel Sambuc commonTailIndex = i;
698f4a2713aSLionel Sambuc }
699f4a2713aSLionel Sambuc }
700f4a2713aSLionel Sambuc
701f4a2713aSLionel Sambuc MachineBasicBlock::iterator BBI =
702f4a2713aSLionel Sambuc SameTails[commonTailIndex].getTailStartPos();
703f4a2713aSLionel Sambuc MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
704f4a2713aSLionel Sambuc
705f4a2713aSLionel Sambuc // If the common tail includes any debug info we will take it pretty
706f4a2713aSLionel Sambuc // randomly from one of the inputs. Might be better to remove it?
707f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
708f4a2713aSLionel Sambuc << maxCommonTailLength);
709f4a2713aSLionel Sambuc
710f4a2713aSLionel Sambuc // If the split block unconditionally falls-thru to SuccBB, it will be
711f4a2713aSLionel Sambuc // merged. In control flow terms it should then take SuccBB's name. e.g. If
712f4a2713aSLionel Sambuc // SuccBB is an inner loop, the common tail is still part of the inner loop.
713f4a2713aSLionel Sambuc const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
714f4a2713aSLionel Sambuc SuccBB->getBasicBlock() : MBB->getBasicBlock();
715f4a2713aSLionel Sambuc MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
716f4a2713aSLionel Sambuc if (!newMBB) {
717f4a2713aSLionel Sambuc DEBUG(dbgs() << "... failed!");
718f4a2713aSLionel Sambuc return false;
719f4a2713aSLionel Sambuc }
720f4a2713aSLionel Sambuc
721f4a2713aSLionel Sambuc SameTails[commonTailIndex].setBlock(newMBB);
722f4a2713aSLionel Sambuc SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
723f4a2713aSLionel Sambuc
724f4a2713aSLionel Sambuc // If we split PredBB, newMBB is the new predecessor.
725f4a2713aSLionel Sambuc if (PredBB == MBB)
726f4a2713aSLionel Sambuc PredBB = newMBB;
727f4a2713aSLionel Sambuc
728f4a2713aSLionel Sambuc return true;
729f4a2713aSLionel Sambuc }
730f4a2713aSLionel Sambuc
731f4a2713aSLionel Sambuc // See if any of the blocks in MergePotentials (which all have a common single
732f4a2713aSLionel Sambuc // successor, or all have no successor) can be tail-merged. If there is a
733f4a2713aSLionel Sambuc // successor, any blocks in MergePotentials that are not tail-merged and
734f4a2713aSLionel Sambuc // are not immediately before Succ must have an unconditional branch to
735f4a2713aSLionel Sambuc // Succ added (but the predecessor/successor lists need no adjustment).
736f4a2713aSLionel Sambuc // The lone predecessor of Succ that falls through into Succ,
737f4a2713aSLionel Sambuc // if any, is given in PredBB.
738f4a2713aSLionel Sambuc
TryTailMergeBlocks(MachineBasicBlock * SuccBB,MachineBasicBlock * PredBB)739f4a2713aSLionel Sambuc bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
740f4a2713aSLionel Sambuc MachineBasicBlock *PredBB) {
741f4a2713aSLionel Sambuc bool MadeChange = false;
742f4a2713aSLionel Sambuc
743f4a2713aSLionel Sambuc // Except for the special cases below, tail-merge if there are at least
744f4a2713aSLionel Sambuc // this many instructions in common.
745f4a2713aSLionel Sambuc unsigned minCommonTailLength = TailMergeSize;
746f4a2713aSLionel Sambuc
747f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
748f4a2713aSLionel Sambuc for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
749f4a2713aSLionel Sambuc dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
750f4a2713aSLionel Sambuc << (i == e-1 ? "" : ", ");
751f4a2713aSLionel Sambuc dbgs() << "\n";
752f4a2713aSLionel Sambuc if (SuccBB) {
753f4a2713aSLionel Sambuc dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
754f4a2713aSLionel Sambuc if (PredBB)
755f4a2713aSLionel Sambuc dbgs() << " which has fall-through from BB#"
756f4a2713aSLionel Sambuc << PredBB->getNumber() << "\n";
757f4a2713aSLionel Sambuc }
758f4a2713aSLionel Sambuc dbgs() << "Looking for common tails of at least "
759f4a2713aSLionel Sambuc << minCommonTailLength << " instruction"
760f4a2713aSLionel Sambuc << (minCommonTailLength == 1 ? "" : "s") << '\n';
761f4a2713aSLionel Sambuc );
762f4a2713aSLionel Sambuc
763f4a2713aSLionel Sambuc // Sort by hash value so that blocks with identical end sequences sort
764f4a2713aSLionel Sambuc // together.
765f4a2713aSLionel Sambuc std::stable_sort(MergePotentials.begin(), MergePotentials.end());
766f4a2713aSLionel Sambuc
767f4a2713aSLionel Sambuc // Walk through equivalence sets looking for actual exact matches.
768f4a2713aSLionel Sambuc while (MergePotentials.size() > 1) {
769f4a2713aSLionel Sambuc unsigned CurHash = MergePotentials.back().getHash();
770f4a2713aSLionel Sambuc
771f4a2713aSLionel Sambuc // Build SameTails, identifying the set of blocks with this hash code
772f4a2713aSLionel Sambuc // and with the maximum number of instructions in common.
773f4a2713aSLionel Sambuc unsigned maxCommonTailLength = ComputeSameTails(CurHash,
774f4a2713aSLionel Sambuc minCommonTailLength,
775f4a2713aSLionel Sambuc SuccBB, PredBB);
776f4a2713aSLionel Sambuc
777f4a2713aSLionel Sambuc // If we didn't find any pair that has at least minCommonTailLength
778f4a2713aSLionel Sambuc // instructions in common, remove all blocks with this hash code and retry.
779f4a2713aSLionel Sambuc if (SameTails.empty()) {
780f4a2713aSLionel Sambuc RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
781f4a2713aSLionel Sambuc continue;
782f4a2713aSLionel Sambuc }
783f4a2713aSLionel Sambuc
784f4a2713aSLionel Sambuc // If one of the blocks is the entire common tail (and not the entry
785f4a2713aSLionel Sambuc // block, which we can't jump to), we can treat all blocks with this same
786f4a2713aSLionel Sambuc // tail at once. Use PredBB if that is one of the possibilities, as that
787f4a2713aSLionel Sambuc // will not introduce any extra branches.
788f4a2713aSLionel Sambuc MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
789f4a2713aSLionel Sambuc getParent()->begin();
790f4a2713aSLionel Sambuc unsigned commonTailIndex = SameTails.size();
791f4a2713aSLionel Sambuc // If there are two blocks, check to see if one can be made to fall through
792f4a2713aSLionel Sambuc // into the other.
793f4a2713aSLionel Sambuc if (SameTails.size() == 2 &&
794f4a2713aSLionel Sambuc SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
795f4a2713aSLionel Sambuc SameTails[1].tailIsWholeBlock())
796f4a2713aSLionel Sambuc commonTailIndex = 1;
797f4a2713aSLionel Sambuc else if (SameTails.size() == 2 &&
798f4a2713aSLionel Sambuc SameTails[1].getBlock()->isLayoutSuccessor(
799f4a2713aSLionel Sambuc SameTails[0].getBlock()) &&
800f4a2713aSLionel Sambuc SameTails[0].tailIsWholeBlock())
801f4a2713aSLionel Sambuc commonTailIndex = 0;
802f4a2713aSLionel Sambuc else {
803f4a2713aSLionel Sambuc // Otherwise just pick one, favoring the fall-through predecessor if
804f4a2713aSLionel Sambuc // there is one.
805f4a2713aSLionel Sambuc for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
806f4a2713aSLionel Sambuc MachineBasicBlock *MBB = SameTails[i].getBlock();
807f4a2713aSLionel Sambuc if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
808f4a2713aSLionel Sambuc continue;
809f4a2713aSLionel Sambuc if (MBB == PredBB) {
810f4a2713aSLionel Sambuc commonTailIndex = i;
811f4a2713aSLionel Sambuc break;
812f4a2713aSLionel Sambuc }
813f4a2713aSLionel Sambuc if (SameTails[i].tailIsWholeBlock())
814f4a2713aSLionel Sambuc commonTailIndex = i;
815f4a2713aSLionel Sambuc }
816f4a2713aSLionel Sambuc }
817f4a2713aSLionel Sambuc
818f4a2713aSLionel Sambuc if (commonTailIndex == SameTails.size() ||
819f4a2713aSLionel Sambuc (SameTails[commonTailIndex].getBlock() == PredBB &&
820f4a2713aSLionel Sambuc !SameTails[commonTailIndex].tailIsWholeBlock())) {
821f4a2713aSLionel Sambuc // None of the blocks consist entirely of the common tail.
822f4a2713aSLionel Sambuc // Split a block so that one does.
823f4a2713aSLionel Sambuc if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
824f4a2713aSLionel Sambuc maxCommonTailLength, commonTailIndex)) {
825f4a2713aSLionel Sambuc RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
826f4a2713aSLionel Sambuc continue;
827f4a2713aSLionel Sambuc }
828f4a2713aSLionel Sambuc }
829f4a2713aSLionel Sambuc
830f4a2713aSLionel Sambuc MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
831*0a6a1f1dSLionel Sambuc
832*0a6a1f1dSLionel Sambuc // Recompute commont tail MBB's edge weights and block frequency.
833*0a6a1f1dSLionel Sambuc setCommonTailEdgeWeights(*MBB);
834*0a6a1f1dSLionel Sambuc
835f4a2713aSLionel Sambuc // MBB is common tail. Adjust all other BB's to jump to this one.
836f4a2713aSLionel Sambuc // Traversal must be forwards so erases work.
837f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
838f4a2713aSLionel Sambuc << " for ");
839f4a2713aSLionel Sambuc for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
840f4a2713aSLionel Sambuc if (commonTailIndex == i)
841f4a2713aSLionel Sambuc continue;
842f4a2713aSLionel Sambuc DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
843f4a2713aSLionel Sambuc << (i == e-1 ? "" : ", "));
844f4a2713aSLionel Sambuc // Hack the end off BB i, making it jump to BB commonTailIndex instead.
845f4a2713aSLionel Sambuc ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
846f4a2713aSLionel Sambuc // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
847f4a2713aSLionel Sambuc MergePotentials.erase(SameTails[i].getMPIter());
848f4a2713aSLionel Sambuc }
849f4a2713aSLionel Sambuc DEBUG(dbgs() << "\n");
850f4a2713aSLionel Sambuc // We leave commonTailIndex in the worklist in case there are other blocks
851f4a2713aSLionel Sambuc // that match it with a smaller number of instructions.
852f4a2713aSLionel Sambuc MadeChange = true;
853f4a2713aSLionel Sambuc }
854f4a2713aSLionel Sambuc return MadeChange;
855f4a2713aSLionel Sambuc }
856f4a2713aSLionel Sambuc
TailMergeBlocks(MachineFunction & MF)857f4a2713aSLionel Sambuc bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
858f4a2713aSLionel Sambuc bool MadeChange = false;
859f4a2713aSLionel Sambuc if (!EnableTailMerge) return MadeChange;
860f4a2713aSLionel Sambuc
861f4a2713aSLionel Sambuc // First find blocks with no successors.
862f4a2713aSLionel Sambuc MergePotentials.clear();
863f4a2713aSLionel Sambuc for (MachineFunction::iterator I = MF.begin(), E = MF.end();
864f4a2713aSLionel Sambuc I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
865f4a2713aSLionel Sambuc if (TriedMerging.count(I))
866f4a2713aSLionel Sambuc continue;
867f4a2713aSLionel Sambuc if (I->succ_empty())
868f4a2713aSLionel Sambuc MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
869f4a2713aSLionel Sambuc }
870f4a2713aSLionel Sambuc
871f4a2713aSLionel Sambuc // If this is a large problem, avoid visiting the same basic blocks
872f4a2713aSLionel Sambuc // multiple times.
873f4a2713aSLionel Sambuc if (MergePotentials.size() == TailMergeThreshold)
874f4a2713aSLionel Sambuc for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
875f4a2713aSLionel Sambuc TriedMerging.insert(MergePotentials[i].getBlock());
876f4a2713aSLionel Sambuc
877f4a2713aSLionel Sambuc // See if we can do any tail merging on those.
878f4a2713aSLionel Sambuc if (MergePotentials.size() >= 2)
879*0a6a1f1dSLionel Sambuc MadeChange |= TryTailMergeBlocks(nullptr, nullptr);
880f4a2713aSLionel Sambuc
881f4a2713aSLionel Sambuc // Look at blocks (IBB) with multiple predecessors (PBB).
882f4a2713aSLionel Sambuc // We change each predecessor to a canonical form, by
883f4a2713aSLionel Sambuc // (1) temporarily removing any unconditional branch from the predecessor
884f4a2713aSLionel Sambuc // to IBB, and
885f4a2713aSLionel Sambuc // (2) alter conditional branches so they branch to the other block
886f4a2713aSLionel Sambuc // not IBB; this may require adding back an unconditional branch to IBB
887f4a2713aSLionel Sambuc // later, where there wasn't one coming in. E.g.
888f4a2713aSLionel Sambuc // Bcc IBB
889f4a2713aSLionel Sambuc // fallthrough to QBB
890f4a2713aSLionel Sambuc // here becomes
891f4a2713aSLionel Sambuc // Bncc QBB
892f4a2713aSLionel Sambuc // with a conceptual B to IBB after that, which never actually exists.
893f4a2713aSLionel Sambuc // With those changes, we see whether the predecessors' tails match,
894f4a2713aSLionel Sambuc // and merge them if so. We change things out of canonical form and
895f4a2713aSLionel Sambuc // back to the way they were later in the process. (OptimizeBranches
896f4a2713aSLionel Sambuc // would undo some of this, but we can't use it, because we'd get into
897f4a2713aSLionel Sambuc // a compile-time infinite loop repeatedly doing and undoing the same
898f4a2713aSLionel Sambuc // transformations.)
899f4a2713aSLionel Sambuc
900*0a6a1f1dSLionel Sambuc for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
901f4a2713aSLionel Sambuc I != E; ++I) {
902f4a2713aSLionel Sambuc if (I->pred_size() < 2) continue;
903f4a2713aSLionel Sambuc SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
904f4a2713aSLionel Sambuc MachineBasicBlock *IBB = I;
905*0a6a1f1dSLionel Sambuc MachineBasicBlock *PredBB = std::prev(I);
906f4a2713aSLionel Sambuc MergePotentials.clear();
907f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
908f4a2713aSLionel Sambuc E2 = I->pred_end();
909f4a2713aSLionel Sambuc P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
910f4a2713aSLionel Sambuc MachineBasicBlock *PBB = *P;
911f4a2713aSLionel Sambuc if (TriedMerging.count(PBB))
912f4a2713aSLionel Sambuc continue;
913f4a2713aSLionel Sambuc
914f4a2713aSLionel Sambuc // Skip blocks that loop to themselves, can't tail merge these.
915f4a2713aSLionel Sambuc if (PBB == IBB)
916f4a2713aSLionel Sambuc continue;
917f4a2713aSLionel Sambuc
918f4a2713aSLionel Sambuc // Visit each predecessor only once.
919*0a6a1f1dSLionel Sambuc if (!UniquePreds.insert(PBB).second)
920f4a2713aSLionel Sambuc continue;
921f4a2713aSLionel Sambuc
922f4a2713aSLionel Sambuc // Skip blocks which may jump to a landing pad. Can't tail merge these.
923f4a2713aSLionel Sambuc if (PBB->getLandingPadSuccessor())
924f4a2713aSLionel Sambuc continue;
925f4a2713aSLionel Sambuc
926*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
927f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> Cond;
928f4a2713aSLionel Sambuc if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
929f4a2713aSLionel Sambuc // Failing case: IBB is the target of a cbr, and we cannot reverse the
930f4a2713aSLionel Sambuc // branch.
931f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> NewCond(Cond);
932f4a2713aSLionel Sambuc if (!Cond.empty() && TBB == IBB) {
933f4a2713aSLionel Sambuc if (TII->ReverseBranchCondition(NewCond))
934f4a2713aSLionel Sambuc continue;
935f4a2713aSLionel Sambuc // This is the QBB case described above
936f4a2713aSLionel Sambuc if (!FBB)
937*0a6a1f1dSLionel Sambuc FBB = std::next(MachineFunction::iterator(PBB));
938f4a2713aSLionel Sambuc }
939f4a2713aSLionel Sambuc
940f4a2713aSLionel Sambuc // Failing case: the only way IBB can be reached from PBB is via
941f4a2713aSLionel Sambuc // exception handling. Happens for landing pads. Would be nice to have
942f4a2713aSLionel Sambuc // a bit in the edge so we didn't have to do all this.
943f4a2713aSLionel Sambuc if (IBB->isLandingPad()) {
944f4a2713aSLionel Sambuc MachineFunction::iterator IP = PBB; IP++;
945*0a6a1f1dSLionel Sambuc MachineBasicBlock *PredNextBB = nullptr;
946f4a2713aSLionel Sambuc if (IP != MF.end())
947f4a2713aSLionel Sambuc PredNextBB = IP;
948*0a6a1f1dSLionel Sambuc if (!TBB) {
949f4a2713aSLionel Sambuc if (IBB != PredNextBB) // fallthrough
950f4a2713aSLionel Sambuc continue;
951f4a2713aSLionel Sambuc } else if (FBB) {
952f4a2713aSLionel Sambuc if (TBB != IBB && FBB != IBB) // cbr then ubr
953f4a2713aSLionel Sambuc continue;
954f4a2713aSLionel Sambuc } else if (Cond.empty()) {
955f4a2713aSLionel Sambuc if (TBB != IBB) // ubr
956f4a2713aSLionel Sambuc continue;
957f4a2713aSLionel Sambuc } else {
958f4a2713aSLionel Sambuc if (TBB != IBB && IBB != PredNextBB) // cbr
959f4a2713aSLionel Sambuc continue;
960f4a2713aSLionel Sambuc }
961f4a2713aSLionel Sambuc }
962f4a2713aSLionel Sambuc
963f4a2713aSLionel Sambuc // Remove the unconditional branch at the end, if any.
964f4a2713aSLionel Sambuc if (TBB && (Cond.empty() || FBB)) {
965f4a2713aSLionel Sambuc DebugLoc dl; // FIXME: this is nowhere
966f4a2713aSLionel Sambuc TII->RemoveBranch(*PBB);
967f4a2713aSLionel Sambuc if (!Cond.empty())
968f4a2713aSLionel Sambuc // reinsert conditional branch only, for now
969*0a6a1f1dSLionel Sambuc TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
970*0a6a1f1dSLionel Sambuc NewCond, dl);
971f4a2713aSLionel Sambuc }
972f4a2713aSLionel Sambuc
973f4a2713aSLionel Sambuc MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
974f4a2713aSLionel Sambuc }
975f4a2713aSLionel Sambuc }
976f4a2713aSLionel Sambuc
977f4a2713aSLionel Sambuc // If this is a large problem, avoid visiting the same basic blocks multiple
978f4a2713aSLionel Sambuc // times.
979f4a2713aSLionel Sambuc if (MergePotentials.size() == TailMergeThreshold)
980f4a2713aSLionel Sambuc for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
981f4a2713aSLionel Sambuc TriedMerging.insert(MergePotentials[i].getBlock());
982f4a2713aSLionel Sambuc
983f4a2713aSLionel Sambuc if (MergePotentials.size() >= 2)
984f4a2713aSLionel Sambuc MadeChange |= TryTailMergeBlocks(IBB, PredBB);
985f4a2713aSLionel Sambuc
986f4a2713aSLionel Sambuc // Reinsert an unconditional branch if needed. The 1 below can occur as a
987f4a2713aSLionel Sambuc // result of removing blocks in TryTailMergeBlocks.
988*0a6a1f1dSLionel Sambuc PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks
989f4a2713aSLionel Sambuc if (MergePotentials.size() == 1 &&
990f4a2713aSLionel Sambuc MergePotentials.begin()->getBlock() != PredBB)
991f4a2713aSLionel Sambuc FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
992f4a2713aSLionel Sambuc }
993f4a2713aSLionel Sambuc
994f4a2713aSLionel Sambuc return MadeChange;
995f4a2713aSLionel Sambuc }
996f4a2713aSLionel Sambuc
setCommonTailEdgeWeights(MachineBasicBlock & TailMBB)997*0a6a1f1dSLionel Sambuc void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
998*0a6a1f1dSLionel Sambuc SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
999*0a6a1f1dSLionel Sambuc BlockFrequency AccumulatedMBBFreq;
1000*0a6a1f1dSLionel Sambuc
1001*0a6a1f1dSLionel Sambuc // Aggregate edge frequency of successor edge j:
1002*0a6a1f1dSLionel Sambuc // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1003*0a6a1f1dSLionel Sambuc // where bb is a basic block that is in SameTails.
1004*0a6a1f1dSLionel Sambuc for (const auto &Src : SameTails) {
1005*0a6a1f1dSLionel Sambuc const MachineBasicBlock *SrcMBB = Src.getBlock();
1006*0a6a1f1dSLionel Sambuc BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1007*0a6a1f1dSLionel Sambuc AccumulatedMBBFreq += BlockFreq;
1008*0a6a1f1dSLionel Sambuc
1009*0a6a1f1dSLionel Sambuc // It is not necessary to recompute edge weights if TailBB has less than two
1010*0a6a1f1dSLionel Sambuc // successors.
1011*0a6a1f1dSLionel Sambuc if (TailMBB.succ_size() <= 1)
1012*0a6a1f1dSLionel Sambuc continue;
1013*0a6a1f1dSLionel Sambuc
1014*0a6a1f1dSLionel Sambuc auto EdgeFreq = EdgeFreqLs.begin();
1015*0a6a1f1dSLionel Sambuc
1016*0a6a1f1dSLionel Sambuc for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1017*0a6a1f1dSLionel Sambuc SuccI != SuccE; ++SuccI, ++EdgeFreq)
1018*0a6a1f1dSLionel Sambuc *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1019*0a6a1f1dSLionel Sambuc }
1020*0a6a1f1dSLionel Sambuc
1021*0a6a1f1dSLionel Sambuc MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1022*0a6a1f1dSLionel Sambuc
1023*0a6a1f1dSLionel Sambuc if (TailMBB.succ_size() <= 1)
1024*0a6a1f1dSLionel Sambuc return;
1025*0a6a1f1dSLionel Sambuc
1026*0a6a1f1dSLionel Sambuc auto MaxEdgeFreq = *std::max_element(EdgeFreqLs.begin(), EdgeFreqLs.end());
1027*0a6a1f1dSLionel Sambuc uint64_t Scale = MaxEdgeFreq.getFrequency() / UINT32_MAX + 1;
1028*0a6a1f1dSLionel Sambuc auto EdgeFreq = EdgeFreqLs.begin();
1029*0a6a1f1dSLionel Sambuc
1030*0a6a1f1dSLionel Sambuc for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1031*0a6a1f1dSLionel Sambuc SuccI != SuccE; ++SuccI, ++EdgeFreq)
1032*0a6a1f1dSLionel Sambuc TailMBB.setSuccWeight(SuccI, EdgeFreq->getFrequency() / Scale);
1033*0a6a1f1dSLionel Sambuc }
1034*0a6a1f1dSLionel Sambuc
1035f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1036f4a2713aSLionel Sambuc // Branch Optimization
1037f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1038f4a2713aSLionel Sambuc
OptimizeBranches(MachineFunction & MF)1039f4a2713aSLionel Sambuc bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1040f4a2713aSLionel Sambuc bool MadeChange = false;
1041f4a2713aSLionel Sambuc
1042f4a2713aSLionel Sambuc // Make sure blocks are numbered in order
1043f4a2713aSLionel Sambuc MF.RenumberBlocks();
1044f4a2713aSLionel Sambuc
1045*0a6a1f1dSLionel Sambuc for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1046f4a2713aSLionel Sambuc I != E; ) {
1047f4a2713aSLionel Sambuc MachineBasicBlock *MBB = I++;
1048f4a2713aSLionel Sambuc MadeChange |= OptimizeBlock(MBB);
1049f4a2713aSLionel Sambuc
1050f4a2713aSLionel Sambuc // If it is dead, remove it.
1051f4a2713aSLionel Sambuc if (MBB->pred_empty()) {
1052f4a2713aSLionel Sambuc RemoveDeadBlock(MBB);
1053f4a2713aSLionel Sambuc MadeChange = true;
1054f4a2713aSLionel Sambuc ++NumDeadBlocks;
1055f4a2713aSLionel Sambuc }
1056f4a2713aSLionel Sambuc }
1057f4a2713aSLionel Sambuc return MadeChange;
1058f4a2713aSLionel Sambuc }
1059f4a2713aSLionel Sambuc
1060f4a2713aSLionel Sambuc // Blocks should be considered empty if they contain only debug info;
1061f4a2713aSLionel Sambuc // else the debug info would affect codegen.
IsEmptyBlock(MachineBasicBlock * MBB)1062f4a2713aSLionel Sambuc static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1063f4a2713aSLionel Sambuc if (MBB->empty())
1064f4a2713aSLionel Sambuc return true;
1065f4a2713aSLionel Sambuc for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
1066f4a2713aSLionel Sambuc MBBI!=MBBE; ++MBBI) {
1067f4a2713aSLionel Sambuc if (!MBBI->isDebugValue())
1068f4a2713aSLionel Sambuc return false;
1069f4a2713aSLionel Sambuc }
1070f4a2713aSLionel Sambuc return true;
1071f4a2713aSLionel Sambuc }
1072f4a2713aSLionel Sambuc
1073f4a2713aSLionel Sambuc // Blocks with only debug info and branches should be considered the same
1074f4a2713aSLionel Sambuc // as blocks with only branches.
IsBranchOnlyBlock(MachineBasicBlock * MBB)1075f4a2713aSLionel Sambuc static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1076f4a2713aSLionel Sambuc MachineBasicBlock::iterator MBBI, MBBE;
1077f4a2713aSLionel Sambuc for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
1078f4a2713aSLionel Sambuc if (!MBBI->isDebugValue())
1079f4a2713aSLionel Sambuc break;
1080f4a2713aSLionel Sambuc }
1081f4a2713aSLionel Sambuc return (MBBI->isBranch());
1082f4a2713aSLionel Sambuc }
1083f4a2713aSLionel Sambuc
1084f4a2713aSLionel Sambuc /// IsBetterFallthrough - Return true if it would be clearly better to
1085f4a2713aSLionel Sambuc /// fall-through to MBB1 than to fall through into MBB2. This has to return
1086f4a2713aSLionel Sambuc /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1087f4a2713aSLionel Sambuc /// result in infinite loops.
IsBetterFallthrough(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2)1088f4a2713aSLionel Sambuc static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1089f4a2713aSLionel Sambuc MachineBasicBlock *MBB2) {
1090f4a2713aSLionel Sambuc // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1091f4a2713aSLionel Sambuc // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1092f4a2713aSLionel Sambuc // optimize branches that branch to either a return block or an assert block
1093f4a2713aSLionel Sambuc // into a fallthrough to the return.
1094f4a2713aSLionel Sambuc if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
1095f4a2713aSLionel Sambuc
1096f4a2713aSLionel Sambuc // If there is a clear successor ordering we make sure that one block
1097f4a2713aSLionel Sambuc // will fall through to the next
1098f4a2713aSLionel Sambuc if (MBB1->isSuccessor(MBB2)) return true;
1099f4a2713aSLionel Sambuc if (MBB2->isSuccessor(MBB1)) return false;
1100f4a2713aSLionel Sambuc
1101f4a2713aSLionel Sambuc // Neither block consists entirely of debug info (per IsEmptyBlock check),
1102f4a2713aSLionel Sambuc // so we needn't test for falling off the beginning here.
1103f4a2713aSLionel Sambuc MachineBasicBlock::iterator MBB1I = --MBB1->end();
1104f4a2713aSLionel Sambuc while (MBB1I->isDebugValue())
1105f4a2713aSLionel Sambuc --MBB1I;
1106f4a2713aSLionel Sambuc MachineBasicBlock::iterator MBB2I = --MBB2->end();
1107f4a2713aSLionel Sambuc while (MBB2I->isDebugValue())
1108f4a2713aSLionel Sambuc --MBB2I;
1109f4a2713aSLionel Sambuc return MBB2I->isCall() && !MBB1I->isCall();
1110f4a2713aSLionel Sambuc }
1111f4a2713aSLionel Sambuc
1112f4a2713aSLionel Sambuc /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1113f4a2713aSLionel Sambuc /// instructions on the block. Always use the DebugLoc of the first
1114f4a2713aSLionel Sambuc /// branching instruction found unless its absent, in which case use the
1115f4a2713aSLionel Sambuc /// DebugLoc of the second if present.
getBranchDebugLoc(MachineBasicBlock & MBB)1116f4a2713aSLionel Sambuc static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1117f4a2713aSLionel Sambuc MachineBasicBlock::iterator I = MBB.end();
1118f4a2713aSLionel Sambuc if (I == MBB.begin())
1119f4a2713aSLionel Sambuc return DebugLoc();
1120f4a2713aSLionel Sambuc --I;
1121f4a2713aSLionel Sambuc while (I->isDebugValue() && I != MBB.begin())
1122f4a2713aSLionel Sambuc --I;
1123f4a2713aSLionel Sambuc if (I->isBranch())
1124f4a2713aSLionel Sambuc return I->getDebugLoc();
1125f4a2713aSLionel Sambuc return DebugLoc();
1126f4a2713aSLionel Sambuc }
1127f4a2713aSLionel Sambuc
1128f4a2713aSLionel Sambuc /// OptimizeBlock - Analyze and optimize control flow related to the specified
1129f4a2713aSLionel Sambuc /// block. This is never called on the entry block.
OptimizeBlock(MachineBasicBlock * MBB)1130f4a2713aSLionel Sambuc bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1131f4a2713aSLionel Sambuc bool MadeChange = false;
1132f4a2713aSLionel Sambuc MachineFunction &MF = *MBB->getParent();
1133f4a2713aSLionel Sambuc ReoptimizeBlock:
1134f4a2713aSLionel Sambuc
1135f4a2713aSLionel Sambuc MachineFunction::iterator FallThrough = MBB;
1136f4a2713aSLionel Sambuc ++FallThrough;
1137f4a2713aSLionel Sambuc
1138f4a2713aSLionel Sambuc // If this block is empty, make everyone use its fall-through, not the block
1139f4a2713aSLionel Sambuc // explicitly. Landing pads should not do this since the landing-pad table
1140f4a2713aSLionel Sambuc // points to this block. Blocks with their addresses taken shouldn't be
1141f4a2713aSLionel Sambuc // optimized away.
1142f4a2713aSLionel Sambuc if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
1143f4a2713aSLionel Sambuc // Dead block? Leave for cleanup later.
1144f4a2713aSLionel Sambuc if (MBB->pred_empty()) return MadeChange;
1145f4a2713aSLionel Sambuc
1146f4a2713aSLionel Sambuc if (FallThrough == MF.end()) {
1147f4a2713aSLionel Sambuc // TODO: Simplify preds to not branch here if possible!
1148f4a2713aSLionel Sambuc } else {
1149f4a2713aSLionel Sambuc // Rewrite all predecessors of the old block to go to the fallthrough
1150f4a2713aSLionel Sambuc // instead.
1151f4a2713aSLionel Sambuc while (!MBB->pred_empty()) {
1152f4a2713aSLionel Sambuc MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1153f4a2713aSLionel Sambuc Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1154f4a2713aSLionel Sambuc }
1155f4a2713aSLionel Sambuc // If MBB was the target of a jump table, update jump tables to go to the
1156f4a2713aSLionel Sambuc // fallthrough instead.
1157f4a2713aSLionel Sambuc if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1158f4a2713aSLionel Sambuc MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1159f4a2713aSLionel Sambuc MadeChange = true;
1160f4a2713aSLionel Sambuc }
1161f4a2713aSLionel Sambuc return MadeChange;
1162f4a2713aSLionel Sambuc }
1163f4a2713aSLionel Sambuc
1164f4a2713aSLionel Sambuc // Check to see if we can simplify the terminator of the block before this
1165f4a2713aSLionel Sambuc // one.
1166*0a6a1f1dSLionel Sambuc MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1167f4a2713aSLionel Sambuc
1168*0a6a1f1dSLionel Sambuc MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1169f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> PriorCond;
1170f4a2713aSLionel Sambuc bool PriorUnAnalyzable =
1171f4a2713aSLionel Sambuc TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1172f4a2713aSLionel Sambuc if (!PriorUnAnalyzable) {
1173f4a2713aSLionel Sambuc // If the CFG for the prior block has extra edges, remove them.
1174f4a2713aSLionel Sambuc MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1175f4a2713aSLionel Sambuc !PriorCond.empty());
1176f4a2713aSLionel Sambuc
1177f4a2713aSLionel Sambuc // If the previous branch is conditional and both conditions go to the same
1178f4a2713aSLionel Sambuc // destination, remove the branch, replacing it with an unconditional one or
1179f4a2713aSLionel Sambuc // a fall-through.
1180f4a2713aSLionel Sambuc if (PriorTBB && PriorTBB == PriorFBB) {
1181f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(PrevBB);
1182f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1183f4a2713aSLionel Sambuc PriorCond.clear();
1184f4a2713aSLionel Sambuc if (PriorTBB != MBB)
1185*0a6a1f1dSLionel Sambuc TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1186f4a2713aSLionel Sambuc MadeChange = true;
1187f4a2713aSLionel Sambuc ++NumBranchOpts;
1188f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1189f4a2713aSLionel Sambuc }
1190f4a2713aSLionel Sambuc
1191f4a2713aSLionel Sambuc // If the previous block unconditionally falls through to this block and
1192f4a2713aSLionel Sambuc // this block has no other predecessors, move the contents of this block
1193f4a2713aSLionel Sambuc // into the prior block. This doesn't usually happen when SimplifyCFG
1194f4a2713aSLionel Sambuc // has been used, but it can happen if tail merging splits a fall-through
1195f4a2713aSLionel Sambuc // predecessor of a block.
1196f4a2713aSLionel Sambuc // This has to check PrevBB->succ_size() because EH edges are ignored by
1197f4a2713aSLionel Sambuc // AnalyzeBranch.
1198f4a2713aSLionel Sambuc if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1199f4a2713aSLionel Sambuc PrevBB.succ_size() == 1 &&
1200f4a2713aSLionel Sambuc !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
1201f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1202f4a2713aSLionel Sambuc << "From MBB: " << *MBB);
1203f4a2713aSLionel Sambuc // Remove redundant DBG_VALUEs first.
1204f4a2713aSLionel Sambuc if (PrevBB.begin() != PrevBB.end()) {
1205f4a2713aSLionel Sambuc MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1206f4a2713aSLionel Sambuc --PrevBBIter;
1207f4a2713aSLionel Sambuc MachineBasicBlock::iterator MBBIter = MBB->begin();
1208f4a2713aSLionel Sambuc // Check if DBG_VALUE at the end of PrevBB is identical to the
1209f4a2713aSLionel Sambuc // DBG_VALUE at the beginning of MBB.
1210f4a2713aSLionel Sambuc while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1211f4a2713aSLionel Sambuc && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1212f4a2713aSLionel Sambuc if (!MBBIter->isIdenticalTo(PrevBBIter))
1213f4a2713aSLionel Sambuc break;
1214f4a2713aSLionel Sambuc MachineInstr *DuplicateDbg = MBBIter;
1215f4a2713aSLionel Sambuc ++MBBIter; -- PrevBBIter;
1216f4a2713aSLionel Sambuc DuplicateDbg->eraseFromParent();
1217f4a2713aSLionel Sambuc }
1218f4a2713aSLionel Sambuc }
1219f4a2713aSLionel Sambuc PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1220f4a2713aSLionel Sambuc PrevBB.removeSuccessor(PrevBB.succ_begin());
1221f4a2713aSLionel Sambuc assert(PrevBB.succ_empty());
1222f4a2713aSLionel Sambuc PrevBB.transferSuccessors(MBB);
1223f4a2713aSLionel Sambuc MadeChange = true;
1224f4a2713aSLionel Sambuc return MadeChange;
1225f4a2713aSLionel Sambuc }
1226f4a2713aSLionel Sambuc
1227f4a2713aSLionel Sambuc // If the previous branch *only* branches to *this* block (conditional or
1228f4a2713aSLionel Sambuc // not) remove the branch.
1229*0a6a1f1dSLionel Sambuc if (PriorTBB == MBB && !PriorFBB) {
1230f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1231f4a2713aSLionel Sambuc MadeChange = true;
1232f4a2713aSLionel Sambuc ++NumBranchOpts;
1233f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1234f4a2713aSLionel Sambuc }
1235f4a2713aSLionel Sambuc
1236f4a2713aSLionel Sambuc // If the prior block branches somewhere else on the condition and here if
1237f4a2713aSLionel Sambuc // the condition is false, remove the uncond second branch.
1238f4a2713aSLionel Sambuc if (PriorFBB == MBB) {
1239f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(PrevBB);
1240f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1241*0a6a1f1dSLionel Sambuc TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1242f4a2713aSLionel Sambuc MadeChange = true;
1243f4a2713aSLionel Sambuc ++NumBranchOpts;
1244f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1245f4a2713aSLionel Sambuc }
1246f4a2713aSLionel Sambuc
1247f4a2713aSLionel Sambuc // If the prior block branches here on true and somewhere else on false, and
1248f4a2713aSLionel Sambuc // if the branch condition is reversible, reverse the branch to create a
1249f4a2713aSLionel Sambuc // fall-through.
1250f4a2713aSLionel Sambuc if (PriorTBB == MBB) {
1251f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1252f4a2713aSLionel Sambuc if (!TII->ReverseBranchCondition(NewPriorCond)) {
1253f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(PrevBB);
1254f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1255*0a6a1f1dSLionel Sambuc TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1256f4a2713aSLionel Sambuc MadeChange = true;
1257f4a2713aSLionel Sambuc ++NumBranchOpts;
1258f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1259f4a2713aSLionel Sambuc }
1260f4a2713aSLionel Sambuc }
1261f4a2713aSLionel Sambuc
1262f4a2713aSLionel Sambuc // If this block has no successors (e.g. it is a return block or ends with
1263f4a2713aSLionel Sambuc // a call to a no-return function like abort or __cxa_throw) and if the pred
1264f4a2713aSLionel Sambuc // falls through into this block, and if it would otherwise fall through
1265f4a2713aSLionel Sambuc // into the block after this, move this block to the end of the function.
1266f4a2713aSLionel Sambuc //
1267f4a2713aSLionel Sambuc // We consider it more likely that execution will stay in the function (e.g.
1268f4a2713aSLionel Sambuc // due to loops) than it is to exit it. This asserts in loops etc, moving
1269f4a2713aSLionel Sambuc // the assert condition out of the loop body.
1270*0a6a1f1dSLionel Sambuc if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1271f4a2713aSLionel Sambuc MachineFunction::iterator(PriorTBB) == FallThrough &&
1272f4a2713aSLionel Sambuc !MBB->canFallThrough()) {
1273f4a2713aSLionel Sambuc bool DoTransform = true;
1274f4a2713aSLionel Sambuc
1275f4a2713aSLionel Sambuc // We have to be careful that the succs of PredBB aren't both no-successor
1276f4a2713aSLionel Sambuc // blocks. If neither have successors and if PredBB is the second from
1277f4a2713aSLionel Sambuc // last block in the function, we'd just keep swapping the two blocks for
1278f4a2713aSLionel Sambuc // last. Only do the swap if one is clearly better to fall through than
1279f4a2713aSLionel Sambuc // the other.
1280f4a2713aSLionel Sambuc if (FallThrough == --MF.end() &&
1281f4a2713aSLionel Sambuc !IsBetterFallthrough(PriorTBB, MBB))
1282f4a2713aSLionel Sambuc DoTransform = false;
1283f4a2713aSLionel Sambuc
1284f4a2713aSLionel Sambuc if (DoTransform) {
1285f4a2713aSLionel Sambuc // Reverse the branch so we will fall through on the previous true cond.
1286f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1287f4a2713aSLionel Sambuc if (!TII->ReverseBranchCondition(NewPriorCond)) {
1288f4a2713aSLionel Sambuc DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1289f4a2713aSLionel Sambuc << "To make fallthrough to: " << *PriorTBB << "\n");
1290f4a2713aSLionel Sambuc
1291f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(PrevBB);
1292f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1293*0a6a1f1dSLionel Sambuc TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1294f4a2713aSLionel Sambuc
1295f4a2713aSLionel Sambuc // Move this block to the end of the function.
1296f4a2713aSLionel Sambuc MBB->moveAfter(--MF.end());
1297f4a2713aSLionel Sambuc MadeChange = true;
1298f4a2713aSLionel Sambuc ++NumBranchOpts;
1299f4a2713aSLionel Sambuc return MadeChange;
1300f4a2713aSLionel Sambuc }
1301f4a2713aSLionel Sambuc }
1302f4a2713aSLionel Sambuc }
1303f4a2713aSLionel Sambuc }
1304f4a2713aSLionel Sambuc
1305f4a2713aSLionel Sambuc // Analyze the branch in the current block.
1306*0a6a1f1dSLionel Sambuc MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1307f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> CurCond;
1308f4a2713aSLionel Sambuc bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1309f4a2713aSLionel Sambuc if (!CurUnAnalyzable) {
1310f4a2713aSLionel Sambuc // If the CFG for the prior block has extra edges, remove them.
1311f4a2713aSLionel Sambuc MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1312f4a2713aSLionel Sambuc
1313f4a2713aSLionel Sambuc // If this is a two-way branch, and the FBB branches to this block, reverse
1314f4a2713aSLionel Sambuc // the condition so the single-basic-block loop is faster. Instead of:
1315f4a2713aSLionel Sambuc // Loop: xxx; jcc Out; jmp Loop
1316f4a2713aSLionel Sambuc // we want:
1317f4a2713aSLionel Sambuc // Loop: xxx; jncc Loop; jmp Out
1318f4a2713aSLionel Sambuc if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1319f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> NewCond(CurCond);
1320f4a2713aSLionel Sambuc if (!TII->ReverseBranchCondition(NewCond)) {
1321f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(*MBB);
1322f4a2713aSLionel Sambuc TII->RemoveBranch(*MBB);
1323f4a2713aSLionel Sambuc TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1324f4a2713aSLionel Sambuc MadeChange = true;
1325f4a2713aSLionel Sambuc ++NumBranchOpts;
1326f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1327f4a2713aSLionel Sambuc }
1328f4a2713aSLionel Sambuc }
1329f4a2713aSLionel Sambuc
1330f4a2713aSLionel Sambuc // If this branch is the only thing in its block, see if we can forward
1331f4a2713aSLionel Sambuc // other blocks across it.
1332*0a6a1f1dSLionel Sambuc if (CurTBB && CurCond.empty() && !CurFBB &&
1333f4a2713aSLionel Sambuc IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1334f4a2713aSLionel Sambuc !MBB->hasAddressTaken()) {
1335f4a2713aSLionel Sambuc DebugLoc dl = getBranchDebugLoc(*MBB);
1336f4a2713aSLionel Sambuc // This block may contain just an unconditional branch. Because there can
1337f4a2713aSLionel Sambuc // be 'non-branch terminators' in the block, try removing the branch and
1338f4a2713aSLionel Sambuc // then seeing if the block is empty.
1339f4a2713aSLionel Sambuc TII->RemoveBranch(*MBB);
1340f4a2713aSLionel Sambuc // If the only things remaining in the block are debug info, remove these
1341f4a2713aSLionel Sambuc // as well, so this will behave the same as an empty block in non-debug
1342f4a2713aSLionel Sambuc // mode.
1343f4a2713aSLionel Sambuc if (!MBB->empty()) {
1344f4a2713aSLionel Sambuc bool NonDebugInfoFound = false;
1345f4a2713aSLionel Sambuc for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1346f4a2713aSLionel Sambuc I != E; ++I) {
1347f4a2713aSLionel Sambuc if (!I->isDebugValue()) {
1348f4a2713aSLionel Sambuc NonDebugInfoFound = true;
1349f4a2713aSLionel Sambuc break;
1350f4a2713aSLionel Sambuc }
1351f4a2713aSLionel Sambuc }
1352f4a2713aSLionel Sambuc if (!NonDebugInfoFound)
1353f4a2713aSLionel Sambuc // Make the block empty, losing the debug info (we could probably
1354f4a2713aSLionel Sambuc // improve this in some cases.)
1355f4a2713aSLionel Sambuc MBB->erase(MBB->begin(), MBB->end());
1356f4a2713aSLionel Sambuc }
1357f4a2713aSLionel Sambuc // If this block is just an unconditional branch to CurTBB, we can
1358f4a2713aSLionel Sambuc // usually completely eliminate the block. The only case we cannot
1359f4a2713aSLionel Sambuc // completely eliminate the block is when the block before this one
1360f4a2713aSLionel Sambuc // falls through into MBB and we can't understand the prior block's branch
1361f4a2713aSLionel Sambuc // condition.
1362f4a2713aSLionel Sambuc if (MBB->empty()) {
1363f4a2713aSLionel Sambuc bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1364f4a2713aSLionel Sambuc if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1365f4a2713aSLionel Sambuc !PrevBB.isSuccessor(MBB)) {
1366f4a2713aSLionel Sambuc // If the prior block falls through into us, turn it into an
1367f4a2713aSLionel Sambuc // explicit branch to us to make updates simpler.
1368f4a2713aSLionel Sambuc if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1369f4a2713aSLionel Sambuc PriorTBB != MBB && PriorFBB != MBB) {
1370*0a6a1f1dSLionel Sambuc if (!PriorTBB) {
1371*0a6a1f1dSLionel Sambuc assert(PriorCond.empty() && !PriorFBB &&
1372f4a2713aSLionel Sambuc "Bad branch analysis");
1373f4a2713aSLionel Sambuc PriorTBB = MBB;
1374f4a2713aSLionel Sambuc } else {
1375*0a6a1f1dSLionel Sambuc assert(!PriorFBB && "Machine CFG out of date!");
1376f4a2713aSLionel Sambuc PriorFBB = MBB;
1377f4a2713aSLionel Sambuc }
1378f4a2713aSLionel Sambuc DebugLoc pdl = getBranchDebugLoc(PrevBB);
1379f4a2713aSLionel Sambuc TII->RemoveBranch(PrevBB);
1380f4a2713aSLionel Sambuc TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1381f4a2713aSLionel Sambuc }
1382f4a2713aSLionel Sambuc
1383f4a2713aSLionel Sambuc // Iterate through all the predecessors, revectoring each in-turn.
1384f4a2713aSLionel Sambuc size_t PI = 0;
1385f4a2713aSLionel Sambuc bool DidChange = false;
1386f4a2713aSLionel Sambuc bool HasBranchToSelf = false;
1387f4a2713aSLionel Sambuc while(PI != MBB->pred_size()) {
1388f4a2713aSLionel Sambuc MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1389f4a2713aSLionel Sambuc if (PMBB == MBB) {
1390f4a2713aSLionel Sambuc // If this block has an uncond branch to itself, leave it.
1391f4a2713aSLionel Sambuc ++PI;
1392f4a2713aSLionel Sambuc HasBranchToSelf = true;
1393f4a2713aSLionel Sambuc } else {
1394f4a2713aSLionel Sambuc DidChange = true;
1395f4a2713aSLionel Sambuc PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1396f4a2713aSLionel Sambuc // If this change resulted in PMBB ending in a conditional
1397f4a2713aSLionel Sambuc // branch where both conditions go to the same destination,
1398f4a2713aSLionel Sambuc // change this to an unconditional branch (and fix the CFG).
1399*0a6a1f1dSLionel Sambuc MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1400f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> NewCurCond;
1401f4a2713aSLionel Sambuc bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1402f4a2713aSLionel Sambuc NewCurFBB, NewCurCond, true);
1403f4a2713aSLionel Sambuc if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1404f4a2713aSLionel Sambuc DebugLoc pdl = getBranchDebugLoc(*PMBB);
1405f4a2713aSLionel Sambuc TII->RemoveBranch(*PMBB);
1406f4a2713aSLionel Sambuc NewCurCond.clear();
1407*0a6a1f1dSLionel Sambuc TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1408f4a2713aSLionel Sambuc MadeChange = true;
1409f4a2713aSLionel Sambuc ++NumBranchOpts;
1410*0a6a1f1dSLionel Sambuc PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1411f4a2713aSLionel Sambuc }
1412f4a2713aSLionel Sambuc }
1413f4a2713aSLionel Sambuc }
1414f4a2713aSLionel Sambuc
1415f4a2713aSLionel Sambuc // Change any jumptables to go to the new MBB.
1416f4a2713aSLionel Sambuc if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1417f4a2713aSLionel Sambuc MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1418f4a2713aSLionel Sambuc if (DidChange) {
1419f4a2713aSLionel Sambuc ++NumBranchOpts;
1420f4a2713aSLionel Sambuc MadeChange = true;
1421f4a2713aSLionel Sambuc if (!HasBranchToSelf) return MadeChange;
1422f4a2713aSLionel Sambuc }
1423f4a2713aSLionel Sambuc }
1424f4a2713aSLionel Sambuc }
1425f4a2713aSLionel Sambuc
1426f4a2713aSLionel Sambuc // Add the branch back if the block is more than just an uncond branch.
1427*0a6a1f1dSLionel Sambuc TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1428f4a2713aSLionel Sambuc }
1429f4a2713aSLionel Sambuc }
1430f4a2713aSLionel Sambuc
1431f4a2713aSLionel Sambuc // If the prior block doesn't fall through into this block, and if this
1432f4a2713aSLionel Sambuc // block doesn't fall through into some other block, see if we can find a
1433f4a2713aSLionel Sambuc // place to move this block where a fall-through will happen.
1434f4a2713aSLionel Sambuc if (!PrevBB.canFallThrough()) {
1435f4a2713aSLionel Sambuc
1436f4a2713aSLionel Sambuc // Now we know that there was no fall-through into this block, check to
1437f4a2713aSLionel Sambuc // see if it has a fall-through into its successor.
1438f4a2713aSLionel Sambuc bool CurFallsThru = MBB->canFallThrough();
1439f4a2713aSLionel Sambuc
1440f4a2713aSLionel Sambuc if (!MBB->isLandingPad()) {
1441f4a2713aSLionel Sambuc // Check all the predecessors of this block. If one of them has no fall
1442f4a2713aSLionel Sambuc // throughs, move this block right after it.
1443f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1444f4a2713aSLionel Sambuc E = MBB->pred_end(); PI != E; ++PI) {
1445f4a2713aSLionel Sambuc // Analyze the branch at the end of the pred.
1446f4a2713aSLionel Sambuc MachineBasicBlock *PredBB = *PI;
1447f4a2713aSLionel Sambuc MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1448*0a6a1f1dSLionel Sambuc MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1449f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> PredCond;
1450f4a2713aSLionel Sambuc if (PredBB != MBB && !PredBB->canFallThrough() &&
1451f4a2713aSLionel Sambuc !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1452f4a2713aSLionel Sambuc && (!CurFallsThru || !CurTBB || !CurFBB)
1453f4a2713aSLionel Sambuc && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1454f4a2713aSLionel Sambuc // If the current block doesn't fall through, just move it.
1455f4a2713aSLionel Sambuc // If the current block can fall through and does not end with a
1456f4a2713aSLionel Sambuc // conditional branch, we need to append an unconditional jump to
1457f4a2713aSLionel Sambuc // the (current) next block. To avoid a possible compile-time
1458f4a2713aSLionel Sambuc // infinite loop, move blocks only backward in this case.
1459f4a2713aSLionel Sambuc // Also, if there are already 2 branches here, we cannot add a third;
1460f4a2713aSLionel Sambuc // this means we have the case
1461f4a2713aSLionel Sambuc // Bcc next
1462f4a2713aSLionel Sambuc // B elsewhere
1463f4a2713aSLionel Sambuc // next:
1464f4a2713aSLionel Sambuc if (CurFallsThru) {
1465*0a6a1f1dSLionel Sambuc MachineBasicBlock *NextBB =
1466*0a6a1f1dSLionel Sambuc std::next(MachineFunction::iterator(MBB));
1467f4a2713aSLionel Sambuc CurCond.clear();
1468*0a6a1f1dSLionel Sambuc TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1469f4a2713aSLionel Sambuc }
1470f4a2713aSLionel Sambuc MBB->moveAfter(PredBB);
1471f4a2713aSLionel Sambuc MadeChange = true;
1472f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1473f4a2713aSLionel Sambuc }
1474f4a2713aSLionel Sambuc }
1475f4a2713aSLionel Sambuc }
1476f4a2713aSLionel Sambuc
1477f4a2713aSLionel Sambuc if (!CurFallsThru) {
1478f4a2713aSLionel Sambuc // Check all successors to see if we can move this block before it.
1479f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1480f4a2713aSLionel Sambuc E = MBB->succ_end(); SI != E; ++SI) {
1481f4a2713aSLionel Sambuc // Analyze the branch at the end of the block before the succ.
1482f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB = *SI;
1483f4a2713aSLionel Sambuc MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1484f4a2713aSLionel Sambuc
1485f4a2713aSLionel Sambuc // If this block doesn't already fall-through to that successor, and if
1486f4a2713aSLionel Sambuc // the succ doesn't already have a block that can fall through into it,
1487f4a2713aSLionel Sambuc // and if the successor isn't an EH destination, we can arrange for the
1488f4a2713aSLionel Sambuc // fallthrough to happen.
1489f4a2713aSLionel Sambuc if (SuccBB != MBB && &*SuccPrev != MBB &&
1490f4a2713aSLionel Sambuc !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1491f4a2713aSLionel Sambuc !SuccBB->isLandingPad()) {
1492f4a2713aSLionel Sambuc MBB->moveBefore(SuccBB);
1493f4a2713aSLionel Sambuc MadeChange = true;
1494f4a2713aSLionel Sambuc goto ReoptimizeBlock;
1495f4a2713aSLionel Sambuc }
1496f4a2713aSLionel Sambuc }
1497f4a2713aSLionel Sambuc
1498f4a2713aSLionel Sambuc // Okay, there is no really great place to put this block. If, however,
1499f4a2713aSLionel Sambuc // the block before this one would be a fall-through if this block were
1500f4a2713aSLionel Sambuc // removed, move this block to the end of the function.
1501*0a6a1f1dSLionel Sambuc MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1502f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> PrevCond;
1503f4a2713aSLionel Sambuc if (FallThrough != MF.end() &&
1504f4a2713aSLionel Sambuc !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1505f4a2713aSLionel Sambuc PrevBB.isSuccessor(FallThrough)) {
1506f4a2713aSLionel Sambuc MBB->moveAfter(--MF.end());
1507f4a2713aSLionel Sambuc MadeChange = true;
1508f4a2713aSLionel Sambuc return MadeChange;
1509f4a2713aSLionel Sambuc }
1510f4a2713aSLionel Sambuc }
1511f4a2713aSLionel Sambuc }
1512f4a2713aSLionel Sambuc
1513f4a2713aSLionel Sambuc return MadeChange;
1514f4a2713aSLionel Sambuc }
1515f4a2713aSLionel Sambuc
1516f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1517f4a2713aSLionel Sambuc // Hoist Common Code
1518f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1519f4a2713aSLionel Sambuc
1520f4a2713aSLionel Sambuc /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1521f4a2713aSLionel Sambuc /// blocks to their common predecessor.
HoistCommonCode(MachineFunction & MF)1522f4a2713aSLionel Sambuc bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1523f4a2713aSLionel Sambuc bool MadeChange = false;
1524f4a2713aSLionel Sambuc for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1525f4a2713aSLionel Sambuc MachineBasicBlock *MBB = I++;
1526f4a2713aSLionel Sambuc MadeChange |= HoistCommonCodeInSuccs(MBB);
1527f4a2713aSLionel Sambuc }
1528f4a2713aSLionel Sambuc
1529f4a2713aSLionel Sambuc return MadeChange;
1530f4a2713aSLionel Sambuc }
1531f4a2713aSLionel Sambuc
1532f4a2713aSLionel Sambuc /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1533f4a2713aSLionel Sambuc /// its 'true' successor.
findFalseBlock(MachineBasicBlock * BB,MachineBasicBlock * TrueBB)1534f4a2713aSLionel Sambuc static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1535f4a2713aSLionel Sambuc MachineBasicBlock *TrueBB) {
1536f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1537f4a2713aSLionel Sambuc E = BB->succ_end(); SI != E; ++SI) {
1538f4a2713aSLionel Sambuc MachineBasicBlock *SuccBB = *SI;
1539f4a2713aSLionel Sambuc if (SuccBB != TrueBB)
1540f4a2713aSLionel Sambuc return SuccBB;
1541f4a2713aSLionel Sambuc }
1542*0a6a1f1dSLionel Sambuc return nullptr;
1543f4a2713aSLionel Sambuc }
1544f4a2713aSLionel Sambuc
1545f4a2713aSLionel Sambuc /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1546f4a2713aSLionel Sambuc /// in successors to. The location is usually just before the terminator,
1547f4a2713aSLionel Sambuc /// however if the terminator is a conditional branch and its previous
1548f4a2713aSLionel Sambuc /// instruction is the flag setting instruction, the previous instruction is
1549f4a2713aSLionel Sambuc /// the preferred location. This function also gathers uses and defs of the
1550f4a2713aSLionel Sambuc /// instructions from the insertion point to the end of the block. The data is
1551f4a2713aSLionel Sambuc /// used by HoistCommonCodeInSuccs to ensure safety.
1552f4a2713aSLionel Sambuc static
findHoistingInsertPosAndDeps(MachineBasicBlock * MBB,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI,SmallSet<unsigned,4> & Uses,SmallSet<unsigned,4> & Defs)1553f4a2713aSLionel Sambuc MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1554f4a2713aSLionel Sambuc const TargetInstrInfo *TII,
1555f4a2713aSLionel Sambuc const TargetRegisterInfo *TRI,
1556f4a2713aSLionel Sambuc SmallSet<unsigned,4> &Uses,
1557f4a2713aSLionel Sambuc SmallSet<unsigned,4> &Defs) {
1558f4a2713aSLionel Sambuc MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1559f4a2713aSLionel Sambuc if (!TII->isUnpredicatedTerminator(Loc))
1560f4a2713aSLionel Sambuc return MBB->end();
1561f4a2713aSLionel Sambuc
1562f4a2713aSLionel Sambuc for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
1563f4a2713aSLionel Sambuc const MachineOperand &MO = Loc->getOperand(i);
1564f4a2713aSLionel Sambuc if (!MO.isReg())
1565f4a2713aSLionel Sambuc continue;
1566f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1567f4a2713aSLionel Sambuc if (!Reg)
1568f4a2713aSLionel Sambuc continue;
1569f4a2713aSLionel Sambuc if (MO.isUse()) {
1570f4a2713aSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1571f4a2713aSLionel Sambuc Uses.insert(*AI);
1572*0a6a1f1dSLionel Sambuc } else {
1573*0a6a1f1dSLionel Sambuc if (!MO.isDead())
1574f4a2713aSLionel Sambuc // Don't try to hoist code in the rare case the terminator defines a
1575f4a2713aSLionel Sambuc // register that is later used.
1576f4a2713aSLionel Sambuc return MBB->end();
1577*0a6a1f1dSLionel Sambuc
1578*0a6a1f1dSLionel Sambuc // If the terminator defines a register, make sure we don't hoist
1579*0a6a1f1dSLionel Sambuc // the instruction whose def might be clobbered by the terminator.
1580*0a6a1f1dSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1581*0a6a1f1dSLionel Sambuc Defs.insert(*AI);
1582*0a6a1f1dSLionel Sambuc }
1583f4a2713aSLionel Sambuc }
1584f4a2713aSLionel Sambuc
1585f4a2713aSLionel Sambuc if (Uses.empty())
1586f4a2713aSLionel Sambuc return Loc;
1587f4a2713aSLionel Sambuc if (Loc == MBB->begin())
1588f4a2713aSLionel Sambuc return MBB->end();
1589f4a2713aSLionel Sambuc
1590f4a2713aSLionel Sambuc // The terminator is probably a conditional branch, try not to separate the
1591f4a2713aSLionel Sambuc // branch from condition setting instruction.
1592f4a2713aSLionel Sambuc MachineBasicBlock::iterator PI = Loc;
1593f4a2713aSLionel Sambuc --PI;
1594*0a6a1f1dSLionel Sambuc while (PI != MBB->begin() && PI->isDebugValue())
1595f4a2713aSLionel Sambuc --PI;
1596f4a2713aSLionel Sambuc
1597f4a2713aSLionel Sambuc bool IsDef = false;
1598f4a2713aSLionel Sambuc for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
1599f4a2713aSLionel Sambuc const MachineOperand &MO = PI->getOperand(i);
1600f4a2713aSLionel Sambuc // If PI has a regmask operand, it is probably a call. Separate away.
1601f4a2713aSLionel Sambuc if (MO.isRegMask())
1602f4a2713aSLionel Sambuc return Loc;
1603f4a2713aSLionel Sambuc if (!MO.isReg() || MO.isUse())
1604f4a2713aSLionel Sambuc continue;
1605f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1606f4a2713aSLionel Sambuc if (!Reg)
1607f4a2713aSLionel Sambuc continue;
1608f4a2713aSLionel Sambuc if (Uses.count(Reg))
1609f4a2713aSLionel Sambuc IsDef = true;
1610f4a2713aSLionel Sambuc }
1611f4a2713aSLionel Sambuc if (!IsDef)
1612f4a2713aSLionel Sambuc // The condition setting instruction is not just before the conditional
1613f4a2713aSLionel Sambuc // branch.
1614f4a2713aSLionel Sambuc return Loc;
1615f4a2713aSLionel Sambuc
1616f4a2713aSLionel Sambuc // Be conservative, don't insert instruction above something that may have
1617f4a2713aSLionel Sambuc // side-effects. And since it's potentially bad to separate flag setting
1618f4a2713aSLionel Sambuc // instruction from the conditional branch, just abort the optimization
1619f4a2713aSLionel Sambuc // completely.
1620f4a2713aSLionel Sambuc // Also avoid moving code above predicated instruction since it's hard to
1621f4a2713aSLionel Sambuc // reason about register liveness with predicated instruction.
1622f4a2713aSLionel Sambuc bool DontMoveAcrossStore = true;
1623*0a6a1f1dSLionel Sambuc if (!PI->isSafeToMove(TII, nullptr, DontMoveAcrossStore) ||
1624f4a2713aSLionel Sambuc TII->isPredicated(PI))
1625f4a2713aSLionel Sambuc return MBB->end();
1626f4a2713aSLionel Sambuc
1627f4a2713aSLionel Sambuc
1628f4a2713aSLionel Sambuc // Find out what registers are live. Note this routine is ignoring other live
1629f4a2713aSLionel Sambuc // registers which are only used by instructions in successor blocks.
1630f4a2713aSLionel Sambuc for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
1631f4a2713aSLionel Sambuc const MachineOperand &MO = PI->getOperand(i);
1632f4a2713aSLionel Sambuc if (!MO.isReg())
1633f4a2713aSLionel Sambuc continue;
1634f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1635f4a2713aSLionel Sambuc if (!Reg)
1636f4a2713aSLionel Sambuc continue;
1637f4a2713aSLionel Sambuc if (MO.isUse()) {
1638f4a2713aSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1639f4a2713aSLionel Sambuc Uses.insert(*AI);
1640f4a2713aSLionel Sambuc } else {
1641f4a2713aSLionel Sambuc if (Uses.erase(Reg)) {
1642f4a2713aSLionel Sambuc for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1643f4a2713aSLionel Sambuc Uses.erase(*SubRegs); // Use sub-registers to be conservative
1644f4a2713aSLionel Sambuc }
1645f4a2713aSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1646f4a2713aSLionel Sambuc Defs.insert(*AI);
1647f4a2713aSLionel Sambuc }
1648f4a2713aSLionel Sambuc }
1649f4a2713aSLionel Sambuc
1650f4a2713aSLionel Sambuc return PI;
1651f4a2713aSLionel Sambuc }
1652f4a2713aSLionel Sambuc
1653f4a2713aSLionel Sambuc /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1654f4a2713aSLionel Sambuc /// sequence at the start of the function, move the instructions before MBB
1655f4a2713aSLionel Sambuc /// terminator if it's legal.
HoistCommonCodeInSuccs(MachineBasicBlock * MBB)1656f4a2713aSLionel Sambuc bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1657*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1658f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> Cond;
1659f4a2713aSLionel Sambuc if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1660f4a2713aSLionel Sambuc return false;
1661f4a2713aSLionel Sambuc
1662f4a2713aSLionel Sambuc if (!FBB) FBB = findFalseBlock(MBB, TBB);
1663f4a2713aSLionel Sambuc if (!FBB)
1664f4a2713aSLionel Sambuc // Malformed bcc? True and false blocks are the same?
1665f4a2713aSLionel Sambuc return false;
1666f4a2713aSLionel Sambuc
1667f4a2713aSLionel Sambuc // Restrict the optimization to cases where MBB is the only predecessor,
1668f4a2713aSLionel Sambuc // it is an obvious win.
1669f4a2713aSLionel Sambuc if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1670f4a2713aSLionel Sambuc return false;
1671f4a2713aSLionel Sambuc
1672f4a2713aSLionel Sambuc // Find a suitable position to hoist the common instructions to. Also figure
1673f4a2713aSLionel Sambuc // out which registers are used or defined by instructions from the insertion
1674f4a2713aSLionel Sambuc // point to the end of the block.
1675f4a2713aSLionel Sambuc SmallSet<unsigned, 4> Uses, Defs;
1676f4a2713aSLionel Sambuc MachineBasicBlock::iterator Loc =
1677f4a2713aSLionel Sambuc findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1678f4a2713aSLionel Sambuc if (Loc == MBB->end())
1679f4a2713aSLionel Sambuc return false;
1680f4a2713aSLionel Sambuc
1681f4a2713aSLionel Sambuc bool HasDups = false;
1682f4a2713aSLionel Sambuc SmallVector<unsigned, 4> LocalDefs;
1683f4a2713aSLionel Sambuc SmallSet<unsigned, 4> LocalDefsSet;
1684f4a2713aSLionel Sambuc MachineBasicBlock::iterator TIB = TBB->begin();
1685f4a2713aSLionel Sambuc MachineBasicBlock::iterator FIB = FBB->begin();
1686f4a2713aSLionel Sambuc MachineBasicBlock::iterator TIE = TBB->end();
1687f4a2713aSLionel Sambuc MachineBasicBlock::iterator FIE = FBB->end();
1688f4a2713aSLionel Sambuc while (TIB != TIE && FIB != FIE) {
1689f4a2713aSLionel Sambuc // Skip dbg_value instructions. These do not count.
1690f4a2713aSLionel Sambuc if (TIB->isDebugValue()) {
1691f4a2713aSLionel Sambuc while (TIB != TIE && TIB->isDebugValue())
1692f4a2713aSLionel Sambuc ++TIB;
1693f4a2713aSLionel Sambuc if (TIB == TIE)
1694f4a2713aSLionel Sambuc break;
1695f4a2713aSLionel Sambuc }
1696f4a2713aSLionel Sambuc if (FIB->isDebugValue()) {
1697f4a2713aSLionel Sambuc while (FIB != FIE && FIB->isDebugValue())
1698f4a2713aSLionel Sambuc ++FIB;
1699f4a2713aSLionel Sambuc if (FIB == FIE)
1700f4a2713aSLionel Sambuc break;
1701f4a2713aSLionel Sambuc }
1702f4a2713aSLionel Sambuc if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1703f4a2713aSLionel Sambuc break;
1704f4a2713aSLionel Sambuc
1705f4a2713aSLionel Sambuc if (TII->isPredicated(TIB))
1706f4a2713aSLionel Sambuc // Hard to reason about register liveness with predicated instruction.
1707f4a2713aSLionel Sambuc break;
1708f4a2713aSLionel Sambuc
1709f4a2713aSLionel Sambuc bool IsSafe = true;
1710f4a2713aSLionel Sambuc for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1711f4a2713aSLionel Sambuc MachineOperand &MO = TIB->getOperand(i);
1712f4a2713aSLionel Sambuc // Don't attempt to hoist instructions with register masks.
1713f4a2713aSLionel Sambuc if (MO.isRegMask()) {
1714f4a2713aSLionel Sambuc IsSafe = false;
1715f4a2713aSLionel Sambuc break;
1716f4a2713aSLionel Sambuc }
1717f4a2713aSLionel Sambuc if (!MO.isReg())
1718f4a2713aSLionel Sambuc continue;
1719f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1720f4a2713aSLionel Sambuc if (!Reg)
1721f4a2713aSLionel Sambuc continue;
1722f4a2713aSLionel Sambuc if (MO.isDef()) {
1723f4a2713aSLionel Sambuc if (Uses.count(Reg)) {
1724f4a2713aSLionel Sambuc // Avoid clobbering a register that's used by the instruction at
1725f4a2713aSLionel Sambuc // the point of insertion.
1726f4a2713aSLionel Sambuc IsSafe = false;
1727f4a2713aSLionel Sambuc break;
1728f4a2713aSLionel Sambuc }
1729f4a2713aSLionel Sambuc
1730f4a2713aSLionel Sambuc if (Defs.count(Reg) && !MO.isDead()) {
1731f4a2713aSLionel Sambuc // Don't hoist the instruction if the def would be clobber by the
1732f4a2713aSLionel Sambuc // instruction at the point insertion. FIXME: This is overly
1733f4a2713aSLionel Sambuc // conservative. It should be possible to hoist the instructions
1734f4a2713aSLionel Sambuc // in BB2 in the following example:
1735f4a2713aSLionel Sambuc // BB1:
1736f4a2713aSLionel Sambuc // r1, eflag = op1 r2, r3
1737f4a2713aSLionel Sambuc // brcc eflag
1738f4a2713aSLionel Sambuc //
1739f4a2713aSLionel Sambuc // BB2:
1740f4a2713aSLionel Sambuc // r1 = op2, ...
1741f4a2713aSLionel Sambuc // = op3, r1<kill>
1742f4a2713aSLionel Sambuc IsSafe = false;
1743f4a2713aSLionel Sambuc break;
1744f4a2713aSLionel Sambuc }
1745f4a2713aSLionel Sambuc } else if (!LocalDefsSet.count(Reg)) {
1746f4a2713aSLionel Sambuc if (Defs.count(Reg)) {
1747f4a2713aSLionel Sambuc // Use is defined by the instruction at the point of insertion.
1748f4a2713aSLionel Sambuc IsSafe = false;
1749f4a2713aSLionel Sambuc break;
1750f4a2713aSLionel Sambuc }
1751f4a2713aSLionel Sambuc
1752f4a2713aSLionel Sambuc if (MO.isKill() && Uses.count(Reg))
1753f4a2713aSLionel Sambuc // Kills a register that's read by the instruction at the point of
1754f4a2713aSLionel Sambuc // insertion. Remove the kill marker.
1755f4a2713aSLionel Sambuc MO.setIsKill(false);
1756f4a2713aSLionel Sambuc }
1757f4a2713aSLionel Sambuc }
1758f4a2713aSLionel Sambuc if (!IsSafe)
1759f4a2713aSLionel Sambuc break;
1760f4a2713aSLionel Sambuc
1761f4a2713aSLionel Sambuc bool DontMoveAcrossStore = true;
1762*0a6a1f1dSLionel Sambuc if (!TIB->isSafeToMove(TII, nullptr, DontMoveAcrossStore))
1763f4a2713aSLionel Sambuc break;
1764f4a2713aSLionel Sambuc
1765f4a2713aSLionel Sambuc // Remove kills from LocalDefsSet, these registers had short live ranges.
1766f4a2713aSLionel Sambuc for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1767f4a2713aSLionel Sambuc MachineOperand &MO = TIB->getOperand(i);
1768f4a2713aSLionel Sambuc if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1769f4a2713aSLionel Sambuc continue;
1770f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1771f4a2713aSLionel Sambuc if (!Reg || !LocalDefsSet.count(Reg))
1772f4a2713aSLionel Sambuc continue;
1773f4a2713aSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1774f4a2713aSLionel Sambuc LocalDefsSet.erase(*AI);
1775f4a2713aSLionel Sambuc }
1776f4a2713aSLionel Sambuc
1777f4a2713aSLionel Sambuc // Track local defs so we can update liveins.
1778f4a2713aSLionel Sambuc for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1779f4a2713aSLionel Sambuc MachineOperand &MO = TIB->getOperand(i);
1780f4a2713aSLionel Sambuc if (!MO.isReg() || !MO.isDef() || MO.isDead())
1781f4a2713aSLionel Sambuc continue;
1782f4a2713aSLionel Sambuc unsigned Reg = MO.getReg();
1783f4a2713aSLionel Sambuc if (!Reg)
1784f4a2713aSLionel Sambuc continue;
1785f4a2713aSLionel Sambuc LocalDefs.push_back(Reg);
1786f4a2713aSLionel Sambuc for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1787f4a2713aSLionel Sambuc LocalDefsSet.insert(*AI);
1788f4a2713aSLionel Sambuc }
1789f4a2713aSLionel Sambuc
1790f4a2713aSLionel Sambuc HasDups = true;
1791f4a2713aSLionel Sambuc ++TIB;
1792f4a2713aSLionel Sambuc ++FIB;
1793f4a2713aSLionel Sambuc }
1794f4a2713aSLionel Sambuc
1795f4a2713aSLionel Sambuc if (!HasDups)
1796f4a2713aSLionel Sambuc return false;
1797f4a2713aSLionel Sambuc
1798f4a2713aSLionel Sambuc MBB->splice(Loc, TBB, TBB->begin(), TIB);
1799f4a2713aSLionel Sambuc FBB->erase(FBB->begin(), FIB);
1800f4a2713aSLionel Sambuc
1801f4a2713aSLionel Sambuc // Update livein's.
1802f4a2713aSLionel Sambuc for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1803f4a2713aSLionel Sambuc unsigned Def = LocalDefs[i];
1804f4a2713aSLionel Sambuc if (LocalDefsSet.count(Def)) {
1805f4a2713aSLionel Sambuc TBB->addLiveIn(Def);
1806f4a2713aSLionel Sambuc FBB->addLiveIn(Def);
1807f4a2713aSLionel Sambuc }
1808f4a2713aSLionel Sambuc }
1809f4a2713aSLionel Sambuc
1810f4a2713aSLionel Sambuc ++NumHoist;
1811f4a2713aSLionel Sambuc return true;
1812f4a2713aSLionel Sambuc }
1813