blob: afaaf519524a880d94adc8c2c4db414113f452f5 [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
Dale Johannesen7aea8322007-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 Lattner12143052006-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 Johannesen7aea8322007-05-23 21:07:20 +0000253 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner12143052006-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 Lattner386e2902006-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 Lattner12143052006-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 Lattner386e2902006-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 Lattner12143052006-10-21 00:47:49 +0000301 OldBB->addSuccessor(NewDest);
302 ++NumTailMerge;
303}
304
Chris Lattner1d08d832006-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 Johannesen69cb9b72007-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 Lattner1d08d832006-11-01 01:16:12 +0000340 return NewMBB;
341}
342
Chris Lattnerd4bf3c22006-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 Johannesen76b38fc2007-05-10 01:01:49 +0000368 const TargetInstrInfo *TII,
369 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-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 Johannesen76b38fc2007-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 Lattnerd4bf3c22006-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 Johannesen76b38fc2007-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 Johannesen7d33b4c2007-05-07 20:57:21 +0000423// See if any of the blocks in MergePotentials (which all have a common single
424// successor, or all have no successor) can be tail-merged. If there is a
425// successor, any blocks in MergePotentials that are not tail-merged and
426// are not immediately before Succ must have an unconditional branch to
427// Succ added (but the predecessor/successor lists need no adjustment).
428// The lone predecessor of Succ that falls through into Succ,
429// if any, is given in PredBB.
430
431bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
432 MachineBasicBlock* PredBB) {
Dale Johannesen7aea8322007-05-23 21:07:20 +0000433 unsigned minCommonTailLength = (SuccBB ? 1 : 2);
Chris Lattner12143052006-10-21 00:47:49 +0000434 MadeChange = false;
435
Chris Lattner12143052006-10-21 00:47:49 +0000436 // Sort by hash value so that blocks with identical end sequences sort
437 // together.
438 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
439
440 // Walk through equivalence sets looking for actual exact matches.
441 while (MergePotentials.size() > 1) {
442 unsigned CurHash = (MergePotentials.end()-1)->first;
443 unsigned PrevHash = (MergePotentials.end()-2)->first;
444 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
445
446 // If there is nothing that matches the hash of the current basic block,
447 // give up.
448 if (CurHash != PrevHash) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000449 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000450 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000451 MergePotentials.pop_back();
452 continue;
453 }
454
Dale Johannesen7aea8322007-05-23 21:07:20 +0000455 // Look through all the blocks that have the same hash as this one, and
456 // find the one that has the largest number of instructions in common.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000457 // Since instructions may get combined later (e.g. single stores into
458 // store multiple) this measure is not particularly accurate.
Dale Johannesen7aea8322007-05-23 21:07:20 +0000459 MachineBasicBlock::iterator BBI1, BBI2;
460
461 unsigned FoundMatch = ~0U;
462 unsigned maxCommonTailLength = 0U;
463 for (int i = MergePotentials.size()-2;
464 i != -1 && MergePotentials[i].first == CurHash; --i) {
465 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
466 unsigned CommonTailLen = ComputeCommonTailLength(CurMBB,
467 MergePotentials[i].second,
468 TrialBBI1, TrialBBI2);
469 if (CommonTailLen >= minCommonTailLength &&
470 CommonTailLen >= maxCommonTailLength) {
471 FoundMatch = i;
472 maxCommonTailLength = CommonTailLen;
473 BBI1 = TrialBBI1;
474 BBI2 = TrialBBI2;
Chris Lattner12143052006-10-21 00:47:49 +0000475 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000476 }
477
478 // If we didn't find anything that has at least minCommonTailLength
479 // instructions matching this one, bail out.
480 if (FoundMatch == ~0U) {
481 // Put the unconditional branch back, if we need one.
482 if (SuccBB && CurMBB != PredBB)
483 FixTail(CurMBB, SuccBB, TII);
484 MergePotentials.pop_back();
485 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000486 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000487
488 // Otherwise, move the matching block to the right position.
489 if (FoundMatch != MergePotentials.size()-2)
490 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
Chris Lattner1d08d832006-11-01 01:16:12 +0000491
Chris Lattner12143052006-10-21 00:47:49 +0000492 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000493
494 // If neither block is the entire common tail, split the tail of one block
Dale Johannesen54f4a672007-05-10 23:59:23 +0000495 // to make it redundant with the other tail. Also, we cannot jump to the
496 // entry block, so if one block is the entry block, split the other one.
497 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
498 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
499 ; // CurMBB is common tail
500 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
501 ; // MBB2 is common tail
502 else {
Chris Lattner1d08d832006-11-01 01:16:12 +0000503 if (0) { // Enable this to disable partial tail merges.
504 MergePotentials.pop_back();
505 continue;
506 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000507
508 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000509 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000510 CurMBB = SplitMBBAt(*CurMBB, BBI1);
511 BBI1 = CurMBB->begin();
512 MergePotentials.back().second = CurMBB;
513 } else {
514 MBB2 = SplitMBBAt(*MBB2, BBI2);
515 BBI2 = MBB2->begin();
516 (MergePotentials.end()-2)->second = MBB2;
517 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000518 }
519
Dale Johannesen54f4a672007-05-10 23:59:23 +0000520 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner12143052006-10-21 00:47:49 +0000521 // Hack the end off CurMBB, making it jump to MBBI@ instead.
522 ReplaceTailWithBranchTo(BBI1, MBB2);
523 // This modifies CurMBB, so remove it from the worklist.
524 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000525 } else {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000526 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
527 "Didn't split block correctly?");
Chris Lattner1d08d832006-11-01 01:16:12 +0000528 // Hack the end off MBB2, making it jump to CurMBB instead.
529 ReplaceTailWithBranchTo(BBI2, CurMBB);
530 // This modifies MBB2, so remove it from the worklist.
531 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000532 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000533 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000534 }
Chris Lattner12143052006-10-21 00:47:49 +0000535 return MadeChange;
536}
537
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000538bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000539
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000540 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000541
542 MadeChange = false;
543
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000544 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000545 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000546 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
547 if (I->succ_empty())
Dale Johannesen7aea8322007-05-23 21:07:20 +0000548 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000549 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000550 // See if we can do any tail merging on those.
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000551 MadeChange |= TryMergeBlocks(NULL, NULL);
552
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000553 // Look at blocks (IBB) with multiple predecessors (PBB).
554 // We change each predecessor to a canonical form, by
555 // (1) temporarily removing any unconditional branch from the predecessor
556 // to IBB, and
557 // (2) alter conditional branches so they branch to the other block
558 // not IBB; this may require adding back an unconditional branch to IBB
559 // later, where there wasn't one coming in. E.g.
560 // Bcc IBB
561 // fallthrough to QBB
562 // here becomes
563 // Bncc QBB
564 // with a conceptual B to IBB after that, which never actually exists.
565 // With those changes, we see whether the predecessors' tails match,
566 // and merge them if so. We change things out of canonical form and
567 // back to the way they were later in the process. (OptimizeBranches
568 // would undo some of this, but we can't use it, because we'd get into
569 // a compile-time infinite loop repeatedly doing and undoing the same
570 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000571
572 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
573 if (!I->succ_empty() && I->pred_size() >= 2) {
574 MachineBasicBlock *IBB = I;
575 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000576 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000577 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
578 P != E2; ++P) {
579 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000580 // Skip blocks that loop to themselves, can't tail merge these.
581 if (PBB==IBB)
582 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000583 MachineBasicBlock *TBB = 0, *FBB = 0;
584 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000585 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
586 // Failing case: IBB is the target of a cbr, and
587 // we cannot reverse the branch.
588 std::vector<MachineOperand> NewCond(Cond);
589 if (Cond.size() && TBB==IBB) {
590 if (TII->ReverseBranchCondition(NewCond))
591 continue;
592 // This is the QBB case described above
593 if (!FBB)
594 FBB = next(MachineFunction::iterator(PBB));
595 }
596 // Remove the unconditional branch at the end, if any.
597 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000598 TII->RemoveBranch(*PBB);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000599 if (Cond.size())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000600 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000601 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000602 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000603 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000604 }
605 }
606 if (MergePotentials.size() >= 2)
607 MadeChange |= TryMergeBlocks(I, PredBB);
608 // Reinsert an unconditional branch if needed.
609 // The 1 below can be either an original single predecessor, or a result
610 // of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000611 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000612 if (MergePotentials.size()==1 &&
613 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000614 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000615 }
616 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000617 return MadeChange;
618}
Chris Lattner12143052006-10-21 00:47:49 +0000619
620//===----------------------------------------------------------------------===//
621// Branch Optimization
622//===----------------------------------------------------------------------===//
623
624bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
625 MadeChange = false;
626
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000627 // Make sure blocks are numbered in order
628 MF.RenumberBlocks();
629
Chris Lattner12143052006-10-21 00:47:49 +0000630 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
631 MachineBasicBlock *MBB = I++;
632 OptimizeBlock(MBB);
633
634 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000635 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000636 RemoveDeadBlock(MBB);
637 MadeChange = true;
638 ++NumDeadBlocks;
639 }
640 }
641 return MadeChange;
642}
643
644
Chris Lattner386e2902006-10-21 05:08:28 +0000645/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
646/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
647/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
648/// be null.
649static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
650 MachineBasicBlock *DestA,
651 MachineBasicBlock *DestB,
652 bool isCond,
653 MachineFunction::iterator FallThru) {
654 bool MadeChange = false;
655 bool AddedFallThrough = false;
656
657 // If this block ends with a conditional branch that falls through to its
658 // successor, set DestB as the successor.
659 if (isCond) {
660 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
661 DestB = FallThru;
662 AddedFallThrough = true;
663 }
664 } else {
665 // If this is an unconditional branch with no explicit dest, it must just be
666 // a fallthrough into DestB.
667 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
668 DestA = FallThru;
669 AddedFallThrough = true;
670 }
671 }
672
673 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
674 while (SI != MBB.succ_end()) {
675 if (*SI == DestA) {
676 DestA = 0;
677 ++SI;
678 } else if (*SI == DestB) {
679 DestB = 0;
680 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000681 } else if ((*SI)->isLandingPad()) {
682 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000683 } else {
684 // Otherwise, this is a superfluous edge, remove it.
685 MBB.removeSuccessor(SI);
686 MadeChange = true;
687 }
688 }
689 if (!AddedFallThrough) {
690 assert(DestA == 0 && DestB == 0 &&
691 "MachineCFG is missing edges!");
692 } else if (isCond) {
693 assert(DestA == 0 && "MachineCFG is missing edges!");
694 }
695 return MadeChange;
696}
697
698
Chris Lattner21ab22e2004-07-31 10:01:27 +0000699/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
700/// 'Old', change the code and CFG so that it branches to 'New' instead.
701static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
702 MachineBasicBlock *Old,
703 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000704 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000705 assert(Old != New && "Cannot replace self with self!");
706
707 MachineBasicBlock::iterator I = BB->end();
708 while (I != BB->begin()) {
709 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000710 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000711
712 // Scan the operands of this machine instruction, replacing any uses of Old
713 // with New.
714 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
715 if (I->getOperand(i).isMachineBasicBlock() &&
716 I->getOperand(i).getMachineBasicBlock() == Old)
717 I->getOperand(i).setMachineBasicBlock(New);
718 }
719
Chris Lattnereb15eee2006-10-13 20:43:10 +0000720 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000721 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
722 for (int i = Succs.size()-1; i >= 0; --i)
723 if (Succs[i] == Old) {
724 BB->removeSuccessor(Old);
725 BB->addSuccessor(New);
726 }
727}
728
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000729/// CanFallThrough - Return true if the specified block (with the specified
730/// branch condition) can implicitly transfer control to the block after it by
731/// falling off the end of it. This should return false if it can reach the
732/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
733///
734/// True is a conservative answer.
735///
736bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
737 bool BranchUnAnalyzable,
738 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
739 const std::vector<MachineOperand> &Cond) {
740 MachineFunction::iterator Fallthrough = CurBB;
741 ++Fallthrough;
742 // If FallthroughBlock is off the end of the function, it can't fall through.
743 if (Fallthrough == CurBB->getParent()->end())
744 return false;
745
746 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
747 if (!CurBB->isSuccessor(Fallthrough))
748 return false;
749
750 // If we couldn't analyze the branch, assume it could fall through.
751 if (BranchUnAnalyzable) return true;
752
Chris Lattner7d097842006-10-24 01:12:32 +0000753 // If there is no branch, control always falls through.
754 if (TBB == 0) return true;
755
756 // If there is some explicit branch to the fallthrough block, it can obviously
757 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000758 if (MachineFunction::iterator(TBB) == Fallthrough ||
759 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000760 return true;
761
762 // If it's an unconditional branch to some block not the fall through, it
763 // doesn't fall through.
764 if (Cond.empty()) return false;
765
766 // Otherwise, if it is conditional and has no explicit false block, it falls
767 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000768 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000769}
770
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000771/// CanFallThrough - Return true if the specified can implicitly transfer
772/// control to the block after it by falling off the end of it. This should
773/// return false if it can reach the block after it, but it uses an explicit
774/// branch to do so (e.g. a table jump).
775///
776/// True is a conservative answer.
777///
778bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
779 MachineBasicBlock *TBB = 0, *FBB = 0;
780 std::vector<MachineOperand> Cond;
781 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
782 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
783}
784
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000785/// IsBetterFallthrough - Return true if it would be clearly better to
786/// fall-through to MBB1 than to fall through into MBB2. This has to return
787/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
788/// result in infinite loops.
789static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
790 MachineBasicBlock *MBB2,
791 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000792 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
793 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000794 // optimize branches that branch to either a return block or an assert block
795 // into a fallthrough to the return.
796 if (MBB1->empty() || MBB2->empty()) return false;
797
798 MachineInstr *MBB1I = --MBB1->end();
799 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000800 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000801}
802
Chris Lattner7821a8a2006-10-14 00:21:48 +0000803/// OptimizeBlock - Analyze and optimize control flow related to the specified
804/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000805void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
806 MachineFunction::iterator FallThrough = MBB;
807 ++FallThrough;
808
Chris Lattnereb15eee2006-10-13 20:43:10 +0000809 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000810 // explicitly.
811 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000812 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000813 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000814
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000815 if (FallThrough == MBB->getParent()->end()) {
816 // TODO: Simplify preds to not branch here if possible!
817 } else {
818 // Rewrite all predecessors of the old block to go to the fallthrough
819 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000820 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000821 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
822 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
823 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000824
825 // If MBB was the target of a jump table, update jump tables to go to the
826 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000827 MBB->getParent()->getJumpTableInfo()->
828 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000829 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000830 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000831 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000832 }
833
Chris Lattner7821a8a2006-10-14 00:21:48 +0000834 // Check to see if we can simplify the terminator of the block before this
835 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000836 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000837
Chris Lattner7821a8a2006-10-14 00:21:48 +0000838 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
839 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000840 bool PriorUnAnalyzable =
841 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000842 if (!PriorUnAnalyzable) {
843 // If the CFG for the prior block has extra edges, remove them.
844 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
845 !PriorCond.empty(), MBB);
846
Chris Lattner7821a8a2006-10-14 00:21:48 +0000847 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000848 // destination, remove the branch, replacing it with an unconditional one or
849 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000850 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000851 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000852 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000853 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000854 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000855 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000856 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000857 return OptimizeBlock(MBB);
858 }
859
860 // If the previous branch *only* branches to *this* block (conditional or
861 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000862 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000863 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000864 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000865 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000866 return OptimizeBlock(MBB);
867 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000868
869 // If the prior block branches somewhere else on the condition and here if
870 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000871 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000872 TII->RemoveBranch(PrevBB);
873 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
874 MadeChange = true;
875 ++NumBranchOpts;
876 return OptimizeBlock(MBB);
877 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000878
879 // If the prior block branches here on true and somewhere else on false, and
880 // if the branch condition is reversible, reverse the branch to create a
881 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000882 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000883 std::vector<MachineOperand> NewPriorCond(PriorCond);
884 if (!TII->ReverseBranchCondition(NewPriorCond)) {
885 TII->RemoveBranch(PrevBB);
886 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
887 MadeChange = true;
888 ++NumBranchOpts;
889 return OptimizeBlock(MBB);
890 }
891 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000892
Chris Lattner154e1042006-11-18 21:30:35 +0000893 // If this block doesn't fall through (e.g. it ends with an uncond branch or
894 // has no successors) and if the pred falls through into this block, and if
895 // it would otherwise fall through into the block after this, move this
896 // block to the end of the function.
897 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000898 // We consider it more likely that execution will stay in the function (e.g.
899 // due to loops) than it is to exit it. This asserts in loops etc, moving
900 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000901 if (!PriorCond.empty() && PriorFBB == 0 &&
902 MachineFunction::iterator(PriorTBB) == FallThrough &&
903 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000904 bool DoTransform = true;
905
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000906 // We have to be careful that the succs of PredBB aren't both no-successor
907 // blocks. If neither have successors and if PredBB is the second from
908 // last block in the function, we'd just keep swapping the two blocks for
909 // last. Only do the swap if one is clearly better to fall through than
910 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000911 if (FallThrough == --MBB->getParent()->end() &&
912 !IsBetterFallthrough(PriorTBB, MBB, *TII))
913 DoTransform = false;
914
915 // We don't want to do this transformation if we have control flow like:
916 // br cond BB2
917 // BB1:
918 // ..
919 // jmp BBX
920 // BB2:
921 // ..
922 // ret
923 //
924 // In this case, we could actually be moving the return block *into* a
925 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000926 if (DoTransform && !MBB->succ_empty() &&
927 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000928 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000929
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000930
931 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000932 // Reverse the branch so we will fall through on the previous true cond.
933 std::vector<MachineOperand> NewPriorCond(PriorCond);
934 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000935 DOUT << "\nMoving MBB: " << *MBB;
936 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
937
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000938 TII->RemoveBranch(PrevBB);
939 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
940
941 // Move this block to the end of the function.
942 MBB->moveAfter(--MBB->getParent()->end());
943 MadeChange = true;
944 ++NumBranchOpts;
945 return;
946 }
947 }
948 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000949 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000950
Chris Lattner386e2902006-10-21 05:08:28 +0000951 // Analyze the branch in the current block.
952 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
953 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000954 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
955 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000956 // If the CFG for the prior block has extra edges, remove them.
957 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000958 !CurCond.empty(),
959 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000960
Chris Lattner5d056952006-11-08 01:03:21 +0000961 // If this is a two-way branch, and the FBB branches to this block, reverse
962 // the condition so the single-basic-block loop is faster. Instead of:
963 // Loop: xxx; jcc Out; jmp Loop
964 // we want:
965 // Loop: xxx; jncc Loop; jmp Out
966 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
967 std::vector<MachineOperand> NewCond(CurCond);
968 if (!TII->ReverseBranchCondition(NewCond)) {
969 TII->RemoveBranch(*MBB);
970 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
971 MadeChange = true;
972 ++NumBranchOpts;
973 return OptimizeBlock(MBB);
974 }
975 }
976
977
Chris Lattner386e2902006-10-21 05:08:28 +0000978 // If this branch is the only thing in its block, see if we can forward
979 // other blocks across it.
980 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000981 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000982 // This block may contain just an unconditional branch. Because there can
983 // be 'non-branch terminators' in the block, try removing the branch and
984 // then seeing if the block is empty.
985 TII->RemoveBranch(*MBB);
986
987 // If this block is just an unconditional branch to CurTBB, we can
988 // usually completely eliminate the block. The only case we cannot
989 // completely eliminate the block is when the block before this one
990 // falls through into MBB and we can't understand the prior block's branch
991 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000992 if (MBB->empty()) {
993 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
994 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
995 !PrevBB.isSuccessor(MBB)) {
996 // If the prior block falls through into us, turn it into an
997 // explicit branch to us to make updates simpler.
998 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
999 PriorTBB != MBB && PriorFBB != MBB) {
1000 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001001 assert(PriorCond.empty() && PriorFBB == 0 &&
1002 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001003 PriorTBB = MBB;
1004 } else {
1005 assert(PriorFBB == 0 && "Machine CFG out of date!");
1006 PriorFBB = MBB;
1007 }
1008 TII->RemoveBranch(PrevBB);
1009 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001010 }
Chris Lattner386e2902006-10-21 05:08:28 +00001011
Chris Lattnercf420cc2006-10-28 17:32:47 +00001012 // Iterate through all the predecessors, revectoring each in-turn.
1013 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1014 bool DidChange = false;
1015 bool HasBranchToSelf = false;
1016 while (PI != MBB->pred_end()) {
1017 if (*PI == MBB) {
1018 // If this block has an uncond branch to itself, leave it.
1019 ++PI;
1020 HasBranchToSelf = true;
1021 } else {
1022 DidChange = true;
1023 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1024 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001025 }
Chris Lattner386e2902006-10-21 05:08:28 +00001026
Chris Lattnercf420cc2006-10-28 17:32:47 +00001027 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001028 MBB->getParent()->getJumpTableInfo()->
1029 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001030 if (DidChange) {
1031 ++NumBranchOpts;
1032 MadeChange = true;
1033 if (!HasBranchToSelf) return;
1034 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001035 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001036 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001037
Chris Lattner386e2902006-10-21 05:08:28 +00001038 // Add the branch back if the block is more than just an uncond branch.
1039 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001040 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001041 }
1042
1043 // If the prior block doesn't fall through into this block, and if this
1044 // block doesn't fall through into some other block, see if we can find a
1045 // place to move this block where a fall-through will happen.
1046 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1047 PriorTBB, PriorFBB, PriorCond)) {
1048 // Now we know that there was no fall-through into this block, check to
1049 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001050 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001051 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001052
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001053 if (!MBB->isLandingPad()) {
1054 // Check all the predecessors of this block. If one of them has no fall
1055 // throughs, move this block right after it.
1056 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1057 E = MBB->pred_end(); PI != E; ++PI) {
1058 // Analyze the branch at the end of the pred.
1059 MachineBasicBlock *PredBB = *PI;
1060 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1061 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001062 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001063 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1064 // If the current block doesn't fall through, just move it.
1065 // If the current block can fall through and does not end with a
1066 // conditional branch, we need to append an unconditional jump to
1067 // the (current) next block. To avoid a possible compile-time
1068 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001069 // Also, if there are already 2 branches here, we cannot add a third;
1070 // this means we have the case
1071 // Bcc next
1072 // B elsewhere
1073 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001074 if (CurFallsThru) {
1075 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1076 CurCond.clear();
1077 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1078 }
1079 MBB->moveAfter(PredBB);
1080 MadeChange = true;
1081 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001082 }
1083 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001084 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001085
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001086 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001087 // Check all successors to see if we can move this block before it.
1088 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1089 E = MBB->succ_end(); SI != E; ++SI) {
1090 // Analyze the branch at the end of the block before the succ.
1091 MachineBasicBlock *SuccBB = *SI;
1092 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001093 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001094
1095 // If this block doesn't already fall-through to that successor, and if
1096 // the succ doesn't already have a block that can fall through into it,
1097 // and if the successor isn't an EH destination, we can arrange for the
1098 // fallthrough to happen.
1099 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1100 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001101 MBB->moveBefore(SuccBB);
1102 MadeChange = true;
1103 return OptimizeBlock(MBB);
1104 }
1105 }
1106
1107 // Okay, there is no really great place to put this block. If, however,
1108 // the block before this one would be a fall-through if this block were
1109 // removed, move this block to the end of the function.
1110 if (FallThrough != MBB->getParent()->end() &&
1111 PrevBB.isSuccessor(FallThrough)) {
1112 MBB->moveAfter(--MBB->getParent()->end());
1113 MadeChange = true;
1114 return;
1115 }
Chris Lattner7d097842006-10-24 01:12:32 +00001116 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001117 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001118}