blob: 7cc4c2db79f2dac6cfdcd364a24ee03c1ad92e6a [file] [log] [blame]
Chris Lattner21ab22e2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner21ab22e2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner21ab22e2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf10a56a2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Chris Lattner21ab22e2004-07-31 10:01:27 +000020#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000024#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000025#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000027#include "llvm/Target/MRegisterInfo.h"
Chris Lattner12143052006-10-21 00:47:49 +000028#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000029#include "llvm/Support/Debug.h"
Chris Lattner12143052006-10-21 00:47:49 +000030#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000032#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000033using namespace llvm;
34
Chris Lattnercd3245a2006-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 Johannesen81da02b2007-05-22 17:14:46 +000038static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
39 cl::init(cl::BOU_UNSET), cl::Hidden);
Chris Lattner21ab22e2004-07-31 10:01:27 +000040namespace {
41 struct BranchFolder : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000042 static char ID;
Dale Johannesen81da02b2007-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 Patel794fd752007-05-01 21:15:47 +000051
Chris Lattner21ab22e2004-07-31 10:01:27 +000052 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000053 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
54 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000055 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000056 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000057 private:
Chris Lattner12143052006-10-21 00:47:49 +000058 // Tail Merging.
Dale Johannesen81da02b2007-05-22 17:14:46 +000059 bool EnableTailMerge;
Chris Lattner12143052006-10-21 00:47:49 +000060 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000061 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
62 MachineBasicBlock* PredBB);
Chris Lattner12143052006-10-21 00:47:49 +000063 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
64 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000065 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
66 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000067
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000068 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
Dale Johannesen69cb9b72007-03-20 21:35:06 +000069 const MRegisterInfo *RegInfo;
70 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000071 // Branch optzn.
72 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000073 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000074 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-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 Lattner21ab22e2004-07-31 10:01:27 +000080 };
Devang Patel19974732007-05-03 01:11:54 +000081 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000082}
83
Dale Johannesen14ba0cc2007-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 Johannesen81da02b2007-05-22 17:14:46 +000090FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
91 return new BranchFolder(DefaultEnableTailMerge); }
Chris Lattner21ab22e2004-07-31 10:01:27 +000092
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000093/// RemoveDeadBlock - Remove the specified dead machine basic block from the
94/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000095void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000096 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000097 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000098
Chris Lattnerc50ffcb2006-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 Lattner683747a2006-10-17 23:17:27 +0000103
Jim Laskey1ee29252007-01-26 14:34:52 +0000104 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000105 // records in the basic block. If so, unregister them from MachineModuleInfo.
106 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +0000107 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
108 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +0000109 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +0000110 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000111 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +0000112 }
113 }
114 }
115
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000116 // Remove the block.
117 MF->getBasicBlockList().erase(MBB);
118}
119
Chris Lattner21ab22e2004-07-31 10:01:27 +0000120bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000121 TII = MF.getTarget().getInstrInfo();
122 if (!TII) return false;
123
Dale Johannesen14ba0cc2007-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 Johannesen69cb9b72007-03-20 21:35:06 +0000134 RegInfo = MF.getTarget().getRegisterInfo();
135 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
136
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000137 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000138
Chris Lattner12143052006-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 Lattner21ab22e2004-07-31 10:01:27 +0000145 }
146
Chris Lattner6acfe122006-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 Johannesen69cb9b72007-03-20 21:35:06 +0000194 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000195 return EverMadeChange;
196}
197
Chris Lattner12143052006-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
237/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
238/// instructions, because cross-jumping only saves code when at least two
239/// instructions are removed (since a branch must be inserted).
240static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
241 MachineBasicBlock::const_iterator I = MBB->end();
242 if (I == MBB->begin())
243 return 0; // Empty MBB.
244
245 --I;
246 unsigned Hash = HashMachineInstr(I);
247
248 if (I == MBB->begin())
249 return Hash; // Single instr MBB.
250
251 --I;
252 // Hash in the second-to-last instruction.
253 Hash ^= HashMachineInstr(I) << 2;
254 return Hash;
255}
256
257/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
258/// of instructions they actually have in common together at their end. Return
259/// iterators for the first shared instruction in each block.
260static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
261 MachineBasicBlock *MBB2,
262 MachineBasicBlock::iterator &I1,
263 MachineBasicBlock::iterator &I2) {
264 I1 = MBB1->end();
265 I2 = MBB2->end();
266
267 unsigned TailLen = 0;
268 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
269 --I1; --I2;
270 if (!I1->isIdenticalTo(I2)) {
271 ++I1; ++I2;
272 break;
273 }
274 ++TailLen;
275 }
276 return TailLen;
277}
278
279/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000280/// after it, replacing it with an unconditional branch to NewDest. This
281/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000282void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
283 MachineBasicBlock *NewDest) {
284 MachineBasicBlock *OldBB = OldInst->getParent();
285
286 // Remove all the old successors of OldBB from the CFG.
287 while (!OldBB->succ_empty())
288 OldBB->removeSuccessor(OldBB->succ_begin());
289
290 // Remove all the dead instructions from the end of OldBB.
291 OldBB->erase(OldInst, OldBB->end());
292
Chris Lattner386e2902006-10-21 05:08:28 +0000293 // If OldBB isn't immediately before OldBB, insert a branch to it.
294 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
295 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000296 OldBB->addSuccessor(NewDest);
297 ++NumTailMerge;
298}
299
Chris Lattner1d08d832006-11-01 01:16:12 +0000300/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
301/// MBB so that the part before the iterator falls into the part starting at the
302/// iterator. This returns the new MBB.
303MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
304 MachineBasicBlock::iterator BBI1) {
305 // Create the fall-through block.
306 MachineFunction::iterator MBBI = &CurMBB;
307 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
308 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
309
310 // Move all the successors of this block to the specified block.
311 while (!CurMBB.succ_empty()) {
312 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
313 NewMBB->addSuccessor(S);
314 CurMBB.removeSuccessor(S);
315 }
316
317 // Add an edge from CurMBB to NewMBB for the fall-through.
318 CurMBB.addSuccessor(NewMBB);
319
320 // Splice the code over.
321 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000322
323 // For targets that use the register scavenger, we must maintain LiveIns.
324 if (RS) {
325 RS->enterBasicBlock(&CurMBB);
326 if (!CurMBB.empty())
327 RS->forward(prior(CurMBB.end()));
328 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
329 RS->getRegsUsed(RegsLiveAtExit, false);
330 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
331 if (RegsLiveAtExit[i])
332 NewMBB->addLiveIn(i);
333 }
334
Chris Lattner1d08d832006-11-01 01:16:12 +0000335 return NewMBB;
336}
337
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000338/// EstimateRuntime - Make a rough estimate for how long it will take to run
339/// the specified code.
340static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
341 MachineBasicBlock::iterator E,
342 const TargetInstrInfo *TII) {
343 unsigned Time = 0;
344 for (; I != E; ++I) {
345 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
346 if (TID.Flags & M_CALL_FLAG)
347 Time += 10;
348 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
349 Time += 2;
350 else
351 ++Time;
352 }
353 return Time;
354}
355
356/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
357/// MBB2I and then insert an unconditional branch in the other block. Determine
358/// which is the best to split
359static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
360 MachineBasicBlock::iterator MBB1I,
361 MachineBasicBlock *MBB2,
362 MachineBasicBlock::iterator MBB2I,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000363 const TargetInstrInfo *TII,
364 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000365 // If one block is the entry block, split the other one; we can't generate
366 // a branch to the entry block, as its label is not emitted.
367 MachineBasicBlock *Entry = MBB1->getParent()->begin();
368 if (MBB1 == Entry)
369 return false;
370 if (MBB2 == Entry)
371 return true;
372
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000373 // If one block falls through into the common successor, choose that
374 // one to split; it is one instruction less to do that.
375 if (PredBB) {
376 if (MBB1 == PredBB)
377 return true;
378 else if (MBB2 == PredBB)
379 return false;
380 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000381 // TODO: if we had some notion of which block was hotter, we could split
382 // the hot block, so it is the fall-through. Since we don't have profile info
383 // make a decision based on which will hurt most to split.
384 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
385 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
386
387 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
388 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
389 // have a lower overall impact on the program execution.
390 return MBB1Time < MBB2Time;
391}
392
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000393// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
394// branches temporarily for tail merging). In the case where CurMBB ends
395// with a conditional branch to the next block, optimize by reversing the
396// test and conditionally branching to SuccMBB instead.
397
398static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
399 const TargetInstrInfo *TII) {
400 MachineFunction *MF = CurMBB->getParent();
401 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
402 MachineBasicBlock *TBB = 0, *FBB = 0;
403 std::vector<MachineOperand> Cond;
404 if (I != MF->end() &&
405 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
406 MachineBasicBlock *NextBB = I;
407 if (TBB == NextBB && Cond.size() && !FBB) {
408 if (!TII->ReverseBranchCondition(Cond)) {
409 TII->RemoveBranch(*CurMBB);
410 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
411 return;
412 }
413 }
414 }
415 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
416}
417
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000418// See if any of the blocks in MergePotentials (which all have a common single
419// successor, or all have no successor) can be tail-merged. If there is a
420// successor, any blocks in MergePotentials that are not tail-merged and
421// are not immediately before Succ must have an unconditional branch to
422// Succ added (but the predecessor/successor lists need no adjustment).
423// The lone predecessor of Succ that falls through into Succ,
424// if any, is given in PredBB.
425
426bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
427 MachineBasicBlock* PredBB) {
Chris Lattner12143052006-10-21 00:47:49 +0000428 MadeChange = false;
429
Chris Lattner12143052006-10-21 00:47:49 +0000430 // Sort by hash value so that blocks with identical end sequences sort
431 // together.
432 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
433
434 // Walk through equivalence sets looking for actual exact matches.
435 while (MergePotentials.size() > 1) {
436 unsigned CurHash = (MergePotentials.end()-1)->first;
437 unsigned PrevHash = (MergePotentials.end()-2)->first;
438 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
439
440 // If there is nothing that matches the hash of the current basic block,
441 // give up.
442 if (CurHash != PrevHash) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000443 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000444 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000445 MergePotentials.pop_back();
446 continue;
447 }
448
449 // Determine the actual length of the shared tail between these two basic
450 // blocks. Because the hash can have collisions, it's possible that this is
451 // less than 2.
452 MachineBasicBlock::iterator BBI1, BBI2;
453 unsigned CommonTailLen =
454 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
455 BBI1, BBI2);
456
457 // If the tails don't have at least two instructions in common, see if there
458 // is anything else in the equivalence class that does match.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000459 // Since instructions may get combined later (e.g. single stores into
460 // store multiple) this measure is not particularly accurate.
Chris Lattner12143052006-10-21 00:47:49 +0000461 if (CommonTailLen < 2) {
462 unsigned FoundMatch = ~0U;
463 for (int i = MergePotentials.size()-2;
464 i != -1 && MergePotentials[i].first == CurHash; --i) {
465 CommonTailLen = ComputeCommonTailLength(CurMBB,
466 MergePotentials[i].second,
467 BBI1, BBI2);
468 if (CommonTailLen >= 2) {
469 FoundMatch = i;
470 break;
471 }
472 }
473
474 // If we didn't find anything that has at least two instructions matching
475 // this one, bail out.
476 if (FoundMatch == ~0U) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000477 // Put the unconditional branch back, if we need one.
478 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000479 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000480 MergePotentials.pop_back();
481 continue;
482 }
483
484 // Otherwise, move the matching block to the right position.
485 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
486 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000487
Chris Lattner12143052006-10-21 00:47:49 +0000488 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000489
490 // If neither block is the entire common tail, split the tail of one block
Dale Johannesen54f4a672007-05-10 23:59:23 +0000491 // to make it redundant with the other tail. Also, we cannot jump to the
492 // entry block, so if one block is the entry block, split the other one.
493 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
494 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
495 ; // CurMBB is common tail
496 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
497 ; // MBB2 is common tail
498 else {
Chris Lattner1d08d832006-11-01 01:16:12 +0000499 if (0) { // Enable this to disable partial tail merges.
500 MergePotentials.pop_back();
501 continue;
502 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000503
504 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000505 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000506 CurMBB = SplitMBBAt(*CurMBB, BBI1);
507 BBI1 = CurMBB->begin();
508 MergePotentials.back().second = CurMBB;
509 } else {
510 MBB2 = SplitMBBAt(*MBB2, BBI2);
511 BBI2 = MBB2->begin();
512 (MergePotentials.end()-2)->second = MBB2;
513 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000514 }
515
Dale Johannesen54f4a672007-05-10 23:59:23 +0000516 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner12143052006-10-21 00:47:49 +0000517 // Hack the end off CurMBB, making it jump to MBBI@ instead.
518 ReplaceTailWithBranchTo(BBI1, MBB2);
519 // This modifies CurMBB, so remove it from the worklist.
520 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000521 } else {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000522 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
523 "Didn't split block correctly?");
Chris Lattner1d08d832006-11-01 01:16:12 +0000524 // Hack the end off MBB2, making it jump to CurMBB instead.
525 ReplaceTailWithBranchTo(BBI2, CurMBB);
526 // This modifies MBB2, so remove it from the worklist.
527 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000528 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000529 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000530 }
Chris Lattner12143052006-10-21 00:47:49 +0000531 return MadeChange;
532}
533
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000534bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000535
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000536 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000537
538 MadeChange = false;
539
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000540 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000541 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000542 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
543 if (I->succ_empty())
544 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
545 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000546 // See if we can do any tail merging on those.
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000547 MadeChange |= TryMergeBlocks(NULL, NULL);
548
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000549 // Look at blocks (IBB) with multiple predecessors (PBB).
550 // We change each predecessor to a canonical form, by
551 // (1) temporarily removing any unconditional branch from the predecessor
552 // to IBB, and
553 // (2) alter conditional branches so they branch to the other block
554 // not IBB; this may require adding back an unconditional branch to IBB
555 // later, where there wasn't one coming in. E.g.
556 // Bcc IBB
557 // fallthrough to QBB
558 // here becomes
559 // Bncc QBB
560 // with a conceptual B to IBB after that, which never actually exists.
561 // With those changes, we see whether the predecessors' tails match,
562 // and merge them if so. We change things out of canonical form and
563 // back to the way they were later in the process. (OptimizeBranches
564 // would undo some of this, but we can't use it, because we'd get into
565 // a compile-time infinite loop repeatedly doing and undoing the same
566 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000567
568 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
569 if (!I->succ_empty() && I->pred_size() >= 2) {
570 MachineBasicBlock *IBB = I;
571 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000572 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000573 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
574 P != E2; ++P) {
575 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000576 // Skip blocks that loop to themselves, can't tail merge these.
577 if (PBB==IBB)
578 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000579 MachineBasicBlock *TBB = 0, *FBB = 0;
580 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000581 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
582 // Failing case: IBB is the target of a cbr, and
583 // we cannot reverse the branch.
584 std::vector<MachineOperand> NewCond(Cond);
585 if (Cond.size() && TBB==IBB) {
586 if (TII->ReverseBranchCondition(NewCond))
587 continue;
588 // This is the QBB case described above
589 if (!FBB)
590 FBB = next(MachineFunction::iterator(PBB));
591 }
592 // Remove the unconditional branch at the end, if any.
593 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000594 TII->RemoveBranch(*PBB);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000595 if (Cond.size())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000596 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000597 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000598 }
599 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB), *P));
600 }
601 }
602 if (MergePotentials.size() >= 2)
603 MadeChange |= TryMergeBlocks(I, PredBB);
604 // Reinsert an unconditional branch if needed.
605 // The 1 below can be either an original single predecessor, or a result
606 // of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000607 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000608 if (MergePotentials.size()==1 &&
609 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000610 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000611 }
612 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000613 return MadeChange;
614}
Chris Lattner12143052006-10-21 00:47:49 +0000615
616//===----------------------------------------------------------------------===//
617// Branch Optimization
618//===----------------------------------------------------------------------===//
619
620bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
621 MadeChange = false;
622
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000623 // Make sure blocks are numbered in order
624 MF.RenumberBlocks();
625
Chris Lattner12143052006-10-21 00:47:49 +0000626 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
627 MachineBasicBlock *MBB = I++;
628 OptimizeBlock(MBB);
629
630 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000631 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000632 RemoveDeadBlock(MBB);
633 MadeChange = true;
634 ++NumDeadBlocks;
635 }
636 }
637 return MadeChange;
638}
639
640
Chris Lattner386e2902006-10-21 05:08:28 +0000641/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
642/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
643/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
644/// be null.
645static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
646 MachineBasicBlock *DestA,
647 MachineBasicBlock *DestB,
648 bool isCond,
649 MachineFunction::iterator FallThru) {
650 bool MadeChange = false;
651 bool AddedFallThrough = false;
652
653 // If this block ends with a conditional branch that falls through to its
654 // successor, set DestB as the successor.
655 if (isCond) {
656 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
657 DestB = FallThru;
658 AddedFallThrough = true;
659 }
660 } else {
661 // If this is an unconditional branch with no explicit dest, it must just be
662 // a fallthrough into DestB.
663 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
664 DestA = FallThru;
665 AddedFallThrough = true;
666 }
667 }
668
669 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
670 while (SI != MBB.succ_end()) {
671 if (*SI == DestA) {
672 DestA = 0;
673 ++SI;
674 } else if (*SI == DestB) {
675 DestB = 0;
676 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000677 } else if ((*SI)->isLandingPad()) {
678 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000679 } else {
680 // Otherwise, this is a superfluous edge, remove it.
681 MBB.removeSuccessor(SI);
682 MadeChange = true;
683 }
684 }
685 if (!AddedFallThrough) {
686 assert(DestA == 0 && DestB == 0 &&
687 "MachineCFG is missing edges!");
688 } else if (isCond) {
689 assert(DestA == 0 && "MachineCFG is missing edges!");
690 }
691 return MadeChange;
692}
693
694
Chris Lattner21ab22e2004-07-31 10:01:27 +0000695/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
696/// 'Old', change the code and CFG so that it branches to 'New' instead.
697static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
698 MachineBasicBlock *Old,
699 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000700 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000701 assert(Old != New && "Cannot replace self with self!");
702
703 MachineBasicBlock::iterator I = BB->end();
704 while (I != BB->begin()) {
705 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000706 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000707
708 // Scan the operands of this machine instruction, replacing any uses of Old
709 // with New.
710 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
711 if (I->getOperand(i).isMachineBasicBlock() &&
712 I->getOperand(i).getMachineBasicBlock() == Old)
713 I->getOperand(i).setMachineBasicBlock(New);
714 }
715
Chris Lattnereb15eee2006-10-13 20:43:10 +0000716 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000717 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
718 for (int i = Succs.size()-1; i >= 0; --i)
719 if (Succs[i] == Old) {
720 BB->removeSuccessor(Old);
721 BB->addSuccessor(New);
722 }
723}
724
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000725/// CanFallThrough - Return true if the specified block (with the specified
726/// branch condition) can implicitly transfer control to the block after it by
727/// falling off the end of it. This should return false if it can reach the
728/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
729///
730/// True is a conservative answer.
731///
732bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
733 bool BranchUnAnalyzable,
734 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
735 const std::vector<MachineOperand> &Cond) {
736 MachineFunction::iterator Fallthrough = CurBB;
737 ++Fallthrough;
738 // If FallthroughBlock is off the end of the function, it can't fall through.
739 if (Fallthrough == CurBB->getParent()->end())
740 return false;
741
742 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
743 if (!CurBB->isSuccessor(Fallthrough))
744 return false;
745
746 // If we couldn't analyze the branch, assume it could fall through.
747 if (BranchUnAnalyzable) return true;
748
Chris Lattner7d097842006-10-24 01:12:32 +0000749 // If there is no branch, control always falls through.
750 if (TBB == 0) return true;
751
752 // If there is some explicit branch to the fallthrough block, it can obviously
753 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000754 if (MachineFunction::iterator(TBB) == Fallthrough ||
755 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000756 return true;
757
758 // If it's an unconditional branch to some block not the fall through, it
759 // doesn't fall through.
760 if (Cond.empty()) return false;
761
762 // Otherwise, if it is conditional and has no explicit false block, it falls
763 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000764 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000765}
766
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000767/// CanFallThrough - Return true if the specified can implicitly transfer
768/// control to the block after it by falling off the end of it. This should
769/// return false if it can reach the block after it, but it uses an explicit
770/// branch to do so (e.g. a table jump).
771///
772/// True is a conservative answer.
773///
774bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
775 MachineBasicBlock *TBB = 0, *FBB = 0;
776 std::vector<MachineOperand> Cond;
777 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
778 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
779}
780
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000781/// IsBetterFallthrough - Return true if it would be clearly better to
782/// fall-through to MBB1 than to fall through into MBB2. This has to return
783/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
784/// result in infinite loops.
785static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
786 MachineBasicBlock *MBB2,
787 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000788 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
789 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000790 // optimize branches that branch to either a return block or an assert block
791 // into a fallthrough to the return.
792 if (MBB1->empty() || MBB2->empty()) return false;
793
794 MachineInstr *MBB1I = --MBB1->end();
795 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000796 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000797}
798
Chris Lattner7821a8a2006-10-14 00:21:48 +0000799/// OptimizeBlock - Analyze and optimize control flow related to the specified
800/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000801void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
802 MachineFunction::iterator FallThrough = MBB;
803 ++FallThrough;
804
Chris Lattnereb15eee2006-10-13 20:43:10 +0000805 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000806 // explicitly.
807 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000808 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000809 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000810
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000811 if (FallThrough == MBB->getParent()->end()) {
812 // TODO: Simplify preds to not branch here if possible!
813 } else {
814 // Rewrite all predecessors of the old block to go to the fallthrough
815 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000816 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000817 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
818 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
819 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000820
821 // If MBB was the target of a jump table, update jump tables to go to the
822 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000823 MBB->getParent()->getJumpTableInfo()->
824 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000825 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000826 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000827 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000828 }
829
Chris Lattner7821a8a2006-10-14 00:21:48 +0000830 // Check to see if we can simplify the terminator of the block before this
831 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000832 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000833
Chris Lattner7821a8a2006-10-14 00:21:48 +0000834 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
835 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000836 bool PriorUnAnalyzable =
837 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000838 if (!PriorUnAnalyzable) {
839 // If the CFG for the prior block has extra edges, remove them.
840 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
841 !PriorCond.empty(), MBB);
842
Chris Lattner7821a8a2006-10-14 00:21:48 +0000843 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000844 // destination, remove the branch, replacing it with an unconditional one or
845 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000846 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000847 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000848 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000849 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000850 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000851 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000852 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000853 return OptimizeBlock(MBB);
854 }
855
856 // If the previous branch *only* branches to *this* block (conditional or
857 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000858 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000859 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000860 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000861 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000862 return OptimizeBlock(MBB);
863 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000864
865 // If the prior block branches somewhere else on the condition and here if
866 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000867 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000868 TII->RemoveBranch(PrevBB);
869 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
870 MadeChange = true;
871 ++NumBranchOpts;
872 return OptimizeBlock(MBB);
873 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000874
875 // If the prior block branches here on true and somewhere else on false, and
876 // if the branch condition is reversible, reverse the branch to create a
877 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000878 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000879 std::vector<MachineOperand> NewPriorCond(PriorCond);
880 if (!TII->ReverseBranchCondition(NewPriorCond)) {
881 TII->RemoveBranch(PrevBB);
882 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
883 MadeChange = true;
884 ++NumBranchOpts;
885 return OptimizeBlock(MBB);
886 }
887 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000888
Chris Lattner154e1042006-11-18 21:30:35 +0000889 // If this block doesn't fall through (e.g. it ends with an uncond branch or
890 // has no successors) and if the pred falls through into this block, and if
891 // it would otherwise fall through into the block after this, move this
892 // block to the end of the function.
893 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000894 // We consider it more likely that execution will stay in the function (e.g.
895 // due to loops) than it is to exit it. This asserts in loops etc, moving
896 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000897 if (!PriorCond.empty() && PriorFBB == 0 &&
898 MachineFunction::iterator(PriorTBB) == FallThrough &&
899 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000900 bool DoTransform = true;
901
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000902 // We have to be careful that the succs of PredBB aren't both no-successor
903 // blocks. If neither have successors and if PredBB is the second from
904 // last block in the function, we'd just keep swapping the two blocks for
905 // last. Only do the swap if one is clearly better to fall through than
906 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000907 if (FallThrough == --MBB->getParent()->end() &&
908 !IsBetterFallthrough(PriorTBB, MBB, *TII))
909 DoTransform = false;
910
911 // We don't want to do this transformation if we have control flow like:
912 // br cond BB2
913 // BB1:
914 // ..
915 // jmp BBX
916 // BB2:
917 // ..
918 // ret
919 //
920 // In this case, we could actually be moving the return block *into* a
921 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000922 if (DoTransform && !MBB->succ_empty() &&
923 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000924 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000925
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000926
927 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000928 // Reverse the branch so we will fall through on the previous true cond.
929 std::vector<MachineOperand> NewPriorCond(PriorCond);
930 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000931 DOUT << "\nMoving MBB: " << *MBB;
932 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
933
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000934 TII->RemoveBranch(PrevBB);
935 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
936
937 // Move this block to the end of the function.
938 MBB->moveAfter(--MBB->getParent()->end());
939 MadeChange = true;
940 ++NumBranchOpts;
941 return;
942 }
943 }
944 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000945 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000946
Chris Lattner386e2902006-10-21 05:08:28 +0000947 // Analyze the branch in the current block.
948 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
949 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000950 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
951 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000952 // If the CFG for the prior block has extra edges, remove them.
953 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000954 !CurCond.empty(),
955 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000956
Chris Lattner5d056952006-11-08 01:03:21 +0000957 // If this is a two-way branch, and the FBB branches to this block, reverse
958 // the condition so the single-basic-block loop is faster. Instead of:
959 // Loop: xxx; jcc Out; jmp Loop
960 // we want:
961 // Loop: xxx; jncc Loop; jmp Out
962 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
963 std::vector<MachineOperand> NewCond(CurCond);
964 if (!TII->ReverseBranchCondition(NewCond)) {
965 TII->RemoveBranch(*MBB);
966 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
967 MadeChange = true;
968 ++NumBranchOpts;
969 return OptimizeBlock(MBB);
970 }
971 }
972
973
Chris Lattner386e2902006-10-21 05:08:28 +0000974 // If this branch is the only thing in its block, see if we can forward
975 // other blocks across it.
976 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000977 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000978 // This block may contain just an unconditional branch. Because there can
979 // be 'non-branch terminators' in the block, try removing the branch and
980 // then seeing if the block is empty.
981 TII->RemoveBranch(*MBB);
982
983 // If this block is just an unconditional branch to CurTBB, we can
984 // usually completely eliminate the block. The only case we cannot
985 // completely eliminate the block is when the block before this one
986 // falls through into MBB and we can't understand the prior block's branch
987 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000988 if (MBB->empty()) {
989 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
990 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
991 !PrevBB.isSuccessor(MBB)) {
992 // If the prior block falls through into us, turn it into an
993 // explicit branch to us to make updates simpler.
994 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
995 PriorTBB != MBB && PriorFBB != MBB) {
996 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000997 assert(PriorCond.empty() && PriorFBB == 0 &&
998 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000999 PriorTBB = MBB;
1000 } else {
1001 assert(PriorFBB == 0 && "Machine CFG out of date!");
1002 PriorFBB = MBB;
1003 }
1004 TII->RemoveBranch(PrevBB);
1005 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001006 }
Chris Lattner386e2902006-10-21 05:08:28 +00001007
Chris Lattnercf420cc2006-10-28 17:32:47 +00001008 // Iterate through all the predecessors, revectoring each in-turn.
1009 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1010 bool DidChange = false;
1011 bool HasBranchToSelf = false;
1012 while (PI != MBB->pred_end()) {
1013 if (*PI == MBB) {
1014 // If this block has an uncond branch to itself, leave it.
1015 ++PI;
1016 HasBranchToSelf = true;
1017 } else {
1018 DidChange = true;
1019 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1020 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001021 }
Chris Lattner386e2902006-10-21 05:08:28 +00001022
Chris Lattnercf420cc2006-10-28 17:32:47 +00001023 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001024 MBB->getParent()->getJumpTableInfo()->
1025 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001026 if (DidChange) {
1027 ++NumBranchOpts;
1028 MadeChange = true;
1029 if (!HasBranchToSelf) return;
1030 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001031 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001032 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001033
Chris Lattner386e2902006-10-21 05:08:28 +00001034 // Add the branch back if the block is more than just an uncond branch.
1035 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001036 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001037 }
1038
1039 // If the prior block doesn't fall through into this block, and if this
1040 // block doesn't fall through into some other block, see if we can find a
1041 // place to move this block where a fall-through will happen.
1042 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1043 PriorTBB, PriorFBB, PriorCond)) {
1044 // Now we know that there was no fall-through into this block, check to
1045 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001046 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001047 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001048
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001049 if (!MBB->isLandingPad()) {
1050 // Check all the predecessors of this block. If one of them has no fall
1051 // throughs, move this block right after it.
1052 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1053 E = MBB->pred_end(); PI != E; ++PI) {
1054 // Analyze the branch at the end of the pred.
1055 MachineBasicBlock *PredBB = *PI;
1056 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1057 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001058 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001059 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1060 // If the current block doesn't fall through, just move it.
1061 // If the current block can fall through and does not end with a
1062 // conditional branch, we need to append an unconditional jump to
1063 // the (current) next block. To avoid a possible compile-time
1064 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001065 // Also, if there are already 2 branches here, we cannot add a third;
1066 // this means we have the case
1067 // Bcc next
1068 // B elsewhere
1069 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001070 if (CurFallsThru) {
1071 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1072 CurCond.clear();
1073 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1074 }
1075 MBB->moveAfter(PredBB);
1076 MadeChange = true;
1077 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001078 }
1079 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001080 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001081
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001082 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001083 // Check all successors to see if we can move this block before it.
1084 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1085 E = MBB->succ_end(); SI != E; ++SI) {
1086 // Analyze the branch at the end of the block before the succ.
1087 MachineBasicBlock *SuccBB = *SI;
1088 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001089 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001090
1091 // If this block doesn't already fall-through to that successor, and if
1092 // the succ doesn't already have a block that can fall through into it,
1093 // and if the successor isn't an EH destination, we can arrange for the
1094 // fallthrough to happen.
1095 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1096 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001097 MBB->moveBefore(SuccBB);
1098 MadeChange = true;
1099 return OptimizeBlock(MBB);
1100 }
1101 }
1102
1103 // Okay, there is no really great place to put this block. If, however,
1104 // the block before this one would be a fall-through if this block were
1105 // removed, move this block to the end of the function.
1106 if (FallThrough != MBB->getParent()->end() &&
1107 PrevBB.isSuccessor(FallThrough)) {
1108 MBB->moveAfter(--MBB->getParent()->end());
1109 MadeChange = true;
1110 return;
1111 }
Chris Lattner7d097842006-10-24 01:12:32 +00001112 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001113 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001114}