blob: 6825bfb10339d6fac86f6a535c3e458cc168030f [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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
19#define DEBUG_TYPE "branchfolding"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/RegisterScavenging.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Evan Cheng682e4aa2008-04-10 02:32:10 +000030#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include <algorithm>
34using namespace llvm;
35
36STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
37STATISTIC(NumBranchOpts, "Number of branches optimized");
38STATISTIC(NumTailMerge , "Number of block tails merged");
39static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
40 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman089efff2008-05-13 00:00:25 +000041// Throttle for huge numbers of predecessors (compile speed problems)
42static cl::opt<unsigned>
43TailMergeThreshold("tail-merge-threshold",
44 cl::desc("Max number of predecessors to consider tail merging"),
45 cl::init(100), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
Dan Gohman089efff2008-05-13 00:00:25 +000047namespace {
Evan Cheng45c1edb2008-02-28 00:43:03 +000048 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 static char ID;
Dan Gohman3a78bbf2007-08-02 21:21:54 +000050 explicit BranchFolder(bool defaultEnableTailMerge) :
Dan Gohmanf17a25c2007-07-18 16:29: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 }
58
59 virtual bool runOnMachineFunction(MachineFunction &MF);
60 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
61 const TargetInstrInfo *TII;
62 MachineModuleInfo *MMI;
63 bool MadeChange;
64 private:
65 // Tail Merging.
66 bool EnableTailMerge;
67 bool TailMergeBlocks(MachineFunction &MF);
68 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
69 MachineBasicBlock* PredBB);
70 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
71 MachineBasicBlock *NewDest);
72 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
73 MachineBasicBlock::iterator BBI1);
Dale Johannesen865e6252008-05-09 23:28:24 +000074 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
75 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
76 MachineBasicBlock* PredBB);
Dale Johannesena3fbac92008-05-12 20:33:57 +000077 unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
78 unsigned maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
Dale Johannesen652b7ff2008-05-09 21:24:35 +000080 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000081 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
Dale Johannesen865e6252008-05-09 23:28:24 +000082 std::vector<MergePotentialsElt> MergePotentials;
Dale Johannesena3fbac92008-05-12 20:33:57 +000083
Dale Johannesen865e6252008-05-09 23:28:24 +000084 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
85 std::vector<SameTailElt> SameTails;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000086
Dan Gohman1e57df32008-02-10 18:45:23 +000087 const TargetRegisterInfo *RegInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 RegScavenger *RS;
89 // Branch optzn.
90 bool OptimizeBranches(MachineFunction &MF);
91 void OptimizeBlock(MachineBasicBlock *MBB);
92 void RemoveDeadBlock(MachineBasicBlock *MBB);
Evan Cheng682e4aa2008-04-10 02:32:10 +000093 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094
95 bool CanFallThrough(MachineBasicBlock *CurBB);
96 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
97 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
98 const std::vector<MachineOperand> &Cond);
99 };
100 char BranchFolder::ID = 0;
101}
102
103FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
104 return new BranchFolder(DefaultEnableTailMerge); }
105
106/// RemoveDeadBlock - Remove the specified dead machine basic block from the
107/// function, updating the CFG.
108void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
109 assert(MBB->pred_empty() && "MBB must be dead!");
110 DOUT << "\nRemoving MBB: " << *MBB;
111
112 MachineFunction *MF = MBB->getParent();
113 // drop all successors.
114 while (!MBB->succ_empty())
115 MBB->removeSuccessor(MBB->succ_end()-1);
116
Dan Gohmanfa607c92008-07-01 00:05:16 +0000117 // If there is DWARF info to active, check to see if there are any DBG_LABEL
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 // records in the basic block. If so, unregister them from MachineModuleInfo.
119 if (MMI && !MBB->empty()) {
120 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
121 I != E; ++I) {
Dan Gohmanfa607c92008-07-01 00:05:16 +0000122 if ((unsigned)I->getOpcode() == TargetInstrInfo::DBG_LABEL) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 // The label ID # is always operand #0, an immediate.
124 MMI->InvalidateLabel(I->getOperand(0).getImm());
125 }
126 }
127 }
128
129 // Remove the block.
130 MF->getBasicBlockList().erase(MBB);
131}
132
Evan Cheng682e4aa2008-04-10 02:32:10 +0000133/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
134/// followed by terminators, and if the implicitly defined registers are not
135/// used by the terminators, remove those implicit_def's. e.g.
136/// BB1:
137/// r0 = implicit_def
138/// r1 = implicit_def
139/// br
140/// This block can be optimized away later if the implicit instructions are
141/// removed.
142bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
143 SmallSet<unsigned, 4> ImpDefRegs;
144 MachineBasicBlock::iterator I = MBB->begin();
145 while (I != MBB->end()) {
146 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
147 break;
148 unsigned Reg = I->getOperand(0).getReg();
149 ImpDefRegs.insert(Reg);
150 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
151 unsigned SubReg = *SubRegs; ++SubRegs)
152 ImpDefRegs.insert(SubReg);
153 ++I;
154 }
155 if (ImpDefRegs.empty())
156 return false;
157
158 MachineBasicBlock::iterator FirstTerm = I;
159 while (I != MBB->end()) {
160 if (!TII->isUnpredicatedTerminator(I))
161 return false;
162 // See if it uses any of the implicitly defined registers.
163 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
164 MachineOperand &MO = I->getOperand(i);
165 if (!MO.isReg() || !MO.isUse())
166 continue;
167 unsigned Reg = MO.getReg();
168 if (ImpDefRegs.count(Reg))
169 return false;
170 }
171 ++I;
172 }
173
174 I = MBB->begin();
175 while (I != FirstTerm) {
176 MachineInstr *ImpDefMI = &*I;
177 ++I;
178 MBB->erase(ImpDefMI);
179 }
180
181 return true;
182}
183
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
185 TII = MF.getTarget().getInstrInfo();
186 if (!TII) return false;
187
Evan Cheng682e4aa2008-04-10 02:32:10 +0000188 RegInfo = MF.getTarget().getRegisterInfo();
189
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 // Fix CFG. The later algorithms expect it to be right.
191 bool EverMadeChange = false;
192 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
193 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
194 std::vector<MachineOperand> Cond;
195 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
196 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng682e4aa2008-04-10 02:32:10 +0000197 EverMadeChange |= OptimizeImpDefsBlock(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 }
199
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
201
202 MMI = getAnalysisToUpdate<MachineModuleInfo>();
203
204 bool MadeChangeThisIteration = true;
205 while (MadeChangeThisIteration) {
206 MadeChangeThisIteration = false;
207 MadeChangeThisIteration |= TailMergeBlocks(MF);
208 MadeChangeThisIteration |= OptimizeBranches(MF);
209 EverMadeChange |= MadeChangeThisIteration;
210 }
211
212 // See if any jump tables have become mergable or dead as the code generator
213 // did its thing.
214 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
215 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
216 if (!JTs.empty()) {
217 // Figure out how these jump tables should be merged.
218 std::vector<unsigned> JTMapping;
219 JTMapping.reserve(JTs.size());
220
221 // We always keep the 0th jump table.
222 JTMapping.push_back(0);
223
224 // Scan the jump tables, seeing if there are any duplicates. Note that this
225 // is N^2, which should be fixed someday.
226 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
227 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
228
229 // If a jump table was merge with another one, walk the function rewriting
230 // references to jump tables to reference the new JT ID's. Keep track of
231 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen865e6252008-05-09 23:28:24 +0000232 BitVector JTIsLive(JTs.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
234 BB != E; ++BB) {
235 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
236 I != E; ++I)
237 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
238 MachineOperand &Op = I->getOperand(op);
239 if (!Op.isJumpTableIndex()) continue;
Chris Lattner6017d482007-12-30 23:10:15 +0000240 unsigned NewIdx = JTMapping[Op.getIndex()];
241 Op.setIndex(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 // Remember that this JT is live.
Dale Johannesen865e6252008-05-09 23:28:24 +0000244 JTIsLive.set(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 }
246 }
247
248 // Finally, remove dead jump tables. This happens either because the
249 // indirect jump was unreachable (and thus deleted) or because the jump
250 // table was merged with some other one.
251 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen865e6252008-05-09 23:28:24 +0000252 if (!JTIsLive.test(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 JTI->RemoveJumpTable(i);
254 EverMadeChange = true;
255 }
256 }
257
258 delete RS;
259 return EverMadeChange;
260}
261
262//===----------------------------------------------------------------------===//
263// Tail Merging of Blocks
264//===----------------------------------------------------------------------===//
265
266/// HashMachineInstr - Compute a hash value for MI and its operands.
267static unsigned HashMachineInstr(const MachineInstr *MI) {
268 unsigned Hash = MI->getOpcode();
269 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
270 const MachineOperand &Op = MI->getOperand(i);
271
272 // Merge in bits from the operand if easy.
273 unsigned OperandHash = 0;
274 switch (Op.getType()) {
275 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
276 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
277 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner6017d482007-12-30 23:10:15 +0000278 OperandHash = Op.getMBB()->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 break;
Chris Lattner6017d482007-12-30 23:10:15 +0000280 case MachineOperand::MO_FrameIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 case MachineOperand::MO_ConstantPoolIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 case MachineOperand::MO_JumpTableIndex:
Chris Lattner6017d482007-12-30 23:10:15 +0000283 OperandHash = Op.getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 break;
285 case MachineOperand::MO_GlobalAddress:
286 case MachineOperand::MO_ExternalSymbol:
287 // Global address / external symbol are too hard, don't bother, but do
288 // pull in the offset.
289 OperandHash = Op.getOffset();
290 break;
291 default: break;
292 }
293
294 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
295 }
296 return Hash;
297}
298
299/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
300/// with no successors, we hash two instructions, because cross-jumping
301/// only saves code when at least two instructions are removed (since a
302/// branch must be inserted). For blocks with a successor, one of the
303/// two blocks to be tail-merged will end with a branch already, so
304/// it gains to cross-jump even for one instruction.
305
306static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
307 unsigned minCommonTailLength) {
308 MachineBasicBlock::const_iterator I = MBB->end();
309 if (I == MBB->begin())
310 return 0; // Empty MBB.
311
312 --I;
313 unsigned Hash = HashMachineInstr(I);
314
315 if (I == MBB->begin() || minCommonTailLength == 1)
316 return Hash; // Single instr MBB.
317
318 --I;
319 // Hash in the second-to-last instruction.
320 Hash ^= HashMachineInstr(I) << 2;
321 return Hash;
322}
323
324/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
325/// of instructions they actually have in common together at their end. Return
326/// iterators for the first shared instruction in each block.
327static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
328 MachineBasicBlock *MBB2,
329 MachineBasicBlock::iterator &I1,
330 MachineBasicBlock::iterator &I2) {
331 I1 = MBB1->end();
332 I2 = MBB2->end();
333
334 unsigned TailLen = 0;
335 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
336 --I1; --I2;
Bill Wendling46329b72007-10-19 21:09:55 +0000337 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingf728a1c2007-10-25 19:49:32 +0000338 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling83628182007-10-25 18:23:45 +0000339 // people incorrectly expect inline asm directives to remain in the same
340 // relative order. This is untenable because normal compiler
341 // optimizations (like this one) may reorder and/or merge these
342 // directives.
Bill Wendling46329b72007-10-19 21:09:55 +0000343 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 ++I1; ++I2;
345 break;
346 }
347 ++TailLen;
348 }
349 return TailLen;
350}
351
352/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
353/// after it, replacing it with an unconditional branch to NewDest. This
354/// returns true if OldInst's block is modified, false if NewDest is modified.
355void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
356 MachineBasicBlock *NewDest) {
357 MachineBasicBlock *OldBB = OldInst->getParent();
358
359 // Remove all the old successors of OldBB from the CFG.
360 while (!OldBB->succ_empty())
361 OldBB->removeSuccessor(OldBB->succ_begin());
362
363 // Remove all the dead instructions from the end of OldBB.
364 OldBB->erase(OldInst, OldBB->end());
365
366 // If OldBB isn't immediately before OldBB, insert a branch to it.
367 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
368 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
369 OldBB->addSuccessor(NewDest);
370 ++NumTailMerge;
371}
372
373/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
374/// MBB so that the part before the iterator falls into the part starting at the
375/// iterator. This returns the new MBB.
376MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
377 MachineBasicBlock::iterator BBI1) {
378 // Create the fall-through block.
379 MachineFunction::iterator MBBI = &CurMBB;
380 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
381 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
382
383 // Move all the successors of this block to the specified block.
Dan Gohmanf995c022008-06-19 17:22:29 +0000384 NewMBB->transferSuccessors(&CurMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385
386 // Add an edge from CurMBB to NewMBB for the fall-through.
387 CurMBB.addSuccessor(NewMBB);
388
389 // Splice the code over.
390 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
391
392 // For targets that use the register scavenger, we must maintain LiveIns.
393 if (RS) {
394 RS->enterBasicBlock(&CurMBB);
395 if (!CurMBB.empty())
396 RS->forward(prior(CurMBB.end()));
397 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
398 RS->getRegsUsed(RegsLiveAtExit, false);
399 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
400 if (RegsLiveAtExit[i])
401 NewMBB->addLiveIn(i);
402 }
403
404 return NewMBB;
405}
406
407/// EstimateRuntime - Make a rough estimate for how long it will take to run
408/// the specified code.
409static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner62327602008-01-07 01:56:04 +0000410 MachineBasicBlock::iterator E) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 unsigned Time = 0;
412 for (; I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000413 const TargetInstrDesc &TID = I->getDesc();
414 if (TID.isCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 Time += 10;
Chris Lattner5b930372008-01-07 07:27:27 +0000416 else if (TID.isSimpleLoad() || TID.mayStore())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 Time += 2;
418 else
419 ++Time;
420 }
421 return Time;
422}
423
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
425// branches temporarily for tail merging). In the case where CurMBB ends
426// with a conditional branch to the next block, optimize by reversing the
427// test and conditionally branching to SuccMBB instead.
428
429static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
430 const TargetInstrInfo *TII) {
431 MachineFunction *MF = CurMBB->getParent();
432 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
433 MachineBasicBlock *TBB = 0, *FBB = 0;
434 std::vector<MachineOperand> Cond;
435 if (I != MF->end() &&
436 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
437 MachineBasicBlock *NextBB = I;
Dale Johannesen865e6252008-05-09 23:28:24 +0000438 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 if (!TII->ReverseBranchCondition(Cond)) {
440 TII->RemoveBranch(*CurMBB);
441 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
442 return;
443 }
444 }
445 }
446 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
447}
448
449static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
450 const std::pair<unsigned,MachineBasicBlock*> &q) {
451 if (p.first < q.first)
452 return true;
453 else if (p.first > q.first)
454 return false;
455 else if (p.second->getNumber() < q.second->getNumber())
456 return true;
457 else if (p.second->getNumber() > q.second->getNumber())
458 return false;
459 else {
460 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
461 // an object with itself.
462#ifndef _GLIBCXX_DEBUG
463 assert(0 && "Predecessor appears twice");
464#endif
465 return(false);
466 }
467}
468
Dale Johannesen865e6252008-05-09 23:28:24 +0000469/// ComputeSameTails - Look through all the blocks in MergePotentials that have
470/// hash CurHash (guaranteed to match the last element). Build the vector
471/// SameTails of all those that have the (same) largest number of instructions
472/// in common of any pair of these blocks. SameTails entries contain an
473/// iterator into MergePotentials (from which the MachineBasicBlock can be
474/// found) and a MachineBasicBlock::iterator into that MBB indicating the
475/// instruction where the matching code sequence begins.
476/// Order of elements in SameTails is the reverse of the order in which
477/// those blocks appear in MergePotentials (where they are not necessarily
478/// consecutive).
479unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
480 unsigned minCommonTailLength) {
481 unsigned maxCommonTailLength = 0U;
482 SameTails.clear();
483 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
484 MPIterator HighestMPIter = prior(MergePotentials.end());
485 for (MPIterator CurMPIter = prior(MergePotentials.end()),
486 B = MergePotentials.begin();
487 CurMPIter!=B && CurMPIter->first==CurHash;
488 --CurMPIter) {
489 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
490 unsigned CommonTailLen = ComputeCommonTailLength(
491 CurMPIter->second,
492 I->second,
493 TrialBBI1, TrialBBI2);
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000494 // If we will have to split a block, there should be at least
495 // minCommonTailLength instructions in common; if not, at worst
496 // we will be replacing a fallthrough into the common tail with a
497 // branch, which at worst breaks even with falling through into
498 // the duplicated common tail, so 1 instruction in common is enough.
499 // We will always pick a block we do not have to split as the common
500 // tail if there is one.
501 // (Empty blocks will get forwarded and need not be considered.)
502 if (CommonTailLen >= minCommonTailLength ||
503 (CommonTailLen > 0 &&
504 (TrialBBI1==CurMPIter->second->begin() ||
505 TrialBBI2==I->second->begin()))) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000506 if (CommonTailLen > maxCommonTailLength) {
507 SameTails.clear();
508 maxCommonTailLength = CommonTailLen;
509 HighestMPIter = CurMPIter;
510 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
511 }
512 if (HighestMPIter == CurMPIter &&
513 CommonTailLen == maxCommonTailLength)
514 SameTails.push_back(std::make_pair(I, TrialBBI2));
515 }
516 if (I==B)
517 break;
518 }
519 }
520 return maxCommonTailLength;
521}
522
523/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
524/// MergePotentials, restoring branches at ends of blocks as appropriate.
525void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
526 MachineBasicBlock* SuccBB,
527 MachineBasicBlock* PredBB) {
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000528 MPIterator CurMPIter, B;
529 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen865e6252008-05-09 23:28:24 +0000530 CurMPIter->first==CurHash;
531 --CurMPIter) {
532 // Put the unconditional branch back, if we need one.
533 MachineBasicBlock *CurMBB = CurMPIter->second;
534 if (SuccBB && CurMBB != PredBB)
535 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000536 if (CurMPIter==B)
Dale Johannesen865e6252008-05-09 23:28:24 +0000537 break;
538 }
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000539 if (CurMPIter->first!=CurHash)
540 CurMPIter++;
541 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen865e6252008-05-09 23:28:24 +0000542}
543
Dale Johannesena3fbac92008-05-12 20:33:57 +0000544/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
545/// only of the common tail. Create a block that does by splitting one.
546unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
547 unsigned maxCommonTailLength) {
548 unsigned i, commonTailIndex;
549 unsigned TimeEstimate = ~0U;
550 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
551 // Use PredBB if possible; that doesn't require a new branch.
552 if (SameTails[i].first->second==PredBB) {
553 commonTailIndex = i;
554 break;
555 }
556 // Otherwise, make a (fairly bogus) choice based on estimate of
557 // how long it will take the various blocks to execute.
558 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
559 SameTails[i].second);
560 if (t<=TimeEstimate) {
561 TimeEstimate = t;
562 commonTailIndex = i;
563 }
564 }
565
566 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
567 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
568
569 DOUT << "\nSplitting " << MBB->getNumber() << ", size " <<
570 maxCommonTailLength;
571
572 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
573 SameTails[commonTailIndex].first->second = newMBB;
574 SameTails[commonTailIndex].second = newMBB->begin();
575 // If we split PredBB, newMBB is the new predecessor.
576 if (PredBB==MBB)
577 PredBB = newMBB;
578
579 return commonTailIndex;
580}
581
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582// See if any of the blocks in MergePotentials (which all have a common single
583// successor, or all have no successor) can be tail-merged. If there is a
584// successor, any blocks in MergePotentials that are not tail-merged and
585// are not immediately before Succ must have an unconditional branch to
586// Succ added (but the predecessor/successor lists need no adjustment).
587// The lone predecessor of Succ that falls through into Succ,
588// if any, is given in PredBB.
589
590bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
591 MachineBasicBlock* PredBB) {
Evan Cheng55d13352008-02-19 02:09:37 +0000592 // It doesn't make sense to save a single instruction since tail merging
593 // will add a jump.
594 // FIXME: Ask the target to provide the threshold?
595 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 MadeChange = false;
597
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000598 DOUT << "\nTryMergeBlocks " << MergePotentials.size();
Dale Johannesen865e6252008-05-09 23:28:24 +0000599
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 // Sort by hash value so that blocks with identical end sequences sort
601 // together.
Dale Johannesen865e6252008-05-09 23:28:24 +0000602 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603
604 // Walk through equivalence sets looking for actual exact matches.
605 while (MergePotentials.size() > 1) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000606 unsigned CurHash = prior(MergePotentials.end())->first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607
Dale Johannesen865e6252008-05-09 23:28:24 +0000608 // Build SameTails, identifying the set of blocks with this hash code
609 // and with the maximum number of instructions in common.
610 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
611 minCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612
613 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000614 // instructions in common, remove all blocks with this hash code and retry.
615 if (SameTails.empty()) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000616 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 continue;
618 }
619
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000620 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesena3fbac92008-05-12 20:33:57 +0000621 // block, which we can't jump to), we can treat all blocks with this same
622 // tail at once. Use PredBB if that is one of the possibilities, as that
623 // will not introduce any extra branches.
624 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
625 getParent()->begin();
626 unsigned int commonTailIndex, i;
627 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000628 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesena3fbac92008-05-12 20:33:57 +0000629 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
630 commonTailIndex = i;
631 if (MBB==PredBB)
632 break;
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000633 }
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000634 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635
Dale Johannesena3fbac92008-05-12 20:33:57 +0000636 if (commonTailIndex==SameTails.size()) {
637 // None of the blocks consist entirely of the common tail.
638 // Split a block so that one does.
639 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 }
Dale Johannesena3fbac92008-05-12 20:33:57 +0000641
642 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
643 // MBB is common tail. Adjust all other BB's to jump to this one.
644 // Traversal must be forwards so erases work.
645 DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
646 for (unsigned int i=0; i<SameTails.size(); ++i) {
647 if (commonTailIndex==i)
648 continue;
649 DOUT << SameTails[i].first->second->getNumber() << ",";
650 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
651 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
652 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
653 MergePotentials.erase(SameTails[i].first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 }
Dale Johannesena3fbac92008-05-12 20:33:57 +0000655 DOUT << "\n";
656 // We leave commonTailIndex in the worklist in case there are other blocks
657 // that match it with a smaller number of instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 MadeChange = true;
659 }
660 return MadeChange;
661}
662
663bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
664
665 if (!EnableTailMerge) return false;
666
667 MadeChange = false;
668
669 // First find blocks with no successors.
670 MergePotentials.clear();
671 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
672 if (I->succ_empty())
673 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
674 }
675 // See if we can do any tail merging on those.
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000676 if (MergePotentials.size() < TailMergeThreshold &&
677 MergePotentials.size() >= 2)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 MadeChange |= TryMergeBlocks(NULL, NULL);
679
680 // Look at blocks (IBB) with multiple predecessors (PBB).
681 // We change each predecessor to a canonical form, by
682 // (1) temporarily removing any unconditional branch from the predecessor
683 // to IBB, and
684 // (2) alter conditional branches so they branch to the other block
685 // not IBB; this may require adding back an unconditional branch to IBB
686 // later, where there wasn't one coming in. E.g.
687 // Bcc IBB
688 // fallthrough to QBB
689 // here becomes
690 // Bncc QBB
691 // with a conceptual B to IBB after that, which never actually exists.
692 // With those changes, we see whether the predecessors' tails match,
693 // and merge them if so. We change things out of canonical form and
694 // back to the way they were later in the process. (OptimizeBranches
695 // would undo some of this, but we can't use it, because we'd get into
696 // a compile-time infinite loop repeatedly doing and undoing the same
697 // transformations.)
698
699 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
700 if (!I->succ_empty() && I->pred_size() >= 2 &&
701 I->pred_size() < TailMergeThreshold) {
702 MachineBasicBlock *IBB = I;
703 MachineBasicBlock *PredBB = prior(I);
704 MergePotentials.clear();
705 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
706 E2 = I->pred_end();
707 P != E2; ++P) {
708 MachineBasicBlock* PBB = *P;
709 // Skip blocks that loop to themselves, can't tail merge these.
710 if (PBB==IBB)
711 continue;
712 MachineBasicBlock *TBB = 0, *FBB = 0;
713 std::vector<MachineOperand> Cond;
714 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
715 // Failing case: IBB is the target of a cbr, and
716 // we cannot reverse the branch.
717 std::vector<MachineOperand> NewCond(Cond);
Dale Johannesen865e6252008-05-09 23:28:24 +0000718 if (!Cond.empty() && TBB==IBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 if (TII->ReverseBranchCondition(NewCond))
720 continue;
721 // This is the QBB case described above
722 if (!FBB)
723 FBB = next(MachineFunction::iterator(PBB));
724 }
725 // Failing case: the only way IBB can be reached from PBB is via
726 // exception handling. Happens for landing pads. Would be nice
727 // to have a bit in the edge so we didn't have to do all this.
728 if (IBB->isLandingPad()) {
729 MachineFunction::iterator IP = PBB; IP++;
730 MachineBasicBlock* PredNextBB = NULL;
731 if (IP!=MF.end())
732 PredNextBB = IP;
733 if (TBB==NULL) {
734 if (IBB!=PredNextBB) // fallthrough
735 continue;
736 } else if (FBB) {
737 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
738 continue;
Dan Gohman301f4052008-01-29 13:02:09 +0000739 } else if (Cond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 if (TBB!=IBB) // ubr
741 continue;
742 } else {
743 if (TBB!=IBB && IBB!=PredNextBB) // cbr
744 continue;
745 }
746 }
747 // Remove the unconditional branch at the end, if any.
Dale Johannesen865e6252008-05-09 23:28:24 +0000748 if (TBB && (Cond.empty() || FBB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 TII->RemoveBranch(*PBB);
Dale Johannesen865e6252008-05-09 23:28:24 +0000750 if (!Cond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 // reinsert conditional branch only, for now
752 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
753 }
754 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
755 }
756 }
757 if (MergePotentials.size() >= 2)
758 MadeChange |= TryMergeBlocks(I, PredBB);
759 // Reinsert an unconditional branch if needed.
Dale Johannesena3fbac92008-05-12 20:33:57 +0000760 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 PredBB = prior(I); // this may have been changed in TryMergeBlocks
762 if (MergePotentials.size()==1 &&
Dale Johannesena3fbac92008-05-12 20:33:57 +0000763 MergePotentials.begin()->second != PredBB)
764 FixTail(MergePotentials.begin()->second, I, TII);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 }
766 }
767 return MadeChange;
768}
769
770//===----------------------------------------------------------------------===//
771// Branch Optimization
772//===----------------------------------------------------------------------===//
773
774bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
775 MadeChange = false;
776
777 // Make sure blocks are numbered in order
778 MF.RenumberBlocks();
779
780 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
781 MachineBasicBlock *MBB = I++;
782 OptimizeBlock(MBB);
783
784 // If it is dead, remove it.
785 if (MBB->pred_empty()) {
786 RemoveDeadBlock(MBB);
787 MadeChange = true;
788 ++NumDeadBlocks;
789 }
790 }
791 return MadeChange;
792}
793
794
795/// CanFallThrough - Return true if the specified block (with the specified
796/// branch condition) can implicitly transfer control to the block after it by
797/// falling off the end of it. This should return false if it can reach the
798/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
799///
800/// True is a conservative answer.
801///
802bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
803 bool BranchUnAnalyzable,
Dale Johannesena3fbac92008-05-12 20:33:57 +0000804 MachineBasicBlock *TBB,
805 MachineBasicBlock *FBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 const std::vector<MachineOperand> &Cond) {
807 MachineFunction::iterator Fallthrough = CurBB;
808 ++Fallthrough;
809 // If FallthroughBlock is off the end of the function, it can't fall through.
810 if (Fallthrough == CurBB->getParent()->end())
811 return false;
812
813 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
814 if (!CurBB->isSuccessor(Fallthrough))
815 return false;
816
817 // If we couldn't analyze the branch, assume it could fall through.
818 if (BranchUnAnalyzable) return true;
819
820 // If there is no branch, control always falls through.
821 if (TBB == 0) return true;
822
823 // If there is some explicit branch to the fallthrough block, it can obviously
824 // reach, even though the branch should get folded to fall through implicitly.
825 if (MachineFunction::iterator(TBB) == Fallthrough ||
826 MachineFunction::iterator(FBB) == Fallthrough)
827 return true;
828
829 // If it's an unconditional branch to some block not the fall through, it
830 // doesn't fall through.
831 if (Cond.empty()) return false;
832
833 // Otherwise, if it is conditional and has no explicit false block, it falls
834 // through.
835 return FBB == 0;
836}
837
838/// CanFallThrough - Return true if the specified can implicitly transfer
839/// control to the block after it by falling off the end of it. This should
840/// return false if it can reach the block after it, but it uses an explicit
841/// branch to do so (e.g. a table jump).
842///
843/// True is a conservative answer.
844///
845bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
846 MachineBasicBlock *TBB = 0, *FBB = 0;
847 std::vector<MachineOperand> Cond;
848 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
849 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
850}
851
852/// IsBetterFallthrough - Return true if it would be clearly better to
853/// fall-through to MBB1 than to fall through into MBB2. This has to return
854/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
855/// result in infinite loops.
856static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner62327602008-01-07 01:56:04 +0000857 MachineBasicBlock *MBB2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
859 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
860 // optimize branches that branch to either a return block or an assert block
861 // into a fallthrough to the return.
862 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lambff904542007-12-10 07:24:06 +0000863
864 // If there is a clear successor ordering we make sure that one block
865 // will fall through to the next
866 if (MBB1->isSuccessor(MBB2)) return true;
867 if (MBB2->isSuccessor(MBB1)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868
869 MachineInstr *MBB1I = --MBB1->end();
870 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner5b930372008-01-07 07:27:27 +0000871 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872}
873
874/// OptimizeBlock - Analyze and optimize control flow related to the specified
875/// block. This is never called on the entry block.
876void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
877 MachineFunction::iterator FallThrough = MBB;
878 ++FallThrough;
879
880 // If this block is empty, make everyone use its fall-through, not the block
881 // explicitly. Landing pads should not do this since the landing-pad table
882 // points to this block.
883 if (MBB->empty() && !MBB->isLandingPad()) {
884 // Dead block? Leave for cleanup later.
885 if (MBB->pred_empty()) return;
886
887 if (FallThrough == MBB->getParent()->end()) {
888 // TODO: Simplify preds to not branch here if possible!
889 } else {
890 // Rewrite all predecessors of the old block to go to the fallthrough
891 // instead.
892 while (!MBB->pred_empty()) {
893 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
894 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
895 }
896
897 // If MBB was the target of a jump table, update jump tables to go to the
898 // fallthrough instead.
899 MBB->getParent()->getJumpTableInfo()->
900 ReplaceMBBInJumpTables(MBB, FallThrough);
901 MadeChange = true;
902 }
903 return;
904 }
905
906 // Check to see if we can simplify the terminator of the block before this
907 // one.
908 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
909
910 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
911 std::vector<MachineOperand> PriorCond;
912 bool PriorUnAnalyzable =
913 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
914 if (!PriorUnAnalyzable) {
915 // If the CFG for the prior block has extra edges, remove them.
916 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
917 !PriorCond.empty());
918
919 // If the previous branch is conditional and both conditions go to the same
920 // destination, remove the branch, replacing it with an unconditional one or
921 // a fall-through.
922 if (PriorTBB && PriorTBB == PriorFBB) {
923 TII->RemoveBranch(PrevBB);
924 PriorCond.clear();
925 if (PriorTBB != MBB)
926 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
927 MadeChange = true;
928 ++NumBranchOpts;
929 return OptimizeBlock(MBB);
930 }
931
932 // If the previous branch *only* branches to *this* block (conditional or
933 // not) remove the branch.
934 if (PriorTBB == MBB && PriorFBB == 0) {
935 TII->RemoveBranch(PrevBB);
936 MadeChange = true;
937 ++NumBranchOpts;
938 return OptimizeBlock(MBB);
939 }
940
941 // If the prior block branches somewhere else on the condition and here if
942 // the condition is false, remove the uncond second branch.
943 if (PriorFBB == MBB) {
944 TII->RemoveBranch(PrevBB);
945 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
946 MadeChange = true;
947 ++NumBranchOpts;
948 return OptimizeBlock(MBB);
949 }
950
951 // If the prior block branches here on true and somewhere else on false, and
952 // if the branch condition is reversible, reverse the branch to create a
953 // fall-through.
954 if (PriorTBB == MBB) {
955 std::vector<MachineOperand> NewPriorCond(PriorCond);
956 if (!TII->ReverseBranchCondition(NewPriorCond)) {
957 TII->RemoveBranch(PrevBB);
958 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
959 MadeChange = true;
960 ++NumBranchOpts;
961 return OptimizeBlock(MBB);
962 }
963 }
964
965 // If this block doesn't fall through (e.g. it ends with an uncond branch or
966 // has no successors) and if the pred falls through into this block, and if
967 // it would otherwise fall through into the block after this, move this
968 // block to the end of the function.
969 //
970 // We consider it more likely that execution will stay in the function (e.g.
971 // due to loops) than it is to exit it. This asserts in loops etc, moving
972 // the assert condition out of the loop body.
973 if (!PriorCond.empty() && PriorFBB == 0 &&
974 MachineFunction::iterator(PriorTBB) == FallThrough &&
975 !CanFallThrough(MBB)) {
976 bool DoTransform = true;
977
978 // We have to be careful that the succs of PredBB aren't both no-successor
979 // blocks. If neither have successors and if PredBB is the second from
980 // last block in the function, we'd just keep swapping the two blocks for
981 // last. Only do the swap if one is clearly better to fall through than
982 // the other.
983 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner62327602008-01-07 01:56:04 +0000984 !IsBetterFallthrough(PriorTBB, MBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 DoTransform = false;
986
987 // We don't want to do this transformation if we have control flow like:
988 // br cond BB2
989 // BB1:
990 // ..
991 // jmp BBX
992 // BB2:
993 // ..
994 // ret
995 //
996 // In this case, we could actually be moving the return block *into* a
997 // loop!
998 if (DoTransform && !MBB->succ_empty() &&
999 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1000 DoTransform = false;
1001
1002
1003 if (DoTransform) {
1004 // Reverse the branch so we will fall through on the previous true cond.
1005 std::vector<MachineOperand> NewPriorCond(PriorCond);
1006 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1007 DOUT << "\nMoving MBB: " << *MBB;
1008 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
1009
1010 TII->RemoveBranch(PrevBB);
1011 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1012
1013 // Move this block to the end of the function.
1014 MBB->moveAfter(--MBB->getParent()->end());
1015 MadeChange = true;
1016 ++NumBranchOpts;
1017 return;
1018 }
1019 }
1020 }
1021 }
1022
1023 // Analyze the branch in the current block.
1024 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1025 std::vector<MachineOperand> CurCond;
1026 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
1027 if (!CurUnAnalyzable) {
1028 // If the CFG for the prior block has extra edges, remove them.
1029 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1030
1031 // If this is a two-way branch, and the FBB branches to this block, reverse
1032 // the condition so the single-basic-block loop is faster. Instead of:
1033 // Loop: xxx; jcc Out; jmp Loop
1034 // we want:
1035 // Loop: xxx; jncc Loop; jmp Out
1036 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1037 std::vector<MachineOperand> NewCond(CurCond);
1038 if (!TII->ReverseBranchCondition(NewCond)) {
1039 TII->RemoveBranch(*MBB);
1040 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1041 MadeChange = true;
1042 ++NumBranchOpts;
1043 return OptimizeBlock(MBB);
1044 }
1045 }
1046
1047
1048 // If this branch is the only thing in its block, see if we can forward
1049 // other blocks across it.
1050 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner5b930372008-01-07 07:27:27 +00001051 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 // This block may contain just an unconditional branch. Because there can
1053 // be 'non-branch terminators' in the block, try removing the branch and
1054 // then seeing if the block is empty.
1055 TII->RemoveBranch(*MBB);
1056
1057 // If this block is just an unconditional branch to CurTBB, we can
1058 // usually completely eliminate the block. The only case we cannot
1059 // completely eliminate the block is when the block before this one
1060 // falls through into MBB and we can't understand the prior block's branch
1061 // condition.
1062 if (MBB->empty()) {
1063 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1064 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1065 !PrevBB.isSuccessor(MBB)) {
1066 // If the prior block falls through into us, turn it into an
1067 // explicit branch to us to make updates simpler.
1068 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1069 PriorTBB != MBB && PriorFBB != MBB) {
1070 if (PriorTBB == 0) {
1071 assert(PriorCond.empty() && PriorFBB == 0 &&
1072 "Bad branch analysis");
1073 PriorTBB = MBB;
1074 } else {
1075 assert(PriorFBB == 0 && "Machine CFG out of date!");
1076 PriorFBB = MBB;
1077 }
1078 TII->RemoveBranch(PrevBB);
1079 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1080 }
1081
1082 // Iterate through all the predecessors, revectoring each in-turn.
1083 size_t PI = 0;
1084 bool DidChange = false;
1085 bool HasBranchToSelf = false;
1086 while(PI != MBB->pred_size()) {
1087 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1088 if (PMBB == MBB) {
1089 // If this block has an uncond branch to itself, leave it.
1090 ++PI;
1091 HasBranchToSelf = true;
1092 } else {
1093 DidChange = true;
1094 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1095 }
1096 }
1097
1098 // Change any jumptables to go to the new MBB.
1099 MBB->getParent()->getJumpTableInfo()->
1100 ReplaceMBBInJumpTables(MBB, CurTBB);
1101 if (DidChange) {
1102 ++NumBranchOpts;
1103 MadeChange = true;
1104 if (!HasBranchToSelf) return;
1105 }
1106 }
1107 }
1108
1109 // Add the branch back if the block is more than just an uncond branch.
1110 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1111 }
1112 }
1113
1114 // If the prior block doesn't fall through into this block, and if this
1115 // block doesn't fall through into some other block, see if we can find a
1116 // place to move this block where a fall-through will happen.
1117 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1118 PriorTBB, PriorFBB, PriorCond)) {
1119 // Now we know that there was no fall-through into this block, check to
1120 // see if it has a fall-through into its successor.
1121 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1122 CurCond);
1123
1124 if (!MBB->isLandingPad()) {
1125 // Check all the predecessors of this block. If one of them has no fall
1126 // throughs, move this block right after it.
1127 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1128 E = MBB->pred_end(); PI != E; ++PI) {
1129 // Analyze the branch at the end of the pred.
1130 MachineBasicBlock *PredBB = *PI;
1131 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1132 if (PredBB != MBB && !CanFallThrough(PredBB)
1133 && (!CurFallsThru || !CurTBB || !CurFBB)
1134 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1135 // If the current block doesn't fall through, just move it.
1136 // If the current block can fall through and does not end with a
1137 // conditional branch, we need to append an unconditional jump to
1138 // the (current) next block. To avoid a possible compile-time
1139 // infinite loop, move blocks only backward in this case.
1140 // Also, if there are already 2 branches here, we cannot add a third;
1141 // this means we have the case
1142 // Bcc next
1143 // B elsewhere
1144 // next:
1145 if (CurFallsThru) {
1146 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1147 CurCond.clear();
1148 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1149 }
1150 MBB->moveAfter(PredBB);
1151 MadeChange = true;
1152 return OptimizeBlock(MBB);
1153 }
1154 }
1155 }
1156
1157 if (!CurFallsThru) {
1158 // Check all successors to see if we can move this block before it.
1159 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1160 E = MBB->succ_end(); SI != E; ++SI) {
1161 // Analyze the branch at the end of the block before the succ.
1162 MachineBasicBlock *SuccBB = *SI;
1163 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1164 std::vector<MachineOperand> SuccPrevCond;
1165
1166 // If this block doesn't already fall-through to that successor, and if
1167 // the succ doesn't already have a block that can fall through into it,
1168 // and if the successor isn't an EH destination, we can arrange for the
1169 // fallthrough to happen.
1170 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1171 !SuccBB->isLandingPad()) {
1172 MBB->moveBefore(SuccBB);
1173 MadeChange = true;
1174 return OptimizeBlock(MBB);
1175 }
1176 }
1177
1178 // Okay, there is no really great place to put this block. If, however,
1179 // the block before this one would be a fall-through if this block were
1180 // removed, move this block to the end of the function.
1181 if (FallThrough != MBB->getParent()->end() &&
1182 PrevBB.isSuccessor(FallThrough)) {
1183 MBB->moveAfter(--MBB->getParent()->end());
1184 MadeChange = true;
1185 return;
1186 }
1187 }
1188 }
1189}