IfConversion.cpp revision 5e25ee8a1fcf8288d00d731b0f7ab7976f33b123
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/MachineBranchProbabilityInfo.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/MC/MCInstrItineraries.h"
22#include "llvm/Target/TargetInstrInfo.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/SmallSet.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");
65STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
66
67namespace {
68  class IfConverter : public MachineFunctionPass {
69    enum IfcvtKind {
70      ICNotClassfied,  // BB data valid, but not classified.
71      ICSimpleFalse,   // Same as ICSimple, but on the false path.
72      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
73      ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
74      ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
75      ICTriangleFalse, // Same as ICTriangle, but on the false path.
76      ICTriangle,      // BB is entry of a triangle sub-CFG.
77      ICDiamond        // BB is entry of a diamond sub-CFG.
78    };
79
80    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
81    /// if-conversion feasibility analysis. This includes results from
82    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
83    /// classification, and common tail block of its successors (if it's a
84    /// diamond shape), its size, whether it's predicable, and whether any
85    /// instruction can clobber the 'would-be' predicate.
86    ///
87    /// IsDone          - True if BB is not to be considered for ifcvt.
88    /// IsBeingAnalyzed - True if BB is currently being analyzed.
89    /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
90    /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
91    /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
92    /// HasFallThrough  - True if BB may fallthrough to the following BB.
93    /// IsUnpredicable  - True if BB is known to be unpredicable.
94    /// ClobbersPred    - True if BB could modify predicates (e.g. has
95    ///                   cmp, call, etc.)
96    /// NonPredSize     - Number of non-predicated instructions.
97    /// ExtraCost       - Extra cost for multi-cycle instructions.
98    /// ExtraCost2      - Some instructions are slower when predicated
99    /// BB              - Corresponding MachineBasicBlock.
100    /// TrueBB / FalseBB- See AnalyzeBranch().
101    /// BrCond          - Conditions for end of block conditional branches.
102    /// Predicate       - Predicate used in the BB.
103    struct BBInfo {
104      bool IsDone          : 1;
105      bool IsBeingAnalyzed : 1;
106      bool IsAnalyzed      : 1;
107      bool IsEnqueued      : 1;
108      bool IsBrAnalyzable  : 1;
109      bool HasFallThrough  : 1;
110      bool IsUnpredicable  : 1;
111      bool CannotBeCopied  : 1;
112      bool ClobbersPred    : 1;
113      unsigned NonPredSize;
114      unsigned ExtraCost;
115      unsigned ExtraCost2;
116      MachineBasicBlock *BB;
117      MachineBasicBlock *TrueBB;
118      MachineBasicBlock *FalseBB;
119      SmallVector<MachineOperand, 4> BrCond;
120      SmallVector<MachineOperand, 4> Predicate;
121      BBInfo() : IsDone(false), IsBeingAnalyzed(false),
122                 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
123                 HasFallThrough(false), IsUnpredicable(false),
124                 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
125                 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
126    };
127
128    /// IfcvtToken - Record information about pending if-conversions to attempt:
129    /// BBI             - Corresponding BBInfo.
130    /// Kind            - Type of block. See IfcvtKind.
131    /// NeedSubsumption - True if the to-be-predicated BB has already been
132    ///                   predicated.
133    /// NumDups      - Number of instructions that would be duplicated due
134    ///                   to this if-conversion. (For diamonds, the number of
135    ///                   identical instructions at the beginnings of both
136    ///                   paths).
137    /// NumDups2     - For diamonds, the number of identical instructions
138    ///                   at the ends of both paths.
139    struct IfcvtToken {
140      BBInfo &BBI;
141      IfcvtKind Kind;
142      bool NeedSubsumption;
143      unsigned NumDups;
144      unsigned NumDups2;
145      IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
146        : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
147    };
148
149    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
150    /// basic block number.
151    std::vector<BBInfo> BBAnalysis;
152
153    const TargetLowering *TLI;
154    const TargetInstrInfo *TII;
155    const TargetRegisterInfo *TRI;
156    const InstrItineraryData *InstrItins;
157    const MachineBranchProbabilityInfo *MBPI;
158
159    bool MadeChange;
160    int FnNum;
161  public:
162    static char ID;
163    IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164      initializeIfConverterPass(*PassRegistry::getPassRegistry());
165    }
166
167    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168      AU.addRequired<MachineBranchProbabilityInfo>();
169      MachineFunctionPass::getAnalysisUsage(AU);
170    }
171
172    virtual bool runOnMachineFunction(MachineFunction &MF);
173    virtual const char *getPassName() const { return "If Converter"; }
174
175  private:
176    bool ReverseBranchCondition(BBInfo &BBI);
177    bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178                     const BranchProbability &Prediction) const;
179    bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
180                       bool FalseBranch, unsigned &Dups,
181                       const BranchProbability &Prediction) const;
182    bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183                      unsigned &Dups1, unsigned &Dups2) const;
184    void ScanInstructions(BBInfo &BBI);
185    BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186                         std::vector<IfcvtToken*> &Tokens);
187    bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
188                             bool isTriangle = false, bool RevBranch = false);
189    void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
190    void InvalidatePreds(MachineBasicBlock *BB);
191    void RemoveExtraEdges(BBInfo &BBI);
192    bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193    bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
194    bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195                          unsigned NumDups1, unsigned NumDups2);
196    void PredicateBlock(BBInfo &BBI,
197                        MachineBasicBlock::iterator E,
198                        SmallVectorImpl<MachineOperand> &Cond,
199                        SmallSet<unsigned, 4> &Redefs,
200                        SmallSet<unsigned, 4> *LaterRedefs = 0);
201    void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
202                               SmallVectorImpl<MachineOperand> &Cond,
203                               SmallSet<unsigned, 4> &Redefs,
204                               bool IgnoreBr = false);
205    void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
206
207    bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
208                            unsigned Cycle, unsigned Extra,
209                            const BranchProbability &Prediction) const {
210      return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
211                                                   Prediction);
212    }
213
214    bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
215                            unsigned TCycle, unsigned TExtra,
216                            MachineBasicBlock &FBB,
217                            unsigned FCycle, unsigned FExtra,
218                            const BranchProbability &Prediction) const {
219      return TCycle > 0 && FCycle > 0 &&
220        TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
221                                 Prediction);
222    }
223
224    // blockAlwaysFallThrough - Block ends without a terminator.
225    bool blockAlwaysFallThrough(BBInfo &BBI) const {
226      return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
227    }
228
229    // IfcvtTokenCmp - Used to sort if-conversion candidates.
230    static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
231      int Incr1 = (C1->Kind == ICDiamond)
232        ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
233      int Incr2 = (C2->Kind == ICDiamond)
234        ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
235      if (Incr1 > Incr2)
236        return true;
237      else if (Incr1 == Incr2) {
238        // Favors subsumption.
239        if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
240          return true;
241        else if (C1->NeedSubsumption == C2->NeedSubsumption) {
242          // Favors diamond over triangle, etc.
243          if ((unsigned)C1->Kind < (unsigned)C2->Kind)
244            return true;
245          else if (C1->Kind == C2->Kind)
246            return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
247        }
248      }
249      return false;
250    }
251  };
252
253  char IfConverter::ID = 0;
254}
255
256INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
257INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
258INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
259
260FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
261
262bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
263  TLI = MF.getTarget().getTargetLowering();
264  TII = MF.getTarget().getInstrInfo();
265  TRI = MF.getTarget().getRegisterInfo();
266  MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
267  InstrItins = MF.getTarget().getInstrItineraryData();
268  if (!TII) return false;
269
270  // Tail merge tend to expose more if-conversion opportunities.
271  BranchFolder BF(true, false);
272  bool BFChange = BF.OptimizeFunction(MF, TII,
273                                   MF.getTarget().getRegisterInfo(),
274                                   getAnalysisIfAvailable<MachineModuleInfo>());
275
276  DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
277               << MF.getFunction()->getName() << "\'");
278
279  if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
280    DEBUG(dbgs() << " skipped\n");
281    return false;
282  }
283  DEBUG(dbgs() << "\n");
284
285  MF.RenumberBlocks();
286  BBAnalysis.resize(MF.getNumBlockIDs());
287
288  std::vector<IfcvtToken*> Tokens;
289  MadeChange = false;
290  unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
291    NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
292  while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
293    // Do an initial analysis for each basic block and find all the potential
294    // candidates to perform if-conversion.
295    bool Change = false;
296    AnalyzeBlocks(MF, Tokens);
297    while (!Tokens.empty()) {
298      IfcvtToken *Token = Tokens.back();
299      Tokens.pop_back();
300      BBInfo &BBI = Token->BBI;
301      IfcvtKind Kind = Token->Kind;
302      unsigned NumDups = Token->NumDups;
303      unsigned NumDups2 = Token->NumDups2;
304
305      delete Token;
306
307      // If the block has been evicted out of the queue or it has already been
308      // marked dead (due to it being predicated), then skip it.
309      if (BBI.IsDone)
310        BBI.IsEnqueued = false;
311      if (!BBI.IsEnqueued)
312        continue;
313
314      BBI.IsEnqueued = false;
315
316      bool RetVal = false;
317      switch (Kind) {
318      default: llvm_unreachable("Unexpected!");
319      case ICSimple:
320      case ICSimpleFalse: {
321        bool isFalse = Kind == ICSimpleFalse;
322        if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
323        DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
324                                            " false" : "")
325                     << "): BB#" << BBI.BB->getNumber() << " ("
326                     << ((Kind == ICSimpleFalse)
327                         ? BBI.FalseBB->getNumber()
328                         : BBI.TrueBB->getNumber()) << ") ");
329        RetVal = IfConvertSimple(BBI, Kind);
330        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
331        if (RetVal) {
332          if (isFalse) ++NumSimpleFalse;
333          else         ++NumSimple;
334        }
335       break;
336      }
337      case ICTriangle:
338      case ICTriangleRev:
339      case ICTriangleFalse:
340      case ICTriangleFRev: {
341        bool isFalse = Kind == ICTriangleFalse;
342        bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
343        if (DisableTriangle && !isFalse && !isRev) break;
344        if (DisableTriangleR && !isFalse && isRev) break;
345        if (DisableTriangleF && isFalse && !isRev) break;
346        if (DisableTriangleFR && isFalse && isRev) break;
347        DEBUG(dbgs() << "Ifcvt (Triangle");
348        if (isFalse)
349          DEBUG(dbgs() << " false");
350        if (isRev)
351          DEBUG(dbgs() << " rev");
352        DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
353                     << BBI.TrueBB->getNumber() << ",F:"
354                     << BBI.FalseBB->getNumber() << ") ");
355        RetVal = IfConvertTriangle(BBI, Kind);
356        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
357        if (RetVal) {
358          if (isFalse) {
359            if (isRev) ++NumTriangleFRev;
360            else       ++NumTriangleFalse;
361          } else {
362            if (isRev) ++NumTriangleRev;
363            else       ++NumTriangle;
364          }
365        }
366        break;
367      }
368      case ICDiamond: {
369        if (DisableDiamond) break;
370        DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
371                     << BBI.TrueBB->getNumber() << ",F:"
372                     << BBI.FalseBB->getNumber() << ") ");
373        RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
374        DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
375        if (RetVal) ++NumDiamonds;
376        break;
377      }
378      }
379
380      Change |= RetVal;
381
382      NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
383        NumTriangleFalse + NumTriangleFRev + NumDiamonds;
384      if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
385        break;
386    }
387
388    if (!Change)
389      break;
390    MadeChange |= Change;
391  }
392
393  // Delete tokens in case of early exit.
394  while (!Tokens.empty()) {
395    IfcvtToken *Token = Tokens.back();
396    Tokens.pop_back();
397    delete Token;
398  }
399
400  Tokens.clear();
401  BBAnalysis.clear();
402
403  if (MadeChange && IfCvtBranchFold) {
404    BranchFolder BF(false, false);
405    BF.OptimizeFunction(MF, TII,
406                        MF.getTarget().getRegisterInfo(),
407                        getAnalysisIfAvailable<MachineModuleInfo>());
408  }
409
410  MadeChange |= BFChange;
411  return MadeChange;
412}
413
414/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
415/// its 'true' successor.
416static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
417                                         MachineBasicBlock *TrueBB) {
418  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
419         E = BB->succ_end(); SI != E; ++SI) {
420    MachineBasicBlock *SuccBB = *SI;
421    if (SuccBB != TrueBB)
422      return SuccBB;
423  }
424  return NULL;
425}
426
427/// ReverseBranchCondition - Reverse the condition of the end of the block
428/// branch. Swap block's 'true' and 'false' successors.
429bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
430  DebugLoc dl;  // FIXME: this is nowhere
431  if (!TII->ReverseBranchCondition(BBI.BrCond)) {
432    TII->RemoveBranch(*BBI.BB);
433    TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
434    std::swap(BBI.TrueBB, BBI.FalseBB);
435    return true;
436  }
437  return false;
438}
439
440/// getNextBlock - Returns the next block in the function blocks ordering. If
441/// it is the end, returns NULL.
442static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
443  MachineFunction::iterator I = BB;
444  MachineFunction::iterator E = BB->getParent()->end();
445  if (++I == E)
446    return NULL;
447  return I;
448}
449
450/// ValidSimple - Returns true if the 'true' block (along with its
451/// predecessor) forms a valid simple shape for ifcvt. It also returns the
452/// number of instructions that the ifcvt would need to duplicate if performed
453/// in Dups.
454bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
455                              const BranchProbability &Prediction) const {
456  Dups = 0;
457  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
458    return false;
459
460  if (TrueBBI.IsBrAnalyzable)
461    return false;
462
463  if (TrueBBI.BB->pred_size() > 1) {
464    if (TrueBBI.CannotBeCopied ||
465        !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
466                                        Prediction))
467      return false;
468    Dups = TrueBBI.NonPredSize;
469  }
470
471  return true;
472}
473
474/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
475/// with their common predecessor) forms a valid triangle shape for ifcvt.
476/// If 'FalseBranch' is true, it checks if 'true' block's false branch
477/// branches to the 'false' block rather than the other way around. It also
478/// returns the number of instructions that the ifcvt would need to duplicate
479/// if performed in 'Dups'.
480bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
481                                bool FalseBranch, unsigned &Dups,
482                                const BranchProbability &Prediction) const {
483  Dups = 0;
484  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
485    return false;
486
487  if (TrueBBI.BB->pred_size() > 1) {
488    if (TrueBBI.CannotBeCopied)
489      return false;
490
491    unsigned Size = TrueBBI.NonPredSize;
492    if (TrueBBI.IsBrAnalyzable) {
493      if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
494        // Ends with an unconditional branch. It will be removed.
495        --Size;
496      else {
497        MachineBasicBlock *FExit = FalseBranch
498          ? TrueBBI.TrueBB : TrueBBI.FalseBB;
499        if (FExit)
500          // Require a conditional branch
501          ++Size;
502      }
503    }
504    if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
505      return false;
506    Dups = Size;
507  }
508
509  MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
510  if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
511    MachineFunction::iterator I = TrueBBI.BB;
512    if (++I == TrueBBI.BB->getParent()->end())
513      return false;
514    TExit = I;
515  }
516  return TExit && TExit == FalseBBI.BB;
517}
518
519/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
520/// with their common predecessor) forms a valid diamond shape for ifcvt.
521bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
522                               unsigned &Dups1, unsigned &Dups2) const {
523  Dups1 = Dups2 = 0;
524  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
525      FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
526    return false;
527
528  MachineBasicBlock *TT = TrueBBI.TrueBB;
529  MachineBasicBlock *FT = FalseBBI.TrueBB;
530
531  if (!TT && blockAlwaysFallThrough(TrueBBI))
532    TT = getNextBlock(TrueBBI.BB);
533  if (!FT && blockAlwaysFallThrough(FalseBBI))
534    FT = getNextBlock(FalseBBI.BB);
535  if (TT != FT)
536    return false;
537  if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
538    return false;
539  if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
540    return false;
541
542  // FIXME: Allow true block to have an early exit?
543  if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
544      (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
545    return false;
546
547  // Count duplicate instructions at the beginning of the true and false blocks.
548  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
549  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
550  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
551  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
552  while (TIB != TIE && FIB != FIE) {
553    // Skip dbg_value instructions. These do not count.
554    if (TIB->isDebugValue()) {
555      while (TIB != TIE && TIB->isDebugValue())
556        ++TIB;
557      if (TIB == TIE)
558        break;
559    }
560    if (FIB->isDebugValue()) {
561      while (FIB != FIE && FIB->isDebugValue())
562        ++FIB;
563      if (FIB == FIE)
564        break;
565    }
566    if (!TIB->isIdenticalTo(FIB))
567      break;
568    ++Dups1;
569    ++TIB;
570    ++FIB;
571  }
572
573  // Now, in preparation for counting duplicate instructions at the ends of the
574  // blocks, move the end iterators up past any branch instructions.
575  while (TIE != TIB) {
576    --TIE;
577    if (!TIE->isBranch())
578      break;
579  }
580  while (FIE != FIB) {
581    --FIE;
582    if (!FIE->isBranch())
583      break;
584  }
585
586  // If Dups1 includes all of a block, then don't count duplicate
587  // instructions at the end of the blocks.
588  if (TIB == TIE || FIB == FIE)
589    return true;
590
591  // Count duplicate instructions at the ends of the blocks.
592  while (TIE != TIB && FIE != FIB) {
593    // Skip dbg_value instructions. These do not count.
594    if (TIE->isDebugValue()) {
595      while (TIE != TIB && TIE->isDebugValue())
596        --TIE;
597      if (TIE == TIB)
598        break;
599    }
600    if (FIE->isDebugValue()) {
601      while (FIE != FIB && FIE->isDebugValue())
602        --FIE;
603      if (FIE == FIB)
604        break;
605    }
606    if (!TIE->isIdenticalTo(FIE))
607      break;
608    ++Dups2;
609    --TIE;
610    --FIE;
611  }
612
613  return true;
614}
615
616/// ScanInstructions - Scan all the instructions in the block to determine if
617/// the block is predicable. In most cases, that means all the instructions
618/// in the block are isPredicable(). Also checks if the block contains any
619/// instruction which can clobber a predicate (e.g. condition code register).
620/// If so, the block is not predicable unless it's the last instruction.
621void IfConverter::ScanInstructions(BBInfo &BBI) {
622  if (BBI.IsDone)
623    return;
624
625  bool AlreadyPredicated = BBI.Predicate.size() > 0;
626  // First analyze the end of BB branches.
627  BBI.TrueBB = BBI.FalseBB = NULL;
628  BBI.BrCond.clear();
629  BBI.IsBrAnalyzable =
630    !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
631  BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
632
633  if (BBI.BrCond.size()) {
634    // No false branch. This BB must end with a conditional branch and a
635    // fallthrough.
636    if (!BBI.FalseBB)
637      BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
638    if (!BBI.FalseBB) {
639      // Malformed bcc? True and false blocks are the same?
640      BBI.IsUnpredicable = true;
641      return;
642    }
643  }
644
645  // Then scan all the instructions.
646  BBI.NonPredSize = 0;
647  BBI.ExtraCost = 0;
648  BBI.ExtraCost2 = 0;
649  BBI.ClobbersPred = false;
650  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
651       I != E; ++I) {
652    if (I->isDebugValue())
653      continue;
654
655    if (I->isNotDuplicable())
656      BBI.CannotBeCopied = true;
657
658    bool isPredicated = TII->isPredicated(I);
659    bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
660
661    if (!isCondBr) {
662      if (!isPredicated) {
663        BBI.NonPredSize++;
664        unsigned ExtraPredCost = 0;
665        unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
666                                                  &ExtraPredCost);
667        if (NumCycles > 1)
668          BBI.ExtraCost += NumCycles-1;
669        BBI.ExtraCost2 += ExtraPredCost;
670      } else if (!AlreadyPredicated) {
671        // FIXME: This instruction is already predicated before the
672        // if-conversion pass. It's probably something like a conditional move.
673        // Mark this block unpredicable for now.
674        BBI.IsUnpredicable = true;
675        return;
676      }
677    }
678
679    if (BBI.ClobbersPred && !isPredicated) {
680      // Predicate modification instruction should end the block (except for
681      // already predicated instructions and end of block branches).
682      if (isCondBr) {
683        // A conditional branch is not predicable, but it may be eliminated.
684        continue;
685      }
686
687      // Predicate may have been modified, the subsequent (currently)
688      // unpredicated instructions cannot be correctly predicated.
689      BBI.IsUnpredicable = true;
690      return;
691    }
692
693    // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
694    // still potentially predicable.
695    std::vector<MachineOperand> PredDefs;
696    if (TII->DefinesPredicate(I, PredDefs))
697      BBI.ClobbersPred = true;
698
699    if (!TII->isPredicable(I)) {
700      BBI.IsUnpredicable = true;
701      return;
702    }
703  }
704}
705
706/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
707/// predicated by the specified predicate.
708bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
709                                      SmallVectorImpl<MachineOperand> &Pred,
710                                      bool isTriangle, bool RevBranch) {
711  // If the block is dead or unpredicable, then it cannot be predicated.
712  if (BBI.IsDone || BBI.IsUnpredicable)
713    return false;
714
715  // If it is already predicated, check if its predicate subsumes the new
716  // predicate.
717  if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
718    return false;
719
720  if (BBI.BrCond.size()) {
721    if (!isTriangle)
722      return false;
723
724    // Test predicate subsumption.
725    SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
726    SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
727    if (RevBranch) {
728      if (TII->ReverseBranchCondition(Cond))
729        return false;
730    }
731    if (TII->ReverseBranchCondition(RevPred) ||
732        !TII->SubsumesPredicate(Cond, RevPred))
733      return false;
734  }
735
736  return true;
737}
738
739/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
740/// the specified block. Record its successors and whether it looks like an
741/// if-conversion candidate.
742IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
743                                             std::vector<IfcvtToken*> &Tokens) {
744  BBInfo &BBI = BBAnalysis[BB->getNumber()];
745
746  if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
747    return BBI;
748
749  BBI.BB = BB;
750  BBI.IsBeingAnalyzed = true;
751
752  ScanInstructions(BBI);
753
754  // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
755  // considered for ifcvt anymore.
756  if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
757    BBI.IsBeingAnalyzed = false;
758    BBI.IsAnalyzed = true;
759    return BBI;
760  }
761
762  // Do not ifcvt if either path is a back edge to the entry block.
763  if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
764    BBI.IsBeingAnalyzed = false;
765    BBI.IsAnalyzed = true;
766    return BBI;
767  }
768
769  // Do not ifcvt if true and false fallthrough blocks are the same.
770  if (!BBI.FalseBB) {
771    BBI.IsBeingAnalyzed = false;
772    BBI.IsAnalyzed = true;
773    return BBI;
774  }
775
776  BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
777  BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
778
779  if (TrueBBI.IsDone && FalseBBI.IsDone) {
780    BBI.IsBeingAnalyzed = false;
781    BBI.IsAnalyzed = true;
782    return BBI;
783  }
784
785  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
786  bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
787
788  unsigned Dups = 0;
789  unsigned Dups2 = 0;
790  bool TNeedSub = TrueBBI.Predicate.size() > 0;
791  bool FNeedSub = FalseBBI.Predicate.size() > 0;
792  bool Enqueued = false;
793
794  BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
795
796  if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
797      MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
798                                       TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
799                         *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
800                                        FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
801                         Prediction) &&
802      FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
803      FeasibilityAnalysis(FalseBBI, RevCond)) {
804    // Diamond:
805    //   EBB
806    //   / \_
807    //  |   |
808    // TBB FBB
809    //   \ /
810    //  TailBB
811    // Note TailBB can be empty.
812    Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
813                                    Dups2));
814    Enqueued = true;
815  }
816
817  if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
818      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
819                         TrueBBI.ExtraCost2, Prediction) &&
820      FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
821    // Triangle:
822    //   EBB
823    //   | \_
824    //   |  |
825    //   | TBB
826    //   |  /
827    //   FBB
828    Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
829    Enqueued = true;
830  }
831
832  if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
833      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
834                         TrueBBI.ExtraCost2, Prediction) &&
835      FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
836    Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
837    Enqueued = true;
838  }
839
840  if (ValidSimple(TrueBBI, Dups, Prediction) &&
841      MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
842                         TrueBBI.ExtraCost2, Prediction) &&
843      FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
844    // Simple (split, no rejoin):
845    //   EBB
846    //   | \_
847    //   |  |
848    //   | TBB---> exit
849    //   |
850    //   FBB
851    Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
852    Enqueued = true;
853  }
854
855  if (CanRevCond) {
856    // Try the other path...
857    if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
858                      Prediction.getCompl()) &&
859        MeetIfcvtSizeLimit(*FalseBBI.BB,
860                           FalseBBI.NonPredSize + FalseBBI.ExtraCost,
861                           FalseBBI.ExtraCost2, Prediction.getCompl()) &&
862        FeasibilityAnalysis(FalseBBI, RevCond, true)) {
863      Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
864      Enqueued = true;
865    }
866
867    if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
868                      Prediction.getCompl()) &&
869        MeetIfcvtSizeLimit(*FalseBBI.BB,
870                           FalseBBI.NonPredSize + FalseBBI.ExtraCost,
871                           FalseBBI.ExtraCost2, Prediction.getCompl()) &&
872        FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
873      Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
874      Enqueued = true;
875    }
876
877    if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
878        MeetIfcvtSizeLimit(*FalseBBI.BB,
879                           FalseBBI.NonPredSize + FalseBBI.ExtraCost,
880                           FalseBBI.ExtraCost2, Prediction.getCompl()) &&
881        FeasibilityAnalysis(FalseBBI, RevCond)) {
882      Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
883      Enqueued = true;
884    }
885  }
886
887  BBI.IsEnqueued = Enqueued;
888  BBI.IsBeingAnalyzed = false;
889  BBI.IsAnalyzed = true;
890  return BBI;
891}
892
893/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
894/// candidates.
895void IfConverter::AnalyzeBlocks(MachineFunction &MF,
896                                std::vector<IfcvtToken*> &Tokens) {
897  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
898    MachineBasicBlock *BB = I;
899    AnalyzeBlock(BB, Tokens);
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      llvm_unreachable("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      llvm_unreachable("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      llvm_unreachable("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    llvm_unreachable("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  // Remove branch from 'true' block and remove duplicated instructions.
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
1298  // Remove 'false' block branch and find the last instruction to predicate.
1299  BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1300  DI2 = BBI2->BB->end();
1301  while (NumDups2 != 0) {
1302    // NumDups2 only counted non-dbg_value instructions, so this won't
1303    // run off the head of the list.
1304    assert (DI2 != BBI2->BB->begin());
1305    --DI2;
1306    // skip dbg_value instructions
1307    if (!DI2->isDebugValue())
1308      --NumDups2;
1309  }
1310
1311  // Remember which registers would later be defined by the false block.
1312  // This allows us not to predicate instructions in the true block that would
1313  // later be re-defined. That is, rather than
1314  //   subeq  r0, r1, #1
1315  //   addne  r0, r1, #1
1316  // generate:
1317  //   sub    r0, r1, #1
1318  //   addne  r0, r1, #1
1319  SmallSet<unsigned, 4> RedefsByFalse;
1320  SmallSet<unsigned, 4> ExtUses;
1321  if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1322    for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1323      if (FI->isDebugValue())
1324        continue;
1325      SmallVector<unsigned, 4> Defs;
1326      for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1327        const MachineOperand &MO = FI->getOperand(i);
1328        if (!MO.isReg())
1329          continue;
1330        unsigned Reg = MO.getReg();
1331        if (!Reg)
1332          continue;
1333        if (MO.isDef()) {
1334          Defs.push_back(Reg);
1335        } else if (!RedefsByFalse.count(Reg)) {
1336          // These are defined before ctrl flow reach the 'false' instructions.
1337          // They cannot be modified by the 'true' instructions.
1338          ExtUses.insert(Reg);
1339          for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1340            ExtUses.insert(*SR);
1341        }
1342      }
1343
1344      for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1345        unsigned Reg = Defs[i];
1346        if (!ExtUses.count(Reg)) {
1347          RedefsByFalse.insert(Reg);
1348          for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1349            RedefsByFalse.insert(*SR);
1350        }
1351      }
1352    }
1353  }
1354
1355  // Predicate the 'true' block.
1356  PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1357
1358  // Predicate the 'false' block.
1359  PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1360
1361  // Merge the true block into the entry of the diamond.
1362  MergeBlocks(BBI, *BBI1, TailBB == 0);
1363  MergeBlocks(BBI, *BBI2, TailBB == 0);
1364
1365  // If the if-converted block falls through or unconditionally branches into
1366  // the tail block, and the tail block does not have other predecessors, then
1367  // fold the tail block in as well. Otherwise, unless it falls through to the
1368  // tail, add a unconditional branch to it.
1369  if (TailBB) {
1370    BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1371    bool CanMergeTail = !TailBBI.HasFallThrough;
1372    // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1373    // check if there are any other predecessors besides those.
1374    unsigned NumPreds = TailBB->pred_size();
1375    if (NumPreds > 1)
1376      CanMergeTail = false;
1377    else if (NumPreds == 1 && CanMergeTail) {
1378      MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1379      if (*PI != BBI1->BB && *PI != BBI2->BB)
1380        CanMergeTail = false;
1381    }
1382    if (CanMergeTail) {
1383      MergeBlocks(BBI, TailBBI);
1384      TailBBI.IsDone = true;
1385    } else {
1386      BBI.BB->addSuccessor(TailBB);
1387      InsertUncondBranch(BBI.BB, TailBB, TII);
1388      BBI.HasFallThrough = false;
1389    }
1390  }
1391
1392  // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1393  // which can happen here if TailBB is unanalyzable and is merged, so
1394  // explicitly remove BBI1 and BBI2 as successors.
1395  BBI.BB->removeSuccessor(BBI1->BB);
1396  BBI.BB->removeSuccessor(BBI2->BB);
1397  RemoveExtraEdges(BBI);
1398
1399  // Update block info.
1400  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1401  InvalidatePreds(BBI.BB);
1402
1403  // FIXME: Must maintain LiveIns.
1404  return true;
1405}
1406
1407static bool MaySpeculate(const MachineInstr *MI,
1408                         SmallSet<unsigned, 4> &LaterRedefs,
1409                         const TargetInstrInfo *TII) {
1410  bool SawStore = true;
1411  if (!MI->isSafeToMove(TII, 0, SawStore))
1412    return false;
1413
1414  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1415    const MachineOperand &MO = MI->getOperand(i);
1416    if (!MO.isReg())
1417      continue;
1418    unsigned Reg = MO.getReg();
1419    if (!Reg)
1420      continue;
1421    if (MO.isDef() && !LaterRedefs.count(Reg))
1422      return false;
1423  }
1424
1425  return true;
1426}
1427
1428/// PredicateBlock - Predicate instructions from the start of the block to the
1429/// specified end with the specified condition.
1430void IfConverter::PredicateBlock(BBInfo &BBI,
1431                                 MachineBasicBlock::iterator E,
1432                                 SmallVectorImpl<MachineOperand> &Cond,
1433                                 SmallSet<unsigned, 4> &Redefs,
1434                                 SmallSet<unsigned, 4> *LaterRedefs) {
1435  bool AnyUnpred = false;
1436  bool MaySpec = LaterRedefs != 0;
1437  for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1438    if (I->isDebugValue() || TII->isPredicated(I))
1439      continue;
1440    // It may be possible not to predicate an instruction if it's the 'true'
1441    // side of a diamond and the 'false' side may re-define the instruction's
1442    // defs.
1443    if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1444      AnyUnpred = true;
1445      continue;
1446    }
1447    // If any instruction is predicated, then every instruction after it must
1448    // be predicated.
1449    MaySpec = false;
1450    if (!TII->PredicateInstruction(I, Cond)) {
1451#ifndef NDEBUG
1452      dbgs() << "Unable to predicate " << *I << "!\n";
1453#endif
1454      llvm_unreachable(0);
1455    }
1456
1457    // If the predicated instruction now redefines a register as the result of
1458    // if-conversion, add an implicit kill.
1459    UpdatePredRedefs(I, Redefs, TRI, true);
1460  }
1461
1462  std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1463
1464  BBI.IsAnalyzed = false;
1465  BBI.NonPredSize = 0;
1466
1467  ++NumIfConvBBs;
1468  if (AnyUnpred)
1469    ++NumUnpred;
1470}
1471
1472/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1473/// the destination block. Skip end of block branches if IgnoreBr is true.
1474void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1475                                        SmallVectorImpl<MachineOperand> &Cond,
1476                                        SmallSet<unsigned, 4> &Redefs,
1477                                        bool IgnoreBr) {
1478  MachineFunction &MF = *ToBBI.BB->getParent();
1479
1480  for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1481         E = FromBBI.BB->end(); I != E; ++I) {
1482    // Do not copy the end of the block branches.
1483    if (IgnoreBr && I->isBranch())
1484      break;
1485
1486    MachineInstr *MI = MF.CloneMachineInstr(I);
1487    ToBBI.BB->insert(ToBBI.BB->end(), MI);
1488    ToBBI.NonPredSize++;
1489    unsigned ExtraPredCost = 0;
1490    unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1491    if (NumCycles > 1)
1492      ToBBI.ExtraCost += NumCycles-1;
1493    ToBBI.ExtraCost2 += ExtraPredCost;
1494
1495    if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1496      if (!TII->PredicateInstruction(MI, Cond)) {
1497#ifndef NDEBUG
1498        dbgs() << "Unable to predicate " << *I << "!\n";
1499#endif
1500        llvm_unreachable(0);
1501      }
1502    }
1503
1504    // If the predicated instruction now redefines a register as the result of
1505    // if-conversion, add an implicit kill.
1506    UpdatePredRedefs(MI, Redefs, TRI, true);
1507  }
1508
1509  if (!IgnoreBr) {
1510    std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1511                                           FromBBI.BB->succ_end());
1512    MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1513    MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1514
1515    for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1516      MachineBasicBlock *Succ = Succs[i];
1517      // Fallthrough edge can't be transferred.
1518      if (Succ == FallThrough)
1519        continue;
1520      ToBBI.BB->addSuccessor(Succ);
1521    }
1522  }
1523
1524  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1525            std::back_inserter(ToBBI.Predicate));
1526  std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1527
1528  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1529  ToBBI.IsAnalyzed = false;
1530
1531  ++NumDupBBs;
1532}
1533
1534/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1535/// This will leave FromBB as an empty block, so remove all of its
1536/// successor edges except for the fall-through edge.  If AddEdges is true,
1537/// i.e., when FromBBI's branch is being moved, add those successor edges to
1538/// ToBBI.
1539void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1540  ToBBI.BB->splice(ToBBI.BB->end(),
1541                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1542
1543  std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1544                                         FromBBI.BB->succ_end());
1545  MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1546  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1547
1548  for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1549    MachineBasicBlock *Succ = Succs[i];
1550    // Fallthrough edge can't be transferred.
1551    if (Succ == FallThrough)
1552      continue;
1553    FromBBI.BB->removeSuccessor(Succ);
1554    if (AddEdges)
1555      ToBBI.BB->addSuccessor(Succ);
1556  }
1557
1558  // Now FromBBI always falls through to the next block!
1559  if (NBB && !FromBBI.BB->isSuccessor(NBB))
1560    FromBBI.BB->addSuccessor(NBB);
1561
1562  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1563            std::back_inserter(ToBBI.Predicate));
1564  FromBBI.Predicate.clear();
1565
1566  ToBBI.NonPredSize += FromBBI.NonPredSize;
1567  ToBBI.ExtraCost += FromBBI.ExtraCost;
1568  ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1569  FromBBI.NonPredSize = 0;
1570  FromBBI.ExtraCost = 0;
1571  FromBBI.ExtraCost2 = 0;
1572
1573  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1574  ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1575  ToBBI.IsAnalyzed = false;
1576  FromBBI.IsAnalyzed = false;
1577}
1578