blob: c34aeebe0ee07c5cc300e0bf0d854da87cf3cb63 [file] [log] [blame]
Chris Lattner25e48dd2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner25e48dd2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner25e48dd2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
Chris Lattner56ec81f2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Chris Lattner25e48dd2004-07-31 10:01:27 +000020#include "llvm/CodeGen/Passes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner56c9d252006-10-17 17:13:52 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesend05a1a22007-03-20 21:35:06 +000024#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner25e48dd2004-07-31 10:01:27 +000025#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dale Johannesend05a1a22007-03-20 21:35:06 +000027#include "llvm/Target/MRegisterInfo.h"
Chris Lattner60c9d4d2006-10-21 00:47:49 +000028#include "llvm/Support/CommandLine.h"
Chris Lattner56ec81f2006-11-18 21:56:39 +000029#include "llvm/Support/Debug.h"
Chris Lattner60c9d4d2006-10-21 00:47:49 +000030#include "llvm/ADT/Statistic.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/ADT/STLExtras.h"
Jeff Cohen7d6f3db2006-11-05 19:31:28 +000032#include <algorithm>
Chris Lattner25e48dd2004-07-31 10:01:27 +000033using namespace llvm;
34
Chris Lattneraee775a2006-12-19 22:41:21 +000035STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36STATISTIC(NumBranchOpts, "Number of branches optimized");
37STATISTIC(NumTailMerge , "Number of block tails merged");
Dale Johannesen82810c82007-05-22 17:14:46 +000038static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
39 cl::init(cl::BOU_UNSET), cl::Hidden);
Chris Lattner25e48dd2004-07-31 10:01:27 +000040namespace {
41 struct BranchFolder : public MachineFunctionPass {
Devang Patel8c78a0b2007-05-03 01:11:54 +000042 static char ID;
Dale Johannesen82810c82007-05-22 17:14:46 +000043 BranchFolder(bool defaultEnableTailMerge) :
44 MachineFunctionPass((intptr_t)&ID) {
45 switch (FlagEnableTailMerge) {
46 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
47 case cl::BOU_TRUE: EnableTailMerge = true; break;
48 case cl::BOU_FALSE: EnableTailMerge = false; break;
49 }
50 }
Devang Patel09f162c2007-05-01 21:15:47 +000051
Chris Lattner25e48dd2004-07-31 10:01:27 +000052 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner3218e0e2006-10-14 00:21:48 +000053 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
54 const TargetInstrInfo *TII;
Jim Laskeyc56315c2007-01-26 21:22:28 +000055 MachineModuleInfo *MMI;
Chris Lattner3218e0e2006-10-14 00:21:48 +000056 bool MadeChange;
Chris Lattner25e48dd2004-07-31 10:01:27 +000057 private:
Chris Lattner60c9d4d2006-10-21 00:47:49 +000058 // Tail Merging.
Dale Johannesen82810c82007-05-22 17:14:46 +000059 bool EnableTailMerge;
Chris Lattner60c9d4d2006-10-21 00:47:49 +000060 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen9a25b3a2007-05-07 20:57:21 +000061 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
62 MachineBasicBlock* PredBB);
Chris Lattner60c9d4d2006-10-21 00:47:49 +000063 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
64 MachineBasicBlock *NewDest);
Chris Lattnerf505a5a2006-11-01 01:16:12 +000065 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
66 MachineBasicBlock::iterator BBI1);
Dale Johannesend05a1a22007-03-20 21:35:06 +000067
Dale Johannesen9a25b3a2007-05-07 20:57:21 +000068 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
Dale Johannesend05a1a22007-03-20 21:35:06 +000069 const MRegisterInfo *RegInfo;
70 RegScavenger *RS;
Chris Lattner60c9d4d2006-10-21 00:47:49 +000071 // Branch optzn.
72 bool OptimizeBranches(MachineFunction &MF);
Chris Lattnerceb51d82006-10-24 01:12:32 +000073 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner73da3202006-10-17 23:17:27 +000074 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner504eeda2006-10-29 21:05:41 +000075
76 bool CanFallThrough(MachineBasicBlock *CurBB);
77 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
78 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
79 const std::vector<MachineOperand> &Cond);
Chris Lattner25e48dd2004-07-31 10:01:27 +000080 };
Devang Patel8c78a0b2007-05-03 01:11:54 +000081 char BranchFolder::ID = 0;
Chris Lattner25e48dd2004-07-31 10:01:27 +000082}
83
Dale Johannesen420a85d2007-05-15 21:19:17 +000084static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
85 MachineBasicBlock *DestA,
86 MachineBasicBlock *DestB,
87 bool isCond,
88 MachineFunction::iterator FallThru);
89
Dale Johannesen82810c82007-05-22 17:14:46 +000090FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
91 return new BranchFolder(DefaultEnableTailMerge); }
Chris Lattner25e48dd2004-07-31 10:01:27 +000092
Chris Lattner56c9d252006-10-17 17:13:52 +000093/// RemoveDeadBlock - Remove the specified dead machine basic block from the
94/// function, updating the CFG.
Chris Lattner73da3202006-10-17 23:17:27 +000095void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey9df1a1d2007-02-22 16:39:03 +000096 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey2dc52452007-02-21 22:42:20 +000097 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner73da3202006-10-17 23:17:27 +000098
Chris Lattner56c9d252006-10-17 17:13:52 +000099 MachineFunction *MF = MBB->getParent();
100 // drop all successors.
101 while (!MBB->succ_empty())
102 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner73da3202006-10-17 23:17:27 +0000103
Jim Laskeyf9e54452007-01-26 14:34:52 +0000104 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskeyc56315c2007-01-26 21:22:28 +0000105 // records in the basic block. If so, unregister them from MachineModuleInfo.
106 if (MMI && !MBB->empty()) {
Chris Lattner73da3202006-10-17 23:17:27 +0000107 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
108 I != E; ++I) {
Jim Laskeyf9e54452007-01-26 14:34:52 +0000109 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner73da3202006-10-17 23:17:27 +0000110 // The label ID # is always operand #0, an immediate.
Jim Laskeyc56315c2007-01-26 21:22:28 +0000111 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner73da3202006-10-17 23:17:27 +0000112 }
113 }
114 }
115
Chris Lattner56c9d252006-10-17 17:13:52 +0000116 // Remove the block.
117 MF->getBasicBlockList().erase(MBB);
118}
119
Chris Lattner25e48dd2004-07-31 10:01:27 +0000120bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner3218e0e2006-10-14 00:21:48 +0000121 TII = MF.getTarget().getInstrInfo();
122 if (!TII) return false;
123
Dale Johannesen420a85d2007-05-15 21:19:17 +0000124 // Fix CFG. The later algorithms expect it to be right.
125 bool EverMadeChange = false;
126 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
127 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
128 std::vector<MachineOperand> Cond;
129 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
130 EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
131 !Cond.empty(), next(I));
132 }
133
Dale Johannesend05a1a22007-03-20 21:35:06 +0000134 RegInfo = MF.getTarget().getRegisterInfo();
135 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
136
Jim Laskeyc56315c2007-01-26 21:22:28 +0000137 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen6e16d092007-05-10 01:01:49 +0000138
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000139 bool MadeChangeThisIteration = true;
140 while (MadeChangeThisIteration) {
141 MadeChangeThisIteration = false;
142 MadeChangeThisIteration |= TailMergeBlocks(MF);
143 MadeChangeThisIteration |= OptimizeBranches(MF);
144 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000145 }
146
Chris Lattnerc07657f2006-10-28 18:34:47 +0000147 // See if any jump tables have become mergable or dead as the code generator
148 // did its thing.
149 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
150 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
151 if (!JTs.empty()) {
152 // Figure out how these jump tables should be merged.
153 std::vector<unsigned> JTMapping;
154 JTMapping.reserve(JTs.size());
155
156 // We always keep the 0th jump table.
157 JTMapping.push_back(0);
158
159 // Scan the jump tables, seeing if there are any duplicates. Note that this
160 // is N^2, which should be fixed someday.
161 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
162 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
163
164 // If a jump table was merge with another one, walk the function rewriting
165 // references to jump tables to reference the new JT ID's. Keep track of
166 // whether we see a jump table idx, if not, we can delete the JT.
167 std::vector<bool> JTIsLive;
168 JTIsLive.resize(JTs.size());
169 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
170 BB != E; ++BB) {
171 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
172 I != E; ++I)
173 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
174 MachineOperand &Op = I->getOperand(op);
175 if (!Op.isJumpTableIndex()) continue;
176 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
177 Op.setJumpTableIndex(NewIdx);
178
179 // Remember that this JT is live.
180 JTIsLive[NewIdx] = true;
181 }
182 }
183
184 // Finally, remove dead jump tables. This happens either because the
185 // indirect jump was unreachable (and thus deleted) or because the jump
186 // table was merged with some other one.
187 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
188 if (!JTIsLive[i]) {
189 JTI->RemoveJumpTable(i);
190 EverMadeChange = true;
191 }
192 }
193
Dale Johannesend05a1a22007-03-20 21:35:06 +0000194 delete RS;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000195 return EverMadeChange;
196}
197
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000198//===----------------------------------------------------------------------===//
199// Tail Merging of Blocks
200//===----------------------------------------------------------------------===//
201
202/// HashMachineInstr - Compute a hash value for MI and its operands.
203static unsigned HashMachineInstr(const MachineInstr *MI) {
204 unsigned Hash = MI->getOpcode();
205 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
206 const MachineOperand &Op = MI->getOperand(i);
207
208 // Merge in bits from the operand if easy.
209 unsigned OperandHash = 0;
210 switch (Op.getType()) {
211 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
212 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
213 case MachineOperand::MO_MachineBasicBlock:
214 OperandHash = Op.getMachineBasicBlock()->getNumber();
215 break;
216 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
217 case MachineOperand::MO_ConstantPoolIndex:
218 OperandHash = Op.getConstantPoolIndex();
219 break;
220 case MachineOperand::MO_JumpTableIndex:
221 OperandHash = Op.getJumpTableIndex();
222 break;
223 case MachineOperand::MO_GlobalAddress:
224 case MachineOperand::MO_ExternalSymbol:
225 // Global address / external symbol are too hard, don't bother, but do
226 // pull in the offset.
227 OperandHash = Op.getOffset();
228 break;
229 default: break;
230 }
231
232 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
233 }
234 return Hash;
235}
236
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000237/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
238/// with no successors, we hash two instructions, because cross-jumping
239/// only saves code when at least two instructions are removed (since a
240/// branch must be inserted). For blocks with a successor, one of the
241/// two blocks to be tail-merged will end with a branch already, so
242/// it gains to cross-jump even for one instruction.
243
244static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
245 unsigned minCommonTailLength) {
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000246 MachineBasicBlock::const_iterator I = MBB->end();
247 if (I == MBB->begin())
248 return 0; // Empty MBB.
249
250 --I;
251 unsigned Hash = HashMachineInstr(I);
252
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000253 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000254 return Hash; // Single instr MBB.
255
256 --I;
257 // Hash in the second-to-last instruction.
258 Hash ^= HashMachineInstr(I) << 2;
259 return Hash;
260}
261
262/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
263/// of instructions they actually have in common together at their end. Return
264/// iterators for the first shared instruction in each block.
265static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
266 MachineBasicBlock *MBB2,
267 MachineBasicBlock::iterator &I1,
268 MachineBasicBlock::iterator &I2) {
269 I1 = MBB1->end();
270 I2 = MBB2->end();
271
272 unsigned TailLen = 0;
273 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
274 --I1; --I2;
275 if (!I1->isIdenticalTo(I2)) {
276 ++I1; ++I2;
277 break;
278 }
279 ++TailLen;
280 }
281 return TailLen;
282}
283
284/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner4fe01c42006-10-21 05:08:28 +0000285/// after it, replacing it with an unconditional branch to NewDest. This
286/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000287void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
288 MachineBasicBlock *NewDest) {
289 MachineBasicBlock *OldBB = OldInst->getParent();
290
291 // Remove all the old successors of OldBB from the CFG.
292 while (!OldBB->succ_empty())
293 OldBB->removeSuccessor(OldBB->succ_begin());
294
295 // Remove all the dead instructions from the end of OldBB.
296 OldBB->erase(OldInst, OldBB->end());
297
Chris Lattner4fe01c42006-10-21 05:08:28 +0000298 // If OldBB isn't immediately before OldBB, insert a branch to it.
299 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
300 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000301 OldBB->addSuccessor(NewDest);
302 ++NumTailMerge;
303}
304
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000305/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
306/// MBB so that the part before the iterator falls into the part starting at the
307/// iterator. This returns the new MBB.
308MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
309 MachineBasicBlock::iterator BBI1) {
310 // Create the fall-through block.
311 MachineFunction::iterator MBBI = &CurMBB;
312 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
313 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
314
315 // Move all the successors of this block to the specified block.
316 while (!CurMBB.succ_empty()) {
317 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
318 NewMBB->addSuccessor(S);
319 CurMBB.removeSuccessor(S);
320 }
321
322 // Add an edge from CurMBB to NewMBB for the fall-through.
323 CurMBB.addSuccessor(NewMBB);
324
325 // Splice the code over.
326 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesend05a1a22007-03-20 21:35:06 +0000327
328 // For targets that use the register scavenger, we must maintain LiveIns.
329 if (RS) {
330 RS->enterBasicBlock(&CurMBB);
331 if (!CurMBB.empty())
332 RS->forward(prior(CurMBB.end()));
333 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
334 RS->getRegsUsed(RegsLiveAtExit, false);
335 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
336 if (RegsLiveAtExit[i])
337 NewMBB->addLiveIn(i);
338 }
339
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000340 return NewMBB;
341}
342
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000343/// EstimateRuntime - Make a rough estimate for how long it will take to run
344/// the specified code.
345static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
346 MachineBasicBlock::iterator E,
347 const TargetInstrInfo *TII) {
348 unsigned Time = 0;
349 for (; I != E; ++I) {
350 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
351 if (TID.Flags & M_CALL_FLAG)
352 Time += 10;
353 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
354 Time += 2;
355 else
356 ++Time;
357 }
358 return Time;
359}
360
361/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
362/// MBB2I and then insert an unconditional branch in the other block. Determine
363/// which is the best to split
364static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
365 MachineBasicBlock::iterator MBB1I,
366 MachineBasicBlock *MBB2,
367 MachineBasicBlock::iterator MBB2I,
Dale Johannesen6e16d092007-05-10 01:01:49 +0000368 const TargetInstrInfo *TII,
369 MachineBasicBlock *PredBB) {
Dale Johannesencc8f5712007-05-10 23:59:23 +0000370 // If one block is the entry block, split the other one; we can't generate
371 // a branch to the entry block, as its label is not emitted.
372 MachineBasicBlock *Entry = MBB1->getParent()->begin();
373 if (MBB1 == Entry)
374 return false;
375 if (MBB2 == Entry)
376 return true;
377
Dale Johannesen6e16d092007-05-10 01:01:49 +0000378 // If one block falls through into the common successor, choose that
379 // one to split; it is one instruction less to do that.
380 if (PredBB) {
381 if (MBB1 == PredBB)
382 return true;
383 else if (MBB2 == PredBB)
384 return false;
385 }
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000386 // TODO: if we had some notion of which block was hotter, we could split
387 // the hot block, so it is the fall-through. Since we don't have profile info
388 // make a decision based on which will hurt most to split.
389 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
390 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
391
392 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
393 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
394 // have a lower overall impact on the program execution.
395 return MBB1Time < MBB2Time;
396}
397
Dale Johannesen6e16d092007-05-10 01:01:49 +0000398// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
399// branches temporarily for tail merging). In the case where CurMBB ends
400// with a conditional branch to the next block, optimize by reversing the
401// test and conditionally branching to SuccMBB instead.
402
403static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
404 const TargetInstrInfo *TII) {
405 MachineFunction *MF = CurMBB->getParent();
406 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
407 MachineBasicBlock *TBB = 0, *FBB = 0;
408 std::vector<MachineOperand> Cond;
409 if (I != MF->end() &&
410 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
411 MachineBasicBlock *NextBB = I;
412 if (TBB == NextBB && Cond.size() && !FBB) {
413 if (!TII->ReverseBranchCondition(Cond)) {
414 TII->RemoveBranch(*CurMBB);
415 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
416 return;
417 }
418 }
419 }
420 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
421}
422
Dale Johannesena69ebdb2007-05-29 23:47:50 +0000423static bool MergeCompare(std::pair<unsigned,MachineBasicBlock*> p,
424 std::pair<unsigned,MachineBasicBlock*> q) {
425
426 if (p.first < q.first)
427 return true;
428 else if (p.first > q.first)
429 return false;
430 else if (p.second->getNumber() < q.second->getNumber())
431 return true;
432 else if (p.second->getNumber() > q.second->getNumber())
433 return false;
434 else
435 assert(0 && "Predecessor appears twice");
436}
437
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000438// See if any of the blocks in MergePotentials (which all have a common single
439// successor, or all have no successor) can be tail-merged. If there is a
440// successor, any blocks in MergePotentials that are not tail-merged and
441// are not immediately before Succ must have an unconditional branch to
442// Succ added (but the predecessor/successor lists need no adjustment).
443// The lone predecessor of Succ that falls through into Succ,
444// if any, is given in PredBB.
445
446bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
447 MachineBasicBlock* PredBB) {
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000448 unsigned minCommonTailLength = (SuccBB ? 1 : 2);
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000449 MadeChange = false;
450
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000451 // Sort by hash value so that blocks with identical end sequences sort
452 // together.
Dale Johannesena69ebdb2007-05-29 23:47:50 +0000453 std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000454
455 // Walk through equivalence sets looking for actual exact matches.
456 while (MergePotentials.size() > 1) {
457 unsigned CurHash = (MergePotentials.end()-1)->first;
458 unsigned PrevHash = (MergePotentials.end()-2)->first;
459 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
460
461 // If there is nothing that matches the hash of the current basic block,
462 // give up.
463 if (CurHash != PrevHash) {
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000464 if (SuccBB && CurMBB != PredBB)
Dale Johannesen6e16d092007-05-10 01:01:49 +0000465 FixTail(CurMBB, SuccBB, TII);
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000466 MergePotentials.pop_back();
467 continue;
468 }
469
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000470 // Look through all the blocks that have the same hash as this one, and
471 // find the one that has the largest number of instructions in common.
Dale Johannesen6e16d092007-05-10 01:01:49 +0000472 // Since instructions may get combined later (e.g. single stores into
473 // store multiple) this measure is not particularly accurate.
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000474 MachineBasicBlock::iterator BBI1, BBI2;
475
476 unsigned FoundMatch = ~0U;
477 unsigned maxCommonTailLength = 0U;
478 for (int i = MergePotentials.size()-2;
479 i != -1 && MergePotentials[i].first == CurHash; --i) {
480 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
481 unsigned CommonTailLen = ComputeCommonTailLength(CurMBB,
482 MergePotentials[i].second,
483 TrialBBI1, TrialBBI2);
484 if (CommonTailLen >= minCommonTailLength &&
485 CommonTailLen >= maxCommonTailLength) {
486 FoundMatch = i;
487 maxCommonTailLength = CommonTailLen;
488 BBI1 = TrialBBI1;
489 BBI2 = TrialBBI2;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000490 }
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000491 }
492
493 // If we didn't find anything that has at least minCommonTailLength
494 // instructions matching this one, bail out.
495 if (FoundMatch == ~0U) {
496 // Put the unconditional branch back, if we need one.
497 if (SuccBB && CurMBB != PredBB)
498 FixTail(CurMBB, SuccBB, TII);
499 MergePotentials.pop_back();
500 continue;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000501 }
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000502
503 // Otherwise, move the matching block to the right position.
504 if (FoundMatch != MergePotentials.size()-2)
505 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000506
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000507 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000508
509 // If neither block is the entire common tail, split the tail of one block
Dale Johannesencc8f5712007-05-10 23:59:23 +0000510 // to make it redundant with the other tail. Also, we cannot jump to the
511 // entry block, so if one block is the entry block, split the other one.
512 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
513 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
514 ; // CurMBB is common tail
515 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
516 ; // MBB2 is common tail
517 else {
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000518 if (0) { // Enable this to disable partial tail merges.
519 MergePotentials.pop_back();
520 continue;
521 }
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000522
523 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen6e16d092007-05-10 01:01:49 +0000524 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattner7cee6dd2006-11-01 19:36:29 +0000525 CurMBB = SplitMBBAt(*CurMBB, BBI1);
526 BBI1 = CurMBB->begin();
527 MergePotentials.back().second = CurMBB;
528 } else {
529 MBB2 = SplitMBBAt(*MBB2, BBI2);
530 BBI2 = MBB2->begin();
531 (MergePotentials.end()-2)->second = MBB2;
532 }
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000533 }
534
Dale Johannesencc8f5712007-05-10 23:59:23 +0000535 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000536 // Hack the end off CurMBB, making it jump to MBBI@ instead.
537 ReplaceTailWithBranchTo(BBI1, MBB2);
538 // This modifies CurMBB, so remove it from the worklist.
539 MergePotentials.pop_back();
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000540 } else {
Dale Johannesencc8f5712007-05-10 23:59:23 +0000541 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
542 "Didn't split block correctly?");
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000543 // Hack the end off MBB2, making it jump to CurMBB instead.
544 ReplaceTailWithBranchTo(BBI2, CurMBB);
545 // This modifies MBB2, so remove it from the worklist.
546 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000547 }
Chris Lattnerf505a5a2006-11-01 01:16:12 +0000548 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000549 }
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000550 return MadeChange;
551}
552
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000553bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen6e16d092007-05-10 01:01:49 +0000554
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000555 if (!EnableTailMerge) return false;
Dale Johannesen6e16d092007-05-10 01:01:49 +0000556
557 MadeChange = false;
558
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000559 // First find blocks with no successors.
Dale Johannesen6e16d092007-05-10 01:01:49 +0000560 MergePotentials.clear();
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000561 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
562 if (I->succ_empty())
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000563 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000564 }
Dale Johannesen6e16d092007-05-10 01:01:49 +0000565 // See if we can do any tail merging on those.
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000566 MadeChange |= TryMergeBlocks(NULL, NULL);
567
Dale Johannesen6e16d092007-05-10 01:01:49 +0000568 // Look at blocks (IBB) with multiple predecessors (PBB).
569 // We change each predecessor to a canonical form, by
570 // (1) temporarily removing any unconditional branch from the predecessor
571 // to IBB, and
572 // (2) alter conditional branches so they branch to the other block
573 // not IBB; this may require adding back an unconditional branch to IBB
574 // later, where there wasn't one coming in. E.g.
575 // Bcc IBB
576 // fallthrough to QBB
577 // here becomes
578 // Bncc QBB
579 // with a conceptual B to IBB after that, which never actually exists.
580 // With those changes, we see whether the predecessors' tails match,
581 // and merge them if so. We change things out of canonical form and
582 // back to the way they were later in the process. (OptimizeBranches
583 // would undo some of this, but we can't use it, because we'd get into
584 // a compile-time infinite loop repeatedly doing and undoing the same
585 // transformations.)
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000586
587 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
588 if (!I->succ_empty() && I->pred_size() >= 2) {
589 MachineBasicBlock *IBB = I;
590 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen6e16d092007-05-10 01:01:49 +0000591 MergePotentials.clear();
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000592 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
593 P != E2; ++P) {
594 MachineBasicBlock* PBB = *P;
Dale Johannesen6e16d092007-05-10 01:01:49 +0000595 // Skip blocks that loop to themselves, can't tail merge these.
596 if (PBB==IBB)
597 continue;
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000598 MachineBasicBlock *TBB = 0, *FBB = 0;
599 std::vector<MachineOperand> Cond;
Dale Johannesen6e16d092007-05-10 01:01:49 +0000600 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
601 // Failing case: IBB is the target of a cbr, and
602 // we cannot reverse the branch.
603 std::vector<MachineOperand> NewCond(Cond);
604 if (Cond.size() && TBB==IBB) {
605 if (TII->ReverseBranchCondition(NewCond))
606 continue;
607 // This is the QBB case described above
608 if (!FBB)
609 FBB = next(MachineFunction::iterator(PBB));
610 }
611 // Remove the unconditional branch at the end, if any.
612 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000613 TII->RemoveBranch(*PBB);
Dale Johannesen6e16d092007-05-10 01:01:49 +0000614 if (Cond.size())
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000615 // reinsert conditional branch only, for now
Dale Johannesen6e16d092007-05-10 01:01:49 +0000616 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000617 }
Dale Johannesenf4a77d22007-05-23 21:07:20 +0000618 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000619 }
620 }
621 if (MergePotentials.size() >= 2)
622 MadeChange |= TryMergeBlocks(I, PredBB);
623 // Reinsert an unconditional branch if needed.
624 // The 1 below can be either an original single predecessor, or a result
625 // of removing blocks in TryMergeBlocks.
Dale Johannesenf8956172007-05-18 01:28:58 +0000626 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000627 if (MergePotentials.size()==1 &&
628 (MergePotentials.begin())->second != PredBB)
Dale Johannesen6e16d092007-05-10 01:01:49 +0000629 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000630 }
631 }
Dale Johannesen9a25b3a2007-05-07 20:57:21 +0000632 return MadeChange;
633}
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000634
635//===----------------------------------------------------------------------===//
636// Branch Optimization
637//===----------------------------------------------------------------------===//
638
639bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
640 MadeChange = false;
641
Dale Johannesen12920dd2007-02-17 00:44:34 +0000642 // Make sure blocks are numbered in order
643 MF.RenumberBlocks();
644
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000645 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
646 MachineBasicBlock *MBB = I++;
647 OptimizeBlock(MBB);
648
649 // If it is dead, remove it.
Jim Laskey9df1a1d2007-02-22 16:39:03 +0000650 if (MBB->pred_empty()) {
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000651 RemoveDeadBlock(MBB);
652 MadeChange = true;
653 ++NumDeadBlocks;
654 }
655 }
656 return MadeChange;
657}
658
659
Chris Lattner4fe01c42006-10-21 05:08:28 +0000660/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
661/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
662/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
663/// be null.
664static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
665 MachineBasicBlock *DestA,
666 MachineBasicBlock *DestB,
667 bool isCond,
668 MachineFunction::iterator FallThru) {
669 bool MadeChange = false;
670 bool AddedFallThrough = false;
671
672 // If this block ends with a conditional branch that falls through to its
673 // successor, set DestB as the successor.
674 if (isCond) {
675 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
676 DestB = FallThru;
677 AddedFallThrough = true;
678 }
679 } else {
680 // If this is an unconditional branch with no explicit dest, it must just be
681 // a fallthrough into DestB.
682 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
683 DestA = FallThru;
684 AddedFallThrough = true;
685 }
686 }
687
688 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
689 while (SI != MBB.succ_end()) {
Dale Johannesen1409b6a2007-05-24 18:31:55 +0000690 if (*SI == DestA && DestA == DestB) {
691 DestA = DestB = 0;
692 ++SI;
693 } else if (*SI == DestA) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000694 DestA = 0;
695 ++SI;
696 } else if (*SI == DestB) {
697 DestB = 0;
698 ++SI;
Jim Laskey2dc52452007-02-21 22:42:20 +0000699 } else if ((*SI)->isLandingPad()) {
700 ++SI;
Chris Lattner4fe01c42006-10-21 05:08:28 +0000701 } else {
702 // Otherwise, this is a superfluous edge, remove it.
703 MBB.removeSuccessor(SI);
704 MadeChange = true;
705 }
706 }
707 if (!AddedFallThrough) {
708 assert(DestA == 0 && DestB == 0 &&
709 "MachineCFG is missing edges!");
710 } else if (isCond) {
711 assert(DestA == 0 && "MachineCFG is missing edges!");
712 }
713 return MadeChange;
714}
715
716
Chris Lattner25e48dd2004-07-31 10:01:27 +0000717/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
718/// 'Old', change the code and CFG so that it branches to 'New' instead.
719static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
720 MachineBasicBlock *Old,
721 MachineBasicBlock *New,
Chris Lattner3218e0e2006-10-14 00:21:48 +0000722 const TargetInstrInfo *TII) {
Chris Lattner25e48dd2004-07-31 10:01:27 +0000723 assert(Old != New && "Cannot replace self with self!");
724
725 MachineBasicBlock::iterator I = BB->end();
726 while (I != BB->begin()) {
727 --I;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000728 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000729
730 // Scan the operands of this machine instruction, replacing any uses of Old
731 // with New.
732 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
733 if (I->getOperand(i).isMachineBasicBlock() &&
734 I->getOperand(i).getMachineBasicBlock() == Old)
735 I->getOperand(i).setMachineBasicBlock(New);
736 }
737
Dale Johannesen1af8c872007-05-24 17:39:32 +0000738 // Update the successor information. If New was already a successor, just
739 // remove the link to Old instead of creating another one. PR 1444.
740 bool HadSuccessorNew = false;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000741 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
742 for (int i = Succs.size()-1; i >= 0; --i)
Dale Johannesen1af8c872007-05-24 17:39:32 +0000743 if (Succs[i] == New) {
744 HadSuccessorNew = true;
745 break;
746 }
747 for (int i = Succs.size()-1; i >= 0; --i)
Chris Lattner25e48dd2004-07-31 10:01:27 +0000748 if (Succs[i] == Old) {
749 BB->removeSuccessor(Old);
Dale Johannesen1af8c872007-05-24 17:39:32 +0000750 if (!HadSuccessorNew)
751 BB->addSuccessor(New);
Chris Lattner25e48dd2004-07-31 10:01:27 +0000752 }
753}
754
Chris Lattner504eeda2006-10-29 21:05:41 +0000755/// CanFallThrough - Return true if the specified block (with the specified
756/// branch condition) can implicitly transfer control to the block after it by
757/// falling off the end of it. This should return false if it can reach the
758/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
759///
760/// True is a conservative answer.
761///
762bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
763 bool BranchUnAnalyzable,
764 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
765 const std::vector<MachineOperand> &Cond) {
766 MachineFunction::iterator Fallthrough = CurBB;
767 ++Fallthrough;
768 // If FallthroughBlock is off the end of the function, it can't fall through.
769 if (Fallthrough == CurBB->getParent()->end())
770 return false;
771
772 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
773 if (!CurBB->isSuccessor(Fallthrough))
774 return false;
775
776 // If we couldn't analyze the branch, assume it could fall through.
777 if (BranchUnAnalyzable) return true;
778
Chris Lattnerceb51d82006-10-24 01:12:32 +0000779 // If there is no branch, control always falls through.
780 if (TBB == 0) return true;
781
782 // If there is some explicit branch to the fallthrough block, it can obviously
783 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner504eeda2006-10-29 21:05:41 +0000784 if (MachineFunction::iterator(TBB) == Fallthrough ||
785 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattnerceb51d82006-10-24 01:12:32 +0000786 return true;
787
788 // If it's an unconditional branch to some block not the fall through, it
789 // doesn't fall through.
790 if (Cond.empty()) return false;
791
792 // Otherwise, if it is conditional and has no explicit false block, it falls
793 // through.
Chris Lattner0d4479b72006-10-25 22:21:37 +0000794 return FBB == 0;
Chris Lattnerceb51d82006-10-24 01:12:32 +0000795}
796
Chris Lattner504eeda2006-10-29 21:05:41 +0000797/// CanFallThrough - Return true if the specified can implicitly transfer
798/// control to the block after it by falling off the end of it. This should
799/// return false if it can reach the block after it, but it uses an explicit
800/// branch to do so (e.g. a table jump).
801///
802/// True is a conservative answer.
803///
804bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
805 MachineBasicBlock *TBB = 0, *FBB = 0;
806 std::vector<MachineOperand> Cond;
807 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
808 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
809}
810
Chris Lattner47ce2612006-11-18 20:47:54 +0000811/// IsBetterFallthrough - Return true if it would be clearly better to
812/// fall-through to MBB1 than to fall through into MBB2. This has to return
813/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
814/// result in infinite loops.
815static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
816 MachineBasicBlock *MBB2,
817 const TargetInstrInfo &TII) {
Chris Lattner7acdc17f2006-11-18 21:30:35 +0000818 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
819 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattner47ce2612006-11-18 20:47:54 +0000820 // optimize branches that branch to either a return block or an assert block
821 // into a fallthrough to the return.
822 if (MBB1->empty() || MBB2->empty()) return false;
823
824 MachineInstr *MBB1I = --MBB1->end();
825 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner7acdc17f2006-11-18 21:30:35 +0000826 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattner47ce2612006-11-18 20:47:54 +0000827}
828
Chris Lattner3218e0e2006-10-14 00:21:48 +0000829/// OptimizeBlock - Analyze and optimize control flow related to the specified
830/// block. This is never called on the entry block.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000831void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
832 MachineFunction::iterator FallThrough = MBB;
833 ++FallThrough;
834
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000835 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner25e48dd2004-07-31 10:01:27 +0000836 // explicitly.
837 if (MBB->empty()) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000838 // Dead block? Leave for cleanup later.
Jim Laskey9df1a1d2007-02-22 16:39:03 +0000839 if (MBB->pred_empty()) return;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000840
Chris Lattner56c9d252006-10-17 17:13:52 +0000841 if (FallThrough == MBB->getParent()->end()) {
842 // TODO: Simplify preds to not branch here if possible!
843 } else {
844 // Rewrite all predecessors of the old block to go to the fallthrough
845 // instead.
Jim Laskey9df1a1d2007-02-22 16:39:03 +0000846 while (!MBB->pred_empty()) {
Chris Lattner3218e0e2006-10-14 00:21:48 +0000847 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
848 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
849 }
Chris Lattner56c9d252006-10-17 17:13:52 +0000850
851 // If MBB was the target of a jump table, update jump tables to go to the
852 // fallthrough instead.
Chris Lattnerc07657f2006-10-28 18:34:47 +0000853 MBB->getParent()->getJumpTableInfo()->
854 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000855 MadeChange = true;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000856 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000857 return;
Chris Lattner25e48dd2004-07-31 10:01:27 +0000858 }
859
Chris Lattner3218e0e2006-10-14 00:21:48 +0000860 // Check to see if we can simplify the terminator of the block before this
861 // one.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000862 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerbca3e292006-10-17 18:16:40 +0000863
Chris Lattner3218e0e2006-10-14 00:21:48 +0000864 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
865 std::vector<MachineOperand> PriorCond;
Chris Lattner504eeda2006-10-29 21:05:41 +0000866 bool PriorUnAnalyzable =
867 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner4fe01c42006-10-21 05:08:28 +0000868 if (!PriorUnAnalyzable) {
869 // If the CFG for the prior block has extra edges, remove them.
870 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
871 !PriorCond.empty(), MBB);
872
Chris Lattner3218e0e2006-10-14 00:21:48 +0000873 // If the previous branch is conditional and both conditions go to the same
Chris Lattner3ca52182006-10-21 05:43:30 +0000874 // destination, remove the branch, replacing it with an unconditional one or
875 // a fall-through.
Chris Lattner3218e0e2006-10-14 00:21:48 +0000876 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000877 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000878 PriorCond.clear();
Chris Lattnerceb51d82006-10-24 01:12:32 +0000879 if (PriorTBB != MBB)
Chris Lattner4fe01c42006-10-21 05:08:28 +0000880 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000881 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000882 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000883 return OptimizeBlock(MBB);
884 }
885
886 // If the previous branch *only* branches to *this* block (conditional or
887 // not) remove the branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000888 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000889 TII->RemoveBranch(PrevBB);
Chris Lattner3218e0e2006-10-14 00:21:48 +0000890 MadeChange = true;
Chris Lattner60c9d4d2006-10-21 00:47:49 +0000891 ++NumBranchOpts;
Chris Lattner3218e0e2006-10-14 00:21:48 +0000892 return OptimizeBlock(MBB);
893 }
Chris Lattner3ca52182006-10-21 05:43:30 +0000894
895 // If the prior block branches somewhere else on the condition and here if
896 // the condition is false, remove the uncond second branch.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000897 if (PriorFBB == MBB) {
Chris Lattner3ca52182006-10-21 05:43:30 +0000898 TII->RemoveBranch(PrevBB);
899 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
900 MadeChange = true;
901 ++NumBranchOpts;
902 return OptimizeBlock(MBB);
903 }
Chris Lattner28f17f42006-10-21 05:54:00 +0000904
905 // If the prior block branches here on true and somewhere else on false, and
906 // if the branch condition is reversible, reverse the branch to create a
907 // fall-through.
Chris Lattnerceb51d82006-10-24 01:12:32 +0000908 if (PriorTBB == MBB) {
Chris Lattner28f17f42006-10-21 05:54:00 +0000909 std::vector<MachineOperand> NewPriorCond(PriorCond);
910 if (!TII->ReverseBranchCondition(NewPriorCond)) {
911 TII->RemoveBranch(PrevBB);
912 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
913 MadeChange = true;
914 ++NumBranchOpts;
915 return OptimizeBlock(MBB);
916 }
917 }
Chris Lattner47ce2612006-11-18 20:47:54 +0000918
Chris Lattner7acdc17f2006-11-18 21:30:35 +0000919 // If this block doesn't fall through (e.g. it ends with an uncond branch or
920 // has no successors) and if the pred falls through into this block, and if
921 // it would otherwise fall through into the block after this, move this
922 // block to the end of the function.
923 //
Chris Lattner47ce2612006-11-18 20:47:54 +0000924 // We consider it more likely that execution will stay in the function (e.g.
925 // due to loops) than it is to exit it. This asserts in loops etc, moving
926 // the assert condition out of the loop body.
Chris Lattner7acdc17f2006-11-18 21:30:35 +0000927 if (!PriorCond.empty() && PriorFBB == 0 &&
928 MachineFunction::iterator(PriorTBB) == FallThrough &&
929 !CanFallThrough(MBB)) {
Chris Lattner56ec81f2006-11-18 21:56:39 +0000930 bool DoTransform = true;
931
Chris Lattner47ce2612006-11-18 20:47:54 +0000932 // We have to be careful that the succs of PredBB aren't both no-successor
933 // blocks. If neither have successors and if PredBB is the second from
934 // last block in the function, we'd just keep swapping the two blocks for
935 // last. Only do the swap if one is clearly better to fall through than
936 // the other.
Chris Lattner56ec81f2006-11-18 21:56:39 +0000937 if (FallThrough == --MBB->getParent()->end() &&
938 !IsBetterFallthrough(PriorTBB, MBB, *TII))
939 DoTransform = false;
940
941 // We don't want to do this transformation if we have control flow like:
942 // br cond BB2
943 // BB1:
944 // ..
945 // jmp BBX
946 // BB2:
947 // ..
948 // ret
949 //
950 // In this case, we could actually be moving the return block *into* a
951 // loop!
Chris Lattnerea017f62006-11-18 22:25:39 +0000952 if (DoTransform && !MBB->succ_empty() &&
953 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattner56ec81f2006-11-18 21:56:39 +0000954 DoTransform = false;
Chris Lattner47ce2612006-11-18 20:47:54 +0000955
Chris Lattner56ec81f2006-11-18 21:56:39 +0000956
957 if (DoTransform) {
Chris Lattner47ce2612006-11-18 20:47:54 +0000958 // Reverse the branch so we will fall through on the previous true cond.
959 std::vector<MachineOperand> NewPriorCond(PriorCond);
960 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattner56ec81f2006-11-18 21:56:39 +0000961 DOUT << "\nMoving MBB: " << *MBB;
962 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
963
Chris Lattner47ce2612006-11-18 20:47:54 +0000964 TII->RemoveBranch(PrevBB);
965 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
966
967 // Move this block to the end of the function.
968 MBB->moveAfter(--MBB->getParent()->end());
969 MadeChange = true;
970 ++NumBranchOpts;
971 return;
972 }
973 }
974 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000975 }
Chris Lattner3218e0e2006-10-14 00:21:48 +0000976
Chris Lattner4fe01c42006-10-21 05:08:28 +0000977 // Analyze the branch in the current block.
978 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
979 std::vector<MachineOperand> CurCond;
Chris Lattner504eeda2006-10-29 21:05:41 +0000980 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
981 if (!CurUnAnalyzable) {
Chris Lattner4fe01c42006-10-21 05:08:28 +0000982 // If the CFG for the prior block has extra edges, remove them.
983 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattnerceb51d82006-10-24 01:12:32 +0000984 !CurCond.empty(),
985 ++MachineFunction::iterator(MBB));
Chris Lattner3e8e57c2006-10-13 20:43:10 +0000986
Chris Lattnerbf3b57f2006-11-08 01:03:21 +0000987 // If this is a two-way branch, and the FBB branches to this block, reverse
988 // the condition so the single-basic-block loop is faster. Instead of:
989 // Loop: xxx; jcc Out; jmp Loop
990 // we want:
991 // Loop: xxx; jncc Loop; jmp Out
992 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
993 std::vector<MachineOperand> NewCond(CurCond);
994 if (!TII->ReverseBranchCondition(NewCond)) {
995 TII->RemoveBranch(*MBB);
996 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
997 MadeChange = true;
998 ++NumBranchOpts;
999 return OptimizeBlock(MBB);
1000 }
1001 }
1002
1003
Chris Lattner4fe01c42006-10-21 05:08:28 +00001004 // If this branch is the only thing in its block, see if we can forward
1005 // other blocks across it.
1006 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattnerceb51d82006-10-24 01:12:32 +00001007 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner4fe01c42006-10-21 05:08:28 +00001008 // This block may contain just an unconditional branch. Because there can
1009 // be 'non-branch terminators' in the block, try removing the branch and
1010 // then seeing if the block is empty.
1011 TII->RemoveBranch(*MBB);
1012
1013 // If this block is just an unconditional branch to CurTBB, we can
1014 // usually completely eliminate the block. The only case we cannot
1015 // completely eliminate the block is when the block before this one
1016 // falls through into MBB and we can't understand the prior block's branch
1017 // condition.
Chris Lattneraf838382006-10-28 17:32:47 +00001018 if (MBB->empty()) {
1019 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1020 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1021 !PrevBB.isSuccessor(MBB)) {
1022 // If the prior block falls through into us, turn it into an
1023 // explicit branch to us to make updates simpler.
1024 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1025 PriorTBB != MBB && PriorFBB != MBB) {
1026 if (PriorTBB == 0) {
Chris Lattnerc07657f2006-10-28 18:34:47 +00001027 assert(PriorCond.empty() && PriorFBB == 0 &&
1028 "Bad branch analysis");
Chris Lattneraf838382006-10-28 17:32:47 +00001029 PriorTBB = MBB;
1030 } else {
1031 assert(PriorFBB == 0 && "Machine CFG out of date!");
1032 PriorFBB = MBB;
1033 }
1034 TII->RemoveBranch(PrevBB);
1035 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner4fe01c42006-10-21 05:08:28 +00001036 }
Chris Lattner4fe01c42006-10-21 05:08:28 +00001037
Chris Lattneraf838382006-10-28 17:32:47 +00001038 // Iterate through all the predecessors, revectoring each in-turn.
1039 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1040 bool DidChange = false;
1041 bool HasBranchToSelf = false;
1042 while (PI != MBB->pred_end()) {
1043 if (*PI == MBB) {
1044 // If this block has an uncond branch to itself, leave it.
1045 ++PI;
1046 HasBranchToSelf = true;
1047 } else {
1048 DidChange = true;
1049 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1050 }
Chris Lattner9f5a1292006-10-21 06:11:43 +00001051 }
Chris Lattner4fe01c42006-10-21 05:08:28 +00001052
Chris Lattneraf838382006-10-28 17:32:47 +00001053 // Change any jumptables to go to the new MBB.
Chris Lattnerc07657f2006-10-28 18:34:47 +00001054 MBB->getParent()->getJumpTableInfo()->
1055 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattneraf838382006-10-28 17:32:47 +00001056 if (DidChange) {
1057 ++NumBranchOpts;
1058 MadeChange = true;
1059 if (!HasBranchToSelf) return;
1060 }
Chris Lattner9f5a1292006-10-21 06:11:43 +00001061 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +00001062 }
Chris Lattner3e8e57c2006-10-13 20:43:10 +00001063
Chris Lattner4fe01c42006-10-21 05:08:28 +00001064 // Add the branch back if the block is more than just an uncond branch.
1065 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner25e48dd2004-07-31 10:01:27 +00001066 }
Chris Lattner504eeda2006-10-29 21:05:41 +00001067 }
1068
1069 // If the prior block doesn't fall through into this block, and if this
1070 // block doesn't fall through into some other block, see if we can find a
1071 // place to move this block where a fall-through will happen.
1072 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1073 PriorTBB, PriorFBB, PriorCond)) {
1074 // Now we know that there was no fall-through into this block, check to
1075 // see if it has a fall-through into its successor.
Dale Johannesen12920dd2007-02-17 00:44:34 +00001076 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner4dbbace2007-04-30 23:35:00 +00001077 CurCond);
Dale Johannesen12920dd2007-02-17 00:44:34 +00001078
Jim Laskey2dc52452007-02-21 22:42:20 +00001079 if (!MBB->isLandingPad()) {
1080 // Check all the predecessors of this block. If one of them has no fall
1081 // throughs, move this block right after it.
1082 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1083 E = MBB->pred_end(); PI != E; ++PI) {
1084 // Analyze the branch at the end of the pred.
1085 MachineBasicBlock *PredBB = *PI;
1086 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1087 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen6e16d092007-05-10 01:01:49 +00001088 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey2dc52452007-02-21 22:42:20 +00001089 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1090 // If the current block doesn't fall through, just move it.
1091 // If the current block can fall through and does not end with a
1092 // conditional branch, we need to append an unconditional jump to
1093 // the (current) next block. To avoid a possible compile-time
1094 // infinite loop, move blocks only backward in this case.
Dale Johannesen6e16d092007-05-10 01:01:49 +00001095 // Also, if there are already 2 branches here, we cannot add a third;
1096 // this means we have the case
1097 // Bcc next
1098 // B elsewhere
1099 // next:
Jim Laskey2dc52452007-02-21 22:42:20 +00001100 if (CurFallsThru) {
1101 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1102 CurCond.clear();
1103 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1104 }
1105 MBB->moveAfter(PredBB);
1106 MadeChange = true;
1107 return OptimizeBlock(MBB);
Chris Lattnerceb51d82006-10-24 01:12:32 +00001108 }
1109 }
Dale Johannesen12920dd2007-02-17 00:44:34 +00001110 }
Chris Lattner504eeda2006-10-29 21:05:41 +00001111
Dale Johannesen12920dd2007-02-17 00:44:34 +00001112 if (!CurFallsThru) {
Chris Lattner504eeda2006-10-29 21:05:41 +00001113 // Check all successors to see if we can move this block before it.
1114 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1115 E = MBB->succ_end(); SI != E; ++SI) {
1116 // Analyze the branch at the end of the block before the succ.
1117 MachineBasicBlock *SuccBB = *SI;
1118 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner504eeda2006-10-29 21:05:41 +00001119 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner4dbbace2007-04-30 23:35:00 +00001120
1121 // If this block doesn't already fall-through to that successor, and if
1122 // the succ doesn't already have a block that can fall through into it,
1123 // and if the successor isn't an EH destination, we can arrange for the
1124 // fallthrough to happen.
1125 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1126 !SuccBB->isLandingPad()) {
Chris Lattner504eeda2006-10-29 21:05:41 +00001127 MBB->moveBefore(SuccBB);
1128 MadeChange = true;
1129 return OptimizeBlock(MBB);
1130 }
1131 }
1132
1133 // Okay, there is no really great place to put this block. If, however,
1134 // the block before this one would be a fall-through if this block were
1135 // removed, move this block to the end of the function.
1136 if (FallThrough != MBB->getParent()->end() &&
1137 PrevBB.isSuccessor(FallThrough)) {
1138 MBB->moveAfter(--MBB->getParent()->end());
1139 MadeChange = true;
1140 return;
1141 }
Chris Lattnerceb51d82006-10-24 01:12:32 +00001142 }
Chris Lattner25e48dd2004-07-31 10:01:27 +00001143 }
Chris Lattner25e48dd2004-07-31 10:01:27 +00001144}