blob: 5fe0486eb10b1d33ccf9d31ddc83bacf8f37c901 [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");
Chris Lattnerd8ccff02006-11-01 00:38:31 +000038static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
Chris Lattner12143052006-10-21 00:47:49 +000039
Chris Lattner21ab22e2004-07-31 10:01:27 +000040namespace {
41 struct BranchFolder : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000042 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +000043 BranchFolder() : MachineFunctionPass((intptr_t)&ID) {}
44
Chris Lattner21ab22e2004-07-31 10:01:27 +000045 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000046 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
47 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000048 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000049 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000050 private:
Chris Lattner12143052006-10-21 00:47:49 +000051 // Tail Merging.
52 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000053 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
54 MachineBasicBlock* PredBB);
Chris Lattner12143052006-10-21 00:47:49 +000055 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
56 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000057 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
58 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000059
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000060 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
Dale Johannesen69cb9b72007-03-20 21:35:06 +000061 const MRegisterInfo *RegInfo;
62 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000063 // Branch optzn.
64 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000065 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000066 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000067
68 bool CanFallThrough(MachineBasicBlock *CurBB);
69 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
70 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
71 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000072 };
Devang Patel19974732007-05-03 01:11:54 +000073 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000074}
75
76FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
77
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000078/// RemoveDeadBlock - Remove the specified dead machine basic block from the
79/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000080void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000081 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +000082 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +000083
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000084 MachineFunction *MF = MBB->getParent();
85 // drop all successors.
86 while (!MBB->succ_empty())
87 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000088
Jim Laskey1ee29252007-01-26 14:34:52 +000089 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +000090 // records in the basic block. If so, unregister them from MachineModuleInfo.
91 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000092 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
93 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +000094 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +000095 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000096 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000097 }
98 }
99 }
100
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000101 // Remove the block.
102 MF->getBasicBlockList().erase(MBB);
103}
104
Chris Lattner21ab22e2004-07-31 10:01:27 +0000105bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000106 TII = MF.getTarget().getInstrInfo();
107 if (!TII) return false;
108
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000109 RegInfo = MF.getTarget().getRegisterInfo();
110 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
111
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000112 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000113
Chris Lattner21ab22e2004-07-31 10:01:27 +0000114 bool EverMadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000115 bool MadeChangeThisIteration = true;
116 while (MadeChangeThisIteration) {
117 MadeChangeThisIteration = false;
118 MadeChangeThisIteration |= TailMergeBlocks(MF);
119 MadeChangeThisIteration |= OptimizeBranches(MF);
120 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000121 }
122
Chris Lattner6acfe122006-10-28 18:34:47 +0000123 // See if any jump tables have become mergable or dead as the code generator
124 // did its thing.
125 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
126 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
127 if (!JTs.empty()) {
128 // Figure out how these jump tables should be merged.
129 std::vector<unsigned> JTMapping;
130 JTMapping.reserve(JTs.size());
131
132 // We always keep the 0th jump table.
133 JTMapping.push_back(0);
134
135 // Scan the jump tables, seeing if there are any duplicates. Note that this
136 // is N^2, which should be fixed someday.
137 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
138 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
139
140 // If a jump table was merge with another one, walk the function rewriting
141 // references to jump tables to reference the new JT ID's. Keep track of
142 // whether we see a jump table idx, if not, we can delete the JT.
143 std::vector<bool> JTIsLive;
144 JTIsLive.resize(JTs.size());
145 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
146 BB != E; ++BB) {
147 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
148 I != E; ++I)
149 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
150 MachineOperand &Op = I->getOperand(op);
151 if (!Op.isJumpTableIndex()) continue;
152 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
153 Op.setJumpTableIndex(NewIdx);
154
155 // Remember that this JT is live.
156 JTIsLive[NewIdx] = true;
157 }
158 }
159
160 // Finally, remove dead jump tables. This happens either because the
161 // indirect jump was unreachable (and thus deleted) or because the jump
162 // table was merged with some other one.
163 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
164 if (!JTIsLive[i]) {
165 JTI->RemoveJumpTable(i);
166 EverMadeChange = true;
167 }
168 }
169
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000170 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000171 return EverMadeChange;
172}
173
Chris Lattner12143052006-10-21 00:47:49 +0000174//===----------------------------------------------------------------------===//
175// Tail Merging of Blocks
176//===----------------------------------------------------------------------===//
177
178/// HashMachineInstr - Compute a hash value for MI and its operands.
179static unsigned HashMachineInstr(const MachineInstr *MI) {
180 unsigned Hash = MI->getOpcode();
181 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
182 const MachineOperand &Op = MI->getOperand(i);
183
184 // Merge in bits from the operand if easy.
185 unsigned OperandHash = 0;
186 switch (Op.getType()) {
187 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
188 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
189 case MachineOperand::MO_MachineBasicBlock:
190 OperandHash = Op.getMachineBasicBlock()->getNumber();
191 break;
192 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
193 case MachineOperand::MO_ConstantPoolIndex:
194 OperandHash = Op.getConstantPoolIndex();
195 break;
196 case MachineOperand::MO_JumpTableIndex:
197 OperandHash = Op.getJumpTableIndex();
198 break;
199 case MachineOperand::MO_GlobalAddress:
200 case MachineOperand::MO_ExternalSymbol:
201 // Global address / external symbol are too hard, don't bother, but do
202 // pull in the offset.
203 OperandHash = Op.getOffset();
204 break;
205 default: break;
206 }
207
208 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
209 }
210 return Hash;
211}
212
213/// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
214/// instructions, because cross-jumping only saves code when at least two
215/// instructions are removed (since a branch must be inserted).
216static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
217 MachineBasicBlock::const_iterator I = MBB->end();
218 if (I == MBB->begin())
219 return 0; // Empty MBB.
220
221 --I;
222 unsigned Hash = HashMachineInstr(I);
223
224 if (I == MBB->begin())
225 return Hash; // Single instr MBB.
226
227 --I;
228 // Hash in the second-to-last instruction.
229 Hash ^= HashMachineInstr(I) << 2;
230 return Hash;
231}
232
233/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
234/// of instructions they actually have in common together at their end. Return
235/// iterators for the first shared instruction in each block.
236static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
237 MachineBasicBlock *MBB2,
238 MachineBasicBlock::iterator &I1,
239 MachineBasicBlock::iterator &I2) {
240 I1 = MBB1->end();
241 I2 = MBB2->end();
242
243 unsigned TailLen = 0;
244 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
245 --I1; --I2;
246 if (!I1->isIdenticalTo(I2)) {
247 ++I1; ++I2;
248 break;
249 }
250 ++TailLen;
251 }
252 return TailLen;
253}
254
255/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000256/// after it, replacing it with an unconditional branch to NewDest. This
257/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000258void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
259 MachineBasicBlock *NewDest) {
260 MachineBasicBlock *OldBB = OldInst->getParent();
261
262 // Remove all the old successors of OldBB from the CFG.
263 while (!OldBB->succ_empty())
264 OldBB->removeSuccessor(OldBB->succ_begin());
265
266 // Remove all the dead instructions from the end of OldBB.
267 OldBB->erase(OldInst, OldBB->end());
268
Chris Lattner386e2902006-10-21 05:08:28 +0000269 // If OldBB isn't immediately before OldBB, insert a branch to it.
270 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
271 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000272 OldBB->addSuccessor(NewDest);
273 ++NumTailMerge;
274}
275
Chris Lattner1d08d832006-11-01 01:16:12 +0000276/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
277/// MBB so that the part before the iterator falls into the part starting at the
278/// iterator. This returns the new MBB.
279MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
280 MachineBasicBlock::iterator BBI1) {
281 // Create the fall-through block.
282 MachineFunction::iterator MBBI = &CurMBB;
283 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
284 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
285
286 // Move all the successors of this block to the specified block.
287 while (!CurMBB.succ_empty()) {
288 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
289 NewMBB->addSuccessor(S);
290 CurMBB.removeSuccessor(S);
291 }
292
293 // Add an edge from CurMBB to NewMBB for the fall-through.
294 CurMBB.addSuccessor(NewMBB);
295
296 // Splice the code over.
297 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000298
299 // For targets that use the register scavenger, we must maintain LiveIns.
300 if (RS) {
301 RS->enterBasicBlock(&CurMBB);
302 if (!CurMBB.empty())
303 RS->forward(prior(CurMBB.end()));
304 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
305 RS->getRegsUsed(RegsLiveAtExit, false);
306 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
307 if (RegsLiveAtExit[i])
308 NewMBB->addLiveIn(i);
309 }
310
Chris Lattner1d08d832006-11-01 01:16:12 +0000311 return NewMBB;
312}
313
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000314/// EstimateRuntime - Make a rough estimate for how long it will take to run
315/// the specified code.
316static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
317 MachineBasicBlock::iterator E,
318 const TargetInstrInfo *TII) {
319 unsigned Time = 0;
320 for (; I != E; ++I) {
321 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
322 if (TID.Flags & M_CALL_FLAG)
323 Time += 10;
324 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
325 Time += 2;
326 else
327 ++Time;
328 }
329 return Time;
330}
331
332/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
333/// MBB2I and then insert an unconditional branch in the other block. Determine
334/// which is the best to split
335static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
336 MachineBasicBlock::iterator MBB1I,
337 MachineBasicBlock *MBB2,
338 MachineBasicBlock::iterator MBB2I,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000339 const TargetInstrInfo *TII,
340 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000341 // If one block is the entry block, split the other one; we can't generate
342 // a branch to the entry block, as its label is not emitted.
343 MachineBasicBlock *Entry = MBB1->getParent()->begin();
344 if (MBB1 == Entry)
345 return false;
346 if (MBB2 == Entry)
347 return true;
348
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000349 // If one block falls through into the common successor, choose that
350 // one to split; it is one instruction less to do that.
351 if (PredBB) {
352 if (MBB1 == PredBB)
353 return true;
354 else if (MBB2 == PredBB)
355 return false;
356 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000357 // TODO: if we had some notion of which block was hotter, we could split
358 // the hot block, so it is the fall-through. Since we don't have profile info
359 // make a decision based on which will hurt most to split.
360 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
361 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
362
363 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
364 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
365 // have a lower overall impact on the program execution.
366 return MBB1Time < MBB2Time;
367}
368
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000369// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
370// branches temporarily for tail merging). In the case where CurMBB ends
371// with a conditional branch to the next block, optimize by reversing the
372// test and conditionally branching to SuccMBB instead.
373
374static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
375 const TargetInstrInfo *TII) {
376 MachineFunction *MF = CurMBB->getParent();
377 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
378 MachineBasicBlock *TBB = 0, *FBB = 0;
379 std::vector<MachineOperand> Cond;
380 if (I != MF->end() &&
381 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
382 MachineBasicBlock *NextBB = I;
383 if (TBB == NextBB && Cond.size() && !FBB) {
384 if (!TII->ReverseBranchCondition(Cond)) {
385 TII->RemoveBranch(*CurMBB);
386 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
387 return;
388 }
389 }
390 }
391 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
392}
393
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000394// See if any of the blocks in MergePotentials (which all have a common single
395// successor, or all have no successor) can be tail-merged. If there is a
396// successor, any blocks in MergePotentials that are not tail-merged and
397// are not immediately before Succ must have an unconditional branch to
398// Succ added (but the predecessor/successor lists need no adjustment).
399// The lone predecessor of Succ that falls through into Succ,
400// if any, is given in PredBB.
401
402bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
403 MachineBasicBlock* PredBB) {
Chris Lattner12143052006-10-21 00:47:49 +0000404 MadeChange = false;
405
Chris Lattner12143052006-10-21 00:47:49 +0000406 // Sort by hash value so that blocks with identical end sequences sort
407 // together.
408 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
409
410 // Walk through equivalence sets looking for actual exact matches.
411 while (MergePotentials.size() > 1) {
412 unsigned CurHash = (MergePotentials.end()-1)->first;
413 unsigned PrevHash = (MergePotentials.end()-2)->first;
414 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
415
416 // If there is nothing that matches the hash of the current basic block,
417 // give up.
418 if (CurHash != PrevHash) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000419 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000420 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000421 MergePotentials.pop_back();
422 continue;
423 }
424
425 // Determine the actual length of the shared tail between these two basic
426 // blocks. Because the hash can have collisions, it's possible that this is
427 // less than 2.
428 MachineBasicBlock::iterator BBI1, BBI2;
429 unsigned CommonTailLen =
430 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
431 BBI1, BBI2);
432
433 // If the tails don't have at least two instructions in common, see if there
434 // is anything else in the equivalence class that does match.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000435 // Since instructions may get combined later (e.g. single stores into
436 // store multiple) this measure is not particularly accurate.
Chris Lattner12143052006-10-21 00:47:49 +0000437 if (CommonTailLen < 2) {
438 unsigned FoundMatch = ~0U;
439 for (int i = MergePotentials.size()-2;
440 i != -1 && MergePotentials[i].first == CurHash; --i) {
441 CommonTailLen = ComputeCommonTailLength(CurMBB,
442 MergePotentials[i].second,
443 BBI1, BBI2);
444 if (CommonTailLen >= 2) {
445 FoundMatch = i;
446 break;
447 }
448 }
449
450 // If we didn't find anything that has at least two instructions matching
451 // this one, bail out.
452 if (FoundMatch == ~0U) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000453 // Put the unconditional branch back, if we need one.
454 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000455 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000456 MergePotentials.pop_back();
457 continue;
458 }
459
460 // Otherwise, move the matching block to the right position.
461 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
462 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000463
Chris Lattner12143052006-10-21 00:47:49 +0000464 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000465
466 // If neither block is the entire common tail, split the tail of one block
Dale Johannesen54f4a672007-05-10 23:59:23 +0000467 // to make it redundant with the other tail. Also, we cannot jump to the
468 // entry block, so if one block is the entry block, split the other one.
469 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
470 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
471 ; // CurMBB is common tail
472 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
473 ; // MBB2 is common tail
474 else {
Chris Lattner1d08d832006-11-01 01:16:12 +0000475 if (0) { // Enable this to disable partial tail merges.
476 MergePotentials.pop_back();
477 continue;
478 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000479
480 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000481 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000482 CurMBB = SplitMBBAt(*CurMBB, BBI1);
483 BBI1 = CurMBB->begin();
484 MergePotentials.back().second = CurMBB;
485 } else {
486 MBB2 = SplitMBBAt(*MBB2, BBI2);
487 BBI2 = MBB2->begin();
488 (MergePotentials.end()-2)->second = MBB2;
489 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000490 }
491
Dale Johannesen54f4a672007-05-10 23:59:23 +0000492 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner12143052006-10-21 00:47:49 +0000493 // Hack the end off CurMBB, making it jump to MBBI@ instead.
494 ReplaceTailWithBranchTo(BBI1, MBB2);
495 // This modifies CurMBB, so remove it from the worklist.
496 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000497 } else {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000498 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
499 "Didn't split block correctly?");
Chris Lattner1d08d832006-11-01 01:16:12 +0000500 // Hack the end off MBB2, making it jump to CurMBB instead.
501 ReplaceTailWithBranchTo(BBI2, CurMBB);
502 // This modifies MBB2, so remove it from the worklist.
503 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000504 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000505 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000506 }
Chris Lattner12143052006-10-21 00:47:49 +0000507 return MadeChange;
508}
509
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000510bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000511
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000512 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000513
514 MadeChange = false;
515
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000516 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000517 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000518 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
519 if (I->succ_empty())
520 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
521 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000522 // See if we can do any tail merging on those.
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000523 MadeChange |= TryMergeBlocks(NULL, NULL);
524
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000525 // Look at blocks (IBB) with multiple predecessors (PBB).
526 // We change each predecessor to a canonical form, by
527 // (1) temporarily removing any unconditional branch from the predecessor
528 // to IBB, and
529 // (2) alter conditional branches so they branch to the other block
530 // not IBB; this may require adding back an unconditional branch to IBB
531 // later, where there wasn't one coming in. E.g.
532 // Bcc IBB
533 // fallthrough to QBB
534 // here becomes
535 // Bncc QBB
536 // with a conceptual B to IBB after that, which never actually exists.
537 // With those changes, we see whether the predecessors' tails match,
538 // and merge them if so. We change things out of canonical form and
539 // back to the way they were later in the process. (OptimizeBranches
540 // would undo some of this, but we can't use it, because we'd get into
541 // a compile-time infinite loop repeatedly doing and undoing the same
542 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000543
544 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
545 if (!I->succ_empty() && I->pred_size() >= 2) {
546 MachineBasicBlock *IBB = I;
547 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000548 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000549 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
550 P != E2; ++P) {
551 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000552 // Skip blocks that loop to themselves, can't tail merge these.
553 if (PBB==IBB)
554 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000555 MachineBasicBlock *TBB = 0, *FBB = 0;
556 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000557 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
558 // Failing case: IBB is the target of a cbr, and
559 // we cannot reverse the branch.
560 std::vector<MachineOperand> NewCond(Cond);
561 if (Cond.size() && TBB==IBB) {
562 if (TII->ReverseBranchCondition(NewCond))
563 continue;
564 // This is the QBB case described above
565 if (!FBB)
566 FBB = next(MachineFunction::iterator(PBB));
567 }
568 // Remove the unconditional branch at the end, if any.
569 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000570 TII->RemoveBranch(*PBB);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000571 if (Cond.size())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000572 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000573 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000574 }
575 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB), *P));
576 }
577 }
578 if (MergePotentials.size() >= 2)
579 MadeChange |= TryMergeBlocks(I, PredBB);
580 // Reinsert an unconditional branch if needed.
581 // The 1 below can be either an original single predecessor, or a result
582 // of removing blocks in TryMergeBlocks.
583 if (MergePotentials.size()==1 &&
584 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000585 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000586 }
587 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000588 return MadeChange;
589}
Chris Lattner12143052006-10-21 00:47:49 +0000590
591//===----------------------------------------------------------------------===//
592// Branch Optimization
593//===----------------------------------------------------------------------===//
594
595bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
596 MadeChange = false;
597
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000598 // Make sure blocks are numbered in order
599 MF.RenumberBlocks();
600
Chris Lattner12143052006-10-21 00:47:49 +0000601 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
602 MachineBasicBlock *MBB = I++;
603 OptimizeBlock(MBB);
604
605 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000606 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000607 RemoveDeadBlock(MBB);
608 MadeChange = true;
609 ++NumDeadBlocks;
610 }
611 }
612 return MadeChange;
613}
614
615
Chris Lattner386e2902006-10-21 05:08:28 +0000616/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
617/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
618/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
619/// be null.
620static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
621 MachineBasicBlock *DestA,
622 MachineBasicBlock *DestB,
623 bool isCond,
624 MachineFunction::iterator FallThru) {
625 bool MadeChange = false;
626 bool AddedFallThrough = false;
627
628 // If this block ends with a conditional branch that falls through to its
629 // successor, set DestB as the successor.
630 if (isCond) {
631 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
632 DestB = FallThru;
633 AddedFallThrough = true;
634 }
635 } else {
636 // If this is an unconditional branch with no explicit dest, it must just be
637 // a fallthrough into DestB.
638 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
639 DestA = FallThru;
640 AddedFallThrough = true;
641 }
642 }
643
644 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
645 while (SI != MBB.succ_end()) {
646 if (*SI == DestA) {
647 DestA = 0;
648 ++SI;
649 } else if (*SI == DestB) {
650 DestB = 0;
651 ++SI;
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000652 } else if ((*SI)->isLandingPad()) {
653 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000654 } else {
655 // Otherwise, this is a superfluous edge, remove it.
656 MBB.removeSuccessor(SI);
657 MadeChange = true;
658 }
659 }
660 if (!AddedFallThrough) {
661 assert(DestA == 0 && DestB == 0 &&
662 "MachineCFG is missing edges!");
663 } else if (isCond) {
664 assert(DestA == 0 && "MachineCFG is missing edges!");
665 }
666 return MadeChange;
667}
668
669
Chris Lattner21ab22e2004-07-31 10:01:27 +0000670/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
671/// 'Old', change the code and CFG so that it branches to 'New' instead.
672static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
673 MachineBasicBlock *Old,
674 MachineBasicBlock *New,
Chris Lattner7821a8a2006-10-14 00:21:48 +0000675 const TargetInstrInfo *TII) {
Chris Lattner21ab22e2004-07-31 10:01:27 +0000676 assert(Old != New && "Cannot replace self with self!");
677
678 MachineBasicBlock::iterator I = BB->end();
679 while (I != BB->begin()) {
680 --I;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000681 if (!TII->isTerminatorInstr(I->getOpcode())) break;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000682
683 // Scan the operands of this machine instruction, replacing any uses of Old
684 // with New.
685 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
686 if (I->getOperand(i).isMachineBasicBlock() &&
687 I->getOperand(i).getMachineBasicBlock() == Old)
688 I->getOperand(i).setMachineBasicBlock(New);
689 }
690
Chris Lattnereb15eee2006-10-13 20:43:10 +0000691 // Update the successor information.
Chris Lattner21ab22e2004-07-31 10:01:27 +0000692 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
693 for (int i = Succs.size()-1; i >= 0; --i)
694 if (Succs[i] == Old) {
695 BB->removeSuccessor(Old);
696 BB->addSuccessor(New);
697 }
698}
699
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000700/// CanFallThrough - Return true if the specified block (with the specified
701/// branch condition) can implicitly transfer control to the block after it by
702/// falling off the end of it. This should return false if it can reach the
703/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
704///
705/// True is a conservative answer.
706///
707bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
708 bool BranchUnAnalyzable,
709 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
710 const std::vector<MachineOperand> &Cond) {
711 MachineFunction::iterator Fallthrough = CurBB;
712 ++Fallthrough;
713 // If FallthroughBlock is off the end of the function, it can't fall through.
714 if (Fallthrough == CurBB->getParent()->end())
715 return false;
716
717 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
718 if (!CurBB->isSuccessor(Fallthrough))
719 return false;
720
721 // If we couldn't analyze the branch, assume it could fall through.
722 if (BranchUnAnalyzable) return true;
723
Chris Lattner7d097842006-10-24 01:12:32 +0000724 // If there is no branch, control always falls through.
725 if (TBB == 0) return true;
726
727 // If there is some explicit branch to the fallthrough block, it can obviously
728 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000729 if (MachineFunction::iterator(TBB) == Fallthrough ||
730 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000731 return true;
732
733 // If it's an unconditional branch to some block not the fall through, it
734 // doesn't fall through.
735 if (Cond.empty()) return false;
736
737 // Otherwise, if it is conditional and has no explicit false block, it falls
738 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000739 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000740}
741
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000742/// CanFallThrough - Return true if the specified can implicitly transfer
743/// control to the block after it by falling off the end of it. This should
744/// return false if it can reach the block after it, but it uses an explicit
745/// branch to do so (e.g. a table jump).
746///
747/// True is a conservative answer.
748///
749bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
750 MachineBasicBlock *TBB = 0, *FBB = 0;
751 std::vector<MachineOperand> Cond;
752 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
753 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
754}
755
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000756/// IsBetterFallthrough - Return true if it would be clearly better to
757/// fall-through to MBB1 than to fall through into MBB2. This has to return
758/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
759/// result in infinite loops.
760static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
761 MachineBasicBlock *MBB2,
762 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000763 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
764 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000765 // optimize branches that branch to either a return block or an assert block
766 // into a fallthrough to the return.
767 if (MBB1->empty() || MBB2->empty()) return false;
768
769 MachineInstr *MBB1I = --MBB1->end();
770 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000771 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000772}
773
Chris Lattner7821a8a2006-10-14 00:21:48 +0000774/// OptimizeBlock - Analyze and optimize control flow related to the specified
775/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000776void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
777 MachineFunction::iterator FallThrough = MBB;
778 ++FallThrough;
779
Chris Lattnereb15eee2006-10-13 20:43:10 +0000780 // If this block is empty, make everyone use its fall-through, not the block
Chris Lattner21ab22e2004-07-31 10:01:27 +0000781 // explicitly.
782 if (MBB->empty()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000783 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000784 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000785
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000786 if (FallThrough == MBB->getParent()->end()) {
787 // TODO: Simplify preds to not branch here if possible!
788 } else {
789 // Rewrite all predecessors of the old block to go to the fallthrough
790 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000791 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000792 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
793 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
794 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000795
796 // If MBB was the target of a jump table, update jump tables to go to the
797 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000798 MBB->getParent()->getJumpTableInfo()->
799 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000800 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000801 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000802 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000803 }
804
Chris Lattner7821a8a2006-10-14 00:21:48 +0000805 // Check to see if we can simplify the terminator of the block before this
806 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000807 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000808
Chris Lattner7821a8a2006-10-14 00:21:48 +0000809 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
810 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000811 bool PriorUnAnalyzable =
812 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000813 if (!PriorUnAnalyzable) {
814 // If the CFG for the prior block has extra edges, remove them.
815 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
816 !PriorCond.empty(), MBB);
817
Chris Lattner7821a8a2006-10-14 00:21:48 +0000818 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000819 // destination, remove the branch, replacing it with an unconditional one or
820 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000821 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000822 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000823 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000824 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000825 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000826 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000827 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000828 return OptimizeBlock(MBB);
829 }
830
831 // If the previous branch *only* branches to *this* block (conditional or
832 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000833 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000834 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000835 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000836 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000837 return OptimizeBlock(MBB);
838 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000839
840 // If the prior block branches somewhere else on the condition and here if
841 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000842 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000843 TII->RemoveBranch(PrevBB);
844 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
845 MadeChange = true;
846 ++NumBranchOpts;
847 return OptimizeBlock(MBB);
848 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000849
850 // If the prior block branches here on true and somewhere else on false, and
851 // if the branch condition is reversible, reverse the branch to create a
852 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000853 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000854 std::vector<MachineOperand> NewPriorCond(PriorCond);
855 if (!TII->ReverseBranchCondition(NewPriorCond)) {
856 TII->RemoveBranch(PrevBB);
857 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
858 MadeChange = true;
859 ++NumBranchOpts;
860 return OptimizeBlock(MBB);
861 }
862 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000863
Chris Lattner154e1042006-11-18 21:30:35 +0000864 // If this block doesn't fall through (e.g. it ends with an uncond branch or
865 // has no successors) and if the pred falls through into this block, and if
866 // it would otherwise fall through into the block after this, move this
867 // block to the end of the function.
868 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000869 // We consider it more likely that execution will stay in the function (e.g.
870 // due to loops) than it is to exit it. This asserts in loops etc, moving
871 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000872 if (!PriorCond.empty() && PriorFBB == 0 &&
873 MachineFunction::iterator(PriorTBB) == FallThrough &&
874 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000875 bool DoTransform = true;
876
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000877 // We have to be careful that the succs of PredBB aren't both no-successor
878 // blocks. If neither have successors and if PredBB is the second from
879 // last block in the function, we'd just keep swapping the two blocks for
880 // last. Only do the swap if one is clearly better to fall through than
881 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000882 if (FallThrough == --MBB->getParent()->end() &&
883 !IsBetterFallthrough(PriorTBB, MBB, *TII))
884 DoTransform = false;
885
886 // We don't want to do this transformation if we have control flow like:
887 // br cond BB2
888 // BB1:
889 // ..
890 // jmp BBX
891 // BB2:
892 // ..
893 // ret
894 //
895 // In this case, we could actually be moving the return block *into* a
896 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000897 if (DoTransform && !MBB->succ_empty() &&
898 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000899 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000900
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000901
902 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000903 // Reverse the branch so we will fall through on the previous true cond.
904 std::vector<MachineOperand> NewPriorCond(PriorCond);
905 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000906 DOUT << "\nMoving MBB: " << *MBB;
907 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
908
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000909 TII->RemoveBranch(PrevBB);
910 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
911
912 // Move this block to the end of the function.
913 MBB->moveAfter(--MBB->getParent()->end());
914 MadeChange = true;
915 ++NumBranchOpts;
916 return;
917 }
918 }
919 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000920 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000921
Chris Lattner386e2902006-10-21 05:08:28 +0000922 // Analyze the branch in the current block.
923 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
924 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000925 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
926 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000927 // If the CFG for the prior block has extra edges, remove them.
928 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000929 !CurCond.empty(),
930 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000931
Chris Lattner5d056952006-11-08 01:03:21 +0000932 // If this is a two-way branch, and the FBB branches to this block, reverse
933 // the condition so the single-basic-block loop is faster. Instead of:
934 // Loop: xxx; jcc Out; jmp Loop
935 // we want:
936 // Loop: xxx; jncc Loop; jmp Out
937 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
938 std::vector<MachineOperand> NewCond(CurCond);
939 if (!TII->ReverseBranchCondition(NewCond)) {
940 TII->RemoveBranch(*MBB);
941 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
942 MadeChange = true;
943 ++NumBranchOpts;
944 return OptimizeBlock(MBB);
945 }
946 }
947
948
Chris Lattner386e2902006-10-21 05:08:28 +0000949 // If this branch is the only thing in its block, see if we can forward
950 // other blocks across it.
951 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +0000952 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000953 // This block may contain just an unconditional branch. Because there can
954 // be 'non-branch terminators' in the block, try removing the branch and
955 // then seeing if the block is empty.
956 TII->RemoveBranch(*MBB);
957
958 // If this block is just an unconditional branch to CurTBB, we can
959 // usually completely eliminate the block. The only case we cannot
960 // completely eliminate the block is when the block before this one
961 // falls through into MBB and we can't understand the prior block's branch
962 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +0000963 if (MBB->empty()) {
964 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
965 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
966 !PrevBB.isSuccessor(MBB)) {
967 // If the prior block falls through into us, turn it into an
968 // explicit branch to us to make updates simpler.
969 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
970 PriorTBB != MBB && PriorFBB != MBB) {
971 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000972 assert(PriorCond.empty() && PriorFBB == 0 &&
973 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +0000974 PriorTBB = MBB;
975 } else {
976 assert(PriorFBB == 0 && "Machine CFG out of date!");
977 PriorFBB = MBB;
978 }
979 TII->RemoveBranch(PrevBB);
980 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000981 }
Chris Lattner386e2902006-10-21 05:08:28 +0000982
Chris Lattnercf420cc2006-10-28 17:32:47 +0000983 // Iterate through all the predecessors, revectoring each in-turn.
984 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
985 bool DidChange = false;
986 bool HasBranchToSelf = false;
987 while (PI != MBB->pred_end()) {
988 if (*PI == MBB) {
989 // If this block has an uncond branch to itself, leave it.
990 ++PI;
991 HasBranchToSelf = true;
992 } else {
993 DidChange = true;
994 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
995 }
Chris Lattner4bc135e2006-10-21 06:11:43 +0000996 }
Chris Lattner386e2902006-10-21 05:08:28 +0000997
Chris Lattnercf420cc2006-10-28 17:32:47 +0000998 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +0000999 MBB->getParent()->getJumpTableInfo()->
1000 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001001 if (DidChange) {
1002 ++NumBranchOpts;
1003 MadeChange = true;
1004 if (!HasBranchToSelf) return;
1005 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001006 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001007 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001008
Chris Lattner386e2902006-10-21 05:08:28 +00001009 // Add the branch back if the block is more than just an uncond branch.
1010 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001011 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001012 }
1013
1014 // If the prior block doesn't fall through into this block, and if this
1015 // block doesn't fall through into some other block, see if we can find a
1016 // place to move this block where a fall-through will happen.
1017 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1018 PriorTBB, PriorFBB, PriorCond)) {
1019 // Now we know that there was no fall-through into this block, check to
1020 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001021 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001022 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001023
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001024 if (!MBB->isLandingPad()) {
1025 // Check all the predecessors of this block. If one of them has no fall
1026 // throughs, move this block right after it.
1027 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1028 E = MBB->pred_end(); PI != E; ++PI) {
1029 // Analyze the branch at the end of the pred.
1030 MachineBasicBlock *PredBB = *PI;
1031 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1032 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001033 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001034 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1035 // If the current block doesn't fall through, just move it.
1036 // If the current block can fall through and does not end with a
1037 // conditional branch, we need to append an unconditional jump to
1038 // the (current) next block. To avoid a possible compile-time
1039 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001040 // Also, if there are already 2 branches here, we cannot add a third;
1041 // this means we have the case
1042 // Bcc next
1043 // B elsewhere
1044 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001045 if (CurFallsThru) {
1046 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1047 CurCond.clear();
1048 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1049 }
1050 MBB->moveAfter(PredBB);
1051 MadeChange = true;
1052 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001053 }
1054 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001055 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001056
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001057 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001058 // Check all successors to see if we can move this block before it.
1059 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1060 E = MBB->succ_end(); SI != E; ++SI) {
1061 // Analyze the branch at the end of the block before the succ.
1062 MachineBasicBlock *SuccBB = *SI;
1063 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001064 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001065
1066 // If this block doesn't already fall-through to that successor, and if
1067 // the succ doesn't already have a block that can fall through into it,
1068 // and if the successor isn't an EH destination, we can arrange for the
1069 // fallthrough to happen.
1070 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1071 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001072 MBB->moveBefore(SuccBB);
1073 MadeChange = true;
1074 return OptimizeBlock(MBB);
1075 }
1076 }
1077
1078 // Okay, there is no really great place to put this block. If, however,
1079 // the block before this one would be a fall-through if this block were
1080 // removed, move this block to the end of the function.
1081 if (FallThrough != MBB->getParent()->end() &&
1082 PrevBB.isSuccessor(FallThrough)) {
1083 MBB->moveAfter(--MBB->getParent()->end());
1084 MadeChange = true;
1085 return;
1086 }
Chris Lattner7d097842006-10-24 01:12:32 +00001087 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001088 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001089}