blob: dd51d5f6f642ecba8c3659b147e044ff3eddd775 [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"
Edwin Török675d5622009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Bill Wendlingef26d402009-08-22 20:03:00 +000031#include "llvm/Support/raw_ostream.h"
Evan Cheng682e4aa2008-04-10 02:32:10 +000032#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36using namespace llvm;
37
38STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
39STATISTIC(NumBranchOpts, "Number of branches optimized");
40STATISTIC(NumTailMerge , "Number of block tails merged");
41static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
42 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman089efff2008-05-13 00:00:25 +000043// Throttle for huge numbers of predecessors (compile speed problems)
44static cl::opt<unsigned>
45TailMergeThreshold("tail-merge-threshold",
46 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen2d9dfce2008-10-27 02:10:21 +000047 cl::init(150), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Dan Gohman089efff2008-05-13 00:00:25 +000049namespace {
Evan Cheng45c1edb2008-02-28 00:43:03 +000050 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051 static char ID;
Dan Gohman3a78bbf2007-08-02 21:21:54 +000052 explicit BranchFolder(bool defaultEnableTailMerge) :
Evan Cheng465a66e2008-09-22 20:58:04 +000053 MachineFunctionPass(&ID) {
54 switch (FlagEnableTailMerge) {
55 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
56 case cl::BOU_TRUE: EnableTailMerge = true; break;
57 case cl::BOU_FALSE: EnableTailMerge = false; break;
58 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 }
60
61 virtual bool runOnMachineFunction(MachineFunction &MF);
62 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
63 const TargetInstrInfo *TII;
64 MachineModuleInfo *MMI;
65 bool MadeChange;
66 private:
67 // Tail Merging.
68 bool EnableTailMerge;
69 bool TailMergeBlocks(MachineFunction &MF);
70 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
71 MachineBasicBlock* PredBB);
72 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
73 MachineBasicBlock *NewDest);
74 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
75 MachineBasicBlock::iterator BBI1);
Dale Johannesen865e6252008-05-09 23:28:24 +000076 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
77 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
78 MachineBasicBlock* PredBB);
Dale Johannesena3fbac92008-05-12 20:33:57 +000079 unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
80 unsigned maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
Dale Johannesen652b7ff2008-05-09 21:24:35 +000082 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000083 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
Dale Johannesen865e6252008-05-09 23:28:24 +000084 std::vector<MergePotentialsElt> MergePotentials;
Dale Johannesena3fbac92008-05-12 20:33:57 +000085
Dale Johannesen865e6252008-05-09 23:28:24 +000086 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
87 std::vector<SameTailElt> SameTails;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000088
Dan Gohman1e57df32008-02-10 18:45:23 +000089 const TargetRegisterInfo *RegInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 RegScavenger *RS;
91 // Branch optzn.
92 bool OptimizeBranches(MachineFunction &MF);
93 void OptimizeBlock(MachineBasicBlock *MBB);
94 void RemoveDeadBlock(MachineBasicBlock *MBB);
Evan Cheng682e4aa2008-04-10 02:32:10 +000095 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096
97 bool CanFallThrough(MachineBasicBlock *CurBB);
98 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
99 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
Owen Andersond131b5b2008-08-14 22:49:33 +0000100 const SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 };
102 char BranchFolder::ID = 0;
103}
104
105FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
Evan Chengfe0a2792009-09-03 23:54:22 +0000106 return new BranchFolder(DefaultEnableTailMerge);
107}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
109/// RemoveDeadBlock - Remove the specified dead machine basic block from the
110/// function, updating the CFG.
111void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
112 assert(MBB->pred_empty() && "MBB must be dead!");
Bill Wendlingef26d402009-08-22 20:03:00 +0000113 DEBUG(errs() << "\nRemoving MBB: " << *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114
115 MachineFunction *MF = MBB->getParent();
116 // drop all successors.
117 while (!MBB->succ_empty())
118 MBB->removeSuccessor(MBB->succ_end()-1);
119
Duncan Sands342271d2008-07-29 20:56:02 +0000120 // If there are any labels in the basic block, unregister them from
121 // MachineModuleInfo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 if (MMI && !MBB->empty()) {
123 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
124 I != E; ++I) {
Duncan Sands342271d2008-07-29 20:56:02 +0000125 if (I->isLabel())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 // The label ID # is always operand #0, an immediate.
127 MMI->InvalidateLabel(I->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 }
129 }
130
131 // Remove the block.
Dan Gohman221a4372008-07-07 23:14:23 +0000132 MF->erase(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133}
134
Evan Cheng682e4aa2008-04-10 02:32:10 +0000135/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
136/// followed by terminators, and if the implicitly defined registers are not
137/// used by the terminators, remove those implicit_def's. e.g.
138/// BB1:
139/// r0 = implicit_def
140/// r1 = implicit_def
141/// br
142/// This block can be optimized away later if the implicit instructions are
143/// removed.
144bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
145 SmallSet<unsigned, 4> ImpDefRegs;
146 MachineBasicBlock::iterator I = MBB->begin();
147 while (I != MBB->end()) {
148 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
149 break;
150 unsigned Reg = I->getOperand(0).getReg();
151 ImpDefRegs.insert(Reg);
152 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
153 unsigned SubReg = *SubRegs; ++SubRegs)
154 ImpDefRegs.insert(SubReg);
155 ++I;
156 }
157 if (ImpDefRegs.empty())
158 return false;
159
160 MachineBasicBlock::iterator FirstTerm = I;
161 while (I != MBB->end()) {
162 if (!TII->isUnpredicatedTerminator(I))
163 return false;
164 // See if it uses any of the implicitly defined registers.
165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
166 MachineOperand &MO = I->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000167 if (!MO.isReg() || !MO.isUse())
Evan Cheng682e4aa2008-04-10 02:32:10 +0000168 continue;
169 unsigned Reg = MO.getReg();
170 if (ImpDefRegs.count(Reg))
171 return false;
172 }
173 ++I;
174 }
175
176 I = MBB->begin();
177 while (I != FirstTerm) {
178 MachineInstr *ImpDefMI = &*I;
179 ++I;
180 MBB->erase(ImpDefMI);
181 }
182
183 return true;
184}
185
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
187 TII = MF.getTarget().getInstrInfo();
188 if (!TII) return false;
189
Evan Cheng682e4aa2008-04-10 02:32:10 +0000190 RegInfo = MF.getTarget().getRegisterInfo();
191
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 // Fix CFG. The later algorithms expect it to be right.
193 bool EverMadeChange = false;
194 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
195 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000196 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000197 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng682e4aa2008-04-10 02:32:10 +0000199 EverMadeChange |= OptimizeImpDefsBlock(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 }
201
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
203
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000204 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205
206 bool MadeChangeThisIteration = true;
207 while (MadeChangeThisIteration) {
208 MadeChangeThisIteration = false;
209 MadeChangeThisIteration |= TailMergeBlocks(MF);
210 MadeChangeThisIteration |= OptimizeBranches(MF);
211 EverMadeChange |= MadeChangeThisIteration;
212 }
213
214 // See if any jump tables have become mergable or dead as the code generator
215 // did its thing.
216 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
217 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
218 if (!JTs.empty()) {
219 // Figure out how these jump tables should be merged.
220 std::vector<unsigned> JTMapping;
221 JTMapping.reserve(JTs.size());
222
223 // We always keep the 0th jump table.
224 JTMapping.push_back(0);
225
226 // Scan the jump tables, seeing if there are any duplicates. Note that this
227 // is N^2, which should be fixed someday.
228 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
229 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
230
231 // If a jump table was merge with another one, walk the function rewriting
232 // references to jump tables to reference the new JT ID's. Keep track of
233 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen865e6252008-05-09 23:28:24 +0000234 BitVector JTIsLive(JTs.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
236 BB != E; ++BB) {
237 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
238 I != E; ++I)
239 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
240 MachineOperand &Op = I->getOperand(op);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000241 if (!Op.isJTI()) continue;
Chris Lattner6017d482007-12-30 23:10:15 +0000242 unsigned NewIdx = JTMapping[Op.getIndex()];
243 Op.setIndex(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
245 // Remember that this JT is live.
Dale Johannesen865e6252008-05-09 23:28:24 +0000246 JTIsLive.set(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 }
248 }
249
250 // Finally, remove dead jump tables. This happens either because the
251 // indirect jump was unreachable (and thus deleted) or because the jump
252 // table was merged with some other one.
253 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen865e6252008-05-09 23:28:24 +0000254 if (!JTIsLive.test(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 JTI->RemoveJumpTable(i);
256 EverMadeChange = true;
257 }
258 }
259
260 delete RS;
261 return EverMadeChange;
262}
263
264//===----------------------------------------------------------------------===//
265// Tail Merging of Blocks
266//===----------------------------------------------------------------------===//
267
268/// HashMachineInstr - Compute a hash value for MI and its operands.
269static unsigned HashMachineInstr(const MachineInstr *MI) {
270 unsigned Hash = MI->getOpcode();
271 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
272 const MachineOperand &Op = MI->getOperand(i);
273
274 // Merge in bits from the operand if easy.
275 unsigned OperandHash = 0;
276 switch (Op.getType()) {
277 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
278 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
279 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner6017d482007-12-30 23:10:15 +0000280 OperandHash = Op.getMBB()->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 break;
Chris Lattner6017d482007-12-30 23:10:15 +0000282 case MachineOperand::MO_FrameIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 case MachineOperand::MO_ConstantPoolIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 case MachineOperand::MO_JumpTableIndex:
Chris Lattner6017d482007-12-30 23:10:15 +0000285 OperandHash = Op.getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 break;
287 case MachineOperand::MO_GlobalAddress:
288 case MachineOperand::MO_ExternalSymbol:
289 // Global address / external symbol are too hard, don't bother, but do
290 // pull in the offset.
291 OperandHash = Op.getOffset();
292 break;
293 default: break;
294 }
295
296 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
297 }
298 return Hash;
299}
300
301/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
302/// with no successors, we hash two instructions, because cross-jumping
303/// only saves code when at least two instructions are removed (since a
304/// branch must be inserted). For blocks with a successor, one of the
305/// two blocks to be tail-merged will end with a branch already, so
306/// it gains to cross-jump even for one instruction.
307
308static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
309 unsigned minCommonTailLength) {
310 MachineBasicBlock::const_iterator I = MBB->end();
311 if (I == MBB->begin())
312 return 0; // Empty MBB.
313
314 --I;
315 unsigned Hash = HashMachineInstr(I);
316
317 if (I == MBB->begin() || minCommonTailLength == 1)
318 return Hash; // Single instr MBB.
319
320 --I;
321 // Hash in the second-to-last instruction.
322 Hash ^= HashMachineInstr(I) << 2;
323 return Hash;
324}
325
326/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
327/// of instructions they actually have in common together at their end. Return
328/// iterators for the first shared instruction in each block.
329static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
330 MachineBasicBlock *MBB2,
331 MachineBasicBlock::iterator &I1,
332 MachineBasicBlock::iterator &I2) {
333 I1 = MBB1->end();
334 I2 = MBB2->end();
335
336 unsigned TailLen = 0;
337 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
338 --I1; --I2;
Bill Wendling46329b72007-10-19 21:09:55 +0000339 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingf728a1c2007-10-25 19:49:32 +0000340 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling83628182007-10-25 18:23:45 +0000341 // people incorrectly expect inline asm directives to remain in the same
342 // relative order. This is untenable because normal compiler
343 // optimizations (like this one) may reorder and/or merge these
344 // directives.
Bill Wendling46329b72007-10-19 21:09:55 +0000345 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 ++I1; ++I2;
347 break;
348 }
349 ++TailLen;
350 }
351 return TailLen;
352}
353
354/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
355/// after it, replacing it with an unconditional branch to NewDest. This
356/// returns true if OldInst's block is modified, false if NewDest is modified.
357void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
358 MachineBasicBlock *NewDest) {
359 MachineBasicBlock *OldBB = OldInst->getParent();
360
361 // Remove all the old successors of OldBB from the CFG.
362 while (!OldBB->succ_empty())
363 OldBB->removeSuccessor(OldBB->succ_begin());
364
365 // Remove all the dead instructions from the end of OldBB.
366 OldBB->erase(OldInst, OldBB->end());
367
368 // If OldBB isn't immediately before OldBB, insert a branch to it.
369 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
Dan Gohmane458ea82008-08-22 16:07:55 +0000370 TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 OldBB->addSuccessor(NewDest);
372 ++NumTailMerge;
373}
374
375/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
376/// MBB so that the part before the iterator falls into the part starting at the
377/// iterator. This returns the new MBB.
378MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
379 MachineBasicBlock::iterator BBI1) {
Dan Gohman221a4372008-07-07 23:14:23 +0000380 MachineFunction &MF = *CurMBB.getParent();
381
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 // Create the fall-through block.
383 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman221a4372008-07-07 23:14:23 +0000384 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
385 CurMBB.getParent()->insert(++MBBI, NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386
387 // Move all the successors of this block to the specified block.
Dan Gohmanf995c022008-06-19 17:22:29 +0000388 NewMBB->transferSuccessors(&CurMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389
390 // Add an edge from CurMBB to NewMBB for the fall-through.
391 CurMBB.addSuccessor(NewMBB);
392
393 // Splice the code over.
394 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
395
396 // For targets that use the register scavenger, we must maintain LiveIns.
397 if (RS) {
398 RS->enterBasicBlock(&CurMBB);
399 if (!CurMBB.empty())
400 RS->forward(prior(CurMBB.end()));
401 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
402 RS->getRegsUsed(RegsLiveAtExit, false);
403 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
404 if (RegsLiveAtExit[i])
405 NewMBB->addLiveIn(i);
406 }
407
408 return NewMBB;
409}
410
411/// EstimateRuntime - Make a rough estimate for how long it will take to run
412/// the specified code.
413static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner62327602008-01-07 01:56:04 +0000414 MachineBasicBlock::iterator E) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 unsigned Time = 0;
416 for (; I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000417 const TargetInstrDesc &TID = I->getDesc();
418 if (TID.isCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 Time += 10;
Dan Gohmanbc1714f2008-12-03 02:30:17 +0000420 else if (TID.mayLoad() || TID.mayStore())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 Time += 2;
422 else
423 ++Time;
424 }
425 return Time;
426}
427
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
429// branches temporarily for tail merging). In the case where CurMBB ends
430// with a conditional branch to the next block, optimize by reversing the
431// test and conditionally branching to SuccMBB instead.
432
433static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
434 const TargetInstrInfo *TII) {
435 MachineFunction *MF = CurMBB->getParent();
436 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
437 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000438 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 if (I != MF->end() &&
Evan Chengeac31642009-02-09 07:14:22 +0000440 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 MachineBasicBlock *NextBB = I;
Dale Johannesen865e6252008-05-09 23:28:24 +0000442 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 if (!TII->ReverseBranchCondition(Cond)) {
444 TII->RemoveBranch(*CurMBB);
445 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
446 return;
447 }
448 }
449 }
Dan Gohmane458ea82008-08-22 16:07:55 +0000450 TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451}
452
453static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
454 const std::pair<unsigned,MachineBasicBlock*> &q) {
455 if (p.first < q.first)
456 return true;
457 else if (p.first > q.first)
458 return false;
459 else if (p.second->getNumber() < q.second->getNumber())
460 return true;
461 else if (p.second->getNumber() > q.second->getNumber())
462 return false;
463 else {
464 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
465 // an object with itself.
466#ifndef _GLIBCXX_DEBUG
Edwin Törökbd448e32009-07-14 16:55:14 +0000467 llvm_unreachable("Predecessor appears twice");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468#endif
Dan Gohmand2826ae2009-01-08 22:19:34 +0000469 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 }
471}
472
Dale Johannesen865e6252008-05-09 23:28:24 +0000473/// ComputeSameTails - Look through all the blocks in MergePotentials that have
474/// hash CurHash (guaranteed to match the last element). Build the vector
475/// SameTails of all those that have the (same) largest number of instructions
476/// in common of any pair of these blocks. SameTails entries contain an
477/// iterator into MergePotentials (from which the MachineBasicBlock can be
478/// found) and a MachineBasicBlock::iterator into that MBB indicating the
479/// instruction where the matching code sequence begins.
480/// Order of elements in SameTails is the reverse of the order in which
481/// those blocks appear in MergePotentials (where they are not necessarily
482/// consecutive).
483unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
484 unsigned minCommonTailLength) {
485 unsigned maxCommonTailLength = 0U;
486 SameTails.clear();
487 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
488 MPIterator HighestMPIter = prior(MergePotentials.end());
489 for (MPIterator CurMPIter = prior(MergePotentials.end()),
490 B = MergePotentials.begin();
491 CurMPIter!=B && CurMPIter->first==CurHash;
492 --CurMPIter) {
493 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
494 unsigned CommonTailLen = ComputeCommonTailLength(
495 CurMPIter->second,
496 I->second,
497 TrialBBI1, TrialBBI2);
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000498 // If we will have to split a block, there should be at least
499 // minCommonTailLength instructions in common; if not, at worst
500 // we will be replacing a fallthrough into the common tail with a
501 // branch, which at worst breaks even with falling through into
502 // the duplicated common tail, so 1 instruction in common is enough.
503 // We will always pick a block we do not have to split as the common
504 // tail if there is one.
505 // (Empty blocks will get forwarded and need not be considered.)
506 if (CommonTailLen >= minCommonTailLength ||
507 (CommonTailLen > 0 &&
508 (TrialBBI1==CurMPIter->second->begin() ||
509 TrialBBI2==I->second->begin()))) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000510 if (CommonTailLen > maxCommonTailLength) {
511 SameTails.clear();
512 maxCommonTailLength = CommonTailLen;
513 HighestMPIter = CurMPIter;
514 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
515 }
516 if (HighestMPIter == CurMPIter &&
517 CommonTailLen == maxCommonTailLength)
518 SameTails.push_back(std::make_pair(I, TrialBBI2));
519 }
520 if (I==B)
521 break;
522 }
523 }
524 return maxCommonTailLength;
525}
526
527/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
528/// MergePotentials, restoring branches at ends of blocks as appropriate.
529void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
530 MachineBasicBlock* SuccBB,
531 MachineBasicBlock* PredBB) {
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000532 MPIterator CurMPIter, B;
533 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen865e6252008-05-09 23:28:24 +0000534 CurMPIter->first==CurHash;
535 --CurMPIter) {
536 // Put the unconditional branch back, if we need one.
537 MachineBasicBlock *CurMBB = CurMPIter->second;
538 if (SuccBB && CurMBB != PredBB)
539 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000540 if (CurMPIter==B)
Dale Johannesen865e6252008-05-09 23:28:24 +0000541 break;
542 }
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000543 if (CurMPIter->first!=CurHash)
544 CurMPIter++;
545 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen865e6252008-05-09 23:28:24 +0000546}
547
Dale Johannesena3fbac92008-05-12 20:33:57 +0000548/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
549/// only of the common tail. Create a block that does by splitting one.
550unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
551 unsigned maxCommonTailLength) {
552 unsigned i, commonTailIndex;
553 unsigned TimeEstimate = ~0U;
554 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
555 // Use PredBB if possible; that doesn't require a new branch.
556 if (SameTails[i].first->second==PredBB) {
557 commonTailIndex = i;
558 break;
559 }
560 // Otherwise, make a (fairly bogus) choice based on estimate of
561 // how long it will take the various blocks to execute.
562 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
563 SameTails[i].second);
564 if (t<=TimeEstimate) {
565 TimeEstimate = t;
566 commonTailIndex = i;
567 }
568 }
569
570 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
571 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
572
Bill Wendlingef26d402009-08-22 20:03:00 +0000573 DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
574 << maxCommonTailLength);
Dale Johannesena3fbac92008-05-12 20:33:57 +0000575
576 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
577 SameTails[commonTailIndex].first->second = newMBB;
578 SameTails[commonTailIndex].second = newMBB->begin();
579 // If we split PredBB, newMBB is the new predecessor.
580 if (PredBB==MBB)
581 PredBB = newMBB;
582
583 return commonTailIndex;
584}
585
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586// See if any of the blocks in MergePotentials (which all have a common single
587// successor, or all have no successor) can be tail-merged. If there is a
588// successor, any blocks in MergePotentials that are not tail-merged and
589// are not immediately before Succ must have an unconditional branch to
590// Succ added (but the predecessor/successor lists need no adjustment).
591// The lone predecessor of Succ that falls through into Succ,
592// if any, is given in PredBB.
593
594bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
595 MachineBasicBlock* PredBB) {
Evan Cheng55d13352008-02-19 02:09:37 +0000596 // It doesn't make sense to save a single instruction since tail merging
597 // will add a jump.
598 // FIXME: Ask the target to provide the threshold?
599 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 MadeChange = false;
601
Bill Wendlingef26d402009-08-22 20:03:00 +0000602 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
Dale Johannesen865e6252008-05-09 23:28:24 +0000603
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 // Sort by hash value so that blocks with identical end sequences sort
605 // together.
Dale Johannesen865e6252008-05-09 23:28:24 +0000606 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607
608 // Walk through equivalence sets looking for actual exact matches.
609 while (MergePotentials.size() > 1) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000610 unsigned CurHash = prior(MergePotentials.end())->first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611
Dale Johannesen865e6252008-05-09 23:28:24 +0000612 // Build SameTails, identifying the set of blocks with this hash code
613 // and with the maximum number of instructions in common.
614 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
615 minCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616
617 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000618 // instructions in common, remove all blocks with this hash code and retry.
619 if (SameTails.empty()) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000620 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 continue;
622 }
623
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000624 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesena3fbac92008-05-12 20:33:57 +0000625 // block, which we can't jump to), we can treat all blocks with this same
626 // tail at once. Use PredBB if that is one of the possibilities, as that
627 // will not introduce any extra branches.
628 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
629 getParent()->begin();
630 unsigned int commonTailIndex, i;
631 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000632 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesena3fbac92008-05-12 20:33:57 +0000633 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
634 commonTailIndex = i;
635 if (MBB==PredBB)
636 break;
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000637 }
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000638 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639
Dale Johannesena3fbac92008-05-12 20:33:57 +0000640 if (commonTailIndex==SameTails.size()) {
641 // None of the blocks consist entirely of the common tail.
642 // Split a block so that one does.
643 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 }
Dale Johannesena3fbac92008-05-12 20:33:57 +0000645
646 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
647 // MBB is common tail. Adjust all other BB's to jump to this one.
648 // Traversal must be forwards so erases work.
Bill Wendlingef26d402009-08-22 20:03:00 +0000649 DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000650 for (unsigned int i=0; i<SameTails.size(); ++i) {
651 if (commonTailIndex==i)
652 continue;
Bill Wendlingef26d402009-08-22 20:03:00 +0000653 DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000654 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
655 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
656 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
657 MergePotentials.erase(SameTails[i].first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 }
Bill Wendlingef26d402009-08-22 20:03:00 +0000659 DEBUG(errs() << "\n");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000660 // We leave commonTailIndex in the worklist in case there are other blocks
661 // that match it with a smaller number of instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 MadeChange = true;
663 }
664 return MadeChange;
665}
666
667bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
668
669 if (!EnableTailMerge) return false;
670
671 MadeChange = false;
672
673 // First find blocks with no successors.
674 MergePotentials.clear();
675 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
676 if (I->succ_empty())
677 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
678 }
679 // See if we can do any tail merging on those.
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000680 if (MergePotentials.size() < TailMergeThreshold &&
681 MergePotentials.size() >= 2)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 MadeChange |= TryMergeBlocks(NULL, NULL);
683
684 // Look at blocks (IBB) with multiple predecessors (PBB).
685 // We change each predecessor to a canonical form, by
686 // (1) temporarily removing any unconditional branch from the predecessor
687 // to IBB, and
688 // (2) alter conditional branches so they branch to the other block
689 // not IBB; this may require adding back an unconditional branch to IBB
690 // later, where there wasn't one coming in. E.g.
691 // Bcc IBB
692 // fallthrough to QBB
693 // here becomes
694 // Bncc QBB
695 // with a conceptual B to IBB after that, which never actually exists.
696 // With those changes, we see whether the predecessors' tails match,
697 // and merge them if so. We change things out of canonical form and
698 // back to the way they were later in the process. (OptimizeBranches
699 // would undo some of this, but we can't use it, because we'd get into
700 // a compile-time infinite loop repeatedly doing and undoing the same
701 // transformations.)
702
703 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen92e84662008-07-01 21:50:14 +0000704 if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
Dan Gohman1a30b662009-08-18 15:18:18 +0000705 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 MachineBasicBlock *IBB = I;
707 MachineBasicBlock *PredBB = prior(I);
708 MergePotentials.clear();
709 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
710 E2 = I->pred_end();
711 P != E2; ++P) {
712 MachineBasicBlock* PBB = *P;
713 // Skip blocks that loop to themselves, can't tail merge these.
714 if (PBB==IBB)
715 continue;
Dan Gohman1a30b662009-08-18 15:18:18 +0000716 // Visit each predecessor only once.
717 if (!UniquePreds.insert(PBB))
718 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000720 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000721 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 // Failing case: IBB is the target of a cbr, and
723 // we cannot reverse the branch.
Owen Andersond131b5b2008-08-14 22:49:33 +0000724 SmallVector<MachineOperand, 4> NewCond(Cond);
Dale Johannesen865e6252008-05-09 23:28:24 +0000725 if (!Cond.empty() && TBB==IBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 if (TII->ReverseBranchCondition(NewCond))
727 continue;
728 // This is the QBB case described above
729 if (!FBB)
730 FBB = next(MachineFunction::iterator(PBB));
731 }
732 // Failing case: the only way IBB can be reached from PBB is via
733 // exception handling. Happens for landing pads. Would be nice
734 // to have a bit in the edge so we didn't have to do all this.
735 if (IBB->isLandingPad()) {
736 MachineFunction::iterator IP = PBB; IP++;
737 MachineBasicBlock* PredNextBB = NULL;
738 if (IP!=MF.end())
739 PredNextBB = IP;
740 if (TBB==NULL) {
741 if (IBB!=PredNextBB) // fallthrough
742 continue;
743 } else if (FBB) {
744 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
745 continue;
Dan Gohman301f4052008-01-29 13:02:09 +0000746 } else if (Cond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 if (TBB!=IBB) // ubr
748 continue;
749 } else {
750 if (TBB!=IBB && IBB!=PredNextBB) // cbr
751 continue;
752 }
753 }
754 // Remove the unconditional branch at the end, if any.
Dale Johannesen865e6252008-05-09 23:28:24 +0000755 if (TBB && (Cond.empty() || FBB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 TII->RemoveBranch(*PBB);
Dale Johannesen865e6252008-05-09 23:28:24 +0000757 if (!Cond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 // reinsert conditional branch only, for now
759 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
760 }
761 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
762 }
763 }
764 if (MergePotentials.size() >= 2)
765 MadeChange |= TryMergeBlocks(I, PredBB);
766 // Reinsert an unconditional branch if needed.
Dale Johannesena3fbac92008-05-12 20:33:57 +0000767 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 PredBB = prior(I); // this may have been changed in TryMergeBlocks
769 if (MergePotentials.size()==1 &&
Dale Johannesena3fbac92008-05-12 20:33:57 +0000770 MergePotentials.begin()->second != PredBB)
771 FixTail(MergePotentials.begin()->second, I, TII);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 }
773 }
774 return MadeChange;
775}
776
777//===----------------------------------------------------------------------===//
778// Branch Optimization
779//===----------------------------------------------------------------------===//
780
781bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
782 MadeChange = false;
783
784 // Make sure blocks are numbered in order
785 MF.RenumberBlocks();
786
787 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
788 MachineBasicBlock *MBB = I++;
789 OptimizeBlock(MBB);
790
791 // If it is dead, remove it.
792 if (MBB->pred_empty()) {
793 RemoveDeadBlock(MBB);
794 MadeChange = true;
795 ++NumDeadBlocks;
796 }
797 }
798 return MadeChange;
799}
800
801
802/// CanFallThrough - Return true if the specified block (with the specified
803/// branch condition) can implicitly transfer control to the block after it by
804/// falling off the end of it. This should return false if it can reach the
805/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
806///
807/// True is a conservative answer.
808///
809bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
810 bool BranchUnAnalyzable,
Dale Johannesena3fbac92008-05-12 20:33:57 +0000811 MachineBasicBlock *TBB,
812 MachineBasicBlock *FBB,
Owen Andersond131b5b2008-08-14 22:49:33 +0000813 const SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 MachineFunction::iterator Fallthrough = CurBB;
815 ++Fallthrough;
816 // If FallthroughBlock is off the end of the function, it can't fall through.
817 if (Fallthrough == CurBB->getParent()->end())
818 return false;
819
820 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
821 if (!CurBB->isSuccessor(Fallthrough))
822 return false;
823
824 // If we couldn't analyze the branch, assume it could fall through.
825 if (BranchUnAnalyzable) return true;
826
827 // If there is no branch, control always falls through.
828 if (TBB == 0) return true;
829
830 // If there is some explicit branch to the fallthrough block, it can obviously
831 // reach, even though the branch should get folded to fall through implicitly.
832 if (MachineFunction::iterator(TBB) == Fallthrough ||
833 MachineFunction::iterator(FBB) == Fallthrough)
834 return true;
835
836 // If it's an unconditional branch to some block not the fall through, it
837 // doesn't fall through.
838 if (Cond.empty()) return false;
839
840 // Otherwise, if it is conditional and has no explicit false block, it falls
841 // through.
842 return FBB == 0;
843}
844
845/// CanFallThrough - Return true if the specified can implicitly transfer
846/// control to the block after it by falling off the end of it. This should
847/// return false if it can reach the block after it, but it uses an explicit
848/// branch to do so (e.g. a table jump).
849///
850/// True is a conservative answer.
851///
852bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
853 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000854 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000855 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
857}
858
859/// IsBetterFallthrough - Return true if it would be clearly better to
860/// fall-through to MBB1 than to fall through into MBB2. This has to return
861/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
862/// result in infinite loops.
863static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner62327602008-01-07 01:56:04 +0000864 MachineBasicBlock *MBB2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
866 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
867 // optimize branches that branch to either a return block or an assert block
868 // into a fallthrough to the return.
869 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lambff904542007-12-10 07:24:06 +0000870
871 // If there is a clear successor ordering we make sure that one block
872 // will fall through to the next
873 if (MBB1->isSuccessor(MBB2)) return true;
874 if (MBB2->isSuccessor(MBB1)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875
876 MachineInstr *MBB1I = --MBB1->end();
877 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner5b930372008-01-07 07:27:27 +0000878 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879}
880
881/// OptimizeBlock - Analyze and optimize control flow related to the specified
882/// block. This is never called on the entry block.
883void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
884 MachineFunction::iterator FallThrough = MBB;
885 ++FallThrough;
886
887 // If this block is empty, make everyone use its fall-through, not the block
888 // explicitly. Landing pads should not do this since the landing-pad table
889 // points to this block.
890 if (MBB->empty() && !MBB->isLandingPad()) {
891 // Dead block? Leave for cleanup later.
892 if (MBB->pred_empty()) return;
893
894 if (FallThrough == MBB->getParent()->end()) {
895 // TODO: Simplify preds to not branch here if possible!
896 } else {
897 // Rewrite all predecessors of the old block to go to the fallthrough
898 // instead.
899 while (!MBB->pred_empty()) {
900 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
901 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
902 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 // If MBB was the target of a jump table, update jump tables to go to the
904 // fallthrough instead.
905 MBB->getParent()->getJumpTableInfo()->
906 ReplaceMBBInJumpTables(MBB, FallThrough);
907 MadeChange = true;
908 }
909 return;
910 }
911
912 // Check to see if we can simplify the terminator of the block before this
913 // one.
914 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
915
916 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000917 SmallVector<MachineOperand, 4> PriorCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000918 bool PriorUnAnalyzable =
Evan Chengeac31642009-02-09 07:14:22 +0000919 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 if (!PriorUnAnalyzable) {
921 // If the CFG for the prior block has extra edges, remove them.
922 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
923 !PriorCond.empty());
924
925 // If the previous branch is conditional and both conditions go to the same
926 // destination, remove the branch, replacing it with an unconditional one or
927 // a fall-through.
928 if (PriorTBB && PriorTBB == PriorFBB) {
929 TII->RemoveBranch(PrevBB);
930 PriorCond.clear();
931 if (PriorTBB != MBB)
932 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
933 MadeChange = true;
934 ++NumBranchOpts;
935 return OptimizeBlock(MBB);
936 }
937
938 // If the previous branch *only* branches to *this* block (conditional or
939 // not) remove the branch.
940 if (PriorTBB == MBB && PriorFBB == 0) {
941 TII->RemoveBranch(PrevBB);
942 MadeChange = true;
943 ++NumBranchOpts;
944 return OptimizeBlock(MBB);
945 }
946
947 // If the prior block branches somewhere else on the condition and here if
948 // the condition is false, remove the uncond second branch.
949 if (PriorFBB == MBB) {
950 TII->RemoveBranch(PrevBB);
951 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
952 MadeChange = true;
953 ++NumBranchOpts;
954 return OptimizeBlock(MBB);
955 }
956
957 // If the prior block branches here on true and somewhere else on false, and
958 // if the branch condition is reversible, reverse the branch to create a
959 // fall-through.
960 if (PriorTBB == MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000961 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 if (!TII->ReverseBranchCondition(NewPriorCond)) {
963 TII->RemoveBranch(PrevBB);
964 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
965 MadeChange = true;
966 ++NumBranchOpts;
967 return OptimizeBlock(MBB);
968 }
969 }
970
971 // If this block doesn't fall through (e.g. it ends with an uncond branch or
972 // has no successors) and if the pred falls through into this block, and if
973 // it would otherwise fall through into the block after this, move this
974 // block to the end of the function.
975 //
976 // We consider it more likely that execution will stay in the function (e.g.
977 // due to loops) than it is to exit it. This asserts in loops etc, moving
978 // the assert condition out of the loop body.
979 if (!PriorCond.empty() && PriorFBB == 0 &&
980 MachineFunction::iterator(PriorTBB) == FallThrough &&
981 !CanFallThrough(MBB)) {
982 bool DoTransform = true;
983
984 // We have to be careful that the succs of PredBB aren't both no-successor
985 // blocks. If neither have successors and if PredBB is the second from
986 // last block in the function, we'd just keep swapping the two blocks for
987 // last. Only do the swap if one is clearly better to fall through than
988 // the other.
989 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner62327602008-01-07 01:56:04 +0000990 !IsBetterFallthrough(PriorTBB, MBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 DoTransform = false;
992
993 // We don't want to do this transformation if we have control flow like:
994 // br cond BB2
995 // BB1:
996 // ..
997 // jmp BBX
998 // BB2:
999 // ..
1000 // ret
1001 //
1002 // In this case, we could actually be moving the return block *into* a
1003 // loop!
1004 if (DoTransform && !MBB->succ_empty() &&
1005 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1006 DoTransform = false;
1007
1008
1009 if (DoTransform) {
1010 // Reverse the branch so we will fall through on the previous true cond.
Owen Andersond131b5b2008-08-14 22:49:33 +00001011 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendlingef26d402009-08-22 20:03:00 +00001013 DEBUG(errs() << "\nMoving MBB: " << *MBB
1014 << "To make fallthrough to: " << *PriorTBB << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015
1016 TII->RemoveBranch(PrevBB);
1017 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1018
1019 // Move this block to the end of the function.
1020 MBB->moveAfter(--MBB->getParent()->end());
1021 MadeChange = true;
1022 ++NumBranchOpts;
1023 return;
1024 }
1025 }
1026 }
1027 }
1028
1029 // Analyze the branch in the current block.
1030 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +00001031 SmallVector<MachineOperand, 4> CurCond;
Evan Chengeac31642009-02-09 07:14:22 +00001032 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 if (!CurUnAnalyzable) {
1034 // If the CFG for the prior block has extra edges, remove them.
1035 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1036
1037 // If this is a two-way branch, and the FBB branches to this block, reverse
1038 // the condition so the single-basic-block loop is faster. Instead of:
1039 // Loop: xxx; jcc Out; jmp Loop
1040 // we want:
1041 // Loop: xxx; jncc Loop; jmp Out
1042 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001043 SmallVector<MachineOperand, 4> NewCond(CurCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 if (!TII->ReverseBranchCondition(NewCond)) {
1045 TII->RemoveBranch(*MBB);
1046 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1047 MadeChange = true;
1048 ++NumBranchOpts;
1049 return OptimizeBlock(MBB);
1050 }
1051 }
1052
1053
1054 // If this branch is the only thing in its block, see if we can forward
1055 // other blocks across it.
1056 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner5b930372008-01-07 07:27:27 +00001057 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 // This block may contain just an unconditional branch. Because there can
1059 // be 'non-branch terminators' in the block, try removing the branch and
1060 // then seeing if the block is empty.
1061 TII->RemoveBranch(*MBB);
1062
1063 // If this block is just an unconditional branch to CurTBB, we can
1064 // usually completely eliminate the block. The only case we cannot
1065 // completely eliminate the block is when the block before this one
1066 // falls through into MBB and we can't understand the prior block's branch
1067 // condition.
1068 if (MBB->empty()) {
1069 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1070 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1071 !PrevBB.isSuccessor(MBB)) {
1072 // If the prior block falls through into us, turn it into an
1073 // explicit branch to us to make updates simpler.
1074 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1075 PriorTBB != MBB && PriorFBB != MBB) {
1076 if (PriorTBB == 0) {
1077 assert(PriorCond.empty() && PriorFBB == 0 &&
1078 "Bad branch analysis");
1079 PriorTBB = MBB;
1080 } else {
1081 assert(PriorFBB == 0 && "Machine CFG out of date!");
1082 PriorFBB = MBB;
1083 }
1084 TII->RemoveBranch(PrevBB);
1085 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1086 }
1087
1088 // Iterate through all the predecessors, revectoring each in-turn.
1089 size_t PI = 0;
1090 bool DidChange = false;
1091 bool HasBranchToSelf = false;
1092 while(PI != MBB->pred_size()) {
1093 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1094 if (PMBB == MBB) {
1095 // If this block has an uncond branch to itself, leave it.
1096 ++PI;
1097 HasBranchToSelf = true;
1098 } else {
1099 DidChange = true;
1100 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenf8031372009-05-11 21:54:13 +00001101 // If this change resulted in PMBB ending in a conditional
1102 // branch where both conditions go to the same destination,
1103 // change this to an unconditional branch (and fix the CFG).
1104 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1105 SmallVector<MachineOperand, 4> NewCurCond;
1106 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1107 NewCurFBB, NewCurCond, true);
1108 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1109 TII->RemoveBranch(*PMBB);
1110 NewCurCond.clear();
1111 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1112 MadeChange = true;
1113 ++NumBranchOpts;
1114 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1115 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 }
1117 }
1118
1119 // Change any jumptables to go to the new MBB.
1120 MBB->getParent()->getJumpTableInfo()->
1121 ReplaceMBBInJumpTables(MBB, CurTBB);
1122 if (DidChange) {
1123 ++NumBranchOpts;
1124 MadeChange = true;
1125 if (!HasBranchToSelf) return;
1126 }
1127 }
1128 }
1129
1130 // Add the branch back if the block is more than just an uncond branch.
1131 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1132 }
1133 }
1134
1135 // If the prior block doesn't fall through into this block, and if this
1136 // block doesn't fall through into some other block, see if we can find a
1137 // place to move this block where a fall-through will happen.
1138 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1139 PriorTBB, PriorFBB, PriorCond)) {
1140 // Now we know that there was no fall-through into this block, check to
1141 // see if it has a fall-through into its successor.
1142 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1143 CurCond);
1144
1145 if (!MBB->isLandingPad()) {
1146 // Check all the predecessors of this block. If one of them has no fall
1147 // throughs, move this block right after it.
1148 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1149 E = MBB->pred_end(); PI != E; ++PI) {
1150 // Analyze the branch at the end of the pred.
1151 MachineBasicBlock *PredBB = *PI;
1152 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1153 if (PredBB != MBB && !CanFallThrough(PredBB)
1154 && (!CurFallsThru || !CurTBB || !CurFBB)
1155 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1156 // If the current block doesn't fall through, just move it.
1157 // If the current block can fall through and does not end with a
1158 // conditional branch, we need to append an unconditional jump to
1159 // the (current) next block. To avoid a possible compile-time
1160 // infinite loop, move blocks only backward in this case.
1161 // Also, if there are already 2 branches here, we cannot add a third;
1162 // this means we have the case
1163 // Bcc next
1164 // B elsewhere
1165 // next:
1166 if (CurFallsThru) {
1167 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1168 CurCond.clear();
1169 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1170 }
1171 MBB->moveAfter(PredBB);
1172 MadeChange = true;
1173 return OptimizeBlock(MBB);
1174 }
1175 }
1176 }
1177
1178 if (!CurFallsThru) {
1179 // Check all successors to see if we can move this block before it.
1180 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1181 E = MBB->succ_end(); SI != E; ++SI) {
1182 // Analyze the branch at the end of the block before the succ.
1183 MachineBasicBlock *SuccBB = *SI;
1184 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1185 std::vector<MachineOperand> SuccPrevCond;
1186
1187 // If this block doesn't already fall-through to that successor, and if
1188 // the succ doesn't already have a block that can fall through into it,
1189 // and if the successor isn't an EH destination, we can arrange for the
1190 // fallthrough to happen.
1191 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1192 !SuccBB->isLandingPad()) {
1193 MBB->moveBefore(SuccBB);
1194 MadeChange = true;
1195 return OptimizeBlock(MBB);
1196 }
1197 }
1198
1199 // Okay, there is no really great place to put this block. If, however,
1200 // the block before this one would be a fall-through if this block were
1201 // removed, move this block to the end of the function.
1202 if (FallThrough != MBB->getParent()->end() &&
1203 PrevBB.isSuccessor(FallThrough)) {
1204 MBB->moveAfter(--MBB->getParent()->end());
1205 MadeChange = true;
1206 return;
1207 }
1208 }
1209 }
1210}