IfConversion.cpp revision 4aad8bdb06a250ddd3d5684a4bb33eb02f5750d5
1//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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 "BranchFolding.h"
16#include "llvm/Function.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachineLoopInfo.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/TargetInstrItineraries.h"
23#include "llvm/Target/TargetLowering.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetRegisterInfo.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/ADT/DepthFirstIterator.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33using namespace llvm;
34
35// Hidden options for help debugging.
36static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
39static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
40                                   cl::init(false), cl::Hidden);
41static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
42                                    cl::init(false), cl::Hidden);
43static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
44                                     cl::init(false), cl::Hidden);
45static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
46                                      cl::init(false), cl::Hidden);
47static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
48                                      cl::init(false), cl::Hidden);
49static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
50                                       cl::init(false), cl::Hidden);
51static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
52                                    cl::init(false), cl::Hidden);
53static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54                                     cl::init(true), cl::Hidden);
55
56STATISTIC(NumSimple,       "Number of simple if-conversions performed");
57STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
58STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
59STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
60STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
63STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
64STATISTIC(NumDupBBs,       "Number of duplicated blocks");
65
66namespace {
67  class IfConverter : public MachineFunctionPass {
68    enum IfcvtKind {
69      ICNotClassfied,  // BB data valid, but not classified.
70      ICSimpleFalse,   // Same as ICSimple, but on the false path.
71      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
72      ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
73      ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
74      ICTriangleFalse, // Same as ICTriangle, but on the false path.
75      ICTriangle,      // BB is entry of a triangle sub-CFG.
76      ICDiamond        // BB is entry of a diamond sub-CFG.
77    };
78
79    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80    /// if-conversion feasibility analysis. This includes results from
81    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
82    /// classification, and common tail block of its successors (if it's a
83    /// diamond shape), its size, whether it's predicable, and whether any
84    /// instruction can clobber the 'would-be' predicate.
85    ///
86    /// IsDone          - True if BB is not to be considered for ifcvt.
87    /// IsBeingAnalyzed - True if BB is currently being analyzed.
88    /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
89    /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
90    /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
91    /// HasFallThrough  - True if BB may fallthrough to the following BB.
92    /// IsUnpredicable  - True if BB is known to be unpredicable.
93    /// ClobbersPred    - True if BB could modify predicates (e.g. has
94    ///                   cmp, call, etc.)
95    /// NonPredSize     - Number of non-predicated instructions.
96    /// BB              - Corresponding MachineBasicBlock.
97    /// TrueBB / FalseBB- See AnalyzeBranch().
98    /// BrCond          - Conditions for end of block conditional branches.
99    /// Predicate       - Predicate used in the BB.
100    struct BBInfo {
101      bool IsDone          : 1;
102      bool IsBeingAnalyzed : 1;
103      bool IsAnalyzed      : 1;
104      bool IsEnqueued      : 1;
105      bool IsBrAnalyzable  : 1;
106      bool HasFallThrough  : 1;
107      bool IsUnpredicable  : 1;
108      bool CannotBeCopied  : 1;
109      bool ClobbersPred    : 1;
110      unsigned NonPredSize;
111      MachineBasicBlock *BB;
112      MachineBasicBlock *TrueBB;
113      MachineBasicBlock *FalseBB;
114      SmallVector<MachineOperand, 4> BrCond;
115      SmallVector<MachineOperand, 4> Predicate;
116      BBInfo() : IsDone(false), IsBeingAnalyzed(false),
117                 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
118                 HasFallThrough(false), IsUnpredicable(false),
119                 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
120                 BB(0), TrueBB(0), FalseBB(0) {}
121    };
122
123    /// IfcvtToken - Record information about pending if-conversions to attempt:
124    /// BBI             - Corresponding BBInfo.
125    /// Kind            - Type of block. See IfcvtKind.
126    /// NeedSubsumption - True if the to-be-predicated BB has already been
127    ///                   predicated.
128    /// NumDups      - Number of instructions that would be duplicated due
129    ///                   to this if-conversion. (For diamonds, the number of
130    ///                   identical instructions at the beginnings of both
131    ///                   paths).
132    /// NumDups2     - For diamonds, the number of identical instructions
133    ///                   at the ends of both paths.
134    struct IfcvtToken {
135      BBInfo &BBI;
136      IfcvtKind Kind;
137      bool NeedSubsumption;
138      unsigned NumDups;
139      unsigned NumDups2;
140      IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
141        : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
142    };
143
144    /// Roots - Basic blocks that do not have successors. These are the starting
145    /// points of Graph traversal.
146    std::vector<MachineBasicBlock*> Roots;
147
148    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
149    /// basic block number.
150    std::vector<BBInfo> BBAnalysis;
151
152    const TargetLowering *TLI;
153    const TargetInstrInfo *TII;
154    const TargetRegisterInfo *TRI;
155    const InstrItineraryData *InstrItins;
156    const MachineLoopInfo *MLI;
157    bool MadeChange;
158    int FnNum;
159  public:
160    static char ID;
161    IfConverter() : MachineFunctionPass(ID), FnNum(-1) {}
162
163    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
164      AU.addRequired<MachineLoopInfo>();
165      MachineFunctionPass::getAnalysisUsage(AU);
166    }
167
168    virtual bool runOnMachineFunction(MachineFunction &MF);
169    virtual const char *getPassName() const { return "If Converter"; }
170
171  private:
172    bool ReverseBranchCondition(BBInfo &BBI);
173    bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups, float Prediction) const;
174    bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
175                       bool FalseBranch, unsigned &Dups) const;
176    bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
177                      unsigned &Dups1, unsigned &Dups2) const;
178    void ScanInstructions(BBInfo &BBI);
179    BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
180                         std::vector<IfcvtToken*> &Tokens);
181    bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
182                             bool isTriangle = false, bool RevBranch = false);
183    void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
184    void InvalidatePreds(MachineBasicBlock *BB);
185    void RemoveExtraEdges(BBInfo &BBI);
186    bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
187    bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
188    bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
189                          unsigned NumDups1, unsigned NumDups2);
190    void PredicateBlock(BBInfo &BBI,
191                        MachineBasicBlock::iterator E,
192                        SmallVectorImpl<MachineOperand> &Cond,
193                        SmallSet<unsigned, 4> &Redefs);
194    void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
195                               SmallVectorImpl<MachineOperand> &Cond,
196                               SmallSet<unsigned, 4> &Redefs,
197                               bool IgnoreBr = false);
198    void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
199
200    bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
201                            float Prediction) const {
202      return Size > 0 && TII->isProfitableToIfCvt(BB, Size, Prediction);
203    }
204
205    bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
206                            MachineBasicBlock &FBB, unsigned FSize,
207                            float Prediction) const {
208      return TSize > 0 && FSize > 0 &&
209        TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize, Prediction);
210    }
211
212    // blockAlwaysFallThrough - Block ends without a terminator.
213    bool blockAlwaysFallThrough(BBInfo &BBI) const {
214      return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
215    }
216
217    // IfcvtTokenCmp - Used to sort if-conversion candidates.
218    static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
219      int Incr1 = (C1->Kind == ICDiamond)
220        ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
221      int Incr2 = (C2->Kind == ICDiamond)
222        ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
223      if (Incr1 > Incr2)
224        return true;
225      else if (Incr1 == Incr2) {
226        // Favors subsumption.
227        if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
228          return true;
229        else if (C1->NeedSubsumption == C2->NeedSubsumption) {
230          // Favors diamond over triangle, etc.
231          if ((unsigned)C1->Kind < (unsigned)C2->Kind)
232            return true;
233          else if (C1->Kind == C2->Kind)
234            return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
235        }
236      }
237      return false;
238    }
239  };
240
241  char IfConverter::ID = 0;
242}
243
244INITIALIZE_PASS(IfConverter, "if-converter", "If Converter", false, false);
245
246FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
247
248bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
249  TLI = MF.getTarget().getTargetLowering();
250  TII = MF.getTarget().getInstrInfo();
251  TRI = MF.getTarget().getRegisterInfo();
252  MLI = &getAnalysis<MachineLoopInfo>();
253  InstrItins = MF.getTarget().getInstrItineraryData();
254  if (!TII) return false;
255
256  // Tail merge tend to expose more if-conversion opportunities.
257  BranchFolder BF(true);
258  bool BFChange = BF.OptimizeFunction(MF, TII,
259                                   MF.getTarget().getRegisterInfo(),
260                                   getAnalysisIfAvailable<MachineModuleInfo>());
261
262  DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
263               << MF.getFunction()->getName() << "\'");
264
265  if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
266    DEBUG(dbgs() << " skipped\n");
267    return false;
268  }
269  DEBUG(dbgs() << "\n");
270
271  MF.RenumberBlocks();
272  BBAnalysis.resize(MF.getNumBlockIDs());
273
274  // Look for root nodes, i.e. blocks without successors.
275  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
276    if (I->succ_empty())
277      Roots.push_back(I);
278
279  std::vector<IfcvtToken*> Tokens;
280  MadeChange = false;
281  unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
282    NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
283  while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
284    // Do an initial analysis for each basic block and find all the potential
285    // candidates to perform if-conversion.
286    bool Change = false;
287    AnalyzeBlocks(MF, Tokens);
288    while (!Tokens.empty()) {
289      IfcvtToken *Token = Tokens.back();
290      Tokens.pop_back();
291      BBInfo &BBI = Token->BBI;
292      IfcvtKind Kind = Token->Kind;
293      unsigned NumDups = Token->NumDups;
294      unsigned NumDups2 = Token->NumDups2;
295
296      delete Token;
297
298      // If the block has been evicted out of the queue or it has already been
299      // marked dead (due to it being predicated), then skip it.
300      if (BBI.IsDone)
301        BBI.IsEnqueued = false;
302      if (!BBI.IsEnqueued)
303        continue;
304
305      BBI.IsEnqueued = false;
306
307      bool RetVal = false;
308      switch (Kind) {
309      default: assert(false && "Unexpected!");
310        break;
311      case ICSimple:
312      case ICSimpleFalse: {
313        bool isFalse = Kind == ICSimpleFalse;
314        if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
315        DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
316                                            " false" : "")
317                     << "): BB#" << BBI.BB->getNumber() << " ("
318                     << ((Kind == ICSimpleFalse)
319                         ? BBI.FalseBB->getNumber()
320                         : BBI.TrueBB->getNumber()) << ") ");
321        RetVal = IfConvertSimple(BBI, Kind);
322        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
323        if (RetVal) {
324          if (isFalse) ++NumSimpleFalse;
325          else         ++NumSimple;
326        }
327       break;
328      }
329      case ICTriangle:
330      case ICTriangleRev:
331      case ICTriangleFalse:
332      case ICTriangleFRev: {
333        bool isFalse = Kind == ICTriangleFalse;
334        bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
335        if (DisableTriangle && !isFalse && !isRev) break;
336        if (DisableTriangleR && !isFalse && isRev) break;
337        if (DisableTriangleF && isFalse && !isRev) break;
338        if (DisableTriangleFR && isFalse && isRev) break;
339        DEBUG(dbgs() << "Ifcvt (Triangle");
340        if (isFalse)
341          DEBUG(dbgs() << " false");
342        if (isRev)
343          DEBUG(dbgs() << " rev");
344        DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
345                     << BBI.TrueBB->getNumber() << ",F:"
346                     << BBI.FalseBB->getNumber() << ") ");
347        RetVal = IfConvertTriangle(BBI, Kind);
348        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
349        if (RetVal) {
350          if (isFalse) {
351            if (isRev) ++NumTriangleFRev;
352            else       ++NumTriangleFalse;
353          } else {
354            if (isRev) ++NumTriangleRev;
355            else       ++NumTriangle;
356          }
357        }
358        break;
359      }
360      case ICDiamond: {
361        if (DisableDiamond) break;
362        DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
363                     << BBI.TrueBB->getNumber() << ",F:"
364                     << BBI.FalseBB->getNumber() << ") ");
365        RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
366        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
367        if (RetVal) ++NumDiamonds;
368        break;
369      }
370      }
371
372      Change |= RetVal;
373
374      NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
375        NumTriangleFalse + NumTriangleFRev + NumDiamonds;
376      if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
377        break;
378    }
379
380    if (!Change)
381      break;
382    MadeChange |= Change;
383  }
384
385  // Delete tokens in case of early exit.
386  while (!Tokens.empty()) {
387    IfcvtToken *Token = Tokens.back();
388    Tokens.pop_back();
389    delete Token;
390  }
391
392  Tokens.clear();
393  Roots.clear();
394  BBAnalysis.clear();
395
396  if (MadeChange && IfCvtBranchFold) {
397    BranchFolder BF(false);
398    BF.OptimizeFunction(MF, TII,
399                        MF.getTarget().getRegisterInfo(),
400                        getAnalysisIfAvailable<MachineModuleInfo>());
401  }
402
403  MadeChange |= BFChange;
404  return MadeChange;
405}
406
407/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
408/// its 'true' successor.
409static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
410                                         MachineBasicBlock *TrueBB) {
411  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
412         E = BB->succ_end(); SI != E; ++SI) {
413    MachineBasicBlock *SuccBB = *SI;
414    if (SuccBB != TrueBB)
415      return SuccBB;
416  }
417  return NULL;
418}
419
420/// ReverseBranchCondition - Reverse the condition of the end of the block
421/// branch. Swap block's 'true' and 'false' successors.
422bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
423  DebugLoc dl;  // FIXME: this is nowhere
424  if (!TII->ReverseBranchCondition(BBI.BrCond)) {
425    TII->RemoveBranch(*BBI.BB);
426    TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
427    std::swap(BBI.TrueBB, BBI.FalseBB);
428    return true;
429  }
430  return false;
431}
432
433/// getNextBlock - Returns the next block in the function blocks ordering. If
434/// it is the end, returns NULL.
435static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
436  MachineFunction::iterator I = BB;
437  MachineFunction::iterator E = BB->getParent()->end();
438  if (++I == E)
439    return NULL;
440  return I;
441}
442
443/// ValidSimple - Returns true if the 'true' block (along with its
444/// predecessor) forms a valid simple shape for ifcvt. It also returns the
445/// number of instructions that the ifcvt would need to duplicate if performed
446/// in Dups.
447bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
448                              float Prediction) const {
449  Dups = 0;
450  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
451    return false;
452
453  if (TrueBBI.IsBrAnalyzable)
454    return false;
455
456  if (TrueBBI.BB->pred_size() > 1) {
457    if (TrueBBI.CannotBeCopied ||
458        !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
459                                        Prediction))
460      return false;
461    Dups = TrueBBI.NonPredSize;
462  }
463
464  return true;
465}
466
467/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
468/// with their common predecessor) forms a valid triangle shape for ifcvt.
469/// If 'FalseBranch' is true, it checks if 'true' block's false branch
470/// branches to the 'false' block rather than the other way around. It also
471/// returns the number of instructions that the ifcvt would need to duplicate
472/// if performed in 'Dups'.
473bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
474                                bool FalseBranch, unsigned &Dups) const {
475  Dups = 0;
476  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
477    return false;
478
479  if (TrueBBI.BB->pred_size() > 1) {
480    if (TrueBBI.CannotBeCopied)
481      return false;
482
483    unsigned Size = TrueBBI.NonPredSize;
484    if (TrueBBI.IsBrAnalyzable) {
485      if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
486        // Ends with an unconditional branch. It will be removed.
487        --Size;
488      else {
489        MachineBasicBlock *FExit = FalseBranch
490          ? TrueBBI.TrueBB : TrueBBI.FalseBB;
491        if (FExit)
492          // Require a conditional branch
493          ++Size;
494      }
495    }
496    if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, 0.5))
497      return false;
498    Dups = Size;
499  }
500
501  MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
502  if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
503    MachineFunction::iterator I = TrueBBI.BB;
504    if (++I == TrueBBI.BB->getParent()->end())
505      return false;
506    TExit = I;
507  }
508  return TExit && TExit == FalseBBI.BB;
509}
510
511static
512MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
513                                               const TargetInstrInfo *TII) {
514  MachineBasicBlock::iterator I = BB->end();
515  while (I != BB->begin()) {
516    --I;
517    if (!I->getDesc().isBranch())
518      break;
519  }
520  return I;
521}
522
523/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
524/// with their common predecessor) forms a valid diamond shape for ifcvt.
525bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
526                               unsigned &Dups1, unsigned &Dups2) const {
527  Dups1 = Dups2 = 0;
528  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
529      FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
530    return false;
531
532  MachineBasicBlock *TT = TrueBBI.TrueBB;
533  MachineBasicBlock *FT = FalseBBI.TrueBB;
534
535  if (!TT && blockAlwaysFallThrough(TrueBBI))
536    TT = getNextBlock(TrueBBI.BB);
537  if (!FT && blockAlwaysFallThrough(FalseBBI))
538    FT = getNextBlock(FalseBBI.BB);
539  if (TT != FT)
540    return false;
541  if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
542    return false;
543  if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
544    return false;
545
546  // FIXME: Allow true block to have an early exit?
547  if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
548      (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
549    return false;
550
551  MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
552  MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
553  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
554  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
555  // Skip dbg_value instructions
556  while (TI != TIE && TI->isDebugValue())
557    ++TI;
558  while (FI != FIE && FI->isDebugValue())
559    ++FI;
560  while (TI != TIE && FI != FIE) {
561    // Skip dbg_value instructions. These do not count.
562    if (TI->isDebugValue()) {
563      while (TI != TIE && TI->isDebugValue())
564        ++TI;
565      if (TI == TIE)
566        break;
567    }
568    if (FI->isDebugValue()) {
569      while (FI != FIE && FI->isDebugValue())
570        ++FI;
571      if (FI == FIE)
572        break;
573    }
574    if (!TI->isIdenticalTo(FI))
575      break;
576    ++Dups1;
577    ++TI;
578    ++FI;
579  }
580
581  TI = firstNonBranchInst(TrueBBI.BB, TII);
582  FI = firstNonBranchInst(FalseBBI.BB, TII);
583  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
584  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
585  // Skip dbg_value instructions at end of the bb's.
586  while (TI != TIB && TI->isDebugValue())
587    --TI;
588  while (FI != FIB && FI->isDebugValue())
589    --FI;
590  while (TI != TIB && FI != FIB) {
591    // Skip dbg_value instructions. These do not count.
592    if (TI->isDebugValue()) {
593      while (TI != TIB && TI->isDebugValue())
594        --TI;
595      if (TI == TIB)
596        break;
597    }
598    if (FI->isDebugValue()) {
599      while (FI != FIB && FI->isDebugValue())
600        --FI;
601      if (FI == FIB)
602        break;
603    }
604    if (!TI->isIdenticalTo(FI))
605      break;
606    ++Dups2;
607    --TI;
608    --FI;
609  }
610
611  return true;
612}
613
614/// ScanInstructions - Scan all the instructions in the block to determine if
615/// the block is predicable. In most cases, that means all the instructions
616/// in the block are isPredicable(). Also checks if the block contains any
617/// instruction which can clobber a predicate (e.g. condition code register).
618/// If so, the block is not predicable unless it's the last instruction.
619void IfConverter::ScanInstructions(BBInfo &BBI) {
620  if (BBI.IsDone)
621    return;
622
623  bool AlreadyPredicated = BBI.Predicate.size() > 0;
624  // First analyze the end of BB branches.
625  BBI.TrueBB = BBI.FalseBB = NULL;
626  BBI.BrCond.clear();
627  BBI.IsBrAnalyzable =
628    !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
629  BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
630
631  if (BBI.BrCond.size()) {
632    // No false branch. This BB must end with a conditional branch and a
633    // fallthrough.
634    if (!BBI.FalseBB)
635      BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
636    if (!BBI.FalseBB) {
637      // Malformed bcc? True and false blocks are the same?
638      BBI.IsUnpredicable = true;
639      return;
640    }
641  }
642
643  // Then scan all the instructions.
644  BBI.NonPredSize = 0;
645  BBI.ClobbersPred = false;
646  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
647       I != E; ++I) {
648    if (I->isDebugValue())
649      continue;
650
651    const TargetInstrDesc &TID = I->getDesc();
652    if (TID.isNotDuplicable())
653      BBI.CannotBeCopied = true;
654
655    bool isPredicated = TII->isPredicated(I);
656    bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
657
658    if (!isCondBr) {
659      if (!isPredicated) {
660        unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
661        BBI.NonPredSize += NumOps;
662      } else if (!AlreadyPredicated) {
663        // FIXME: This instruction is already predicated before the
664        // if-conversion pass. It's probably something like a conditional move.
665        // Mark this block unpredicable for now.
666        BBI.IsUnpredicable = true;
667        return;
668      }
669    }
670
671    if (BBI.ClobbersPred && !isPredicated) {
672      // Predicate modification instruction should end the block (except for
673      // already predicated instructions and end of block branches).
674      if (isCondBr) {
675        // A conditional branch is not predicable, but it may be eliminated.
676        continue;
677      }
678
679      // Predicate may have been modified, the subsequent (currently)
680      // unpredicated instructions cannot be correctly predicated.
681      BBI.IsUnpredicable = true;
682      return;
683    }
684
685    // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
686    // still potentially predicable.
687    std::vector<MachineOperand> PredDefs;
688    if (TII->DefinesPredicate(I, PredDefs))
689      BBI.ClobbersPred = true;
690
691    if (!TII->isPredicable(I)) {
692      BBI.IsUnpredicable = true;
693      return;
694    }
695  }
696}
697
698/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
699/// predicated by the specified predicate.
700bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
701                                      SmallVectorImpl<MachineOperand> &Pred,
702                                      bool isTriangle, bool RevBranch) {
703  // If the block is dead or unpredicable, then it cannot be predicated.
704  if (BBI.IsDone || BBI.IsUnpredicable)
705    return false;
706
707  // If it is already predicated, check if its predicate subsumes the new
708  // predicate.
709  if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
710    return false;
711
712  if (BBI.BrCond.size()) {
713    if (!isTriangle)
714      return false;
715
716    // Test predicate subsumption.
717    SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
718    SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
719    if (RevBranch) {
720      if (TII->ReverseBranchCondition(Cond))
721        return false;
722    }
723    if (TII->ReverseBranchCondition(RevPred) ||
724        !TII->SubsumesPredicate(Cond, RevPred))
725      return false;
726  }
727
728  return true;
729}
730
731/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
732/// the specified block. Record its successors and whether it looks like an
733/// if-conversion candidate.
734IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
735                                             std::vector<IfcvtToken*> &Tokens) {
736  BBInfo &BBI = BBAnalysis[BB->getNumber()];
737
738  if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
739    return BBI;
740
741  BBI.BB = BB;
742  BBI.IsBeingAnalyzed = true;
743
744  ScanInstructions(BBI);
745
746  // Unanalyzable or ends with fallthrough or unconditional branch.
747  if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
748    BBI.IsBeingAnalyzed = false;
749    BBI.IsAnalyzed = true;
750    return BBI;
751  }
752
753  // Do not ifcvt if either path is a back edge to the entry block.
754  if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
755    BBI.IsBeingAnalyzed = false;
756    BBI.IsAnalyzed = true;
757    return BBI;
758  }
759
760  // Do not ifcvt if true and false fallthrough blocks are the same.
761  if (!BBI.FalseBB) {
762    BBI.IsBeingAnalyzed = false;
763    BBI.IsAnalyzed = true;
764    return BBI;
765  }
766
767  BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
768  BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
769
770  if (TrueBBI.IsDone && FalseBBI.IsDone) {
771    BBI.IsBeingAnalyzed = false;
772    BBI.IsAnalyzed = true;
773    return BBI;
774  }
775
776  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
777  bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
778
779  unsigned Dups = 0;
780  unsigned Dups2 = 0;
781  bool TNeedSub = TrueBBI.Predicate.size() > 0;
782  bool FNeedSub = FalseBBI.Predicate.size() > 0;
783  bool Enqueued = false;
784
785  // Try to predict the branch, using loop info to guide us.
786  // General heuristics are:
787  //   - backedge -> 90% taken
788  //   - early exit -> 20% taken
789  float Prediction = 0.5f;
790  MachineLoop *Loop = MLI->getLoopFor(BB);
791  if (Loop) {
792    if (TrueBBI.BB == Loop->getHeader())
793      Prediction = 0.9f;
794    else if (FalseBBI.BB == Loop->getHeader())
795      Prediction = 0.1f;
796
797    MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
798    MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
799    if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
800      Prediction = 0.2f;
801    else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
802      Prediction = 0.8f;
803  }
804
805  if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
806      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize - (Dups + Dups2),
807                         *FalseBBI.BB, FalseBBI.NonPredSize - (Dups + Dups2),
808                         Prediction) &&
809      FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
810      FeasibilityAnalysis(FalseBBI, RevCond)) {
811    // Diamond:
812    //   EBB
813    //   / \_
814    //  |   |
815    // TBB FBB
816    //   \ /
817    //  TailBB
818    // Note TailBB can be empty.
819    Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
820                                    Dups2));
821    Enqueued = true;
822  }
823
824  if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
825      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize, Prediction) &&
826      FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
827    // Triangle:
828    //   EBB
829    //   | \_
830    //   |  |
831    //   | TBB
832    //   |  /
833    //   FBB
834    Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
835    Enqueued = true;
836  }
837
838  if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
839      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize, Prediction) &&
840      FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
841    Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
842    Enqueued = true;
843  }
844
845  if (ValidSimple(TrueBBI, Dups, Prediction) &&
846      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize, Prediction) &&
847      FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
848    // Simple (split, no rejoin):
849    //   EBB
850    //   | \_
851    //   |  |
852    //   | TBB---> exit
853    //   |
854    //   FBB
855    Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
856    Enqueued = true;
857  }
858
859  if (CanRevCond) {
860    // Try the other path...
861    if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
862        MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,1.0-Prediction) &&
863        FeasibilityAnalysis(FalseBBI, RevCond, true)) {
864      Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
865      Enqueued = true;
866    }
867
868    if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
869        MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,1.0-Prediction) &&
870        FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
871      Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
872      Enqueued = true;
873    }
874
875    if (ValidSimple(FalseBBI, Dups, 1.0-Prediction) &&
876        MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,1.0-Prediction) &&
877        FeasibilityAnalysis(FalseBBI, RevCond)) {
878      Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
879      Enqueued = true;
880    }
881  }
882
883  BBI.IsEnqueued = Enqueued;
884  BBI.IsBeingAnalyzed = false;
885  BBI.IsAnalyzed = true;
886  return BBI;
887}
888
889/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
890/// candidates.
891void IfConverter::AnalyzeBlocks(MachineFunction &MF,
892                                std::vector<IfcvtToken*> &Tokens) {
893  std::set<MachineBasicBlock*> Visited;
894  for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
895    for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
896           E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
897      MachineBasicBlock *BB = *I;
898      AnalyzeBlock(BB, Tokens);
899    }
900  }
901
902  // Sort to favor more complex ifcvt scheme.
903  std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
904}
905
906/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
907/// that all the intervening blocks are empty (given BB can fall through to its
908/// next block).
909static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
910  MachineFunction::iterator PI = BB;
911  MachineFunction::iterator I = llvm::next(PI);
912  MachineFunction::iterator TI = ToBB;
913  MachineFunction::iterator E = BB->getParent()->end();
914  while (I != TI) {
915    // Check isSuccessor to avoid case where the next block is empty, but
916    // it's not a successor.
917    if (I == E || !I->empty() || !PI->isSuccessor(I))
918      return false;
919    PI = I++;
920  }
921  return true;
922}
923
924/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
925/// to determine if it can be if-converted. If predecessor is already enqueued,
926/// dequeue it!
927void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
928  for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
929         E = BB->pred_end(); PI != E; ++PI) {
930    BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
931    if (PBBI.IsDone || PBBI.BB == BB)
932      continue;
933    PBBI.IsAnalyzed = false;
934    PBBI.IsEnqueued = false;
935  }
936}
937
938/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
939///
940static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
941                               const TargetInstrInfo *TII) {
942  DebugLoc dl;  // FIXME: this is nowhere
943  SmallVector<MachineOperand, 0> NoCond;
944  TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
945}
946
947/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
948/// successors.
949void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
950  MachineBasicBlock *TBB = NULL, *FBB = NULL;
951  SmallVector<MachineOperand, 4> Cond;
952  if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
953    BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
954}
955
956/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
957/// modeled as read + write (sort like two-address instructions). These
958/// routines track register liveness and add implicit uses to if-converted
959/// instructions to conform to the model.
960static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
961                           const TargetRegisterInfo *TRI) {
962  for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
963         E = BB->livein_end(); I != E; ++I) {
964    unsigned Reg = *I;
965    Redefs.insert(Reg);
966    for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
967         *Subreg; ++Subreg)
968      Redefs.insert(*Subreg);
969  }
970}
971
972static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
973                             const TargetRegisterInfo *TRI,
974                             bool AddImpUse = false) {
975  SmallVector<unsigned, 4> Defs;
976  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
977    const MachineOperand &MO = MI->getOperand(i);
978    if (!MO.isReg())
979      continue;
980    unsigned Reg = MO.getReg();
981    if (!Reg)
982      continue;
983    if (MO.isDef())
984      Defs.push_back(Reg);
985    else if (MO.isKill()) {
986      Redefs.erase(Reg);
987      for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
988        Redefs.erase(*SR);
989    }
990  }
991  for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
992    unsigned Reg = Defs[i];
993    if (Redefs.count(Reg)) {
994      if (AddImpUse)
995        // Treat predicated update as read + write.
996        MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
997                                                true/*IsImp*/,false/*IsKill*/));
998    } else {
999      Redefs.insert(Reg);
1000      for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1001        Redefs.insert(*SR);
1002    }
1003  }
1004}
1005
1006static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1007                             MachineBasicBlock::iterator E,
1008                             SmallSet<unsigned,4> &Redefs,
1009                             const TargetRegisterInfo *TRI) {
1010  while (I != E) {
1011    UpdatePredRedefs(I, Redefs, TRI);
1012    ++I;
1013  }
1014}
1015
1016/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1017///
1018bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1019  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1020  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1021  BBInfo *CvtBBI = &TrueBBI;
1022  BBInfo *NextBBI = &FalseBBI;
1023
1024  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1025  if (Kind == ICSimpleFalse)
1026    std::swap(CvtBBI, NextBBI);
1027
1028  if (CvtBBI->IsDone ||
1029      (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1030    // Something has changed. It's no longer safe to predicate this block.
1031    BBI.IsAnalyzed = false;
1032    CvtBBI->IsAnalyzed = false;
1033    return false;
1034  }
1035
1036  if (Kind == ICSimpleFalse)
1037    if (TII->ReverseBranchCondition(Cond))
1038      assert(false && "Unable to reverse branch condition!");
1039
1040  // Initialize liveins to the first BB. These are potentiall redefined by
1041  // predicated instructions.
1042  SmallSet<unsigned, 4> Redefs;
1043  InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1044  InitPredRedefs(NextBBI->BB, Redefs, TRI);
1045
1046  if (CvtBBI->BB->pred_size() > 1) {
1047    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1048    // Copy instructions in the true block, predicate them, and add them to
1049    // the entry block.
1050    CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1051  } else {
1052    PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1053
1054    // Merge converted block into entry block.
1055    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1056    MergeBlocks(BBI, *CvtBBI);
1057  }
1058
1059  bool IterIfcvt = true;
1060  if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1061    InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1062    BBI.HasFallThrough = false;
1063    // Now ifcvt'd block will look like this:
1064    // BB:
1065    // ...
1066    // t, f = cmp
1067    // if t op
1068    // b BBf
1069    //
1070    // We cannot further ifcvt this block because the unconditional branch
1071    // will have to be predicated on the new condition, that will not be
1072    // available if cmp executes.
1073    IterIfcvt = false;
1074  }
1075
1076  RemoveExtraEdges(BBI);
1077
1078  // Update block info. BB can be iteratively if-converted.
1079  if (!IterIfcvt)
1080    BBI.IsDone = true;
1081  InvalidatePreds(BBI.BB);
1082  CvtBBI->IsDone = true;
1083
1084  // FIXME: Must maintain LiveIns.
1085  return true;
1086}
1087
1088/// IfConvertTriangle - If convert a triangle sub-CFG.
1089///
1090bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1091  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1092  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1093  BBInfo *CvtBBI = &TrueBBI;
1094  BBInfo *NextBBI = &FalseBBI;
1095  DebugLoc dl;  // FIXME: this is nowhere
1096
1097  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1098  if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1099    std::swap(CvtBBI, NextBBI);
1100
1101  if (CvtBBI->IsDone ||
1102      (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1103    // Something has changed. It's no longer safe to predicate this block.
1104    BBI.IsAnalyzed = false;
1105    CvtBBI->IsAnalyzed = false;
1106    return false;
1107  }
1108
1109  if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1110    if (TII->ReverseBranchCondition(Cond))
1111      assert(false && "Unable to reverse branch condition!");
1112
1113  if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1114    if (ReverseBranchCondition(*CvtBBI)) {
1115      // BB has been changed, modify its predecessors (except for this
1116      // one) so they don't get ifcvt'ed based on bad intel.
1117      for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1118             E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1119        MachineBasicBlock *PBB = *PI;
1120        if (PBB == BBI.BB)
1121          continue;
1122        BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1123        if (PBBI.IsEnqueued) {
1124          PBBI.IsAnalyzed = false;
1125          PBBI.IsEnqueued = false;
1126        }
1127      }
1128    }
1129  }
1130
1131  // Initialize liveins to the first BB. These are potentially redefined by
1132  // predicated instructions.
1133  SmallSet<unsigned, 4> Redefs;
1134  InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1135  InitPredRedefs(NextBBI->BB, Redefs, TRI);
1136
1137  bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1138  if (CvtBBI->BB->pred_size() > 1) {
1139    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1140    // Copy instructions in the true block, predicate them, and add them to
1141    // the entry block.
1142    CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1143  } else {
1144    // Predicate the 'true' block after removing its branch.
1145    CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1146    PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1147
1148    // Now merge the entry of the triangle with the true block.
1149    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1150    MergeBlocks(BBI, *CvtBBI, false);
1151  }
1152
1153  // If 'true' block has a 'false' successor, add an exit branch to it.
1154  if (HasEarlyExit) {
1155    SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1156                                           CvtBBI->BrCond.end());
1157    if (TII->ReverseBranchCondition(RevCond))
1158      assert(false && "Unable to reverse branch condition!");
1159    TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1160    BBI.BB->addSuccessor(CvtBBI->FalseBB);
1161  }
1162
1163  // Merge in the 'false' block if the 'false' block has no other
1164  // predecessors. Otherwise, add an unconditional branch to 'false'.
1165  bool FalseBBDead = false;
1166  bool IterIfcvt = true;
1167  bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1168  if (!isFallThrough) {
1169    // Only merge them if the true block does not fallthrough to the false
1170    // block. By not merging them, we make it possible to iteratively
1171    // ifcvt the blocks.
1172    if (!HasEarlyExit &&
1173        NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1174      MergeBlocks(BBI, *NextBBI);
1175      FalseBBDead = true;
1176    } else {
1177      InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1178      BBI.HasFallThrough = false;
1179    }
1180    // Mixed predicated and unpredicated code. This cannot be iteratively
1181    // predicated.
1182    IterIfcvt = false;
1183  }
1184
1185  RemoveExtraEdges(BBI);
1186
1187  // Update block info. BB can be iteratively if-converted.
1188  if (!IterIfcvt)
1189    BBI.IsDone = true;
1190  InvalidatePreds(BBI.BB);
1191  CvtBBI->IsDone = true;
1192  if (FalseBBDead)
1193    NextBBI->IsDone = true;
1194
1195  // FIXME: Must maintain LiveIns.
1196  return true;
1197}
1198
1199/// IfConvertDiamond - If convert a diamond sub-CFG.
1200///
1201bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1202                                   unsigned NumDups1, unsigned NumDups2) {
1203  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1204  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1205  MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1206  // True block must fall through or end with an unanalyzable terminator.
1207  if (!TailBB) {
1208    if (blockAlwaysFallThrough(TrueBBI))
1209      TailBB = FalseBBI.TrueBB;
1210    assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1211  }
1212
1213  if (TrueBBI.IsDone || FalseBBI.IsDone ||
1214      TrueBBI.BB->pred_size() > 1 ||
1215      FalseBBI.BB->pred_size() > 1) {
1216    // Something has changed. It's no longer safe to predicate these blocks.
1217    BBI.IsAnalyzed = false;
1218    TrueBBI.IsAnalyzed = false;
1219    FalseBBI.IsAnalyzed = false;
1220    return false;
1221  }
1222
1223  // Put the predicated instructions from the 'true' block before the
1224  // instructions from the 'false' block, unless the true block would clobber
1225  // the predicate, in which case, do the opposite.
1226  BBInfo *BBI1 = &TrueBBI;
1227  BBInfo *BBI2 = &FalseBBI;
1228  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1229  if (TII->ReverseBranchCondition(RevCond))
1230    assert(false && "Unable to reverse branch condition!");
1231  SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1232  SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1233
1234  // Figure out the more profitable ordering.
1235  bool DoSwap = false;
1236  if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1237    DoSwap = true;
1238  else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1239    if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1240      DoSwap = true;
1241  }
1242  if (DoSwap) {
1243    std::swap(BBI1, BBI2);
1244    std::swap(Cond1, Cond2);
1245  }
1246
1247  // Remove the conditional branch from entry to the blocks.
1248  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1249
1250  // Initialize liveins to the first BB. These are potentially redefined by
1251  // predicated instructions.
1252  SmallSet<unsigned, 4> Redefs;
1253  InitPredRedefs(BBI1->BB, Redefs, TRI);
1254
1255  // Remove the duplicated instructions at the beginnings of both paths.
1256  MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1257  MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1258  MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1259  MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1260  // Skip dbg_value instructions
1261  while (DI1 != DIE1 && DI1->isDebugValue())
1262    ++DI1;
1263  while (DI2 != DIE2 && DI2->isDebugValue())
1264    ++DI2;
1265  BBI1->NonPredSize -= NumDups1;
1266  BBI2->NonPredSize -= NumDups1;
1267
1268  // Skip past the dups on each side separately since there may be
1269  // differing dbg_value entries.
1270  for (unsigned i = 0; i < NumDups1; ++DI1) {
1271    if (!DI1->isDebugValue())
1272      ++i;
1273  }
1274  while (NumDups1 != 0) {
1275    ++DI2;
1276    if (!DI2->isDebugValue())
1277      --NumDups1;
1278  }
1279
1280  UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1281  BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1282  BBI2->BB->erase(BBI2->BB->begin(), DI2);
1283
1284  // Predicate the 'true' block after removing its branch.
1285  BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1286  DI1 = BBI1->BB->end();
1287  for (unsigned i = 0; i != NumDups2; ) {
1288    // NumDups2 only counted non-dbg_value instructions, so this won't
1289    // run off the head of the list.
1290    assert (DI1 != BBI1->BB->begin());
1291    --DI1;
1292    // skip dbg_value instructions
1293    if (!DI1->isDebugValue())
1294      ++i;
1295  }
1296  BBI1->BB->erase(DI1, BBI1->BB->end());
1297  PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1298
1299  // Predicate the 'false' block.
1300  BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1301  DI2 = BBI2->BB->end();
1302  while (NumDups2 != 0) {
1303    // NumDups2 only counted non-dbg_value instructions, so this won't
1304    // run off the head of the list.
1305    assert (DI2 != BBI2->BB->begin());
1306    --DI2;
1307    // skip dbg_value instructions
1308    if (!DI2->isDebugValue())
1309      --NumDups2;
1310  }
1311  PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1312
1313  // Merge the true block into the entry of the diamond.
1314  MergeBlocks(BBI, *BBI1, TailBB == 0);
1315  MergeBlocks(BBI, *BBI2, TailBB == 0);
1316
1317  // If the if-converted block falls through or unconditionally branches into
1318  // the tail block, and the tail block does not have other predecessors, then
1319  // fold the tail block in as well. Otherwise, unless it falls through to the
1320  // tail, add a unconditional branch to it.
1321  if (TailBB) {
1322    BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1323    bool CanMergeTail = !TailBBI.HasFallThrough;
1324    // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1325    // check if there are any other predecessors besides those.
1326    unsigned NumPreds = TailBB->pred_size();
1327    if (NumPreds > 1)
1328      CanMergeTail = false;
1329    else if (NumPreds == 1 && CanMergeTail) {
1330      MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1331      if (*PI != BBI1->BB && *PI != BBI2->BB)
1332        CanMergeTail = false;
1333    }
1334    if (CanMergeTail) {
1335      MergeBlocks(BBI, TailBBI);
1336      TailBBI.IsDone = true;
1337    } else {
1338      BBI.BB->addSuccessor(TailBB);
1339      InsertUncondBranch(BBI.BB, TailBB, TII);
1340      BBI.HasFallThrough = false;
1341    }
1342  }
1343
1344  // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1345  // which can happen here if TailBB is unanalyzable and is merged, so
1346  // explicitly remove BBI1 and BBI2 as successors.
1347  BBI.BB->removeSuccessor(BBI1->BB);
1348  BBI.BB->removeSuccessor(BBI2->BB);
1349  RemoveExtraEdges(BBI);
1350
1351  // Update block info.
1352  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1353  InvalidatePreds(BBI.BB);
1354
1355  // FIXME: Must maintain LiveIns.
1356  return true;
1357}
1358
1359/// PredicateBlock - Predicate instructions from the start of the block to the
1360/// specified end with the specified condition.
1361void IfConverter::PredicateBlock(BBInfo &BBI,
1362                                 MachineBasicBlock::iterator E,
1363                                 SmallVectorImpl<MachineOperand> &Cond,
1364                                 SmallSet<unsigned, 4> &Redefs) {
1365  for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1366    if (I->isDebugValue() || TII->isPredicated(I))
1367      continue;
1368    if (!TII->PredicateInstruction(I, Cond)) {
1369#ifndef NDEBUG
1370      dbgs() << "Unable to predicate " << *I << "!\n";
1371#endif
1372      llvm_unreachable(0);
1373    }
1374
1375    // If the predicated instruction now redefines a register as the result of
1376    // if-conversion, add an implicit kill.
1377    UpdatePredRedefs(I, Redefs, TRI, true);
1378  }
1379
1380  std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1381
1382  BBI.IsAnalyzed = false;
1383  BBI.NonPredSize = 0;
1384
1385  ++NumIfConvBBs;
1386}
1387
1388/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1389/// the destination block. Skip end of block branches if IgnoreBr is true.
1390void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1391                                        SmallVectorImpl<MachineOperand> &Cond,
1392                                        SmallSet<unsigned, 4> &Redefs,
1393                                        bool IgnoreBr) {
1394  MachineFunction &MF = *ToBBI.BB->getParent();
1395
1396  for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1397         E = FromBBI.BB->end(); I != E; ++I) {
1398    const TargetInstrDesc &TID = I->getDesc();
1399    // Do not copy the end of the block branches.
1400    if (IgnoreBr && TID.isBranch())
1401      break;
1402
1403    MachineInstr *MI = MF.CloneMachineInstr(I);
1404    ToBBI.BB->insert(ToBBI.BB->end(), MI);
1405    unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
1406    ToBBI.NonPredSize += NumOps;
1407
1408    if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1409      if (!TII->PredicateInstruction(MI, Cond)) {
1410#ifndef NDEBUG
1411        dbgs() << "Unable to predicate " << *I << "!\n";
1412#endif
1413        llvm_unreachable(0);
1414      }
1415    }
1416
1417    // If the predicated instruction now redefines a register as the result of
1418    // if-conversion, add an implicit kill.
1419    UpdatePredRedefs(MI, Redefs, TRI, true);
1420  }
1421
1422  if (!IgnoreBr) {
1423    std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1424                                           FromBBI.BB->succ_end());
1425    MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1426    MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1427
1428    for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1429      MachineBasicBlock *Succ = Succs[i];
1430      // Fallthrough edge can't be transferred.
1431      if (Succ == FallThrough)
1432        continue;
1433      ToBBI.BB->addSuccessor(Succ);
1434    }
1435  }
1436
1437  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1438            std::back_inserter(ToBBI.Predicate));
1439  std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1440
1441  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1442  ToBBI.IsAnalyzed = false;
1443
1444  ++NumDupBBs;
1445}
1446
1447/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1448/// This will leave FromBB as an empty block, so remove all of its
1449/// successor edges except for the fall-through edge.  If AddEdges is true,
1450/// i.e., when FromBBI's branch is being moved, add those successor edges to
1451/// ToBBI.
1452void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1453  ToBBI.BB->splice(ToBBI.BB->end(),
1454                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1455
1456  std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1457                                         FromBBI.BB->succ_end());
1458  MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1459  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1460
1461  for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1462    MachineBasicBlock *Succ = Succs[i];
1463    // Fallthrough edge can't be transferred.
1464    if (Succ == FallThrough)
1465      continue;
1466    FromBBI.BB->removeSuccessor(Succ);
1467    if (AddEdges)
1468      ToBBI.BB->addSuccessor(Succ);
1469  }
1470
1471  // Now FromBBI always falls through to the next block!
1472  if (NBB && !FromBBI.BB->isSuccessor(NBB))
1473    FromBBI.BB->addSuccessor(NBB);
1474
1475  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1476            std::back_inserter(ToBBI.Predicate));
1477  FromBBI.Predicate.clear();
1478
1479  ToBBI.NonPredSize += FromBBI.NonPredSize;
1480  FromBBI.NonPredSize = 0;
1481
1482  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1483  ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1484  ToBBI.IsAnalyzed = false;
1485  FromBBI.IsAnalyzed = false;
1486}
1487