blob: 9895ab7a0348799bea4357408b064d7e2dd15e8d [file] [log] [blame]
Chris Lattner21ab22e2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner21ab22e2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner21ab22e2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf10a56a2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Chris Lattner21ab22e2004-07-31 10:01:27 +000020#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000024#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000025#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner12143052006-10-21 00:47:49 +000028#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000029#include "llvm/Support/Debug.h"
Evan Cheng80b09fe2008-04-10 02:32:10 +000030#include "llvm/ADT/SmallSet.h"
Chris Lattner12143052006-10-21 00:47:49 +000031#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000033#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000034using namespace llvm;
35
Chris Lattnercd3245a2006-12-19 22:41:21 +000036STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
37STATISTIC(NumBranchOpts, "Number of branches optimized");
38STATISTIC(NumTailMerge , "Number of block tails merged");
Dale Johannesen81da02b2007-05-22 17:14:46 +000039static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
40 cl::init(cl::BOU_UNSET), cl::Hidden);
Chris Lattner21ab22e2004-07-31 10:01:27 +000041namespace {
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000042 // Throttle for huge numbers of predecessors (compile speed problems)
Dan Gohman4a3f6c82008-05-06 01:53:16 +000043 static cl::opt<unsigned>
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000044 TailMergeThreshold("tail-merge-threshold",
45 cl::desc("Max number of predecessors to consider tail merging"),
46 cl::init(100), cl::Hidden);
47
Evan Chengfb8075d2008-02-28 00:43:03 +000048 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000049 static char ID;
Dan Gohman61e729e2007-08-02 21:21:54 +000050 explicit BranchFolder(bool defaultEnableTailMerge) :
Dale Johannesen81da02b2007-05-22 17:14:46 +000051 MachineFunctionPass((intptr_t)&ID) {
52 switch (FlagEnableTailMerge) {
53 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
54 case cl::BOU_TRUE: EnableTailMerge = true; break;
55 case cl::BOU_FALSE: EnableTailMerge = false; break;
56 }
57 }
Devang Patel794fd752007-05-01 21:15:47 +000058
Chris Lattner21ab22e2004-07-31 10:01:27 +000059 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000060 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
61 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000062 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000063 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000064 private:
Chris Lattner12143052006-10-21 00:47:49 +000065 // Tail Merging.
Dale Johannesen81da02b2007-05-22 17:14:46 +000066 bool EnableTailMerge;
Chris Lattner12143052006-10-21 00:47:49 +000067 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000068 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
69 MachineBasicBlock* PredBB);
Chris Lattner12143052006-10-21 00:47:49 +000070 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
71 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000072 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
73 MachineBasicBlock::iterator BBI1);
Dale Johannesen6b8583c2008-05-09 23:28:24 +000074 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
75 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
76 MachineBasicBlock* PredBB);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000077
Dale Johannesen6ae83fa2008-05-09 21:24:35 +000078 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
Dale Johannesen6ae83fa2008-05-09 21:24:35 +000079 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
Dale Johannesen6b8583c2008-05-09 23:28:24 +000080 std::vector<MergePotentialsElt> MergePotentials;
81 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
82 std::vector<SameTailElt> SameTails;
Dale Johannesen6ae83fa2008-05-09 21:24:35 +000083
Dan Gohman6f0d0242008-02-10 18:45:23 +000084 const TargetRegisterInfo *RegInfo;
Dale Johannesen69cb9b72007-03-20 21:35:06 +000085 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000086 // Branch optzn.
87 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000088 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000089 void RemoveDeadBlock(MachineBasicBlock *MBB);
Evan Cheng80b09fe2008-04-10 02:32:10 +000090 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000091
92 bool CanFallThrough(MachineBasicBlock *CurBB);
93 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
94 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
95 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000096 };
Devang Patel19974732007-05-03 01:11:54 +000097 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000098}
99
Dale Johannesen81da02b2007-05-22 17:14:46 +0000100FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
101 return new BranchFolder(DefaultEnableTailMerge); }
Chris Lattner21ab22e2004-07-31 10:01:27 +0000102
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000103/// RemoveDeadBlock - Remove the specified dead machine basic block from the
104/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +0000105void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +0000106 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000107 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +0000108
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000109 MachineFunction *MF = MBB->getParent();
110 // drop all successors.
111 while (!MBB->succ_empty())
112 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +0000113
Jim Laskey1ee29252007-01-26 14:34:52 +0000114 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000115 // records in the basic block. If so, unregister them from MachineModuleInfo.
116 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +0000117 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
118 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +0000119 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +0000120 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000121 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +0000122 }
123 }
124 }
125
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000126 // Remove the block.
127 MF->getBasicBlockList().erase(MBB);
128}
129
Evan Cheng80b09fe2008-04-10 02:32:10 +0000130/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
131/// followed by terminators, and if the implicitly defined registers are not
132/// used by the terminators, remove those implicit_def's. e.g.
133/// BB1:
134/// r0 = implicit_def
135/// r1 = implicit_def
136/// br
137/// This block can be optimized away later if the implicit instructions are
138/// removed.
139bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
140 SmallSet<unsigned, 4> ImpDefRegs;
141 MachineBasicBlock::iterator I = MBB->begin();
142 while (I != MBB->end()) {
143 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
144 break;
145 unsigned Reg = I->getOperand(0).getReg();
146 ImpDefRegs.insert(Reg);
147 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
148 unsigned SubReg = *SubRegs; ++SubRegs)
149 ImpDefRegs.insert(SubReg);
150 ++I;
151 }
152 if (ImpDefRegs.empty())
153 return false;
154
155 MachineBasicBlock::iterator FirstTerm = I;
156 while (I != MBB->end()) {
157 if (!TII->isUnpredicatedTerminator(I))
158 return false;
159 // See if it uses any of the implicitly defined registers.
160 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
161 MachineOperand &MO = I->getOperand(i);
162 if (!MO.isReg() || !MO.isUse())
163 continue;
164 unsigned Reg = MO.getReg();
165 if (ImpDefRegs.count(Reg))
166 return false;
167 }
168 ++I;
169 }
170
171 I = MBB->begin();
172 while (I != FirstTerm) {
173 MachineInstr *ImpDefMI = &*I;
174 ++I;
175 MBB->erase(ImpDefMI);
176 }
177
178 return true;
179}
180
Chris Lattner21ab22e2004-07-31 10:01:27 +0000181bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000182 TII = MF.getTarget().getInstrInfo();
183 if (!TII) return false;
184
Evan Cheng80b09fe2008-04-10 02:32:10 +0000185 RegInfo = MF.getTarget().getRegisterInfo();
186
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000187 // Fix CFG. The later algorithms expect it to be right.
188 bool EverMadeChange = false;
189 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
190 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
191 std::vector<MachineOperand> Cond;
192 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
Evan Cheng2bdb7d02007-06-18 22:43:58 +0000193 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng80b09fe2008-04-10 02:32:10 +0000194 EverMadeChange |= OptimizeImpDefsBlock(MBB);
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000195 }
196
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000197 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
198
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000199 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000200
Chris Lattner12143052006-10-21 00:47:49 +0000201 bool MadeChangeThisIteration = true;
202 while (MadeChangeThisIteration) {
203 MadeChangeThisIteration = false;
204 MadeChangeThisIteration |= TailMergeBlocks(MF);
205 MadeChangeThisIteration |= OptimizeBranches(MF);
206 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000207 }
208
Chris Lattner6acfe122006-10-28 18:34:47 +0000209 // See if any jump tables have become mergable or dead as the code generator
210 // did its thing.
211 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
212 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
213 if (!JTs.empty()) {
214 // Figure out how these jump tables should be merged.
215 std::vector<unsigned> JTMapping;
216 JTMapping.reserve(JTs.size());
217
218 // We always keep the 0th jump table.
219 JTMapping.push_back(0);
220
221 // Scan the jump tables, seeing if there are any duplicates. Note that this
222 // is N^2, which should be fixed someday.
223 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
224 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
225
226 // If a jump table was merge with another one, walk the function rewriting
227 // references to jump tables to reference the new JT ID's. Keep track of
228 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000229 BitVector JTIsLive(JTs.size());
Chris Lattner6acfe122006-10-28 18:34:47 +0000230 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
231 BB != E; ++BB) {
232 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
233 I != E; ++I)
234 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
235 MachineOperand &Op = I->getOperand(op);
236 if (!Op.isJumpTableIndex()) continue;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000237 unsigned NewIdx = JTMapping[Op.getIndex()];
238 Op.setIndex(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000239
240 // Remember that this JT is live.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000241 JTIsLive.set(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000242 }
243 }
244
245 // Finally, remove dead jump tables. This happens either because the
246 // indirect jump was unreachable (and thus deleted) or because the jump
247 // table was merged with some other one.
248 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000249 if (!JTIsLive.test(i)) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000250 JTI->RemoveJumpTable(i);
251 EverMadeChange = true;
252 }
253 }
254
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000255 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000256 return EverMadeChange;
257}
258
Chris Lattner12143052006-10-21 00:47:49 +0000259//===----------------------------------------------------------------------===//
260// Tail Merging of Blocks
261//===----------------------------------------------------------------------===//
262
263/// HashMachineInstr - Compute a hash value for MI and its operands.
264static unsigned HashMachineInstr(const MachineInstr *MI) {
265 unsigned Hash = MI->getOpcode();
266 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
267 const MachineOperand &Op = MI->getOperand(i);
268
269 // Merge in bits from the operand if easy.
270 unsigned OperandHash = 0;
271 switch (Op.getType()) {
272 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
273 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
274 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000275 OperandHash = Op.getMBB()->getNumber();
Chris Lattner12143052006-10-21 00:47:49 +0000276 break;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000277 case MachineOperand::MO_FrameIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000278 case MachineOperand::MO_ConstantPoolIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000279 case MachineOperand::MO_JumpTableIndex:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000280 OperandHash = Op.getIndex();
Chris Lattner12143052006-10-21 00:47:49 +0000281 break;
282 case MachineOperand::MO_GlobalAddress:
283 case MachineOperand::MO_ExternalSymbol:
284 // Global address / external symbol are too hard, don't bother, but do
285 // pull in the offset.
286 OperandHash = Op.getOffset();
287 break;
288 default: break;
289 }
290
291 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
292 }
293 return Hash;
294}
295
Dale Johannesen7aea8322007-05-23 21:07:20 +0000296/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
297/// with no successors, we hash two instructions, because cross-jumping
298/// only saves code when at least two instructions are removed (since a
299/// branch must be inserted). For blocks with a successor, one of the
300/// two blocks to be tail-merged will end with a branch already, so
301/// it gains to cross-jump even for one instruction.
302
303static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
304 unsigned minCommonTailLength) {
Chris Lattner12143052006-10-21 00:47:49 +0000305 MachineBasicBlock::const_iterator I = MBB->end();
306 if (I == MBB->begin())
307 return 0; // Empty MBB.
308
309 --I;
310 unsigned Hash = HashMachineInstr(I);
311
Dale Johannesen7aea8322007-05-23 21:07:20 +0000312 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner12143052006-10-21 00:47:49 +0000313 return Hash; // Single instr MBB.
314
315 --I;
316 // Hash in the second-to-last instruction.
317 Hash ^= HashMachineInstr(I) << 2;
318 return Hash;
319}
320
321/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
322/// of instructions they actually have in common together at their end. Return
323/// iterators for the first shared instruction in each block.
324static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
325 MachineBasicBlock *MBB2,
326 MachineBasicBlock::iterator &I1,
327 MachineBasicBlock::iterator &I2) {
328 I1 = MBB1->end();
329 I2 = MBB2->end();
330
331 unsigned TailLen = 0;
332 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
333 --I1; --I2;
Bill Wendling80629c82007-10-19 21:09:55 +0000334 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingda6efc52007-10-25 19:49:32 +0000335 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling0713a222007-10-25 18:23:45 +0000336 // people incorrectly expect inline asm directives to remain in the same
337 // relative order. This is untenable because normal compiler
338 // optimizations (like this one) may reorder and/or merge these
339 // directives.
Bill Wendling80629c82007-10-19 21:09:55 +0000340 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Chris Lattner12143052006-10-21 00:47:49 +0000341 ++I1; ++I2;
342 break;
343 }
344 ++TailLen;
345 }
346 return TailLen;
347}
348
349/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000350/// after it, replacing it with an unconditional branch to NewDest. This
351/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000352void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
353 MachineBasicBlock *NewDest) {
354 MachineBasicBlock *OldBB = OldInst->getParent();
355
356 // Remove all the old successors of OldBB from the CFG.
357 while (!OldBB->succ_empty())
358 OldBB->removeSuccessor(OldBB->succ_begin());
359
360 // Remove all the dead instructions from the end of OldBB.
361 OldBB->erase(OldInst, OldBB->end());
362
Chris Lattner386e2902006-10-21 05:08:28 +0000363 // If OldBB isn't immediately before OldBB, insert a branch to it.
364 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
365 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000366 OldBB->addSuccessor(NewDest);
367 ++NumTailMerge;
368}
369
Chris Lattner1d08d832006-11-01 01:16:12 +0000370/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
371/// MBB so that the part before the iterator falls into the part starting at the
372/// iterator. This returns the new MBB.
373MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
374 MachineBasicBlock::iterator BBI1) {
375 // Create the fall-through block.
376 MachineFunction::iterator MBBI = &CurMBB;
377 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
378 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
379
380 // Move all the successors of this block to the specified block.
381 while (!CurMBB.succ_empty()) {
382 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
383 NewMBB->addSuccessor(S);
384 CurMBB.removeSuccessor(S);
385 }
386
387 // Add an edge from CurMBB to NewMBB for the fall-through.
388 CurMBB.addSuccessor(NewMBB);
389
390 // Splice the code over.
391 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000392
393 // For targets that use the register scavenger, we must maintain LiveIns.
394 if (RS) {
395 RS->enterBasicBlock(&CurMBB);
396 if (!CurMBB.empty())
397 RS->forward(prior(CurMBB.end()));
398 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
399 RS->getRegsUsed(RegsLiveAtExit, false);
400 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
401 if (RegsLiveAtExit[i])
402 NewMBB->addLiveIn(i);
403 }
404
Chris Lattner1d08d832006-11-01 01:16:12 +0000405 return NewMBB;
406}
407
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000408/// EstimateRuntime - Make a rough estimate for how long it will take to run
409/// the specified code.
410static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner69244302008-01-07 01:56:04 +0000411 MachineBasicBlock::iterator E) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000412 unsigned Time = 0;
413 for (; I != E; ++I) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000414 const TargetInstrDesc &TID = I->getDesc();
415 if (TID.isCall())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000416 Time += 10;
Chris Lattner749c6f62008-01-07 07:27:27 +0000417 else if (TID.isSimpleLoad() || TID.mayStore())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000418 Time += 2;
419 else
420 ++Time;
421 }
422 return Time;
423}
424
425/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
426/// MBB2I and then insert an unconditional branch in the other block. Determine
427/// which is the best to split
428static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
429 MachineBasicBlock::iterator MBB1I,
430 MachineBasicBlock *MBB2,
431 MachineBasicBlock::iterator MBB2I,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000432 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000433 // If one block is the entry block, split the other one; we can't generate
434 // a branch to the entry block, as its label is not emitted.
435 MachineBasicBlock *Entry = MBB1->getParent()->begin();
436 if (MBB1 == Entry)
437 return false;
438 if (MBB2 == Entry)
439 return true;
440
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000441 // If one block falls through into the common successor, choose that
442 // one to split; it is one instruction less to do that.
443 if (PredBB) {
444 if (MBB1 == PredBB)
445 return true;
446 else if (MBB2 == PredBB)
447 return false;
448 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000449 // TODO: if we had some notion of which block was hotter, we could split
450 // the hot block, so it is the fall-through. Since we don't have profile info
451 // make a decision based on which will hurt most to split.
Chris Lattner69244302008-01-07 01:56:04 +0000452 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I);
453 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I);
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000454
455 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
456 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
457 // have a lower overall impact on the program execution.
458 return MBB1Time < MBB2Time;
459}
460
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000461// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
462// branches temporarily for tail merging). In the case where CurMBB ends
463// with a conditional branch to the next block, optimize by reversing the
464// test and conditionally branching to SuccMBB instead.
465
466static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
467 const TargetInstrInfo *TII) {
468 MachineFunction *MF = CurMBB->getParent();
469 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
470 MachineBasicBlock *TBB = 0, *FBB = 0;
471 std::vector<MachineOperand> Cond;
472 if (I != MF->end() &&
473 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
474 MachineBasicBlock *NextBB = I;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000475 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000476 if (!TII->ReverseBranchCondition(Cond)) {
477 TII->RemoveBranch(*CurMBB);
478 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
479 return;
480 }
481 }
482 }
483 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
484}
485
Dale Johannesen44008c52007-05-30 00:32:01 +0000486static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
487 const std::pair<unsigned,MachineBasicBlock*> &q) {
Dale Johannesen95ef4062007-05-29 23:47:50 +0000488 if (p.first < q.first)
489 return true;
490 else if (p.first > q.first)
491 return false;
492 else if (p.second->getNumber() < q.second->getNumber())
493 return true;
494 else if (p.second->getNumber() > q.second->getNumber())
495 return false;
David Greene67fcdf72007-07-10 22:00:30 +0000496 else {
Duncan Sands97b4ac82007-07-11 08:47:55 +0000497 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
498 // an object with itself.
499#ifndef _GLIBCXX_DEBUG
Dale Johannesen95ef4062007-05-29 23:47:50 +0000500 assert(0 && "Predecessor appears twice");
David Greene67fcdf72007-07-10 22:00:30 +0000501#endif
Duncan Sands97b4ac82007-07-11 08:47:55 +0000502 return(false);
David Greene67fcdf72007-07-10 22:00:30 +0000503 }
Dale Johannesen95ef4062007-05-29 23:47:50 +0000504}
505
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000506/// ComputeSameTails - Look through all the blocks in MergePotentials that have
507/// hash CurHash (guaranteed to match the last element). Build the vector
508/// SameTails of all those that have the (same) largest number of instructions
509/// in common of any pair of these blocks. SameTails entries contain an
510/// iterator into MergePotentials (from which the MachineBasicBlock can be
511/// found) and a MachineBasicBlock::iterator into that MBB indicating the
512/// instruction where the matching code sequence begins.
513/// Order of elements in SameTails is the reverse of the order in which
514/// those blocks appear in MergePotentials (where they are not necessarily
515/// consecutive).
516unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
517 unsigned minCommonTailLength) {
518 unsigned maxCommonTailLength = 0U;
519 SameTails.clear();
520 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
521 MPIterator HighestMPIter = prior(MergePotentials.end());
522 for (MPIterator CurMPIter = prior(MergePotentials.end()),
523 B = MergePotentials.begin();
524 CurMPIter!=B && CurMPIter->first==CurHash;
525 --CurMPIter) {
526 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
527 unsigned CommonTailLen = ComputeCommonTailLength(
528 CurMPIter->second,
529 I->second,
530 TrialBBI1, TrialBBI2);
531 if (CommonTailLen >= minCommonTailLength) {
532 if (CommonTailLen > maxCommonTailLength) {
533 SameTails.clear();
534 maxCommonTailLength = CommonTailLen;
535 HighestMPIter = CurMPIter;
536 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
537 }
538 if (HighestMPIter == CurMPIter &&
539 CommonTailLen == maxCommonTailLength)
540 SameTails.push_back(std::make_pair(I, TrialBBI2));
541 }
542 if (I==B)
543 break;
544 }
545 }
546 return maxCommonTailLength;
547}
548
549/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
550/// MergePotentials, restoring branches at ends of blocks as appropriate.
551void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
552 MachineBasicBlock* SuccBB,
553 MachineBasicBlock* PredBB) {
554 for (MPIterator CurMPIter = prior(MergePotentials.end()),
555 B = MergePotentials.begin();
556 CurMPIter->first==CurHash;
557 --CurMPIter) {
558 // Put the unconditional branch back, if we need one.
559 MachineBasicBlock *CurMBB = CurMPIter->second;
560 if (SuccBB && CurMBB != PredBB)
561 FixTail(CurMBB, SuccBB, TII);
562 MergePotentials.erase(CurMPIter);
563 if (CurMPIter==B)
564 break;
565 }
566}
567
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000568// See if any of the blocks in MergePotentials (which all have a common single
569// successor, or all have no successor) can be tail-merged. If there is a
570// successor, any blocks in MergePotentials that are not tail-merged and
571// are not immediately before Succ must have an unconditional branch to
572// Succ added (but the predecessor/successor lists need no adjustment).
573// The lone predecessor of Succ that falls through into Succ,
574// if any, is given in PredBB.
575
576bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
577 MachineBasicBlock* PredBB) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000578 // We cannot jump to the entry block, which affects various choices below.
579 MachineBasicBlock *Entry = MergePotentials.begin()->second->
580 getParent()->begin();
581
Evan Cheng31886db2008-02-19 02:09:37 +0000582 // It doesn't make sense to save a single instruction since tail merging
583 // will add a jump.
584 // FIXME: Ask the target to provide the threshold?
585 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Chris Lattner12143052006-10-21 00:47:49 +0000586 MadeChange = false;
587
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000588 DOUT << "\nTryMergeBlocks " << MergePotentials.size();
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000589
Chris Lattner12143052006-10-21 00:47:49 +0000590 // Sort by hash value so that blocks with identical end sequences sort
591 // together.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000592 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Chris Lattner12143052006-10-21 00:47:49 +0000593
594 // Walk through equivalence sets looking for actual exact matches.
595 while (MergePotentials.size() > 1) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000596 unsigned CurHash = prior(MergePotentials.end())->first;
Chris Lattner12143052006-10-21 00:47:49 +0000597
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000598 // Build SameTails, identifying the set of blocks with this hash code
599 // and with the maximum number of instructions in common.
600 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
601 minCommonTailLength);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000602
Dale Johannesena5a21172007-06-01 23:02:45 +0000603 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000604 // instructions in common, remove all blocks with this hash code and retry.
605 if (SameTails.empty()) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000606 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000607 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000608 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000609
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000610 // If one of the blocks is the entire common tail (and not the entry
611 // block, which we can't jump to), treat all blocks with this same
612 // tail at once.
613 unsigned int i;
614 for (i=0; i<SameTails.size(); i++) {
615 MachineBasicBlock *MBB = SameTails[i].first->second;
616 if (MBB->begin() == SameTails[i].second && MBB != Entry)
617 break;
618 }
619 if (i!=SameTails.size()) {
620 MachineBasicBlock *MBB = SameTails[i].first->second;
621 // MBB is common tail. Adjust all other BB's to jump to this one.
622 // Traversal must be forwards so erases work.
623 DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
624 for (unsigned int j=0; j<SameTails.size(); ++j) {
625 if (i==j)
626 continue;
627 DOUT << SameTails[j].first->second->getNumber() << ",";
628 // Hack the end off BB j, making it jump to BB i instead.
629 ReplaceTailWithBranchTo(SameTails[j].second, MBB);
630 // This modifies BB j, so remove it from the worklist.
631 MergePotentials.erase(SameTails[j].first);
632 }
633 DOUT << "\n";
634 // We leave i in the worklist in case there are other blocks that
635 // match it with a smaller number of instructions.
636 MadeChange = true;
637 continue;
638 }
Dale Johannesena5a21172007-06-01 23:02:45 +0000639
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000640 // Otherwise, merge the 2 blocks in SameTails that are latest in
641 // MergePotentials; these are at indices 0 and 1 in SameTails.
642 MachineBasicBlock::iterator BBI1 = (SameTails[0]).second;
643 MachineBasicBlock::iterator BBI2 = (SameTails[1]).second;
644 MachineBasicBlock *MBB1 = (SameTails[0]).first->second;
645 MachineBasicBlock *MBB2 = (SameTails[1]).first->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000646
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000647 DOUT << "\nMerging " << MBB1->getNumber() << "," <<
648 MBB2->getNumber() << ", size " << maxCommonTailLength;
649
650 // Neither block is the entire common tail; split the tail of one block
651 // to make it redundant with the other tail. We cannot jump to the
Dale Johannesen54f4a672007-05-10 23:59:23 +0000652 // entry block, so if one block is the entry block, split the other one.
Evan Cheng31886db2008-02-19 02:09:37 +0000653
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000654 // The second half of the split block will remain in SameTails, and will
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000655 // consist entirely of common code. Thus in the case where there are
656 // multiple blocks that would all need to be split, the next iteration of
657 // the outer loop will handle all the rest of them.
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000658
659 // Decide whether we want to split MBB1 or MBB2.
660 if (ShouldSplitFirstBlock(MBB1, BBI1, MBB2, BBI2, PredBB)) {
661 MBB1 = SplitMBBAt(*MBB1, BBI1);
662 BBI1 = MBB1->begin();
663 SameTails[0].first->second = MBB1;
664 } else {
665 MBB2 = SplitMBBAt(*MBB2, BBI2);
666 BBI2 = MBB2->begin();
667 SameTails[1].first->second = MBB2;
Chris Lattner1d08d832006-11-01 01:16:12 +0000668 }
669
Dale Johannesen54f4a672007-05-10 23:59:23 +0000670 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000671 // Hack the end off MBB1, making it jump to MBB2 instead.
Chris Lattner12143052006-10-21 00:47:49 +0000672 ReplaceTailWithBranchTo(BBI1, MBB2);
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000673 // This modifies MBB1, so remove it from the worklist.
674 MergePotentials.erase(SameTails[0].first);
Chris Lattner1d08d832006-11-01 01:16:12 +0000675 } else {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000676 assert(MBB1->begin() == BBI1 && MBB1 != Entry &&
Dale Johannesen54f4a672007-05-10 23:59:23 +0000677 "Didn't split block correctly?");
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000678 // Hack the end off MBB2, making it jump to MBB1 instead.
679 ReplaceTailWithBranchTo(BBI2, MBB1);
Chris Lattner1d08d832006-11-01 01:16:12 +0000680 // This modifies MBB2, so remove it from the worklist.
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000681 MergePotentials.erase(SameTails[1].first);
Chris Lattner12143052006-10-21 00:47:49 +0000682 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000683 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000684 }
Chris Lattner12143052006-10-21 00:47:49 +0000685 return MadeChange;
686}
687
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000688bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000689
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000690 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000691
692 MadeChange = false;
693
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000694 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000695 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000696 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
697 if (I->succ_empty())
Dale Johannesen7aea8322007-05-23 21:07:20 +0000698 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000699 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000700 // See if we can do any tail merging on those.
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000701 if (MergePotentials.size() < TailMergeThreshold &&
702 MergePotentials.size() >= 2)
Dale Johannesen53af4c02007-06-08 00:34:27 +0000703 MadeChange |= TryMergeBlocks(NULL, NULL);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000704
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000705 // Look at blocks (IBB) with multiple predecessors (PBB).
706 // We change each predecessor to a canonical form, by
707 // (1) temporarily removing any unconditional branch from the predecessor
708 // to IBB, and
709 // (2) alter conditional branches so they branch to the other block
710 // not IBB; this may require adding back an unconditional branch to IBB
711 // later, where there wasn't one coming in. E.g.
712 // Bcc IBB
713 // fallthrough to QBB
714 // here becomes
715 // Bncc QBB
716 // with a conceptual B to IBB after that, which never actually exists.
717 // With those changes, we see whether the predecessors' tails match,
718 // and merge them if so. We change things out of canonical form and
719 // back to the way they were later in the process. (OptimizeBranches
720 // would undo some of this, but we can't use it, because we'd get into
721 // a compile-time infinite loop repeatedly doing and undoing the same
722 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000723
724 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000725 if (!I->succ_empty() && I->pred_size() >= 2 &&
726 I->pred_size() < TailMergeThreshold) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000727 MachineBasicBlock *IBB = I;
728 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000729 MergePotentials.clear();
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000730 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
731 E2 = I->pred_end();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000732 P != E2; ++P) {
733 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000734 // Skip blocks that loop to themselves, can't tail merge these.
735 if (PBB==IBB)
736 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000737 MachineBasicBlock *TBB = 0, *FBB = 0;
738 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000739 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
740 // Failing case: IBB is the target of a cbr, and
741 // we cannot reverse the branch.
742 std::vector<MachineOperand> NewCond(Cond);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000743 if (!Cond.empty() && TBB==IBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000744 if (TII->ReverseBranchCondition(NewCond))
745 continue;
746 // This is the QBB case described above
747 if (!FBB)
748 FBB = next(MachineFunction::iterator(PBB));
749 }
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000750 // Failing case: the only way IBB can be reached from PBB is via
751 // exception handling. Happens for landing pads. Would be nice
752 // to have a bit in the edge so we didn't have to do all this.
753 if (IBB->isLandingPad()) {
754 MachineFunction::iterator IP = PBB; IP++;
755 MachineBasicBlock* PredNextBB = NULL;
756 if (IP!=MF.end())
757 PredNextBB = IP;
758 if (TBB==NULL) {
759 if (IBB!=PredNextBB) // fallthrough
760 continue;
761 } else if (FBB) {
762 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
763 continue;
Dan Gohman30359592008-01-29 13:02:09 +0000764 } else if (Cond.empty()) {
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000765 if (TBB!=IBB) // ubr
766 continue;
767 } else {
768 if (TBB!=IBB && IBB!=PredNextBB) // cbr
769 continue;
770 }
771 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000772 // Remove the unconditional branch at the end, if any.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000773 if (TBB && (Cond.empty() || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000774 TII->RemoveBranch(*PBB);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000775 if (!Cond.empty())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000776 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000777 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000778 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000779 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000780 }
781 }
782 if (MergePotentials.size() >= 2)
783 MadeChange |= TryMergeBlocks(I, PredBB);
784 // Reinsert an unconditional branch if needed.
785 // The 1 below can be either an original single predecessor, or a result
786 // of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000787 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000788 if (MergePotentials.size()==1 &&
789 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000790 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000791 }
792 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000793 return MadeChange;
794}
Chris Lattner12143052006-10-21 00:47:49 +0000795
796//===----------------------------------------------------------------------===//
797// Branch Optimization
798//===----------------------------------------------------------------------===//
799
800bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
801 MadeChange = false;
802
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000803 // Make sure blocks are numbered in order
804 MF.RenumberBlocks();
805
Chris Lattner12143052006-10-21 00:47:49 +0000806 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
807 MachineBasicBlock *MBB = I++;
808 OptimizeBlock(MBB);
809
810 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000811 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000812 RemoveDeadBlock(MBB);
813 MadeChange = true;
814 ++NumDeadBlocks;
815 }
816 }
817 return MadeChange;
818}
819
820
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000821/// CanFallThrough - Return true if the specified block (with the specified
822/// branch condition) can implicitly transfer control to the block after it by
823/// falling off the end of it. This should return false if it can reach the
824/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
825///
826/// True is a conservative answer.
827///
828bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
829 bool BranchUnAnalyzable,
830 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
831 const std::vector<MachineOperand> &Cond) {
832 MachineFunction::iterator Fallthrough = CurBB;
833 ++Fallthrough;
834 // If FallthroughBlock is off the end of the function, it can't fall through.
835 if (Fallthrough == CurBB->getParent()->end())
836 return false;
837
838 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
839 if (!CurBB->isSuccessor(Fallthrough))
840 return false;
841
842 // If we couldn't analyze the branch, assume it could fall through.
843 if (BranchUnAnalyzable) return true;
844
Chris Lattner7d097842006-10-24 01:12:32 +0000845 // If there is no branch, control always falls through.
846 if (TBB == 0) return true;
847
848 // If there is some explicit branch to the fallthrough block, it can obviously
849 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000850 if (MachineFunction::iterator(TBB) == Fallthrough ||
851 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000852 return true;
853
854 // If it's an unconditional branch to some block not the fall through, it
855 // doesn't fall through.
856 if (Cond.empty()) return false;
857
858 // Otherwise, if it is conditional and has no explicit false block, it falls
859 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000860 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000861}
862
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000863/// CanFallThrough - Return true if the specified can implicitly transfer
864/// control to the block after it by falling off the end of it. This should
865/// return false if it can reach the block after it, but it uses an explicit
866/// branch to do so (e.g. a table jump).
867///
868/// True is a conservative answer.
869///
870bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
871 MachineBasicBlock *TBB = 0, *FBB = 0;
872 std::vector<MachineOperand> Cond;
873 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
874 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
875}
876
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000877/// IsBetterFallthrough - Return true if it would be clearly better to
878/// fall-through to MBB1 than to fall through into MBB2. This has to return
879/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
880/// result in infinite loops.
881static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner69244302008-01-07 01:56:04 +0000882 MachineBasicBlock *MBB2) {
Chris Lattner154e1042006-11-18 21:30:35 +0000883 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
884 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000885 // optimize branches that branch to either a return block or an assert block
886 // into a fallthrough to the return.
887 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lamb11a4f642007-12-10 07:24:06 +0000888
889 // If there is a clear successor ordering we make sure that one block
890 // will fall through to the next
891 if (MBB1->isSuccessor(MBB2)) return true;
892 if (MBB2->isSuccessor(MBB1)) return false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000893
894 MachineInstr *MBB1I = --MBB1->end();
895 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner749c6f62008-01-07 07:27:27 +0000896 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000897}
898
Chris Lattner7821a8a2006-10-14 00:21:48 +0000899/// OptimizeBlock - Analyze and optimize control flow related to the specified
900/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000901void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
902 MachineFunction::iterator FallThrough = MBB;
903 ++FallThrough;
904
Chris Lattnereb15eee2006-10-13 20:43:10 +0000905 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesena52dd152007-05-31 21:54:00 +0000906 // explicitly. Landing pads should not do this since the landing-pad table
907 // points to this block.
908 if (MBB->empty() && !MBB->isLandingPad()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000909 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000910 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000911
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000912 if (FallThrough == MBB->getParent()->end()) {
913 // TODO: Simplify preds to not branch here if possible!
914 } else {
915 // Rewrite all predecessors of the old block to go to the fallthrough
916 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000917 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000918 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Evan Cheng0370fad2007-06-04 06:44:01 +0000919 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000920 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000921
922 // If MBB was the target of a jump table, update jump tables to go to the
923 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000924 MBB->getParent()->getJumpTableInfo()->
925 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000926 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000927 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000928 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000929 }
930
Chris Lattner7821a8a2006-10-14 00:21:48 +0000931 // Check to see if we can simplify the terminator of the block before this
932 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000933 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000934
Chris Lattner7821a8a2006-10-14 00:21:48 +0000935 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
936 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000937 bool PriorUnAnalyzable =
938 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000939 if (!PriorUnAnalyzable) {
940 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +0000941 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
942 !PriorCond.empty());
Chris Lattner386e2902006-10-21 05:08:28 +0000943
Chris Lattner7821a8a2006-10-14 00:21:48 +0000944 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000945 // destination, remove the branch, replacing it with an unconditional one or
946 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000947 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000948 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000949 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000950 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000951 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000952 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000953 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000954 return OptimizeBlock(MBB);
955 }
956
957 // If the previous branch *only* branches to *this* block (conditional or
958 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000959 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000960 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000961 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000962 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000963 return OptimizeBlock(MBB);
964 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000965
966 // If the prior block branches somewhere else on the condition and here if
967 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000968 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000969 TII->RemoveBranch(PrevBB);
970 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
971 MadeChange = true;
972 ++NumBranchOpts;
973 return OptimizeBlock(MBB);
974 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000975
976 // If the prior block branches here on true and somewhere else on false, and
977 // if the branch condition is reversible, reverse the branch to create a
978 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000979 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000980 std::vector<MachineOperand> NewPriorCond(PriorCond);
981 if (!TII->ReverseBranchCondition(NewPriorCond)) {
982 TII->RemoveBranch(PrevBB);
983 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
984 MadeChange = true;
985 ++NumBranchOpts;
986 return OptimizeBlock(MBB);
987 }
988 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000989
Chris Lattner154e1042006-11-18 21:30:35 +0000990 // If this block doesn't fall through (e.g. it ends with an uncond branch or
991 // has no successors) and if the pred falls through into this block, and if
992 // it would otherwise fall through into the block after this, move this
993 // block to the end of the function.
994 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000995 // We consider it more likely that execution will stay in the function (e.g.
996 // due to loops) than it is to exit it. This asserts in loops etc, moving
997 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000998 if (!PriorCond.empty() && PriorFBB == 0 &&
999 MachineFunction::iterator(PriorTBB) == FallThrough &&
1000 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001001 bool DoTransform = true;
1002
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001003 // We have to be careful that the succs of PredBB aren't both no-successor
1004 // blocks. If neither have successors and if PredBB is the second from
1005 // last block in the function, we'd just keep swapping the two blocks for
1006 // last. Only do the swap if one is clearly better to fall through than
1007 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001008 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner69244302008-01-07 01:56:04 +00001009 !IsBetterFallthrough(PriorTBB, MBB))
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001010 DoTransform = false;
1011
1012 // We don't want to do this transformation if we have control flow like:
1013 // br cond BB2
1014 // BB1:
1015 // ..
1016 // jmp BBX
1017 // BB2:
1018 // ..
1019 // ret
1020 //
1021 // In this case, we could actually be moving the return block *into* a
1022 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +00001023 if (DoTransform && !MBB->succ_empty() &&
1024 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001025 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001026
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001027
1028 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001029 // Reverse the branch so we will fall through on the previous true cond.
1030 std::vector<MachineOperand> NewPriorCond(PriorCond);
1031 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001032 DOUT << "\nMoving MBB: " << *MBB;
1033 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
1034
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001035 TII->RemoveBranch(PrevBB);
1036 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1037
1038 // Move this block to the end of the function.
1039 MBB->moveAfter(--MBB->getParent()->end());
1040 MadeChange = true;
1041 ++NumBranchOpts;
1042 return;
1043 }
1044 }
1045 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001046 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001047
Chris Lattner386e2902006-10-21 05:08:28 +00001048 // Analyze the branch in the current block.
1049 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1050 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001051 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
1052 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +00001053 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001054 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
Chris Lattnereb15eee2006-10-13 20:43:10 +00001055
Chris Lattner5d056952006-11-08 01:03:21 +00001056 // If this is a two-way branch, and the FBB branches to this block, reverse
1057 // the condition so the single-basic-block loop is faster. Instead of:
1058 // Loop: xxx; jcc Out; jmp Loop
1059 // we want:
1060 // Loop: xxx; jncc Loop; jmp Out
1061 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1062 std::vector<MachineOperand> NewCond(CurCond);
1063 if (!TII->ReverseBranchCondition(NewCond)) {
1064 TII->RemoveBranch(*MBB);
1065 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1066 MadeChange = true;
1067 ++NumBranchOpts;
1068 return OptimizeBlock(MBB);
1069 }
1070 }
1071
1072
Chris Lattner386e2902006-10-21 05:08:28 +00001073 // If this branch is the only thing in its block, see if we can forward
1074 // other blocks across it.
1075 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner749c6f62008-01-07 07:27:27 +00001076 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +00001077 // This block may contain just an unconditional branch. Because there can
1078 // be 'non-branch terminators' in the block, try removing the branch and
1079 // then seeing if the block is empty.
1080 TII->RemoveBranch(*MBB);
1081
1082 // If this block is just an unconditional branch to CurTBB, we can
1083 // usually completely eliminate the block. The only case we cannot
1084 // completely eliminate the block is when the block before this one
1085 // falls through into MBB and we can't understand the prior block's branch
1086 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +00001087 if (MBB->empty()) {
1088 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1089 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1090 !PrevBB.isSuccessor(MBB)) {
1091 // If the prior block falls through into us, turn it into an
1092 // explicit branch to us to make updates simpler.
1093 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1094 PriorTBB != MBB && PriorFBB != MBB) {
1095 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001096 assert(PriorCond.empty() && PriorFBB == 0 &&
1097 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001098 PriorTBB = MBB;
1099 } else {
1100 assert(PriorFBB == 0 && "Machine CFG out of date!");
1101 PriorFBB = MBB;
1102 }
1103 TII->RemoveBranch(PrevBB);
1104 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001105 }
Chris Lattner386e2902006-10-21 05:08:28 +00001106
Chris Lattnercf420cc2006-10-28 17:32:47 +00001107 // Iterate through all the predecessors, revectoring each in-turn.
David Greene8a46d342007-06-29 02:45:24 +00001108 size_t PI = 0;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001109 bool DidChange = false;
1110 bool HasBranchToSelf = false;
David Greene8a46d342007-06-29 02:45:24 +00001111 while(PI != MBB->pred_size()) {
1112 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1113 if (PMBB == MBB) {
Chris Lattnercf420cc2006-10-28 17:32:47 +00001114 // If this block has an uncond branch to itself, leave it.
1115 ++PI;
1116 HasBranchToSelf = true;
1117 } else {
1118 DidChange = true;
David Greene8a46d342007-06-29 02:45:24 +00001119 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001120 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001121 }
Chris Lattner386e2902006-10-21 05:08:28 +00001122
Chris Lattnercf420cc2006-10-28 17:32:47 +00001123 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001124 MBB->getParent()->getJumpTableInfo()->
1125 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001126 if (DidChange) {
1127 ++NumBranchOpts;
1128 MadeChange = true;
1129 if (!HasBranchToSelf) return;
1130 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001131 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001132 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001133
Chris Lattner386e2902006-10-21 05:08:28 +00001134 // Add the branch back if the block is more than just an uncond branch.
1135 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001136 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001137 }
1138
1139 // If the prior block doesn't fall through into this block, and if this
1140 // block doesn't fall through into some other block, see if we can find a
1141 // place to move this block where a fall-through will happen.
1142 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1143 PriorTBB, PriorFBB, PriorCond)) {
1144 // Now we know that there was no fall-through into this block, check to
1145 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001146 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001147 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001148
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001149 if (!MBB->isLandingPad()) {
1150 // Check all the predecessors of this block. If one of them has no fall
1151 // throughs, move this block right after it.
1152 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1153 E = MBB->pred_end(); PI != E; ++PI) {
1154 // Analyze the branch at the end of the pred.
1155 MachineBasicBlock *PredBB = *PI;
1156 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1157 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001158 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001159 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1160 // If the current block doesn't fall through, just move it.
1161 // If the current block can fall through and does not end with a
1162 // conditional branch, we need to append an unconditional jump to
1163 // the (current) next block. To avoid a possible compile-time
1164 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001165 // Also, if there are already 2 branches here, we cannot add a third;
1166 // this means we have the case
1167 // Bcc next
1168 // B elsewhere
1169 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001170 if (CurFallsThru) {
1171 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1172 CurCond.clear();
1173 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1174 }
1175 MBB->moveAfter(PredBB);
1176 MadeChange = true;
1177 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001178 }
1179 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001180 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001181
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001182 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001183 // Check all successors to see if we can move this block before it.
1184 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1185 E = MBB->succ_end(); SI != E; ++SI) {
1186 // Analyze the branch at the end of the block before the succ.
1187 MachineBasicBlock *SuccBB = *SI;
1188 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001189 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001190
1191 // If this block doesn't already fall-through to that successor, and if
1192 // the succ doesn't already have a block that can fall through into it,
1193 // and if the successor isn't an EH destination, we can arrange for the
1194 // fallthrough to happen.
1195 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1196 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001197 MBB->moveBefore(SuccBB);
1198 MadeChange = true;
1199 return OptimizeBlock(MBB);
1200 }
1201 }
1202
1203 // Okay, there is no really great place to put this block. If, however,
1204 // the block before this one would be a fall-through if this block were
1205 // removed, move this block to the end of the function.
1206 if (FallThrough != MBB->getParent()->end() &&
1207 PrevBB.isSuccessor(FallThrough)) {
1208 MBB->moveAfter(--MBB->getParent()->end());
1209 MadeChange = true;
1210 return;
1211 }
Chris Lattner7d097842006-10-24 01:12:32 +00001212 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001213 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001214}