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