BranchFolding.cpp revision 77edc4b1b004726d96c932356750b9f3c96d74dd
1//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3//                     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.
7//
8//===----------------------------------------------------------------------===//
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
19#define DEBUG_TYPE "branchfolding"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/RegisterScavenging.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Target/MRegisterInfo.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/ADT/STLExtras.h"
32#include <algorithm>
33using namespace llvm;
34
35STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36STATISTIC(NumBranchOpts, "Number of branches optimized");
37STATISTIC(NumTailMerge , "Number of block tails merged");
38static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
39
40namespace {
41  struct BranchFolder : public MachineFunctionPass {
42    virtual bool runOnMachineFunction(MachineFunction &MF);
43    virtual const char *getPassName() const { return "Control Flow Optimizer"; }
44    const TargetInstrInfo *TII;
45    MachineModuleInfo *MMI;
46    bool MadeChange;
47  private:
48    // Tail Merging.
49    bool TailMergeBlocks(MachineFunction &MF);
50    void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
51                                 MachineBasicBlock *NewDest);
52    MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
53                                  MachineBasicBlock::iterator BBI1);
54
55    const MRegisterInfo *RegInfo;
56    RegScavenger *RS;
57    // Branch optzn.
58    bool OptimizeBranches(MachineFunction &MF);
59    void OptimizeBlock(MachineBasicBlock *MBB);
60    void RemoveDeadBlock(MachineBasicBlock *MBB);
61
62    bool CanFallThrough(MachineBasicBlock *CurBB);
63    bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
64                        MachineBasicBlock *TBB, MachineBasicBlock *FBB,
65                        const std::vector<MachineOperand> &Cond);
66  };
67}
68
69FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
70
71/// RemoveDeadBlock - Remove the specified dead machine basic block from the
72/// function, updating the CFG.
73void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
74  assert(MBB->pred_empty() && "MBB must be dead!");
75  DOUT << "\nRemoving MBB: " << *MBB;
76
77  MachineFunction *MF = MBB->getParent();
78  // drop all successors.
79  while (!MBB->succ_empty())
80    MBB->removeSuccessor(MBB->succ_end()-1);
81
82  // If there is DWARF info to active, check to see if there are any LABEL
83  // records in the basic block.  If so, unregister them from MachineModuleInfo.
84  if (MMI && !MBB->empty()) {
85    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
86         I != E; ++I) {
87      if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
88        // The label ID # is always operand #0, an immediate.
89        MMI->InvalidateLabel(I->getOperand(0).getImm());
90      }
91    }
92  }
93
94  // Remove the block.
95  MF->getBasicBlockList().erase(MBB);
96}
97
98bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
99  TII = MF.getTarget().getInstrInfo();
100  if (!TII) return false;
101
102  RegInfo = MF.getTarget().getRegisterInfo();
103  RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
104
105  MMI = getAnalysisToUpdate<MachineModuleInfo>();
106
107  bool EverMadeChange = false;
108  bool MadeChangeThisIteration = true;
109  while (MadeChangeThisIteration) {
110    MadeChangeThisIteration = false;
111    MadeChangeThisIteration |= TailMergeBlocks(MF);
112    MadeChangeThisIteration |= OptimizeBranches(MF);
113    EverMadeChange |= MadeChangeThisIteration;
114  }
115
116  // See if any jump tables have become mergable or dead as the code generator
117  // did its thing.
118  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
119  const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
120  if (!JTs.empty()) {
121    // Figure out how these jump tables should be merged.
122    std::vector<unsigned> JTMapping;
123    JTMapping.reserve(JTs.size());
124
125    // We always keep the 0th jump table.
126    JTMapping.push_back(0);
127
128    // Scan the jump tables, seeing if there are any duplicates.  Note that this
129    // is N^2, which should be fixed someday.
130    for (unsigned i = 1, e = JTs.size(); i != e; ++i)
131      JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
132
133    // If a jump table was merge with another one, walk the function rewriting
134    // references to jump tables to reference the new JT ID's.  Keep track of
135    // whether we see a jump table idx, if not, we can delete the JT.
136    std::vector<bool> JTIsLive;
137    JTIsLive.resize(JTs.size());
138    for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
139         BB != E; ++BB) {
140      for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
141           I != E; ++I)
142        for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
143          MachineOperand &Op = I->getOperand(op);
144          if (!Op.isJumpTableIndex()) continue;
145          unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
146          Op.setJumpTableIndex(NewIdx);
147
148          // Remember that this JT is live.
149          JTIsLive[NewIdx] = true;
150        }
151    }
152
153    // Finally, remove dead jump tables.  This happens either because the
154    // indirect jump was unreachable (and thus deleted) or because the jump
155    // table was merged with some other one.
156    for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
157      if (!JTIsLive[i]) {
158        JTI->RemoveJumpTable(i);
159        EverMadeChange = true;
160      }
161  }
162
163  delete RS;
164  return EverMadeChange;
165}
166
167//===----------------------------------------------------------------------===//
168//  Tail Merging of Blocks
169//===----------------------------------------------------------------------===//
170
171/// HashMachineInstr - Compute a hash value for MI and its operands.
172static unsigned HashMachineInstr(const MachineInstr *MI) {
173  unsigned Hash = MI->getOpcode();
174  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
175    const MachineOperand &Op = MI->getOperand(i);
176
177    // Merge in bits from the operand if easy.
178    unsigned OperandHash = 0;
179    switch (Op.getType()) {
180    case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
181    case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
182    case MachineOperand::MO_MachineBasicBlock:
183      OperandHash = Op.getMachineBasicBlock()->getNumber();
184      break;
185    case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
186    case MachineOperand::MO_ConstantPoolIndex:
187      OperandHash = Op.getConstantPoolIndex();
188      break;
189    case MachineOperand::MO_JumpTableIndex:
190      OperandHash = Op.getJumpTableIndex();
191      break;
192    case MachineOperand::MO_GlobalAddress:
193    case MachineOperand::MO_ExternalSymbol:
194      // Global address / external symbol are too hard, don't bother, but do
195      // pull in the offset.
196      OperandHash = Op.getOffset();
197      break;
198    default: break;
199    }
200
201    Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
202  }
203  return Hash;
204}
205
206/// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
207/// instructions, because cross-jumping only saves code when at least two
208/// instructions are removed (since a branch must be inserted).
209static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
210  MachineBasicBlock::const_iterator I = MBB->end();
211  if (I == MBB->begin())
212    return 0;   // Empty MBB.
213
214  --I;
215  unsigned Hash = HashMachineInstr(I);
216
217  if (I == MBB->begin())
218    return Hash;   // Single instr MBB.
219
220  --I;
221  // Hash in the second-to-last instruction.
222  Hash ^= HashMachineInstr(I) << 2;
223  return Hash;
224}
225
226/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
227/// of instructions they actually have in common together at their end.  Return
228/// iterators for the first shared instruction in each block.
229static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
230                                        MachineBasicBlock *MBB2,
231                                        MachineBasicBlock::iterator &I1,
232                                        MachineBasicBlock::iterator &I2) {
233  I1 = MBB1->end();
234  I2 = MBB2->end();
235
236  unsigned TailLen = 0;
237  while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
238    --I1; --I2;
239    if (!I1->isIdenticalTo(I2)) {
240      ++I1; ++I2;
241      break;
242    }
243    ++TailLen;
244  }
245  return TailLen;
246}
247
248/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
249/// after it, replacing it with an unconditional branch to NewDest.  This
250/// returns true if OldInst's block is modified, false if NewDest is modified.
251void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
252                                           MachineBasicBlock *NewDest) {
253  MachineBasicBlock *OldBB = OldInst->getParent();
254
255  // Remove all the old successors of OldBB from the CFG.
256  while (!OldBB->succ_empty())
257    OldBB->removeSuccessor(OldBB->succ_begin());
258
259  // Remove all the dead instructions from the end of OldBB.
260  OldBB->erase(OldInst, OldBB->end());
261
262  // If OldBB isn't immediately before OldBB, insert a branch to it.
263  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
264    TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
265  OldBB->addSuccessor(NewDest);
266  ++NumTailMerge;
267}
268
269/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
270/// MBB so that the part before the iterator falls into the part starting at the
271/// iterator.  This returns the new MBB.
272MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
273                                            MachineBasicBlock::iterator BBI1) {
274  // Create the fall-through block.
275  MachineFunction::iterator MBBI = &CurMBB;
276  MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
277  CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
278
279  // Move all the successors of this block to the specified block.
280  while (!CurMBB.succ_empty()) {
281    MachineBasicBlock *S = *(CurMBB.succ_end()-1);
282    NewMBB->addSuccessor(S);
283    CurMBB.removeSuccessor(S);
284  }
285
286  // Add an edge from CurMBB to NewMBB for the fall-through.
287  CurMBB.addSuccessor(NewMBB);
288
289  // Splice the code over.
290  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
291
292  // For targets that use the register scavenger, we must maintain LiveIns.
293  if (RS) {
294    RS->enterBasicBlock(&CurMBB);
295    if (!CurMBB.empty())
296      RS->forward(prior(CurMBB.end()));
297    BitVector RegsLiveAtExit(RegInfo->getNumRegs());
298    RS->getRegsUsed(RegsLiveAtExit, false);
299    for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
300      if (RegsLiveAtExit[i])
301        NewMBB->addLiveIn(i);
302  }
303
304  return NewMBB;
305}
306
307/// EstimateRuntime - Make a rough estimate for how long it will take to run
308/// the specified code.
309static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
310                                MachineBasicBlock::iterator E,
311                                const TargetInstrInfo *TII) {
312  unsigned Time = 0;
313  for (; I != E; ++I) {
314    const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
315    if (TID.Flags & M_CALL_FLAG)
316      Time += 10;
317    else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
318      Time += 2;
319    else
320      ++Time;
321  }
322  return Time;
323}
324
325/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
326/// MBB2I and then insert an unconditional branch in the other block.  Determine
327/// which is the best to split
328static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
329                                  MachineBasicBlock::iterator MBB1I,
330                                  MachineBasicBlock *MBB2,
331                                  MachineBasicBlock::iterator MBB2I,
332                                  const TargetInstrInfo *TII) {
333  // TODO: if we had some notion of which block was hotter, we could split
334  // the hot block, so it is the fall-through.  Since we don't have profile info
335  // make a decision based on which will hurt most to split.
336  unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
337  unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
338
339  // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
340  // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
341  // have a lower overall impact on the program execution.
342  return MBB1Time < MBB2Time;
343}
344
345bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
346  MadeChange = false;
347
348  if (!EnableTailMerge) return false;
349
350  // Find blocks with no successors.
351  std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
352  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
353    if (I->succ_empty())
354      MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
355  }
356
357  // Sort by hash value so that blocks with identical end sequences sort
358  // together.
359  std::stable_sort(MergePotentials.begin(), MergePotentials.end());
360
361  // Walk through equivalence sets looking for actual exact matches.
362  while (MergePotentials.size() > 1) {
363    unsigned CurHash  = (MergePotentials.end()-1)->first;
364    unsigned PrevHash = (MergePotentials.end()-2)->first;
365    MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
366
367    // If there is nothing that matches the hash of the current basic block,
368    // give up.
369    if (CurHash != PrevHash) {
370      MergePotentials.pop_back();
371      continue;
372    }
373
374    // Determine the actual length of the shared tail between these two basic
375    // blocks.  Because the hash can have collisions, it's possible that this is
376    // less than 2.
377    MachineBasicBlock::iterator BBI1, BBI2;
378    unsigned CommonTailLen =
379      ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
380                              BBI1, BBI2);
381
382    // If the tails don't have at least two instructions in common, see if there
383    // is anything else in the equivalence class that does match.
384    if (CommonTailLen < 2) {
385      unsigned FoundMatch = ~0U;
386      for (int i = MergePotentials.size()-2;
387           i != -1 && MergePotentials[i].first == CurHash; --i) {
388        CommonTailLen = ComputeCommonTailLength(CurMBB,
389                                                MergePotentials[i].second,
390                                                BBI1, BBI2);
391        if (CommonTailLen >= 2) {
392          FoundMatch = i;
393          break;
394        }
395      }
396
397      // If we didn't find anything that has at least two instructions matching
398      // this one, bail out.
399      if (FoundMatch == ~0U) {
400        MergePotentials.pop_back();
401        continue;
402      }
403
404      // Otherwise, move the matching block to the right position.
405      std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
406    }
407
408    MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
409
410    // If neither block is the entire common tail, split the tail of one block
411    // to make it redundant with the other tail.
412    if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
413      if (0) { // Enable this to disable partial tail merges.
414        MergePotentials.pop_back();
415        continue;
416      }
417
418      // Decide whether we want to split CurMBB or MBB2.
419      if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
420        CurMBB = SplitMBBAt(*CurMBB, BBI1);
421        BBI1 = CurMBB->begin();
422        MergePotentials.back().second = CurMBB;
423      } else {
424        MBB2 = SplitMBBAt(*MBB2, BBI2);
425        BBI2 = MBB2->begin();
426        (MergePotentials.end()-2)->second = MBB2;
427      }
428    }
429
430    if (MBB2->begin() == BBI2) {
431      // Hack the end off CurMBB, making it jump to MBBI@ instead.
432      ReplaceTailWithBranchTo(BBI1, MBB2);
433      // This modifies CurMBB, so remove it from the worklist.
434      MergePotentials.pop_back();
435    } else {
436      assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
437      // Hack the end off MBB2, making it jump to CurMBB instead.
438      ReplaceTailWithBranchTo(BBI2, CurMBB);
439      // This modifies MBB2, so remove it from the worklist.
440      MergePotentials.erase(MergePotentials.end()-2);
441    }
442    MadeChange = true;
443  }
444
445  return MadeChange;
446}
447
448
449//===----------------------------------------------------------------------===//
450//  Branch Optimization
451//===----------------------------------------------------------------------===//
452
453bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
454  MadeChange = false;
455
456  // Make sure blocks are numbered in order
457  MF.RenumberBlocks();
458
459  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
460    MachineBasicBlock *MBB = I++;
461    OptimizeBlock(MBB);
462
463    // If it is dead, remove it.
464    if (MBB->pred_empty()) {
465      RemoveDeadBlock(MBB);
466      MadeChange = true;
467      ++NumDeadBlocks;
468    }
469  }
470  return MadeChange;
471}
472
473
474/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
475/// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
476/// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
477/// be null.
478static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
479                                 MachineBasicBlock *DestA,
480                                 MachineBasicBlock *DestB,
481                                 bool isCond,
482                                 MachineFunction::iterator FallThru) {
483  bool MadeChange = false;
484  bool AddedFallThrough = false;
485
486  // If this block ends with a conditional branch that falls through to its
487  // successor, set DestB as the successor.
488  if (isCond) {
489    if (DestB == 0 && FallThru != MBB.getParent()->end()) {
490      DestB = FallThru;
491      AddedFallThrough = true;
492    }
493  } else {
494    // If this is an unconditional branch with no explicit dest, it must just be
495    // a fallthrough into DestB.
496    if (DestA == 0 && FallThru != MBB.getParent()->end()) {
497      DestA = FallThru;
498      AddedFallThrough = true;
499    }
500  }
501
502  MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
503  while (SI != MBB.succ_end()) {
504    if (*SI == DestA) {
505      DestA = 0;
506      ++SI;
507    } else if (*SI == DestB) {
508      DestB = 0;
509      ++SI;
510    } else if ((*SI)->isLandingPad()) {
511      ++SI;
512    } else {
513      // Otherwise, this is a superfluous edge, remove it.
514      MBB.removeSuccessor(SI);
515      MadeChange = true;
516    }
517  }
518  if (!AddedFallThrough) {
519    assert(DestA == 0 && DestB == 0 &&
520           "MachineCFG is missing edges!");
521  } else if (isCond) {
522    assert(DestA == 0 && "MachineCFG is missing edges!");
523  }
524  return MadeChange;
525}
526
527
528/// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
529/// 'Old', change the code and CFG so that it branches to 'New' instead.
530static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
531                                   MachineBasicBlock *Old,
532                                   MachineBasicBlock *New,
533                                   const TargetInstrInfo *TII) {
534  assert(Old != New && "Cannot replace self with self!");
535
536  MachineBasicBlock::iterator I = BB->end();
537  while (I != BB->begin()) {
538    --I;
539    if (!TII->isTerminatorInstr(I->getOpcode())) break;
540
541    // Scan the operands of this machine instruction, replacing any uses of Old
542    // with New.
543    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
544      if (I->getOperand(i).isMachineBasicBlock() &&
545          I->getOperand(i).getMachineBasicBlock() == Old)
546        I->getOperand(i).setMachineBasicBlock(New);
547  }
548
549  // Update the successor information.
550  std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
551  for (int i = Succs.size()-1; i >= 0; --i)
552    if (Succs[i] == Old) {
553      BB->removeSuccessor(Old);
554      BB->addSuccessor(New);
555    }
556}
557
558/// CanFallThrough - Return true if the specified block (with the specified
559/// branch condition) can implicitly transfer control to the block after it by
560/// falling off the end of it.  This should return false if it can reach the
561/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
562///
563/// True is a conservative answer.
564///
565bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
566                                  bool BranchUnAnalyzable,
567                                  MachineBasicBlock *TBB, MachineBasicBlock *FBB,
568                                  const std::vector<MachineOperand> &Cond) {
569  MachineFunction::iterator Fallthrough = CurBB;
570  ++Fallthrough;
571  // If FallthroughBlock is off the end of the function, it can't fall through.
572  if (Fallthrough == CurBB->getParent()->end())
573    return false;
574
575  // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
576  if (!CurBB->isSuccessor(Fallthrough))
577    return false;
578
579  // If we couldn't analyze the branch, assume it could fall through.
580  if (BranchUnAnalyzable) return true;
581
582  // If there is no branch, control always falls through.
583  if (TBB == 0) return true;
584
585  // If there is some explicit branch to the fallthrough block, it can obviously
586  // reach, even though the branch should get folded to fall through implicitly.
587  if (MachineFunction::iterator(TBB) == Fallthrough ||
588      MachineFunction::iterator(FBB) == Fallthrough)
589    return true;
590
591  // If it's an unconditional branch to some block not the fall through, it
592  // doesn't fall through.
593  if (Cond.empty()) return false;
594
595  // Otherwise, if it is conditional and has no explicit false block, it falls
596  // through.
597  return FBB == 0;
598}
599
600/// CanFallThrough - Return true if the specified can implicitly transfer
601/// control to the block after it by falling off the end of it.  This should
602/// return false if it can reach the block after it, but it uses an explicit
603/// branch to do so (e.g. a table jump).
604///
605/// True is a conservative answer.
606///
607bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
608  MachineBasicBlock *TBB = 0, *FBB = 0;
609  std::vector<MachineOperand> Cond;
610  bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
611  return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
612}
613
614/// IsBetterFallthrough - Return true if it would be clearly better to
615/// fall-through to MBB1 than to fall through into MBB2.  This has to return
616/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
617/// result in infinite loops.
618static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
619                                MachineBasicBlock *MBB2,
620                                const TargetInstrInfo &TII) {
621  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
622  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
623  // optimize branches that branch to either a return block or an assert block
624  // into a fallthrough to the return.
625  if (MBB1->empty() || MBB2->empty()) return false;
626
627  MachineInstr *MBB1I = --MBB1->end();
628  MachineInstr *MBB2I = --MBB2->end();
629  return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
630}
631
632/// OptimizeBlock - Analyze and optimize control flow related to the specified
633/// block.  This is never called on the entry block.
634void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
635  MachineFunction::iterator FallThrough = MBB;
636  ++FallThrough;
637
638  // If this block is empty, make everyone use its fall-through, not the block
639  // explicitly.
640  if (MBB->empty()) {
641    // Dead block?  Leave for cleanup later.
642    if (MBB->pred_empty()) return;
643
644    if (FallThrough == MBB->getParent()->end()) {
645      // TODO: Simplify preds to not branch here if possible!
646    } else {
647      // Rewrite all predecessors of the old block to go to the fallthrough
648      // instead.
649      while (!MBB->pred_empty()) {
650        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
651        ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
652      }
653
654      // If MBB was the target of a jump table, update jump tables to go to the
655      // fallthrough instead.
656      MBB->getParent()->getJumpTableInfo()->
657        ReplaceMBBInJumpTables(MBB, FallThrough);
658      MadeChange = true;
659    }
660    return;
661  }
662
663  // Check to see if we can simplify the terminator of the block before this
664  // one.
665  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
666
667  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
668  std::vector<MachineOperand> PriorCond;
669  bool PriorUnAnalyzable =
670    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
671  if (!PriorUnAnalyzable) {
672    // If the CFG for the prior block has extra edges, remove them.
673    MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
674                                       !PriorCond.empty(), MBB);
675
676    // If the previous branch is conditional and both conditions go to the same
677    // destination, remove the branch, replacing it with an unconditional one or
678    // a fall-through.
679    if (PriorTBB && PriorTBB == PriorFBB) {
680      TII->RemoveBranch(PrevBB);
681      PriorCond.clear();
682      if (PriorTBB != MBB)
683        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
684      MadeChange = true;
685      ++NumBranchOpts;
686      return OptimizeBlock(MBB);
687    }
688
689    // If the previous branch *only* branches to *this* block (conditional or
690    // not) remove the branch.
691    if (PriorTBB == MBB && PriorFBB == 0) {
692      TII->RemoveBranch(PrevBB);
693      MadeChange = true;
694      ++NumBranchOpts;
695      return OptimizeBlock(MBB);
696    }
697
698    // If the prior block branches somewhere else on the condition and here if
699    // the condition is false, remove the uncond second branch.
700    if (PriorFBB == MBB) {
701      TII->RemoveBranch(PrevBB);
702      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
703      MadeChange = true;
704      ++NumBranchOpts;
705      return OptimizeBlock(MBB);
706    }
707
708    // If the prior block branches here on true and somewhere else on false, and
709    // if the branch condition is reversible, reverse the branch to create a
710    // fall-through.
711    if (PriorTBB == MBB) {
712      std::vector<MachineOperand> NewPriorCond(PriorCond);
713      if (!TII->ReverseBranchCondition(NewPriorCond)) {
714        TII->RemoveBranch(PrevBB);
715        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
716        MadeChange = true;
717        ++NumBranchOpts;
718        return OptimizeBlock(MBB);
719      }
720    }
721
722    // If this block doesn't fall through (e.g. it ends with an uncond branch or
723    // has no successors) and if the pred falls through into this block, and if
724    // it would otherwise fall through into the block after this, move this
725    // block to the end of the function.
726    //
727    // We consider it more likely that execution will stay in the function (e.g.
728    // due to loops) than it is to exit it.  This asserts in loops etc, moving
729    // the assert condition out of the loop body.
730    if (!PriorCond.empty() && PriorFBB == 0 &&
731        MachineFunction::iterator(PriorTBB) == FallThrough &&
732        !CanFallThrough(MBB)) {
733      bool DoTransform = true;
734
735      // We have to be careful that the succs of PredBB aren't both no-successor
736      // blocks.  If neither have successors and if PredBB is the second from
737      // last block in the function, we'd just keep swapping the two blocks for
738      // last.  Only do the swap if one is clearly better to fall through than
739      // the other.
740      if (FallThrough == --MBB->getParent()->end() &&
741          !IsBetterFallthrough(PriorTBB, MBB, *TII))
742        DoTransform = false;
743
744      // We don't want to do this transformation if we have control flow like:
745      //   br cond BB2
746      // BB1:
747      //   ..
748      //   jmp BBX
749      // BB2:
750      //   ..
751      //   ret
752      //
753      // In this case, we could actually be moving the return block *into* a
754      // loop!
755      if (DoTransform && !MBB->succ_empty() &&
756          (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
757        DoTransform = false;
758
759
760      if (DoTransform) {
761        // Reverse the branch so we will fall through on the previous true cond.
762        std::vector<MachineOperand> NewPriorCond(PriorCond);
763        if (!TII->ReverseBranchCondition(NewPriorCond)) {
764          DOUT << "\nMoving MBB: " << *MBB;
765          DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
766
767          TII->RemoveBranch(PrevBB);
768          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
769
770          // Move this block to the end of the function.
771          MBB->moveAfter(--MBB->getParent()->end());
772          MadeChange = true;
773          ++NumBranchOpts;
774          return;
775        }
776      }
777    }
778  }
779
780  // Analyze the branch in the current block.
781  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
782  std::vector<MachineOperand> CurCond;
783  bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
784  if (!CurUnAnalyzable) {
785    // If the CFG for the prior block has extra edges, remove them.
786    MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
787                                       !CurCond.empty(),
788                                       ++MachineFunction::iterator(MBB));
789
790    // If this is a two-way branch, and the FBB branches to this block, reverse
791    // the condition so the single-basic-block loop is faster.  Instead of:
792    //    Loop: xxx; jcc Out; jmp Loop
793    // we want:
794    //    Loop: xxx; jncc Loop; jmp Out
795    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
796      std::vector<MachineOperand> NewCond(CurCond);
797      if (!TII->ReverseBranchCondition(NewCond)) {
798        TII->RemoveBranch(*MBB);
799        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
800        MadeChange = true;
801        ++NumBranchOpts;
802        return OptimizeBlock(MBB);
803      }
804    }
805
806
807    // If this branch is the only thing in its block, see if we can forward
808    // other blocks across it.
809    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
810        TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
811      // This block may contain just an unconditional branch.  Because there can
812      // be 'non-branch terminators' in the block, try removing the branch and
813      // then seeing if the block is empty.
814      TII->RemoveBranch(*MBB);
815
816      // If this block is just an unconditional branch to CurTBB, we can
817      // usually completely eliminate the block.  The only case we cannot
818      // completely eliminate the block is when the block before this one
819      // falls through into MBB and we can't understand the prior block's branch
820      // condition.
821      if (MBB->empty()) {
822        bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
823        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
824            !PrevBB.isSuccessor(MBB)) {
825          // If the prior block falls through into us, turn it into an
826          // explicit branch to us to make updates simpler.
827          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
828              PriorTBB != MBB && PriorFBB != MBB) {
829            if (PriorTBB == 0) {
830              assert(PriorCond.empty() && PriorFBB == 0 &&
831                     "Bad branch analysis");
832              PriorTBB = MBB;
833            } else {
834              assert(PriorFBB == 0 && "Machine CFG out of date!");
835              PriorFBB = MBB;
836            }
837            TII->RemoveBranch(PrevBB);
838            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
839          }
840
841          // Iterate through all the predecessors, revectoring each in-turn.
842          MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
843          bool DidChange = false;
844          bool HasBranchToSelf = false;
845          while (PI != MBB->pred_end()) {
846            if (*PI == MBB) {
847              // If this block has an uncond branch to itself, leave it.
848              ++PI;
849              HasBranchToSelf = true;
850            } else {
851              DidChange = true;
852              ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
853            }
854          }
855
856          // Change any jumptables to go to the new MBB.
857          MBB->getParent()->getJumpTableInfo()->
858            ReplaceMBBInJumpTables(MBB, CurTBB);
859          if (DidChange) {
860            ++NumBranchOpts;
861            MadeChange = true;
862            if (!HasBranchToSelf) return;
863          }
864        }
865      }
866
867      // Add the branch back if the block is more than just an uncond branch.
868      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
869    }
870  }
871
872  // If the prior block doesn't fall through into this block, and if this
873  // block doesn't fall through into some other block, see if we can find a
874  // place to move this block where a fall-through will happen.
875  if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
876                      PriorTBB, PriorFBB, PriorCond)) {
877    // Now we know that there was no fall-through into this block, check to
878    // see if it has a fall-through into its successor.
879    bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
880                                       CurCond);
881
882    if (!MBB->isLandingPad()) {
883      // Check all the predecessors of this block.  If one of them has no fall
884      // throughs, move this block right after it.
885      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
886           E = MBB->pred_end(); PI != E; ++PI) {
887        // Analyze the branch at the end of the pred.
888        MachineBasicBlock *PredBB = *PI;
889        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
890        if (PredBB != MBB && !CanFallThrough(PredBB)
891            && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
892          // If the current block doesn't fall through, just move it.
893          // If the current block can fall through and does not end with a
894          // conditional branch, we need to append an unconditional jump to
895          // the (current) next block.  To avoid a possible compile-time
896          // infinite loop, move blocks only backward in this case.
897          if (CurFallsThru) {
898            MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
899            CurCond.clear();
900            TII->InsertBranch(*MBB, NextBB, 0, CurCond);
901          }
902          MBB->moveAfter(PredBB);
903          MadeChange = true;
904          return OptimizeBlock(MBB);
905        }
906      }
907    }
908
909    if (!CurFallsThru) {
910      // Check all successors to see if we can move this block before it.
911      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
912           E = MBB->succ_end(); SI != E; ++SI) {
913        // Analyze the branch at the end of the block before the succ.
914        MachineBasicBlock *SuccBB = *SI;
915        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
916        std::vector<MachineOperand> SuccPrevCond;
917
918        // If this block doesn't already fall-through to that successor, and if
919        // the succ doesn't already have a block that can fall through into it,
920        // and if the successor isn't an EH destination, we can arrange for the
921        // fallthrough to happen.
922        if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
923            !SuccBB->isLandingPad()) {
924          MBB->moveBefore(SuccBB);
925          MadeChange = true;
926          return OptimizeBlock(MBB);
927        }
928      }
929
930      // Okay, there is no really great place to put this block.  If, however,
931      // the block before this one would be a fall-through if this block were
932      // removed, move this block to the end of the function.
933      if (FallThrough != MBB->getParent()->end() &&
934          PrevBB.isSuccessor(FallThrough)) {
935        MBB->moveAfter(--MBB->getParent()->end());
936        MadeChange = true;
937        return;
938      }
939    }
940  }
941}
942