blob: 71fac0b8eb766b216bf945110ac9fe6c67696d17 [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 {
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000041 // Throttle for huge numbers of predecessors (compile speed problems)
42 cl::opt<unsigned>
43 TailMergeThreshold("tail-merge-threshold",
44 cl::desc("Max number of predecessors to consider tail merging"),
45 cl::init(100), cl::Hidden);
46
Chris Lattner21ab22e2004-07-31 10:01:27 +000047 struct BranchFolder : public MachineFunctionPass {
Devang Patel19974732007-05-03 01:11:54 +000048 static char ID;
Dale Johannesen81da02b2007-05-22 17:14:46 +000049 BranchFolder(bool defaultEnableTailMerge) :
50 MachineFunctionPass((intptr_t)&ID) {
51 switch (FlagEnableTailMerge) {
52 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
53 case cl::BOU_TRUE: EnableTailMerge = true; break;
54 case cl::BOU_FALSE: EnableTailMerge = false; break;
55 }
56 }
Devang Patel794fd752007-05-01 21:15:47 +000057
Chris Lattner21ab22e2004-07-31 10:01:27 +000058 virtual bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner7821a8a2006-10-14 00:21:48 +000059 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
60 const TargetInstrInfo *TII;
Jim Laskey44c3b9f2007-01-26 21:22:28 +000061 MachineModuleInfo *MMI;
Chris Lattner7821a8a2006-10-14 00:21:48 +000062 bool MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +000063 private:
Chris Lattner12143052006-10-21 00:47:49 +000064 // Tail Merging.
Dale Johannesen81da02b2007-05-22 17:14:46 +000065 bool EnableTailMerge;
Chris Lattner12143052006-10-21 00:47:49 +000066 bool TailMergeBlocks(MachineFunction &MF);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000067 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
68 MachineBasicBlock* PredBB);
Chris Lattner12143052006-10-21 00:47:49 +000069 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
70 MachineBasicBlock *NewDest);
Chris Lattner1d08d832006-11-01 01:16:12 +000071 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
72 MachineBasicBlock::iterator BBI1);
Dale Johannesen69cb9b72007-03-20 21:35:06 +000073
Dale Johannesen7d33b4c2007-05-07 20:57:21 +000074 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
Dale Johannesen69cb9b72007-03-20 21:35:06 +000075 const MRegisterInfo *RegInfo;
76 RegScavenger *RS;
Chris Lattner12143052006-10-21 00:47:49 +000077 // Branch optzn.
78 bool OptimizeBranches(MachineFunction &MF);
Chris Lattner7d097842006-10-24 01:12:32 +000079 void OptimizeBlock(MachineBasicBlock *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000080 void RemoveDeadBlock(MachineBasicBlock *MBB);
Chris Lattner6b0e3f82006-10-29 21:05:41 +000081
82 bool CanFallThrough(MachineBasicBlock *CurBB);
83 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
84 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
85 const std::vector<MachineOperand> &Cond);
Chris Lattner21ab22e2004-07-31 10:01:27 +000086 };
Devang Patel19974732007-05-03 01:11:54 +000087 char BranchFolder::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000088}
89
Dale Johannesen14ba0cc2007-05-15 21:19:17 +000090static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
91 MachineBasicBlock *DestA,
92 MachineBasicBlock *DestB,
93 bool isCond,
94 MachineFunction::iterator FallThru);
95
Dale Johannesen81da02b2007-05-22 17:14:46 +000096FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
97 return new BranchFolder(DefaultEnableTailMerge); }
Chris Lattner21ab22e2004-07-31 10:01:27 +000098
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000099/// RemoveDeadBlock - Remove the specified dead machine basic block from the
100/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +0000101void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +0000102 assert(MBB->pred_empty() && "MBB must be dead!");
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000103 DOUT << "\nRemoving MBB: " << *MBB;
Chris Lattner683747a2006-10-17 23:17:27 +0000104
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000105 MachineFunction *MF = MBB->getParent();
106 // drop all successors.
107 while (!MBB->succ_empty())
108 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +0000109
Jim Laskey1ee29252007-01-26 14:34:52 +0000110 // If there is DWARF info to active, check to see if there are any LABEL
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000111 // records in the basic block. If so, unregister them from MachineModuleInfo.
112 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +0000113 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
114 I != E; ++I) {
Jim Laskey1ee29252007-01-26 14:34:52 +0000115 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
Chris Lattner683747a2006-10-17 23:17:27 +0000116 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000117 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +0000118 }
119 }
120 }
121
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000122 // Remove the block.
123 MF->getBasicBlockList().erase(MBB);
124}
125
Chris Lattner21ab22e2004-07-31 10:01:27 +0000126bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000127 TII = MF.getTarget().getInstrInfo();
128 if (!TII) return false;
129
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000130 // Fix CFG. The later algorithms expect it to be right.
131 bool EverMadeChange = false;
132 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
133 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
134 std::vector<MachineOperand> Cond;
135 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
136 EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
137 !Cond.empty(), next(I));
138 }
139
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000140 RegInfo = MF.getTarget().getRegisterInfo();
141 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
142
Jim Laskey44c3b9f2007-01-26 21:22:28 +0000143 MMI = getAnalysisToUpdate<MachineModuleInfo>();
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000144
Chris Lattner12143052006-10-21 00:47:49 +0000145 bool MadeChangeThisIteration = true;
146 while (MadeChangeThisIteration) {
147 MadeChangeThisIteration = false;
148 MadeChangeThisIteration |= TailMergeBlocks(MF);
149 MadeChangeThisIteration |= OptimizeBranches(MF);
150 EverMadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000151 }
152
Chris Lattner6acfe122006-10-28 18:34:47 +0000153 // See if any jump tables have become mergable or dead as the code generator
154 // did its thing.
155 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
156 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
157 if (!JTs.empty()) {
158 // Figure out how these jump tables should be merged.
159 std::vector<unsigned> JTMapping;
160 JTMapping.reserve(JTs.size());
161
162 // We always keep the 0th jump table.
163 JTMapping.push_back(0);
164
165 // Scan the jump tables, seeing if there are any duplicates. Note that this
166 // is N^2, which should be fixed someday.
167 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
168 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
169
170 // If a jump table was merge with another one, walk the function rewriting
171 // references to jump tables to reference the new JT ID's. Keep track of
172 // whether we see a jump table idx, if not, we can delete the JT.
173 std::vector<bool> JTIsLive;
174 JTIsLive.resize(JTs.size());
175 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
176 BB != E; ++BB) {
177 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
178 I != E; ++I)
179 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
180 MachineOperand &Op = I->getOperand(op);
181 if (!Op.isJumpTableIndex()) continue;
182 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
183 Op.setJumpTableIndex(NewIdx);
184
185 // Remember that this JT is live.
186 JTIsLive[NewIdx] = true;
187 }
188 }
189
190 // Finally, remove dead jump tables. This happens either because the
191 // indirect jump was unreachable (and thus deleted) or because the jump
192 // table was merged with some other one.
193 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
194 if (!JTIsLive[i]) {
195 JTI->RemoveJumpTable(i);
196 EverMadeChange = true;
197 }
198 }
199
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000200 delete RS;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000201 return EverMadeChange;
202}
203
Chris Lattner12143052006-10-21 00:47:49 +0000204//===----------------------------------------------------------------------===//
205// Tail Merging of Blocks
206//===----------------------------------------------------------------------===//
207
208/// HashMachineInstr - Compute a hash value for MI and its operands.
209static unsigned HashMachineInstr(const MachineInstr *MI) {
210 unsigned Hash = MI->getOpcode();
211 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
212 const MachineOperand &Op = MI->getOperand(i);
213
214 // Merge in bits from the operand if easy.
215 unsigned OperandHash = 0;
216 switch (Op.getType()) {
217 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
218 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
219 case MachineOperand::MO_MachineBasicBlock:
220 OperandHash = Op.getMachineBasicBlock()->getNumber();
221 break;
222 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
223 case MachineOperand::MO_ConstantPoolIndex:
224 OperandHash = Op.getConstantPoolIndex();
225 break;
226 case MachineOperand::MO_JumpTableIndex:
227 OperandHash = Op.getJumpTableIndex();
228 break;
229 case MachineOperand::MO_GlobalAddress:
230 case MachineOperand::MO_ExternalSymbol:
231 // Global address / external symbol are too hard, don't bother, but do
232 // pull in the offset.
233 OperandHash = Op.getOffset();
234 break;
235 default: break;
236 }
237
238 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
239 }
240 return Hash;
241}
242
Dale Johannesen7aea8322007-05-23 21:07:20 +0000243/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
244/// with no successors, we hash two instructions, because cross-jumping
245/// only saves code when at least two instructions are removed (since a
246/// branch must be inserted). For blocks with a successor, one of the
247/// two blocks to be tail-merged will end with a branch already, so
248/// it gains to cross-jump even for one instruction.
249
250static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
251 unsigned minCommonTailLength) {
Chris Lattner12143052006-10-21 00:47:49 +0000252 MachineBasicBlock::const_iterator I = MBB->end();
253 if (I == MBB->begin())
254 return 0; // Empty MBB.
255
256 --I;
257 unsigned Hash = HashMachineInstr(I);
258
Dale Johannesen7aea8322007-05-23 21:07:20 +0000259 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner12143052006-10-21 00:47:49 +0000260 return Hash; // Single instr MBB.
261
262 --I;
263 // Hash in the second-to-last instruction.
264 Hash ^= HashMachineInstr(I) << 2;
265 return Hash;
266}
267
268/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
269/// of instructions they actually have in common together at their end. Return
270/// iterators for the first shared instruction in each block.
271static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
272 MachineBasicBlock *MBB2,
273 MachineBasicBlock::iterator &I1,
274 MachineBasicBlock::iterator &I2) {
275 I1 = MBB1->end();
276 I2 = MBB2->end();
277
278 unsigned TailLen = 0;
279 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
280 --I1; --I2;
281 if (!I1->isIdenticalTo(I2)) {
282 ++I1; ++I2;
283 break;
284 }
285 ++TailLen;
286 }
287 return TailLen;
288}
289
290/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000291/// after it, replacing it with an unconditional branch to NewDest. This
292/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000293void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
294 MachineBasicBlock *NewDest) {
295 MachineBasicBlock *OldBB = OldInst->getParent();
296
297 // Remove all the old successors of OldBB from the CFG.
298 while (!OldBB->succ_empty())
299 OldBB->removeSuccessor(OldBB->succ_begin());
300
301 // Remove all the dead instructions from the end of OldBB.
302 OldBB->erase(OldInst, OldBB->end());
303
Chris Lattner386e2902006-10-21 05:08:28 +0000304 // If OldBB isn't immediately before OldBB, insert a branch to it.
305 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
306 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
Chris Lattner12143052006-10-21 00:47:49 +0000307 OldBB->addSuccessor(NewDest);
308 ++NumTailMerge;
309}
310
Chris Lattner1d08d832006-11-01 01:16:12 +0000311/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
312/// MBB so that the part before the iterator falls into the part starting at the
313/// iterator. This returns the new MBB.
314MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
315 MachineBasicBlock::iterator BBI1) {
316 // Create the fall-through block.
317 MachineFunction::iterator MBBI = &CurMBB;
318 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
319 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
320
321 // Move all the successors of this block to the specified block.
322 while (!CurMBB.succ_empty()) {
323 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
324 NewMBB->addSuccessor(S);
325 CurMBB.removeSuccessor(S);
326 }
327
328 // Add an edge from CurMBB to NewMBB for the fall-through.
329 CurMBB.addSuccessor(NewMBB);
330
331 // Splice the code over.
332 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000333
334 // For targets that use the register scavenger, we must maintain LiveIns.
335 if (RS) {
336 RS->enterBasicBlock(&CurMBB);
337 if (!CurMBB.empty())
338 RS->forward(prior(CurMBB.end()));
339 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
340 RS->getRegsUsed(RegsLiveAtExit, false);
341 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
342 if (RegsLiveAtExit[i])
343 NewMBB->addLiveIn(i);
344 }
345
Chris Lattner1d08d832006-11-01 01:16:12 +0000346 return NewMBB;
347}
348
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000349/// EstimateRuntime - Make a rough estimate for how long it will take to run
350/// the specified code.
351static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
352 MachineBasicBlock::iterator E,
353 const TargetInstrInfo *TII) {
354 unsigned Time = 0;
355 for (; I != E; ++I) {
356 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
357 if (TID.Flags & M_CALL_FLAG)
358 Time += 10;
359 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
360 Time += 2;
361 else
362 ++Time;
363 }
364 return Time;
365}
366
367/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
368/// MBB2I and then insert an unconditional branch in the other block. Determine
369/// which is the best to split
370static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
371 MachineBasicBlock::iterator MBB1I,
372 MachineBasicBlock *MBB2,
373 MachineBasicBlock::iterator MBB2I,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000374 const TargetInstrInfo *TII,
375 MachineBasicBlock *PredBB) {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000376 // If one block is the entry block, split the other one; we can't generate
377 // a branch to the entry block, as its label is not emitted.
378 MachineBasicBlock *Entry = MBB1->getParent()->begin();
379 if (MBB1 == Entry)
380 return false;
381 if (MBB2 == Entry)
382 return true;
383
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000384 // If one block falls through into the common successor, choose that
385 // one to split; it is one instruction less to do that.
386 if (PredBB) {
387 if (MBB1 == PredBB)
388 return true;
389 else if (MBB2 == PredBB)
390 return false;
391 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000392 // TODO: if we had some notion of which block was hotter, we could split
393 // the hot block, so it is the fall-through. Since we don't have profile info
394 // make a decision based on which will hurt most to split.
395 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
396 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
397
398 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
399 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
400 // have a lower overall impact on the program execution.
401 return MBB1Time < MBB2Time;
402}
403
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000404// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
405// branches temporarily for tail merging). In the case where CurMBB ends
406// with a conditional branch to the next block, optimize by reversing the
407// test and conditionally branching to SuccMBB instead.
408
409static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
410 const TargetInstrInfo *TII) {
411 MachineFunction *MF = CurMBB->getParent();
412 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
413 MachineBasicBlock *TBB = 0, *FBB = 0;
414 std::vector<MachineOperand> Cond;
415 if (I != MF->end() &&
416 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
417 MachineBasicBlock *NextBB = I;
418 if (TBB == NextBB && Cond.size() && !FBB) {
419 if (!TII->ReverseBranchCondition(Cond)) {
420 TII->RemoveBranch(*CurMBB);
421 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
422 return;
423 }
424 }
425 }
426 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
427}
428
Dale Johannesen44008c52007-05-30 00:32:01 +0000429static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
430 const std::pair<unsigned,MachineBasicBlock*> &q) {
Dale Johannesen95ef4062007-05-29 23:47:50 +0000431 if (p.first < q.first)
432 return true;
433 else if (p.first > q.first)
434 return false;
435 else if (p.second->getNumber() < q.second->getNumber())
436 return true;
437 else if (p.second->getNumber() > q.second->getNumber())
438 return false;
439 else
440 assert(0 && "Predecessor appears twice");
441}
442
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000443// See if any of the blocks in MergePotentials (which all have a common single
444// successor, or all have no successor) can be tail-merged. If there is a
445// successor, any blocks in MergePotentials that are not tail-merged and
446// are not immediately before Succ must have an unconditional branch to
447// Succ added (but the predecessor/successor lists need no adjustment).
448// The lone predecessor of Succ that falls through into Succ,
449// if any, is given in PredBB.
450
451bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
452 MachineBasicBlock* PredBB) {
Dale Johannesen7aea8322007-05-23 21:07:20 +0000453 unsigned minCommonTailLength = (SuccBB ? 1 : 2);
Chris Lattner12143052006-10-21 00:47:49 +0000454 MadeChange = false;
455
Chris Lattner12143052006-10-21 00:47:49 +0000456 // Sort by hash value so that blocks with identical end sequences sort
457 // together.
Dale Johannesen95ef4062007-05-29 23:47:50 +0000458 std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
Chris Lattner12143052006-10-21 00:47:49 +0000459
460 // Walk through equivalence sets looking for actual exact matches.
461 while (MergePotentials.size() > 1) {
462 unsigned CurHash = (MergePotentials.end()-1)->first;
463 unsigned PrevHash = (MergePotentials.end()-2)->first;
464 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
465
466 // If there is nothing that matches the hash of the current basic block,
467 // give up.
468 if (CurHash != PrevHash) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000469 if (SuccBB && CurMBB != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000470 FixTail(CurMBB, SuccBB, TII);
Chris Lattner12143052006-10-21 00:47:49 +0000471 MergePotentials.pop_back();
472 continue;
473 }
474
Dale Johannesena5a21172007-06-01 23:02:45 +0000475 // Look through all the pairs of blocks that have the same hash as this
476 // one, and find the pair that has the largest number of instructions in
477 // common.
478 // Since instructions may get combined later (e.g. single stores into
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000479 // store multiple) this measure is not particularly accurate.
Dale Johannesena5a21172007-06-01 23:02:45 +0000480 MachineBasicBlock::iterator BBI1, BBI2;
Dale Johannesen7aea8322007-05-23 21:07:20 +0000481
Dale Johannesena5a21172007-06-01 23:02:45 +0000482 unsigned FoundI = ~0U, FoundJ = ~0U;
Dale Johannesen7aea8322007-05-23 21:07:20 +0000483 unsigned maxCommonTailLength = 0U;
Dale Johannesena5a21172007-06-01 23:02:45 +0000484 for (int i = MergePotentials.size()-1;
Dale Johannesen7aea8322007-05-23 21:07:20 +0000485 i != -1 && MergePotentials[i].first == CurHash; --i) {
Dale Johannesena5a21172007-06-01 23:02:45 +0000486 for (int j = i-1;
487 j != -1 && MergePotentials[j].first == CurHash; --j) {
488 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
489 unsigned CommonTailLen = ComputeCommonTailLength(
490 MergePotentials[i].second,
491 MergePotentials[j].second,
492 TrialBBI1, TrialBBI2);
493 if (CommonTailLen >= minCommonTailLength &&
494 CommonTailLen > maxCommonTailLength) {
495 FoundI = i;
496 FoundJ = j;
497 maxCommonTailLength = CommonTailLen;
498 BBI1 = TrialBBI1;
499 BBI2 = TrialBBI2;
500 }
Chris Lattner12143052006-10-21 00:47:49 +0000501 }
Dale Johannesena5a21172007-06-01 23:02:45 +0000502 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000503
Dale Johannesena5a21172007-06-01 23:02:45 +0000504 // If we didn't find any pair that has at least minCommonTailLength
505 // instructions in common, bail out. All entries with this
506 // hash code can go away now.
507 if (FoundI == ~0U) {
508 for (int i = MergePotentials.size()-1;
509 i != -1 && MergePotentials[i].first == CurHash; --i) {
510 // Put the unconditional branch back, if we need one.
511 CurMBB = MergePotentials[i].second;
512 if (SuccBB && CurMBB != PredBB)
513 FixTail(CurMBB, SuccBB, TII);
514 MergePotentials.pop_back();
515 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000516 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000517 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000518
Dale Johannesena5a21172007-06-01 23:02:45 +0000519 // Otherwise, move the block(s) to the right position(s). So that
520 // BBI1/2 will be valid, the last must be I and the next-to-last J.
521 if (FoundI != MergePotentials.size()-1)
522 std::swap(MergePotentials[FoundI], *(MergePotentials.end()-1));
523 if (FoundJ != MergePotentials.size()-2)
524 std::swap(MergePotentials[FoundJ], *(MergePotentials.end()-2));
525
526 CurMBB = (MergePotentials.end()-1)->second;
Chris Lattner12143052006-10-21 00:47:49 +0000527 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
Chris Lattner1d08d832006-11-01 01:16:12 +0000528
529 // If neither block is the entire common tail, split the tail of one block
Dale Johannesen54f4a672007-05-10 23:59:23 +0000530 // to make it redundant with the other tail. Also, we cannot jump to the
531 // entry block, so if one block is the entry block, split the other one.
532 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
533 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
534 ; // CurMBB is common tail
535 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
536 ; // MBB2 is common tail
537 else {
Chris Lattner1d08d832006-11-01 01:16:12 +0000538 if (0) { // Enable this to disable partial tail merges.
539 MergePotentials.pop_back();
540 continue;
541 }
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000542
543 // Decide whether we want to split CurMBB or MBB2.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000544 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000545 CurMBB = SplitMBBAt(*CurMBB, BBI1);
546 BBI1 = CurMBB->begin();
547 MergePotentials.back().second = CurMBB;
548 } else {
549 MBB2 = SplitMBBAt(*MBB2, BBI2);
550 BBI2 = MBB2->begin();
551 (MergePotentials.end()-2)->second = MBB2;
552 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000553 }
554
Dale Johannesen54f4a672007-05-10 23:59:23 +0000555 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
Chris Lattner12143052006-10-21 00:47:49 +0000556 // Hack the end off CurMBB, making it jump to MBBI@ instead.
557 ReplaceTailWithBranchTo(BBI1, MBB2);
558 // This modifies CurMBB, so remove it from the worklist.
559 MergePotentials.pop_back();
Chris Lattner1d08d832006-11-01 01:16:12 +0000560 } else {
Dale Johannesen54f4a672007-05-10 23:59:23 +0000561 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
562 "Didn't split block correctly?");
Chris Lattner1d08d832006-11-01 01:16:12 +0000563 // Hack the end off MBB2, making it jump to CurMBB instead.
564 ReplaceTailWithBranchTo(BBI2, CurMBB);
565 // This modifies MBB2, so remove it from the worklist.
566 MergePotentials.erase(MergePotentials.end()-2);
Chris Lattner12143052006-10-21 00:47:49 +0000567 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000568 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000569 }
Chris Lattner12143052006-10-21 00:47:49 +0000570 return MadeChange;
571}
572
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000573bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000574
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000575 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000576
577 MadeChange = false;
578
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000579 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000580 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000581 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
582 if (I->succ_empty())
Dale Johannesen7aea8322007-05-23 21:07:20 +0000583 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000584 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000585 // See if we can do any tail merging on those.
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000586 if (MergePotentials.size() < TailMergeThreshold)
Dale Johannesen53af4c02007-06-08 00:34:27 +0000587 MadeChange |= TryMergeBlocks(NULL, NULL);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000588
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000589 // Look at blocks (IBB) with multiple predecessors (PBB).
590 // We change each predecessor to a canonical form, by
591 // (1) temporarily removing any unconditional branch from the predecessor
592 // to IBB, and
593 // (2) alter conditional branches so they branch to the other block
594 // not IBB; this may require adding back an unconditional branch to IBB
595 // later, where there wasn't one coming in. E.g.
596 // Bcc IBB
597 // fallthrough to QBB
598 // here becomes
599 // Bncc QBB
600 // with a conceptual B to IBB after that, which never actually exists.
601 // With those changes, we see whether the predecessors' tails match,
602 // and merge them if so. We change things out of canonical form and
603 // back to the way they were later in the process. (OptimizeBranches
604 // would undo some of this, but we can't use it, because we'd get into
605 // a compile-time infinite loop repeatedly doing and undoing the same
606 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000607
608 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000609 if (!I->succ_empty() && I->pred_size() >= 2 &&
610 I->pred_size() < TailMergeThreshold) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000611 MachineBasicBlock *IBB = I;
612 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000613 MergePotentials.clear();
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000614 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
615 E2 = I->pred_end();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000616 P != E2; ++P) {
617 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000618 // Skip blocks that loop to themselves, can't tail merge these.
619 if (PBB==IBB)
620 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000621 MachineBasicBlock *TBB = 0, *FBB = 0;
622 std::vector<MachineOperand> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000623 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
624 // Failing case: IBB is the target of a cbr, and
625 // we cannot reverse the branch.
626 std::vector<MachineOperand> NewCond(Cond);
627 if (Cond.size() && TBB==IBB) {
628 if (TII->ReverseBranchCondition(NewCond))
629 continue;
630 // This is the QBB case described above
631 if (!FBB)
632 FBB = next(MachineFunction::iterator(PBB));
633 }
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000634 // Failing case: the only way IBB can be reached from PBB is via
635 // exception handling. Happens for landing pads. Would be nice
636 // to have a bit in the edge so we didn't have to do all this.
637 if (IBB->isLandingPad()) {
638 MachineFunction::iterator IP = PBB; IP++;
639 MachineBasicBlock* PredNextBB = NULL;
640 if (IP!=MF.end())
641 PredNextBB = IP;
642 if (TBB==NULL) {
643 if (IBB!=PredNextBB) // fallthrough
644 continue;
645 } else if (FBB) {
646 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
647 continue;
648 } else if (Cond.size() == 0) {
649 if (TBB!=IBB) // ubr
650 continue;
651 } else {
652 if (TBB!=IBB && IBB!=PredNextBB) // cbr
653 continue;
654 }
655 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000656 // Remove the unconditional branch at the end, if any.
657 if (TBB && (Cond.size()==0 || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000658 TII->RemoveBranch(*PBB);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000659 if (Cond.size())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000660 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000661 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000662 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000663 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000664 }
665 }
666 if (MergePotentials.size() >= 2)
667 MadeChange |= TryMergeBlocks(I, PredBB);
668 // Reinsert an unconditional branch if needed.
669 // The 1 below can be either an original single predecessor, or a result
670 // of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000671 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000672 if (MergePotentials.size()==1 &&
673 (MergePotentials.begin())->second != PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000674 FixTail((MergePotentials.begin())->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000675 }
676 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000677 return MadeChange;
678}
Chris Lattner12143052006-10-21 00:47:49 +0000679
680//===----------------------------------------------------------------------===//
681// Branch Optimization
682//===----------------------------------------------------------------------===//
683
684bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
685 MadeChange = false;
686
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000687 // Make sure blocks are numbered in order
688 MF.RenumberBlocks();
689
Chris Lattner12143052006-10-21 00:47:49 +0000690 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
691 MachineBasicBlock *MBB = I++;
692 OptimizeBlock(MBB);
693
694 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000695 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000696 RemoveDeadBlock(MBB);
697 MadeChange = true;
698 ++NumDeadBlocks;
699 }
700 }
701 return MadeChange;
702}
703
704
Chris Lattner386e2902006-10-21 05:08:28 +0000705/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
706/// CFG to be inserted. If we have proven that MBB can only branch to DestA and
707/// DestB, remove any other MBB successors from the CFG. DestA and DestB can
708/// be null.
Dale Johannesen8e63bf32007-06-02 00:08:15 +0000709/// Besides DestA and DestB, retain other edges leading to LandingPads (currently
710/// there can be only one; we don't check or require that here).
711/// Note it is possible that DestA and/or DestB are LandingPads.
Chris Lattner386e2902006-10-21 05:08:28 +0000712static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
713 MachineBasicBlock *DestA,
714 MachineBasicBlock *DestB,
715 bool isCond,
716 MachineFunction::iterator FallThru) {
717 bool MadeChange = false;
718 bool AddedFallThrough = false;
719
720 // If this block ends with a conditional branch that falls through to its
721 // successor, set DestB as the successor.
722 if (isCond) {
723 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
724 DestB = FallThru;
725 AddedFallThrough = true;
726 }
727 } else {
728 // If this is an unconditional branch with no explicit dest, it must just be
729 // a fallthrough into DestB.
730 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
731 DestA = FallThru;
732 AddedFallThrough = true;
733 }
734 }
735
Dale Johannesena52dd152007-05-31 21:54:00 +0000736 MachineBasicBlock::succ_iterator SI = MBB.succ_begin();
Dale Johannesen8e63bf32007-06-02 00:08:15 +0000737 MachineBasicBlock *OrigDestA = DestA, *OrigDestB = DestB;
Chris Lattner386e2902006-10-21 05:08:28 +0000738 while (SI != MBB.succ_end()) {
Dale Johannesen035fdeb2007-05-24 18:31:55 +0000739 if (*SI == DestA && DestA == DestB) {
740 DestA = DestB = 0;
741 ++SI;
742 } else if (*SI == DestA) {
Chris Lattner386e2902006-10-21 05:08:28 +0000743 DestA = 0;
744 ++SI;
745 } else if (*SI == DestB) {
746 DestB = 0;
747 ++SI;
Dale Johannesen8e63bf32007-06-02 00:08:15 +0000748 } else if ((*SI)->isLandingPad() &&
749 *SI!=OrigDestA && *SI!=OrigDestB) {
Jim Laskey02b3f5e2007-02-21 22:42:20 +0000750 ++SI;
Chris Lattner386e2902006-10-21 05:08:28 +0000751 } else {
752 // Otherwise, this is a superfluous edge, remove it.
753 MBB.removeSuccessor(SI);
754 MadeChange = true;
755 }
756 }
757 if (!AddedFallThrough) {
758 assert(DestA == 0 && DestB == 0 &&
759 "MachineCFG is missing edges!");
760 } else if (isCond) {
761 assert(DestA == 0 && "MachineCFG is missing edges!");
762 }
763 return MadeChange;
764}
765
766
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000767/// CanFallThrough - Return true if the specified block (with the specified
768/// branch condition) can implicitly transfer control to the block after it by
769/// falling off the end of it. This should return false if it can reach the
770/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
771///
772/// True is a conservative answer.
773///
774bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
775 bool BranchUnAnalyzable,
776 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
777 const std::vector<MachineOperand> &Cond) {
778 MachineFunction::iterator Fallthrough = CurBB;
779 ++Fallthrough;
780 // If FallthroughBlock is off the end of the function, it can't fall through.
781 if (Fallthrough == CurBB->getParent()->end())
782 return false;
783
784 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
785 if (!CurBB->isSuccessor(Fallthrough))
786 return false;
787
788 // If we couldn't analyze the branch, assume it could fall through.
789 if (BranchUnAnalyzable) return true;
790
Chris Lattner7d097842006-10-24 01:12:32 +0000791 // If there is no branch, control always falls through.
792 if (TBB == 0) return true;
793
794 // If there is some explicit branch to the fallthrough block, it can obviously
795 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000796 if (MachineFunction::iterator(TBB) == Fallthrough ||
797 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000798 return true;
799
800 // If it's an unconditional branch to some block not the fall through, it
801 // doesn't fall through.
802 if (Cond.empty()) return false;
803
804 // Otherwise, if it is conditional and has no explicit false block, it falls
805 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000806 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000807}
808
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000809/// CanFallThrough - Return true if the specified can implicitly transfer
810/// control to the block after it by falling off the end of it. This should
811/// return false if it can reach the block after it, but it uses an explicit
812/// branch to do so (e.g. a table jump).
813///
814/// True is a conservative answer.
815///
816bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
817 MachineBasicBlock *TBB = 0, *FBB = 0;
818 std::vector<MachineOperand> Cond;
819 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
820 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
821}
822
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000823/// IsBetterFallthrough - Return true if it would be clearly better to
824/// fall-through to MBB1 than to fall through into MBB2. This has to return
825/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
826/// result in infinite loops.
827static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
828 MachineBasicBlock *MBB2,
829 const TargetInstrInfo &TII) {
Chris Lattner154e1042006-11-18 21:30:35 +0000830 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
831 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000832 // optimize branches that branch to either a return block or an assert block
833 // into a fallthrough to the return.
834 if (MBB1->empty() || MBB2->empty()) return false;
835
836 MachineInstr *MBB1I = --MBB1->end();
837 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner154e1042006-11-18 21:30:35 +0000838 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000839}
840
Chris Lattner7821a8a2006-10-14 00:21:48 +0000841/// OptimizeBlock - Analyze and optimize control flow related to the specified
842/// block. This is never called on the entry block.
Chris Lattner7d097842006-10-24 01:12:32 +0000843void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
844 MachineFunction::iterator FallThrough = MBB;
845 ++FallThrough;
846
Chris Lattnereb15eee2006-10-13 20:43:10 +0000847 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesena52dd152007-05-31 21:54:00 +0000848 // explicitly. Landing pads should not do this since the landing-pad table
849 // points to this block.
850 if (MBB->empty() && !MBB->isLandingPad()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000851 // Dead block? Leave for cleanup later.
Jim Laskey033c9712007-02-22 16:39:03 +0000852 if (MBB->pred_empty()) return;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000853
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000854 if (FallThrough == MBB->getParent()->end()) {
855 // TODO: Simplify preds to not branch here if possible!
856 } else {
857 // Rewrite all predecessors of the old block to go to the fallthrough
858 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000859 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000860 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Evan Cheng0370fad2007-06-04 06:44:01 +0000861 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000862 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000863
864 // If MBB was the target of a jump table, update jump tables to go to the
865 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000866 MBB->getParent()->getJumpTableInfo()->
867 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000868 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000869 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000870 return;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000871 }
872
Chris Lattner7821a8a2006-10-14 00:21:48 +0000873 // Check to see if we can simplify the terminator of the block before this
874 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000875 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000876
Chris Lattner7821a8a2006-10-14 00:21:48 +0000877 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
878 std::vector<MachineOperand> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000879 bool PriorUnAnalyzable =
880 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +0000881 if (!PriorUnAnalyzable) {
882 // If the CFG for the prior block has extra edges, remove them.
883 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
884 !PriorCond.empty(), MBB);
885
Chris Lattner7821a8a2006-10-14 00:21:48 +0000886 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000887 // destination, remove the branch, replacing it with an unconditional one or
888 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000889 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000890 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000891 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000892 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000893 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000894 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000895 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000896 return OptimizeBlock(MBB);
897 }
898
899 // If the previous branch *only* branches to *this* block (conditional or
900 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000901 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000902 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000903 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000904 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000905 return OptimizeBlock(MBB);
906 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000907
908 // If the prior block branches somewhere else on the condition and here if
909 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000910 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000911 TII->RemoveBranch(PrevBB);
912 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
913 MadeChange = true;
914 ++NumBranchOpts;
915 return OptimizeBlock(MBB);
916 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000917
918 // If the prior block branches here on true and somewhere else on false, and
919 // if the branch condition is reversible, reverse the branch to create a
920 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000921 if (PriorTBB == MBB) {
Chris Lattnera2d79952006-10-21 05:54:00 +0000922 std::vector<MachineOperand> NewPriorCond(PriorCond);
923 if (!TII->ReverseBranchCondition(NewPriorCond)) {
924 TII->RemoveBranch(PrevBB);
925 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
926 MadeChange = true;
927 ++NumBranchOpts;
928 return OptimizeBlock(MBB);
929 }
930 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000931
Chris Lattner154e1042006-11-18 21:30:35 +0000932 // If this block doesn't fall through (e.g. it ends with an uncond branch or
933 // has no successors) and if the pred falls through into this block, and if
934 // it would otherwise fall through into the block after this, move this
935 // block to the end of the function.
936 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000937 // We consider it more likely that execution will stay in the function (e.g.
938 // due to loops) than it is to exit it. This asserts in loops etc, moving
939 // the assert condition out of the loop body.
Chris Lattner154e1042006-11-18 21:30:35 +0000940 if (!PriorCond.empty() && PriorFBB == 0 &&
941 MachineFunction::iterator(PriorTBB) == FallThrough &&
942 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000943 bool DoTransform = true;
944
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000945 // We have to be careful that the succs of PredBB aren't both no-successor
946 // blocks. If neither have successors and if PredBB is the second from
947 // last block in the function, we'd just keep swapping the two blocks for
948 // last. Only do the swap if one is clearly better to fall through than
949 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000950 if (FallThrough == --MBB->getParent()->end() &&
951 !IsBetterFallthrough(PriorTBB, MBB, *TII))
952 DoTransform = false;
953
954 // We don't want to do this transformation if we have control flow like:
955 // br cond BB2
956 // BB1:
957 // ..
958 // jmp BBX
959 // BB2:
960 // ..
961 // ret
962 //
963 // In this case, we could actually be moving the return block *into* a
964 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000965 if (DoTransform && !MBB->succ_empty() &&
966 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000967 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000968
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000969
970 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000971 // Reverse the branch so we will fall through on the previous true cond.
972 std::vector<MachineOperand> NewPriorCond(PriorCond);
973 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000974 DOUT << "\nMoving MBB: " << *MBB;
975 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
976
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000977 TII->RemoveBranch(PrevBB);
978 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
979
980 // Move this block to the end of the function.
981 MBB->moveAfter(--MBB->getParent()->end());
982 MadeChange = true;
983 ++NumBranchOpts;
984 return;
985 }
986 }
987 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000988 }
Chris Lattner7821a8a2006-10-14 00:21:48 +0000989
Chris Lattner386e2902006-10-21 05:08:28 +0000990 // Analyze the branch in the current block.
991 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
992 std::vector<MachineOperand> CurCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000993 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
994 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +0000995 // If the CFG for the prior block has extra edges, remove them.
996 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
Chris Lattner7d097842006-10-24 01:12:32 +0000997 !CurCond.empty(),
998 ++MachineFunction::iterator(MBB));
Chris Lattnereb15eee2006-10-13 20:43:10 +0000999
Chris Lattner5d056952006-11-08 01:03:21 +00001000 // If this is a two-way branch, and the FBB branches to this block, reverse
1001 // the condition so the single-basic-block loop is faster. Instead of:
1002 // Loop: xxx; jcc Out; jmp Loop
1003 // we want:
1004 // Loop: xxx; jncc Loop; jmp Out
1005 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1006 std::vector<MachineOperand> NewCond(CurCond);
1007 if (!TII->ReverseBranchCondition(NewCond)) {
1008 TII->RemoveBranch(*MBB);
1009 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1010 MadeChange = true;
1011 ++NumBranchOpts;
1012 return OptimizeBlock(MBB);
1013 }
1014 }
1015
1016
Chris Lattner386e2902006-10-21 05:08:28 +00001017 // If this branch is the only thing in its block, see if we can forward
1018 // other blocks across it.
1019 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner7d097842006-10-24 01:12:32 +00001020 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +00001021 // This block may contain just an unconditional branch. Because there can
1022 // be 'non-branch terminators' in the block, try removing the branch and
1023 // then seeing if the block is empty.
1024 TII->RemoveBranch(*MBB);
1025
1026 // If this block is just an unconditional branch to CurTBB, we can
1027 // usually completely eliminate the block. The only case we cannot
1028 // completely eliminate the block is when the block before this one
1029 // falls through into MBB and we can't understand the prior block's branch
1030 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +00001031 if (MBB->empty()) {
1032 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1033 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1034 !PrevBB.isSuccessor(MBB)) {
1035 // If the prior block falls through into us, turn it into an
1036 // explicit branch to us to make updates simpler.
1037 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1038 PriorTBB != MBB && PriorFBB != MBB) {
1039 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001040 assert(PriorCond.empty() && PriorFBB == 0 &&
1041 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001042 PriorTBB = MBB;
1043 } else {
1044 assert(PriorFBB == 0 && "Machine CFG out of date!");
1045 PriorFBB = MBB;
1046 }
1047 TII->RemoveBranch(PrevBB);
1048 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001049 }
Chris Lattner386e2902006-10-21 05:08:28 +00001050
Chris Lattnercf420cc2006-10-28 17:32:47 +00001051 // Iterate through all the predecessors, revectoring each in-turn.
1052 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1053 bool DidChange = false;
1054 bool HasBranchToSelf = false;
1055 while (PI != MBB->pred_end()) {
1056 if (*PI == MBB) {
1057 // If this block has an uncond branch to itself, leave it.
1058 ++PI;
1059 HasBranchToSelf = true;
1060 } else {
1061 DidChange = true;
Evan Cheng0370fad2007-06-04 06:44:01 +00001062 (*PI)->ReplaceUsesOfBlockWith(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001063 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001064 }
Chris Lattner386e2902006-10-21 05:08:28 +00001065
Chris Lattnercf420cc2006-10-28 17:32:47 +00001066 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001067 MBB->getParent()->getJumpTableInfo()->
1068 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001069 if (DidChange) {
1070 ++NumBranchOpts;
1071 MadeChange = true;
1072 if (!HasBranchToSelf) return;
1073 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001074 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001075 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001076
Chris Lattner386e2902006-10-21 05:08:28 +00001077 // Add the branch back if the block is more than just an uncond branch.
1078 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001079 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001080 }
1081
1082 // If the prior block doesn't fall through into this block, and if this
1083 // block doesn't fall through into some other block, see if we can find a
1084 // place to move this block where a fall-through will happen.
1085 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1086 PriorTBB, PriorFBB, PriorCond)) {
1087 // Now we know that there was no fall-through into this block, check to
1088 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001089 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001090 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001091
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001092 if (!MBB->isLandingPad()) {
1093 // Check all the predecessors of this block. If one of them has no fall
1094 // throughs, move this block right after it.
1095 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1096 E = MBB->pred_end(); PI != E; ++PI) {
1097 // Analyze the branch at the end of the pred.
1098 MachineBasicBlock *PredBB = *PI;
1099 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1100 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001101 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001102 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1103 // If the current block doesn't fall through, just move it.
1104 // If the current block can fall through and does not end with a
1105 // conditional branch, we need to append an unconditional jump to
1106 // the (current) next block. To avoid a possible compile-time
1107 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001108 // Also, if there are already 2 branches here, we cannot add a third;
1109 // this means we have the case
1110 // Bcc next
1111 // B elsewhere
1112 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001113 if (CurFallsThru) {
1114 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1115 CurCond.clear();
1116 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1117 }
1118 MBB->moveAfter(PredBB);
1119 MadeChange = true;
1120 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001121 }
1122 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001123 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001124
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001125 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001126 // Check all successors to see if we can move this block before it.
1127 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1128 E = MBB->succ_end(); SI != E; ++SI) {
1129 // Analyze the branch at the end of the block before the succ.
1130 MachineBasicBlock *SuccBB = *SI;
1131 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001132 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001133
1134 // If this block doesn't already fall-through to that successor, and if
1135 // the succ doesn't already have a block that can fall through into it,
1136 // and if the successor isn't an EH destination, we can arrange for the
1137 // fallthrough to happen.
1138 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1139 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001140 MBB->moveBefore(SuccBB);
1141 MadeChange = true;
1142 return OptimizeBlock(MBB);
1143 }
1144 }
1145
1146 // Okay, there is no really great place to put this block. If, however,
1147 // the block before this one would be a fall-through if this block were
1148 // removed, move this block to the end of the function.
1149 if (FallThrough != MBB->getParent()->end() &&
1150 PrevBB.isSuccessor(FallThrough)) {
1151 MBB->moveAfter(--MBB->getParent()->end());
1152 MadeChange = true;
1153 return;
1154 }
Chris Lattner7d097842006-10-24 01:12:32 +00001155 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001156 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001157}