IfConversion.cpp revision 27af5c414b44315676b4625dc22e29a507ca9dca
1//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the Evan Cheng and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "ifcvt"
15#include "llvm/Function.h"
16#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/Target/TargetInstrInfo.h"
20#include "llvm/Target/TargetLowering.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/Statistic.h"
25using namespace llvm;
26
27STATISTIC(NumSimple,    "Number of simple if-conversions performed");
28STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
29STATISTIC(NumTriangle,  "Number of triangle if-conversions performed");
30STATISTIC(NumDiamonds,  "Number of diamond if-conversions performed");
31STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
32
33namespace {
34  class IfConverter : public MachineFunctionPass {
35    enum BBICKind {
36      ICNotAnalyzed,   // BB has not been analyzed.
37      ICReAnalyze,     // BB must be re-analyzed.
38      ICNotClassfied,  // BB data valid, but not classified.
39      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
40      ICSimpleFalse,   // Same as ICSimple, but on the false path.
41      ICTriangle,      // BB is entry of a triangle sub-CFG.
42      ICDiamond,       // BB is entry of a diamond sub-CFG.
43      ICChild,         // BB is part of the sub-CFG that'll be predicated.
44      ICDead           // BB cannot be if-converted again.
45    };
46
47    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
48    /// if-conversion feasibility analysis. This includes results from
49    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
50    /// classification, and common tail block of its successors (if it's a
51    /// diamond shape), its size, whether it's predicable, and whether any
52    /// instruction can clobber the 'would-be' predicate.
53    ///
54    /// Kind            - Type of block. See BBICKind.
55    /// NonPredSize     - Number of non-predicated instructions.
56    /// IsAnalyzable    - True if AnalyzeBranch() returns false.
57    /// ModifyPredicate - True if BB would modify the predicate (e.g. has
58    ///                   cmp, call, etc.)
59    /// BB              - Corresponding MachineBasicBlock.
60    /// TrueBB / FalseBB- See AnalyzeBranch().
61    /// BrCond          - Conditions for end of block conditional branches.
62    /// Predicate       - Predicate used in the BB.
63    struct BBInfo {
64      BBICKind Kind;
65      unsigned NonPredSize;
66      bool IsAnalyzable;
67      bool hasFallThrough;
68      bool ModifyPredicate;
69      MachineBasicBlock *BB;
70      MachineBasicBlock *TrueBB;
71      MachineBasicBlock *FalseBB;
72      MachineBasicBlock *TailBB;
73      std::vector<MachineOperand> BrCond;
74      std::vector<MachineOperand> Predicate;
75      BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
76                 IsAnalyzable(false), hasFallThrough(false),
77                 ModifyPredicate(false),
78                 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
79    };
80
81    /// Roots - Basic blocks that do not have successors. These are the starting
82    /// points of Graph traversal.
83    std::vector<MachineBasicBlock*> Roots;
84
85    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
86    /// basic block number.
87    std::vector<BBInfo> BBAnalysis;
88
89    const TargetLowering *TLI;
90    const TargetInstrInfo *TII;
91    bool MadeChange;
92  public:
93    static char ID;
94    IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
95
96    virtual bool runOnMachineFunction(MachineFunction &MF);
97    virtual const char *getPassName() const { return "If converter"; }
98
99  private:
100    bool ReverseBranchCondition(BBInfo &BBI);
101    bool BlockModifyPredicate(MachineBasicBlock *BB) const;
102    bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
103    bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
104    void StructuralAnalysis(MachineBasicBlock *BB);
105    bool FeasibilityAnalysis(BBInfo &BBI,
106                             std::vector<MachineOperand> &Cond,
107                             bool IgnoreTerm = false);
108    bool AttemptRestructuring(BBInfo &BBI);
109    bool AnalyzeBlocks(MachineFunction &MF,
110                       std::vector<BBInfo*> &Candidates);
111    void ReTryPreds(MachineBasicBlock *BB);
112    bool IfConvertSimple(BBInfo &BBI);
113    bool IfConvertTriangle(BBInfo &BBI);
114    bool IfConvertDiamond(BBInfo &BBI);
115    void PredicateBlock(BBInfo &BBI,
116                        std::vector<MachineOperand> &Cond,
117                        bool IgnoreTerm = false);
118    void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
119
120    // blockAlwaysFallThrough - Block ends without a terminator.
121    bool blockAlwaysFallThrough(BBInfo &BBI) const {
122      return BBI.IsAnalyzable && BBI.TrueBB == NULL;
123    }
124
125    // IfcvtCandidateCmp - Used to sort if-conversion candidates.
126    static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
127      // Favor diamond over triangle, etc.
128      return (unsigned)C1->Kind < (unsigned)C2->Kind;
129    }
130  };
131  char IfConverter::ID = 0;
132}
133
134FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
135
136bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
137  TLI = MF.getTarget().getTargetLowering();
138  TII = MF.getTarget().getInstrInfo();
139  if (!TII) return false;
140
141  DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
142
143  MF.RenumberBlocks();
144  BBAnalysis.resize(MF.getNumBlockIDs());
145
146  // Look for root nodes, i.e. blocks without successors.
147  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
148    if (I->succ_size() == 0)
149      Roots.push_back(I);
150
151  std::vector<BBInfo*> Candidates;
152  MadeChange = false;
153  while (true) {
154    // Do an intial analysis for each basic block and finding all the potential
155    // candidates to perform if-convesion.
156    bool Change = AnalyzeBlocks(MF, Candidates);
157    while (!Candidates.empty()) {
158      BBInfo &BBI = *Candidates.back();
159      Candidates.pop_back();
160
161      bool RetVal = false;
162      switch (BBI.Kind) {
163      default: assert(false && "Unexpected!");
164        break;
165      case ICReAnalyze:
166        // One or more of 'children' have been modified, abort!
167      case ICDead:
168        // Block has been already been if-converted, abort!
169        break;
170      case ICSimple:
171      case ICSimpleFalse: {
172        bool isRev = BBI.Kind == ICSimpleFalse;
173        DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
174             << "): BB#" << BBI.BB->getNumber() << " ("
175             << ((BBI.Kind == ICSimpleFalse)
176                 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
177        RetVal = IfConvertSimple(BBI);
178        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
179        if (RetVal)
180          if (isRev) NumSimpleRev++;
181          else       NumSimple++;
182       break;
183      }
184      case ICTriangle:
185        DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
186             << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
187             << ") ";
188        RetVal = IfConvertTriangle(BBI);
189        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
190        if (RetVal) NumTriangle++;
191        break;
192      case ICDiamond:
193        DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
194             << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
195        if (BBI.TailBB)
196          DOUT << "," << BBI.TailBB->getNumber() ;
197        DOUT << ") ";
198        RetVal = IfConvertDiamond(BBI);
199        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
200        if (RetVal) NumDiamonds++;
201        break;
202      }
203      Change |= RetVal;
204    }
205
206    if (!Change)
207      break;
208    MadeChange |= Change;
209  }
210
211  Roots.clear();
212  BBAnalysis.clear();
213
214  return MadeChange;
215}
216
217static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
218                                         MachineBasicBlock *TrueBB) {
219  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
220         E = BB->succ_end(); SI != E; ++SI) {
221    MachineBasicBlock *SuccBB = *SI;
222    if (SuccBB != TrueBB)
223      return SuccBB;
224  }
225  return NULL;
226}
227
228bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
229  if (!TII->ReverseBranchCondition(BBI.BrCond)) {
230    TII->RemoveBranch(*BBI.BB);
231    TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
232    std::swap(BBI.TrueBB, BBI.FalseBB);
233    return true;
234  }
235  return false;
236}
237
238/// BlockModifyPredicate - Returns true if any instruction in the block may
239/// clobber the condition code or register(s) used to predicate instructions,
240/// e.g. call, cmp.
241bool IfConverter::BlockModifyPredicate(MachineBasicBlock *BB) const {
242  for (MachineBasicBlock::const_reverse_iterator I = BB->rbegin(),
243         E = BB->rend(); I != E; ++I)
244    if (I->getInstrDescriptor()->Flags & M_CLOBBERS_PRED)
245      return true;
246  return false;
247}
248
249/// ValidTriangle - Returns true if the 'true' and 'false' blocks paths (along
250/// with their common predecessor) forms a valid triangle shape for ifcvt.
251bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
252  if (TrueBBI.BB->pred_size() != 1)
253    return false;
254
255  MachineBasicBlock *TTBB = TrueBBI.TrueBB;
256  if (!TTBB && blockAlwaysFallThrough(TrueBBI)) {
257    MachineFunction::iterator I = TrueBBI.BB;
258    if (++I == TrueBBI.BB->getParent()->end())
259      return false;
260    TTBB = I;
261  }
262  return TTBB && TTBB == FalseBBI.BB;
263}
264
265/// ValidDiamond - Returns true if the 'true' and 'false' blocks paths (along
266/// with their common predecessor) forms a valid diamond shape for ifcvt.
267bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
268  return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
269          TrueBBI.BB->pred_size() == 1 &&
270          FalseBBI.BB->pred_size() == 1 &&
271          !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
272          !TrueBBI.FalseBB && !FalseBBI.FalseBB);
273}
274
275/// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
276/// the specified block. Record its successors and whether it looks like an
277/// if-conversion candidate.
278void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
279  BBInfo &BBI = BBAnalysis[BB->getNumber()];
280
281  if (BBI.Kind == ICReAnalyze) {
282    BBI.BrCond.clear();
283    BBI.TrueBB = BBI.FalseBB = NULL;
284  } else {
285    if (BBI.Kind != ICNotAnalyzed)
286      return;  // Already analyzed.
287    BBI.BB = BB;
288    BBI.NonPredSize = std::distance(BB->begin(), BB->end());
289    BBI.ModifyPredicate = BlockModifyPredicate(BB);
290  }
291
292  // Look for 'root' of a simple (non-nested) triangle or diamond.
293  BBI.Kind = ICNotClassfied;
294  BBI.IsAnalyzable =
295    !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
296  BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
297  // Unanalyable or ends with fallthrough or unconditional branch.
298  if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
299    return;
300  // Do not ifcvt if either path is a back edge to the entry block.
301  if (BBI.TrueBB == BB || BBI.FalseBB == BB)
302    return;
303
304  StructuralAnalysis(BBI.TrueBB);
305  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
306
307  // No false branch. This BB must end with a conditional branch and a
308  // fallthrough.
309  if (!BBI.FalseBB)
310    BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
311  assert(BBI.FalseBB && "Expected to find the fallthrough block!");
312
313  StructuralAnalysis(BBI.FalseBB);
314  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
315
316  // If both paths are dead, then forget about it.
317  if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
318    BBI.Kind = ICDead;
319    return;
320  }
321
322  // Look for more opportunities to if-convert a triangle. Try to restructure
323  // the CFG to form a triangle with the 'false' path.
324  std::vector<MachineOperand> RevCond(BBI.BrCond);
325  bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
326  if (FalseBBI.FalseBB) {
327    if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB)
328      return;
329    std::vector<MachineOperand> Cond(BBI.BrCond);
330    if (CanRevCond &&
331        FalseBBI.TrueBB && FalseBBI.BB->pred_size() == 1 &&
332        FeasibilityAnalysis(FalseBBI, RevCond, true)) {
333      std::vector<MachineOperand> FalseCond(FalseBBI.BrCond);
334      if (FalseBBI.TrueBB == BBI.TrueBB &&
335          TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
336        // Reverse 'true' and 'false' paths.
337        ReverseBranchCondition(BBI);
338        BBI.Kind = ICTriangle;
339        FalseBBI.Kind = ICChild;
340      } else if (FalseBBI.FalseBB == BBI.TrueBB &&
341                 !TII->ReverseBranchCondition(FalseCond) &&
342                 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
343        // Reverse 'false' block's 'true' and 'false' paths and then
344        // reverse 'true' and 'false' paths.
345        ReverseBranchCondition(FalseBBI);
346        ReverseBranchCondition(BBI);
347        BBI.Kind = ICTriangle;
348        FalseBBI.Kind = ICChild;
349      }
350    }
351  } else if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
352             FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
353             FeasibilityAnalysis(FalseBBI, RevCond)) {
354    // Diamond:
355    //   EBB
356    //   / \_
357    //  |   |
358    // TBB FBB
359    //   \ /
360    //  TailBB
361    // Note TailBB can be empty.
362    BBI.Kind = ICDiamond;
363    TrueBBI.Kind = FalseBBI.Kind = ICChild;
364    BBI.TailBB = TrueBBI.TrueBB;
365  } else {
366    // FIXME: Consider duplicating if BB is small.
367    bool TryTriangle = ValidTriangle(TrueBBI, FalseBBI);
368    bool TrySimple = !blockAlwaysFallThrough(TrueBBI) &&
369                     TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
370    if ((TryTriangle || TrySimple) &&
371        FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
372      if (TryTriangle) {
373        // Triangle:
374        //   EBB
375        //   | \_
376        //   |  |
377        //   | TBB
378        //   |  /
379        //   FBB
380        BBI.Kind = ICTriangle;
381        TrueBBI.Kind = ICChild;
382      } else {
383        // Simple (split, no rejoin):
384        //   EBB
385        //   | \_
386        //   |  |
387        //   | TBB---> exit
388        //   |
389        //   FBB
390        BBI.Kind = ICSimple;
391        TrueBBI.Kind = ICChild;
392      }
393    } else if (FalseBBI.BrCond.size() == 0 && FalseBBI.BB->pred_size() == 1) {
394      // Try the other path...
395      bool TryTriangle = ValidTriangle(FalseBBI, TrueBBI);
396      bool TrySimple = !blockAlwaysFallThrough(FalseBBI);
397      if (TryTriangle || TrySimple) {
398        std::vector<MachineOperand> RevCond(BBI.BrCond);
399        if (!TII->ReverseBranchCondition(RevCond) &&
400            FeasibilityAnalysis(FalseBBI, RevCond)) {
401          if (TryTriangle) {
402            // Reverse 'true' and 'false' paths.
403            ReverseBranchCondition(BBI);
404            BBI.Kind = ICTriangle;
405            FalseBBI.Kind = ICChild;
406          } else {
407            BBI.Kind = ICSimpleFalse;
408            FalseBBI.Kind = ICChild;
409          }
410        }
411      }
412    }
413  }
414  return;
415}
416
417/// FeasibilityAnalysis - Determine if the block is predicable. In most
418/// cases, that means all the instructions in the block has M_PREDICABLE flag.
419/// Also checks if the block contains any instruction which can clobber a
420/// predicate (e.g. condition code register). If so, the block is not
421/// predicable unless it's the last instruction. If IgnoreTerm is true then
422/// all the terminator instructions are skipped.
423bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
424                                      std::vector<MachineOperand> &Cond,
425                                      bool IgnoreTerm) {
426  // If the block is dead, or it is going to be the entry block of a sub-CFG
427  // that will be if-converted, then it cannot be predicated.
428  if (BBI.Kind != ICNotAnalyzed &&
429      BBI.Kind != ICNotClassfied &&
430      BBI.Kind != ICChild)
431    return false;
432
433  // Check predication threshold.
434  if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
435    return false;
436
437  // If it is already predicated, check if its predicate subsumes the new
438  // predicate.
439  if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
440    return false;
441
442  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
443       I != E; ++I) {
444    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
445      continue;
446    if (!I->isPredicable())
447      return false;
448  }
449
450  return true;
451}
452
453/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
454/// expose more if-conversion opportunities. e.g.
455///
456///                cmp
457///                b le BB1
458///                /  \____
459///               /        |
460///             cmp        |
461///             b eq BB1   |
462///              /  \____  |
463///             /        \ |
464///                      BB1
465///  ==>
466///
467///                cmp
468///                b eq BB1
469///                /  \____
470///               /        |
471///             cmp        |
472///             b le BB1   |
473///              /  \____  |
474///             /        \ |
475///                      BB1
476bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
477  return false;
478}
479
480/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
481/// candidates. It returns true if any CFG restructuring is done to expose more
482/// if-conversion opportunities.
483bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
484                                std::vector<BBInfo*> &Candidates) {
485  bool Change = false;
486  std::set<MachineBasicBlock*> Visited;
487  for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
488    for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
489           E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
490      MachineBasicBlock *BB = *I;
491      StructuralAnalysis(BB);
492      BBInfo &BBI = BBAnalysis[BB->getNumber()];
493      switch (BBI.Kind) {
494        case ICSimple:
495        case ICSimpleFalse:
496        case ICTriangle:
497        case ICDiamond:
498          Candidates.push_back(&BBI);
499          break;
500        default:
501          Change |= AttemptRestructuring(BBI);
502          break;
503      }
504    }
505  }
506
507  // Sort to favor more complex ifcvt scheme.
508  std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
509
510  return Change;
511}
512
513/// isNextBlock - Returns true either if ToBB the next block after BB or
514/// that all the intervening blocks are empty.
515static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
516  MachineFunction::iterator I = BB;
517  MachineFunction::iterator TI = ToBB;
518  MachineFunction::iterator E = BB->getParent()->end();
519  while (++I != TI)
520    if (I == E || !I->empty())
521      return false;
522  return true;
523}
524
525/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
526/// to determine if it can be if-converted.
527void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
528  for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
529         E = BB->pred_end(); PI != E; ++PI) {
530    BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
531    PBBI.Kind = ICReAnalyze;
532  }
533}
534
535/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
536///
537static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
538                               const TargetInstrInfo *TII) {
539  std::vector<MachineOperand> NoCond;
540  TII->InsertBranch(*BB, ToBB, NULL, NoCond);
541}
542
543/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
544///
545bool IfConverter::IfConvertSimple(BBInfo &BBI) {
546  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
547  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
548  BBInfo *CvtBBI = &TrueBBI;
549  BBInfo *NextBBI = &FalseBBI;
550
551  std::vector<MachineOperand> Cond(BBI.BrCond);
552  if (BBI.Kind == ICSimpleFalse) {
553    std::swap(CvtBBI, NextBBI);
554    TII->ReverseBranchCondition(Cond);
555  }
556
557  PredicateBlock(*CvtBBI, Cond);
558
559  // Merge converted block into entry block. Also add an unconditional branch
560  // to the 'false' branch.
561  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
562  MergeBlocks(BBI, *CvtBBI);
563
564  bool IterIfcvt = true;
565  if (!isNextBlock(BBI.BB, NextBBI->BB)) {
566    InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
567    BBI.hasFallThrough = false;
568    if (BBI.ModifyPredicate)
569      // Now ifcvt'd block will look like this:
570      // BB:
571      // ...
572      // t, f = cmp
573      // if t op
574      // b BBf
575      //
576      // We cannot further ifcvt this block because the unconditional branch
577      // will have to be predicated on the new condition, that will not be
578      // available if cmp executes.
579      IterIfcvt = false;
580  }
581  std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
582
583  // Update block info. BB can be iteratively if-converted.
584  if (IterIfcvt)
585    BBI.Kind = ICReAnalyze;
586  else
587    BBI.Kind = ICDead;
588  ReTryPreds(BBI.BB);
589  CvtBBI->Kind = ICDead;
590
591  // FIXME: Must maintain LiveIns.
592  return true;
593}
594
595/// IfConvertTriangle - If convert a triangle sub-CFG.
596///
597bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
598  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
599
600  // Predicate the 'true' block after removing its branch.
601  TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
602  PredicateBlock(TrueBBI, BBI.BrCond);
603
604  // If 'true' block has a 'false' successor, add an exit branch to it.
605  bool HasEarlyExit = TrueBBI.FalseBB != NULL;
606  if (HasEarlyExit) {
607    std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
608    if (TII->ReverseBranchCondition(RevCond))
609      assert(false && "Unable to reverse branch condition!");
610    TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
611  }
612
613  // Join the 'true' and 'false' blocks if the 'false' block has no other
614  // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
615  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
616  bool FalseBBDead = false;
617  bool IterIfcvt = true;
618  bool isFallThrough = isNextBlock(TrueBBI.BB, FalseBBI.BB);
619  if (!isFallThrough) {
620    // Only merge them if the true block does not fallthrough to the false
621    // block. By not merging them, we make it possible to iteratively
622    // ifcvt the blocks.
623    if (!HasEarlyExit && FalseBBI.BB->pred_size() == 2) {
624      MergeBlocks(TrueBBI, FalseBBI);
625      FalseBBDead = true;
626      // Mixed predicated and unpredicated code. This cannot be iteratively
627      // predicated.
628      IterIfcvt = false;
629    } else {
630      InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
631      TrueBBI.hasFallThrough = false;
632      if (BBI.ModifyPredicate || TrueBBI.ModifyPredicate)
633        // Now ifcvt'd block will look like this:
634        // BB:
635        // ...
636        // t, f = cmp
637        // if t op
638        // b BBf
639        //
640        // We cannot further ifcvt this block because the unconditional branch will
641        // have to be predicated on the new condition, that will not be available
642        // if cmp executes.
643        IterIfcvt = false;
644    }
645  }
646
647  // Now merge the entry of the triangle with the true block.
648  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
649  MergeBlocks(BBI, TrueBBI);
650  // Remove entry to false edge if false block is merged in as well.
651  if (FalseBBDead && BBI.BB->isSuccessor(FalseBBI.BB))
652    BBI.BB->removeSuccessor(FalseBBI.BB);
653  std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
654            std::back_inserter(BBI.Predicate));
655
656  // Update block info. BB can be iteratively if-converted.
657  if (IterIfcvt)
658    BBI.Kind = ICReAnalyze;
659  else
660    BBI.Kind = ICDead;
661  ReTryPreds(BBI.BB);
662  TrueBBI.Kind = ICDead;
663  if (FalseBBDead)
664    FalseBBI.Kind = ICDead;
665
666  // FIXME: Must maintain LiveIns.
667  return true;
668}
669
670/// IfConvertDiamond - If convert a diamond sub-CFG.
671///
672bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
673  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
674  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
675
676  SmallVector<MachineInstr*, 2> Dups;
677  if (!BBI.TailBB) {
678    // No common merge block. Check if the terminators (e.g. return) are
679    // the same or predicable.
680    MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
681    MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
682    while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
683      if (TT->isIdenticalTo(FT))
684        Dups.push_back(TT);  // Will erase these later.
685      else if (!TT->isPredicable() && !FT->isPredicable())
686        return false; // Can't if-convert. Abort!
687      ++TT;
688      ++FT;
689    }
690
691    // One of the two pathes have more terminators, make sure they are
692    // all predicable.
693    while (TT != BBI.TrueBB->end()) {
694      if (!TT->isPredicable()) {
695        return false; // Can't if-convert. Abort!
696      }
697      ++TT;
698    }
699    while (FT != BBI.FalseBB->end()) {
700      if (!FT->isPredicable()) {
701        return false; // Can't if-convert. Abort!
702      }
703      ++FT;
704    }
705  }
706
707  // Remove the duplicated instructions from the 'true' block.
708  for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
709    Dups[i]->eraseFromParent();
710    --TrueBBI.NonPredSize;
711  }
712
713  // Merge the 'true' and 'false' blocks by copying the instructions
714  // from the 'false' block to the 'true' block. That is, unless the true
715  // block would clobber the predicate, in that case, do the opposite.
716  BBInfo *BBI1 = &TrueBBI;
717  BBInfo *BBI2 = &FalseBBI;
718  std::vector<MachineOperand> RevCond(BBI.BrCond);
719  TII->ReverseBranchCondition(RevCond);
720  std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
721  std::vector<MachineOperand> *Cond2 = &RevCond;
722  // Check the 'true' and 'false' blocks if either isn't ended with a branch.
723  // Either the block fallthrough to another block or it ends with a
724  // return. If it's the former, add a branch to its successor.
725  bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
726  bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
727
728  if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
729      (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
730       NeedBr1 && !NeedBr2)) {
731    std::swap(BBI1, BBI2);
732    std::swap(Cond1, Cond2);
733    std::swap(NeedBr1, NeedBr2);
734  }
735
736  // Predicate the 'true' block after removing its branch.
737  BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
738  PredicateBlock(*BBI1, *Cond1);
739
740  // Add an early exit branch if needed.
741  if (NeedBr1)
742    TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
743
744  // Predicate the 'false' block.
745  PredicateBlock(*BBI2, *Cond2, true);
746
747  // Add an unconditional branch from 'false' to to 'false' successor if it
748  // will not be the fallthrough block.
749  if (NeedBr2 && !NeedBr1) {
750    // If BBI2 isn't going to be merged in, then the existing fallthrough
751    // or branch is fine.
752    if (!isNextBlock(BBI.BB, *BBI2->BB->succ_begin())) {
753      InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
754      BBI2->hasFallThrough = false;
755    }
756  }
757
758  // Keep them as two separate blocks if there is an early exit.
759  if (!NeedBr1)
760    MergeBlocks(*BBI1, *BBI2);
761
762  // Remove the conditional branch from entry to the blocks.
763  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
764
765  // Merge the combined block into the entry of the diamond.
766  MergeBlocks(BBI, *BBI1);
767  std::copy(Cond1->begin(), Cond1->end(),
768            std::back_inserter(BBI.Predicate));
769  if (!NeedBr1)
770    std::copy(Cond2->begin(), Cond2->end(),
771              std::back_inserter(BBI.Predicate));
772
773  // 'True' and 'false' aren't combined, see if we need to add a unconditional
774  // branch to the 'false' block.
775  if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB)) {
776    InsertUncondBranch(BBI.BB, BBI2->BB, TII);
777    BBI1->hasFallThrough = false;
778  }
779
780  // If the if-converted block fallthrough or unconditionally branch into the
781  // tail block, and the tail block does not have other predecessors, then
782  // fold the tail block in as well.
783  BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
784  if (BBI.TailBB &&
785      BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
786    CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
787    BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
788    MergeBlocks(*CvtBBI, TailBBI);
789    TailBBI.Kind = ICDead;
790  }
791
792  // Update block info.
793  BBI.Kind = ICDead;
794  TrueBBI.Kind = ICDead;
795  FalseBBI.Kind = ICDead;
796
797  // FIXME: Must maintain LiveIns.
798  return true;
799}
800
801/// PredicateBlock - Predicate every instruction in the block with the specified
802/// condition. If IgnoreTerm is true, skip over all terminator instructions.
803void IfConverter::PredicateBlock(BBInfo &BBI,
804                                 std::vector<MachineOperand> &Cond,
805                                 bool IgnoreTerm) {
806  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
807       I != E; ++I) {
808    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
809      continue;
810    if (TII->isPredicated(I))
811      continue;
812    if (!TII->PredicateInstruction(I, Cond)) {
813      cerr << "Unable to predicate " << *I << "!\n";
814      abort();
815    }
816  }
817
818  BBI.NonPredSize = 0;
819  NumIfConvBBs++;
820}
821
822static MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
823  MachineFunction::iterator I = BB;
824  MachineFunction::iterator E = BB->getParent()->end();
825  if (++I == E)
826    return NULL;
827  return I;
828}
829
830/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
831///
832void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
833  ToBBI.BB->splice(ToBBI.BB->end(),
834                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
835
836  // Redirect all branches to FromBB to ToBB.
837  std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
838                                         FromBBI.BB->pred_end());
839  for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
840    MachineBasicBlock *Pred = Preds[i];
841    if (Pred == ToBBI.BB)
842      continue;
843    Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
844  }
845
846  std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
847                                         FromBBI.BB->succ_end());
848  MachineBasicBlock *FallThrough = FromBBI.hasFallThrough
849    ? getNextBlock(FromBBI.BB) : NULL;
850
851  for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
852    MachineBasicBlock *Succ = Succs[i];
853    if (Succ == FallThrough)
854      continue;
855    FromBBI.BB->removeSuccessor(Succ);
856    if (!ToBBI.BB->isSuccessor(Succ))
857      ToBBI.BB->addSuccessor(Succ);
858  }
859
860  ToBBI.NonPredSize += FromBBI.NonPredSize;
861  FromBBI.NonPredSize = 0;
862
863  ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
864  ToBBI.hasFallThrough = FromBBI.hasFallThrough;
865}
866