LLVM API Documentation

IfConversion.cpp
Go to the documentation of this file.
00001 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the machine instruction level if-conversion pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/Passes.h"
00015 #include "BranchFolding.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/ADT/SmallSet.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/CodeGen/LivePhysRegs.h"
00020 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00021 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineInstrBuilder.h"
00024 #include "llvm/CodeGen/MachineModuleInfo.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/CodeGen/TargetSchedule.h"
00027 #include "llvm/MC/MCInstrItineraries.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/ErrorHandling.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include "llvm/Target/TargetInstrInfo.h"
00033 #include "llvm/Target/TargetLowering.h"
00034 #include "llvm/Target/TargetMachine.h"
00035 #include "llvm/Target/TargetRegisterInfo.h"
00036 #include "llvm/Target/TargetSubtargetInfo.h"
00037 
00038 using namespace llvm;
00039 
00040 #define DEBUG_TYPE "ifcvt"
00041 
00042 // Hidden options for help debugging.
00043 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
00044 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
00045 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
00046 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
00047                                    cl::init(false), cl::Hidden);
00048 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
00049                                     cl::init(false), cl::Hidden);
00050 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
00051                                      cl::init(false), cl::Hidden);
00052 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
00053                                       cl::init(false), cl::Hidden);
00054 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
00055                                       cl::init(false), cl::Hidden);
00056 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
00057                                        cl::init(false), cl::Hidden);
00058 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
00059                                     cl::init(false), cl::Hidden);
00060 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
00061                                      cl::init(true), cl::Hidden);
00062 
00063 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
00064 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
00065 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
00066 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
00067 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
00068 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
00069 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
00070 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
00071 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
00072 STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
00073 
00074 namespace {
00075   class IfConverter : public MachineFunctionPass {
00076     enum IfcvtKind {
00077       ICNotClassfied,  // BB data valid, but not classified.
00078       ICSimpleFalse,   // Same as ICSimple, but on the false path.
00079       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
00080       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
00081       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
00082       ICTriangleFalse, // Same as ICTriangle, but on the false path.
00083       ICTriangle,      // BB is entry of a triangle sub-CFG.
00084       ICDiamond        // BB is entry of a diamond sub-CFG.
00085     };
00086 
00087     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
00088     /// if-conversion feasibility analysis. This includes results from
00089     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
00090     /// classification, and common tail block of its successors (if it's a
00091     /// diamond shape), its size, whether it's predicable, and whether any
00092     /// instruction can clobber the 'would-be' predicate.
00093     ///
00094     /// IsDone          - True if BB is not to be considered for ifcvt.
00095     /// IsBeingAnalyzed - True if BB is currently being analyzed.
00096     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
00097     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
00098     /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
00099     /// HasFallThrough  - True if BB may fallthrough to the following BB.
00100     /// IsUnpredicable  - True if BB is known to be unpredicable.
00101     /// ClobbersPred    - True if BB could modify predicates (e.g. has
00102     ///                   cmp, call, etc.)
00103     /// NonPredSize     - Number of non-predicated instructions.
00104     /// ExtraCost       - Extra cost for multi-cycle instructions.
00105     /// ExtraCost2      - Some instructions are slower when predicated
00106     /// BB              - Corresponding MachineBasicBlock.
00107     /// TrueBB / FalseBB- See AnalyzeBranch().
00108     /// BrCond          - Conditions for end of block conditional branches.
00109     /// Predicate       - Predicate used in the BB.
00110     struct BBInfo {
00111       bool IsDone          : 1;
00112       bool IsBeingAnalyzed : 1;
00113       bool IsAnalyzed      : 1;
00114       bool IsEnqueued      : 1;
00115       bool IsBrAnalyzable  : 1;
00116       bool HasFallThrough  : 1;
00117       bool IsUnpredicable  : 1;
00118       bool CannotBeCopied  : 1;
00119       bool ClobbersPred    : 1;
00120       unsigned NonPredSize;
00121       unsigned ExtraCost;
00122       unsigned ExtraCost2;
00123       MachineBasicBlock *BB;
00124       MachineBasicBlock *TrueBB;
00125       MachineBasicBlock *FalseBB;
00126       SmallVector<MachineOperand, 4> BrCond;
00127       SmallVector<MachineOperand, 4> Predicate;
00128       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
00129                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
00130                  HasFallThrough(false), IsUnpredicable(false),
00131                  CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
00132                  ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
00133                  FalseBB(nullptr) {}
00134     };
00135 
00136     /// IfcvtToken - Record information about pending if-conversions to attempt:
00137     /// BBI             - Corresponding BBInfo.
00138     /// Kind            - Type of block. See IfcvtKind.
00139     /// NeedSubsumption - True if the to-be-predicated BB has already been
00140     ///                   predicated.
00141     /// NumDups      - Number of instructions that would be duplicated due
00142     ///                   to this if-conversion. (For diamonds, the number of
00143     ///                   identical instructions at the beginnings of both
00144     ///                   paths).
00145     /// NumDups2     - For diamonds, the number of identical instructions
00146     ///                   at the ends of both paths.
00147     struct IfcvtToken {
00148       BBInfo &BBI;
00149       IfcvtKind Kind;
00150       bool NeedSubsumption;
00151       unsigned NumDups;
00152       unsigned NumDups2;
00153       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
00154         : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
00155     };
00156 
00157     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
00158     /// basic block number.
00159     std::vector<BBInfo> BBAnalysis;
00160     TargetSchedModel SchedModel;
00161 
00162     const TargetLoweringBase *TLI;
00163     const TargetInstrInfo *TII;
00164     const TargetRegisterInfo *TRI;
00165     const MachineBlockFrequencyInfo *MBFI;
00166     const MachineBranchProbabilityInfo *MBPI;
00167     MachineRegisterInfo *MRI;
00168 
00169     LivePhysRegs Redefs;
00170     LivePhysRegs DontKill;
00171 
00172     bool PreRegAlloc;
00173     bool MadeChange;
00174     int FnNum;
00175   public:
00176     static char ID;
00177     IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
00178       initializeIfConverterPass(*PassRegistry::getPassRegistry());
00179     }
00180 
00181     void getAnalysisUsage(AnalysisUsage &AU) const override {
00182       AU.addRequired<MachineBlockFrequencyInfo>();
00183       AU.addRequired<MachineBranchProbabilityInfo>();
00184       MachineFunctionPass::getAnalysisUsage(AU);
00185     }
00186 
00187     bool runOnMachineFunction(MachineFunction &MF) override;
00188 
00189   private:
00190     bool ReverseBranchCondition(BBInfo &BBI);
00191     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
00192                      const BranchProbability &Prediction) const;
00193     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
00194                        bool FalseBranch, unsigned &Dups,
00195                        const BranchProbability &Prediction) const;
00196     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
00197                       unsigned &Dups1, unsigned &Dups2) const;
00198     void ScanInstructions(BBInfo &BBI);
00199     BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
00200                          std::vector<IfcvtToken*> &Tokens);
00201     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
00202                              bool isTriangle = false, bool RevBranch = false);
00203     void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
00204     void InvalidatePreds(MachineBasicBlock *BB);
00205     void RemoveExtraEdges(BBInfo &BBI);
00206     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
00207     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
00208     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
00209                           unsigned NumDups1, unsigned NumDups2);
00210     void PredicateBlock(BBInfo &BBI,
00211                         MachineBasicBlock::iterator E,
00212                         SmallVectorImpl<MachineOperand> &Cond,
00213                         SmallSet<unsigned, 4> *LaterRedefs = nullptr);
00214     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
00215                                SmallVectorImpl<MachineOperand> &Cond,
00216                                bool IgnoreBr = false);
00217     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
00218 
00219     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
00220                             unsigned Cycle, unsigned Extra,
00221                             const BranchProbability &Prediction) const {
00222       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
00223                                                    Prediction);
00224     }
00225 
00226     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
00227                             unsigned TCycle, unsigned TExtra,
00228                             MachineBasicBlock &FBB,
00229                             unsigned FCycle, unsigned FExtra,
00230                             const BranchProbability &Prediction) const {
00231       return TCycle > 0 && FCycle > 0 &&
00232         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
00233                                  Prediction);
00234     }
00235 
00236     // blockAlwaysFallThrough - Block ends without a terminator.
00237     bool blockAlwaysFallThrough(BBInfo &BBI) const {
00238       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
00239     }
00240 
00241     // IfcvtTokenCmp - Used to sort if-conversion candidates.
00242     static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
00243       int Incr1 = (C1->Kind == ICDiamond)
00244         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
00245       int Incr2 = (C2->Kind == ICDiamond)
00246         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
00247       if (Incr1 > Incr2)
00248         return true;
00249       else if (Incr1 == Incr2) {
00250         // Favors subsumption.
00251         if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
00252           return true;
00253         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
00254           // Favors diamond over triangle, etc.
00255           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
00256             return true;
00257           else if (C1->Kind == C2->Kind)
00258             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
00259         }
00260       }
00261       return false;
00262     }
00263   };
00264 
00265   char IfConverter::ID = 0;
00266 }
00267 
00268 char &llvm::IfConverterID = IfConverter::ID;
00269 
00270 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
00271 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
00272 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
00273 
00274 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
00275   TLI = MF.getSubtarget().getTargetLowering();
00276   TII = MF.getSubtarget().getInstrInfo();
00277   TRI = MF.getSubtarget().getRegisterInfo();
00278   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
00279   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
00280   MRI = &MF.getRegInfo();
00281 
00282   const TargetSubtargetInfo &ST =
00283     MF.getTarget().getSubtarget<TargetSubtargetInfo>();
00284   SchedModel.init(ST.getSchedModel(), &ST, TII);
00285 
00286   if (!TII) return false;
00287 
00288   PreRegAlloc = MRI->isSSA();
00289 
00290   bool BFChange = false;
00291   if (!PreRegAlloc) {
00292     // Tail merge tend to expose more if-conversion opportunities.
00293     BranchFolder BF(true, false, *MBFI, *MBPI);
00294     BFChange = BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
00295                                    getAnalysisIfAvailable<MachineModuleInfo>());
00296   }
00297 
00298   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
00299                << MF.getName() << "\'");
00300 
00301   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
00302     DEBUG(dbgs() << " skipped\n");
00303     return false;
00304   }
00305   DEBUG(dbgs() << "\n");
00306 
00307   MF.RenumberBlocks();
00308   BBAnalysis.resize(MF.getNumBlockIDs());
00309 
00310   std::vector<IfcvtToken*> Tokens;
00311   MadeChange = false;
00312   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
00313     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
00314   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
00315     // Do an initial analysis for each basic block and find all the potential
00316     // candidates to perform if-conversion.
00317     bool Change = false;
00318     AnalyzeBlocks(MF, Tokens);
00319     while (!Tokens.empty()) {
00320       IfcvtToken *Token = Tokens.back();
00321       Tokens.pop_back();
00322       BBInfo &BBI = Token->BBI;
00323       IfcvtKind Kind = Token->Kind;
00324       unsigned NumDups = Token->NumDups;
00325       unsigned NumDups2 = Token->NumDups2;
00326 
00327       delete Token;
00328 
00329       // If the block has been evicted out of the queue or it has already been
00330       // marked dead (due to it being predicated), then skip it.
00331       if (BBI.IsDone)
00332         BBI.IsEnqueued = false;
00333       if (!BBI.IsEnqueued)
00334         continue;
00335 
00336       BBI.IsEnqueued = false;
00337 
00338       bool RetVal = false;
00339       switch (Kind) {
00340       default: llvm_unreachable("Unexpected!");
00341       case ICSimple:
00342       case ICSimpleFalse: {
00343         bool isFalse = Kind == ICSimpleFalse;
00344         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
00345         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
00346                                             " false" : "")
00347                      << "): BB#" << BBI.BB->getNumber() << " ("
00348                      << ((Kind == ICSimpleFalse)
00349                          ? BBI.FalseBB->getNumber()
00350                          : BBI.TrueBB->getNumber()) << ") ");
00351         RetVal = IfConvertSimple(BBI, Kind);
00352         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
00353         if (RetVal) {
00354           if (isFalse) ++NumSimpleFalse;
00355           else         ++NumSimple;
00356         }
00357        break;
00358       }
00359       case ICTriangle:
00360       case ICTriangleRev:
00361       case ICTriangleFalse:
00362       case ICTriangleFRev: {
00363         bool isFalse = Kind == ICTriangleFalse;
00364         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
00365         if (DisableTriangle && !isFalse && !isRev) break;
00366         if (DisableTriangleR && !isFalse && isRev) break;
00367         if (DisableTriangleF && isFalse && !isRev) break;
00368         if (DisableTriangleFR && isFalse && isRev) break;
00369         DEBUG(dbgs() << "Ifcvt (Triangle");
00370         if (isFalse)
00371           DEBUG(dbgs() << " false");
00372         if (isRev)
00373           DEBUG(dbgs() << " rev");
00374         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
00375                      << BBI.TrueBB->getNumber() << ",F:"
00376                      << BBI.FalseBB->getNumber() << ") ");
00377         RetVal = IfConvertTriangle(BBI, Kind);
00378         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
00379         if (RetVal) {
00380           if (isFalse) {
00381             if (isRev) ++NumTriangleFRev;
00382             else       ++NumTriangleFalse;
00383           } else {
00384             if (isRev) ++NumTriangleRev;
00385             else       ++NumTriangle;
00386           }
00387         }
00388         break;
00389       }
00390       case ICDiamond: {
00391         if (DisableDiamond) break;
00392         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
00393                      << BBI.TrueBB->getNumber() << ",F:"
00394                      << BBI.FalseBB->getNumber() << ") ");
00395         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
00396         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
00397         if (RetVal) ++NumDiamonds;
00398         break;
00399       }
00400       }
00401 
00402       Change |= RetVal;
00403 
00404       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
00405         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
00406       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
00407         break;
00408     }
00409 
00410     if (!Change)
00411       break;
00412     MadeChange |= Change;
00413   }
00414 
00415   // Delete tokens in case of early exit.
00416   while (!Tokens.empty()) {
00417     IfcvtToken *Token = Tokens.back();
00418     Tokens.pop_back();
00419     delete Token;
00420   }
00421 
00422   Tokens.clear();
00423   BBAnalysis.clear();
00424 
00425   if (MadeChange && IfCvtBranchFold) {
00426     BranchFolder BF(false, false, *MBFI, *MBPI);
00427     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
00428                         getAnalysisIfAvailable<MachineModuleInfo>());
00429   }
00430 
00431   MadeChange |= BFChange;
00432   return MadeChange;
00433 }
00434 
00435 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
00436 /// its 'true' successor.
00437 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
00438                                          MachineBasicBlock *TrueBB) {
00439   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00440          E = BB->succ_end(); SI != E; ++SI) {
00441     MachineBasicBlock *SuccBB = *SI;
00442     if (SuccBB != TrueBB)
00443       return SuccBB;
00444   }
00445   return nullptr;
00446 }
00447 
00448 /// ReverseBranchCondition - Reverse the condition of the end of the block
00449 /// branch. Swap block's 'true' and 'false' successors.
00450 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
00451   DebugLoc dl;  // FIXME: this is nowhere
00452   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
00453     TII->RemoveBranch(*BBI.BB);
00454     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
00455     std::swap(BBI.TrueBB, BBI.FalseBB);
00456     return true;
00457   }
00458   return false;
00459 }
00460 
00461 /// getNextBlock - Returns the next block in the function blocks ordering. If
00462 /// it is the end, returns NULL.
00463 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
00464   MachineFunction::iterator I = BB;
00465   MachineFunction::iterator E = BB->getParent()->end();
00466   if (++I == E)
00467     return nullptr;
00468   return I;
00469 }
00470 
00471 /// ValidSimple - Returns true if the 'true' block (along with its
00472 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
00473 /// number of instructions that the ifcvt would need to duplicate if performed
00474 /// in Dups.
00475 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
00476                               const BranchProbability &Prediction) const {
00477   Dups = 0;
00478   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
00479     return false;
00480 
00481   if (TrueBBI.IsBrAnalyzable)
00482     return false;
00483 
00484   if (TrueBBI.BB->pred_size() > 1) {
00485     if (TrueBBI.CannotBeCopied ||
00486         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
00487                                         Prediction))
00488       return false;
00489     Dups = TrueBBI.NonPredSize;
00490   }
00491 
00492   return true;
00493 }
00494 
00495 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
00496 /// with their common predecessor) forms a valid triangle shape for ifcvt.
00497 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
00498 /// branches to the 'false' block rather than the other way around. It also
00499 /// returns the number of instructions that the ifcvt would need to duplicate
00500 /// if performed in 'Dups'.
00501 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
00502                                 bool FalseBranch, unsigned &Dups,
00503                                 const BranchProbability &Prediction) const {
00504   Dups = 0;
00505   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
00506     return false;
00507 
00508   if (TrueBBI.BB->pred_size() > 1) {
00509     if (TrueBBI.CannotBeCopied)
00510       return false;
00511 
00512     unsigned Size = TrueBBI.NonPredSize;
00513     if (TrueBBI.IsBrAnalyzable) {
00514       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
00515         // Ends with an unconditional branch. It will be removed.
00516         --Size;
00517       else {
00518         MachineBasicBlock *FExit = FalseBranch
00519           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
00520         if (FExit)
00521           // Require a conditional branch
00522           ++Size;
00523       }
00524     }
00525     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
00526       return false;
00527     Dups = Size;
00528   }
00529 
00530   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
00531   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
00532     MachineFunction::iterator I = TrueBBI.BB;
00533     if (++I == TrueBBI.BB->getParent()->end())
00534       return false;
00535     TExit = I;
00536   }
00537   return TExit && TExit == FalseBBI.BB;
00538 }
00539 
00540 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
00541 /// with their common predecessor) forms a valid diamond shape for ifcvt.
00542 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
00543                                unsigned &Dups1, unsigned &Dups2) const {
00544   Dups1 = Dups2 = 0;
00545   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
00546       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
00547     return false;
00548 
00549   MachineBasicBlock *TT = TrueBBI.TrueBB;
00550   MachineBasicBlock *FT = FalseBBI.TrueBB;
00551 
00552   if (!TT && blockAlwaysFallThrough(TrueBBI))
00553     TT = getNextBlock(TrueBBI.BB);
00554   if (!FT && blockAlwaysFallThrough(FalseBBI))
00555     FT = getNextBlock(FalseBBI.BB);
00556   if (TT != FT)
00557     return false;
00558   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
00559     return false;
00560   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
00561     return false;
00562 
00563   // FIXME: Allow true block to have an early exit?
00564   if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
00565       (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
00566     return false;
00567 
00568   // Count duplicate instructions at the beginning of the true and false blocks.
00569   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
00570   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
00571   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
00572   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
00573   while (TIB != TIE && FIB != FIE) {
00574     // Skip dbg_value instructions. These do not count.
00575     if (TIB->isDebugValue()) {
00576       while (TIB != TIE && TIB->isDebugValue())
00577         ++TIB;
00578       if (TIB == TIE)
00579         break;
00580     }
00581     if (FIB->isDebugValue()) {
00582       while (FIB != FIE && FIB->isDebugValue())
00583         ++FIB;
00584       if (FIB == FIE)
00585         break;
00586     }
00587     if (!TIB->isIdenticalTo(FIB))
00588       break;
00589     ++Dups1;
00590     ++TIB;
00591     ++FIB;
00592   }
00593 
00594   // Now, in preparation for counting duplicate instructions at the ends of the
00595   // blocks, move the end iterators up past any branch instructions.
00596   while (TIE != TIB) {
00597     --TIE;
00598     if (!TIE->isBranch())
00599       break;
00600   }
00601   while (FIE != FIB) {
00602     --FIE;
00603     if (!FIE->isBranch())
00604       break;
00605   }
00606 
00607   // If Dups1 includes all of a block, then don't count duplicate
00608   // instructions at the end of the blocks.
00609   if (TIB == TIE || FIB == FIE)
00610     return true;
00611 
00612   // Count duplicate instructions at the ends of the blocks.
00613   while (TIE != TIB && FIE != FIB) {
00614     // Skip dbg_value instructions. These do not count.
00615     if (TIE->isDebugValue()) {
00616       while (TIE != TIB && TIE->isDebugValue())
00617         --TIE;
00618       if (TIE == TIB)
00619         break;
00620     }
00621     if (FIE->isDebugValue()) {
00622       while (FIE != FIB && FIE->isDebugValue())
00623         --FIE;
00624       if (FIE == FIB)
00625         break;
00626     }
00627     if (!TIE->isIdenticalTo(FIE))
00628       break;
00629     ++Dups2;
00630     --TIE;
00631     --FIE;
00632   }
00633 
00634   return true;
00635 }
00636 
00637 /// ScanInstructions - Scan all the instructions in the block to determine if
00638 /// the block is predicable. In most cases, that means all the instructions
00639 /// in the block are isPredicable(). Also checks if the block contains any
00640 /// instruction which can clobber a predicate (e.g. condition code register).
00641 /// If so, the block is not predicable unless it's the last instruction.
00642 void IfConverter::ScanInstructions(BBInfo &BBI) {
00643   if (BBI.IsDone)
00644     return;
00645 
00646   bool AlreadyPredicated = !BBI.Predicate.empty();
00647   // First analyze the end of BB branches.
00648   BBI.TrueBB = BBI.FalseBB = nullptr;
00649   BBI.BrCond.clear();
00650   BBI.IsBrAnalyzable =
00651     !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
00652   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
00653 
00654   if (BBI.BrCond.size()) {
00655     // No false branch. This BB must end with a conditional branch and a
00656     // fallthrough.
00657     if (!BBI.FalseBB)
00658       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
00659     if (!BBI.FalseBB) {
00660       // Malformed bcc? True and false blocks are the same?
00661       BBI.IsUnpredicable = true;
00662       return;
00663     }
00664   }
00665 
00666   // Then scan all the instructions.
00667   BBI.NonPredSize = 0;
00668   BBI.ExtraCost = 0;
00669   BBI.ExtraCost2 = 0;
00670   BBI.ClobbersPred = false;
00671   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
00672        I != E; ++I) {
00673     if (I->isDebugValue())
00674       continue;
00675 
00676     if (I->isNotDuplicable())
00677       BBI.CannotBeCopied = true;
00678 
00679     bool isPredicated = TII->isPredicated(I);
00680     bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
00681 
00682     // A conditional branch is not predicable, but it may be eliminated.
00683     if (isCondBr)
00684       continue;
00685 
00686     if (!isPredicated) {
00687       BBI.NonPredSize++;
00688       unsigned ExtraPredCost = TII->getPredicationCost(&*I);
00689       unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
00690       if (NumCycles > 1)
00691         BBI.ExtraCost += NumCycles-1;
00692       BBI.ExtraCost2 += ExtraPredCost;
00693     } else if (!AlreadyPredicated) {
00694       // FIXME: This instruction is already predicated before the
00695       // if-conversion pass. It's probably something like a conditional move.
00696       // Mark this block unpredicable for now.
00697       BBI.IsUnpredicable = true;
00698       return;
00699     }
00700 
00701     if (BBI.ClobbersPred && !isPredicated) {
00702       // Predicate modification instruction should end the block (except for
00703       // already predicated instructions and end of block branches).
00704       // Predicate may have been modified, the subsequent (currently)
00705       // unpredicated instructions cannot be correctly predicated.
00706       BBI.IsUnpredicable = true;
00707       return;
00708     }
00709 
00710     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
00711     // still potentially predicable.
00712     std::vector<MachineOperand> PredDefs;
00713     if (TII->DefinesPredicate(I, PredDefs))
00714       BBI.ClobbersPred = true;
00715 
00716     if (!TII->isPredicable(I)) {
00717       BBI.IsUnpredicable = true;
00718       return;
00719     }
00720   }
00721 }
00722 
00723 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
00724 /// predicated by the specified predicate.
00725 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
00726                                       SmallVectorImpl<MachineOperand> &Pred,
00727                                       bool isTriangle, bool RevBranch) {
00728   // If the block is dead or unpredicable, then it cannot be predicated.
00729   if (BBI.IsDone || BBI.IsUnpredicable)
00730     return false;
00731 
00732   // If it is already predicated, check if the new predicate subsumes
00733   // its predicate.
00734   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
00735     return false;
00736 
00737   if (BBI.BrCond.size()) {
00738     if (!isTriangle)
00739       return false;
00740 
00741     // Test predicate subsumption.
00742     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
00743     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
00744     if (RevBranch) {
00745       if (TII->ReverseBranchCondition(Cond))
00746         return false;
00747     }
00748     if (TII->ReverseBranchCondition(RevPred) ||
00749         !TII->SubsumesPredicate(Cond, RevPred))
00750       return false;
00751   }
00752 
00753   return true;
00754 }
00755 
00756 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
00757 /// the specified block. Record its successors and whether it looks like an
00758 /// if-conversion candidate.
00759 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
00760                                              std::vector<IfcvtToken*> &Tokens) {
00761   BBInfo &BBI = BBAnalysis[BB->getNumber()];
00762 
00763   if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
00764     return BBI;
00765 
00766   BBI.BB = BB;
00767   BBI.IsBeingAnalyzed = true;
00768 
00769   ScanInstructions(BBI);
00770 
00771   // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
00772   // considered for ifcvt anymore.
00773   if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
00774     BBI.IsBeingAnalyzed = false;
00775     BBI.IsAnalyzed = true;
00776     return BBI;
00777   }
00778 
00779   // Do not ifcvt if either path is a back edge to the entry block.
00780   if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
00781     BBI.IsBeingAnalyzed = false;
00782     BBI.IsAnalyzed = true;
00783     return BBI;
00784   }
00785 
00786   // Do not ifcvt if true and false fallthrough blocks are the same.
00787   if (!BBI.FalseBB) {
00788     BBI.IsBeingAnalyzed = false;
00789     BBI.IsAnalyzed = true;
00790     return BBI;
00791   }
00792 
00793   BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
00794   BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
00795 
00796   if (TrueBBI.IsDone && FalseBBI.IsDone) {
00797     BBI.IsBeingAnalyzed = false;
00798     BBI.IsAnalyzed = true;
00799     return BBI;
00800   }
00801 
00802   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
00803   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
00804 
00805   unsigned Dups = 0;
00806   unsigned Dups2 = 0;
00807   bool TNeedSub = !TrueBBI.Predicate.empty();
00808   bool FNeedSub = !FalseBBI.Predicate.empty();
00809   bool Enqueued = false;
00810 
00811   BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
00812 
00813   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
00814       MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
00815                                        TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
00816                          *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
00817                                         FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
00818                          Prediction) &&
00819       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
00820       FeasibilityAnalysis(FalseBBI, RevCond)) {
00821     // Diamond:
00822     //   EBB
00823     //   / \_
00824     //  |   |
00825     // TBB FBB
00826     //   \ /
00827     //  TailBB
00828     // Note TailBB can be empty.
00829     Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
00830                                     Dups2));
00831     Enqueued = true;
00832   }
00833 
00834   if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
00835       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
00836                          TrueBBI.ExtraCost2, Prediction) &&
00837       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
00838     // Triangle:
00839     //   EBB
00840     //   | \_
00841     //   |  |
00842     //   | TBB
00843     //   |  /
00844     //   FBB
00845     Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
00846     Enqueued = true;
00847   }
00848 
00849   if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
00850       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
00851                          TrueBBI.ExtraCost2, Prediction) &&
00852       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
00853     Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
00854     Enqueued = true;
00855   }
00856 
00857   if (ValidSimple(TrueBBI, Dups, Prediction) &&
00858       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
00859                          TrueBBI.ExtraCost2, Prediction) &&
00860       FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
00861     // Simple (split, no rejoin):
00862     //   EBB
00863     //   | \_
00864     //   |  |
00865     //   | TBB---> exit
00866     //   |
00867     //   FBB
00868     Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
00869     Enqueued = true;
00870   }
00871 
00872   if (CanRevCond) {
00873     // Try the other path...
00874     if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
00875                       Prediction.getCompl()) &&
00876         MeetIfcvtSizeLimit(*FalseBBI.BB,
00877                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
00878                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
00879         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
00880       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
00881       Enqueued = true;
00882     }
00883 
00884     if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
00885                       Prediction.getCompl()) &&
00886         MeetIfcvtSizeLimit(*FalseBBI.BB,
00887                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
00888                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
00889         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
00890       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
00891       Enqueued = true;
00892     }
00893 
00894     if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
00895         MeetIfcvtSizeLimit(*FalseBBI.BB,
00896                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
00897                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
00898         FeasibilityAnalysis(FalseBBI, RevCond)) {
00899       Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
00900       Enqueued = true;
00901     }
00902   }
00903 
00904   BBI.IsEnqueued = Enqueued;
00905   BBI.IsBeingAnalyzed = false;
00906   BBI.IsAnalyzed = true;
00907   return BBI;
00908 }
00909 
00910 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
00911 /// candidates.
00912 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
00913                                 std::vector<IfcvtToken*> &Tokens) {
00914   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
00915     MachineBasicBlock *BB = I;
00916     AnalyzeBlock(BB, Tokens);
00917   }
00918 
00919   // Sort to favor more complex ifcvt scheme.
00920   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
00921 }
00922 
00923 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
00924 /// that all the intervening blocks are empty (given BB can fall through to its
00925 /// next block).
00926 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
00927   MachineFunction::iterator PI = BB;
00928   MachineFunction::iterator I = std::next(PI);
00929   MachineFunction::iterator TI = ToBB;
00930   MachineFunction::iterator E = BB->getParent()->end();
00931   while (I != TI) {
00932     // Check isSuccessor to avoid case where the next block is empty, but
00933     // it's not a successor.
00934     if (I == E || !I->empty() || !PI->isSuccessor(I))
00935       return false;
00936     PI = I++;
00937   }
00938   return true;
00939 }
00940 
00941 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
00942 /// to determine if it can be if-converted. If predecessor is already enqueued,
00943 /// dequeue it!
00944 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
00945   for (const auto &Predecessor : BB->predecessors()) {
00946     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
00947     if (PBBI.IsDone || PBBI.BB == BB)
00948       continue;
00949     PBBI.IsAnalyzed = false;
00950     PBBI.IsEnqueued = false;
00951   }
00952 }
00953 
00954 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
00955 ///
00956 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
00957                                const TargetInstrInfo *TII) {
00958   DebugLoc dl;  // FIXME: this is nowhere
00959   SmallVector<MachineOperand, 0> NoCond;
00960   TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
00961 }
00962 
00963 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
00964 /// successors.
00965 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
00966   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00967   SmallVector<MachineOperand, 4> Cond;
00968   if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
00969     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
00970 }
00971 
00972 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
00973 /// values defined in MI which are not live/used by MI.
00974 static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
00975   for (ConstMIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
00976     if (!Ops->isReg() || !Ops->isKill())
00977       continue;
00978     unsigned Reg = Ops->getReg();
00979     if (Reg == 0)
00980       continue;
00981     Redefs.removeReg(Reg);
00982   }
00983   for (MIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
00984     if (!Ops->isReg() || !Ops->isDef())
00985       continue;
00986     unsigned Reg = Ops->getReg();
00987     if (Reg == 0 || Redefs.contains(Reg))
00988       continue;
00989     Redefs.addReg(Reg);
00990 
00991     MachineOperand &Op = *Ops;
00992     MachineInstr *MI = Op.getParent();
00993     MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
00994     MIB.addReg(Reg, RegState::Implicit | RegState::Undef);
00995   }
00996 }
00997 
00998 /**
00999  * Remove kill flags from operands with a registers in the @p DontKill set.
01000  */
01001 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
01002   for (MIBundleOperands O(&MI); O.isValid(); ++O) {
01003     if (!O->isReg() || !O->isKill())
01004       continue;
01005     if (DontKill.contains(O->getReg()))
01006       O->setIsKill(false);
01007   }
01008 }
01009 
01010 /**
01011  * Walks a range of machine instructions and removes kill flags for registers
01012  * in the @p DontKill set.
01013  */
01014 static void RemoveKills(MachineBasicBlock::iterator I,
01015                         MachineBasicBlock::iterator E,
01016                         const LivePhysRegs &DontKill,
01017                         const MCRegisterInfo &MCRI) {
01018   for ( ; I != E; ++I)
01019     RemoveKills(*I, DontKill);
01020 }
01021 
01022 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
01023 ///
01024 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
01025   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
01026   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
01027   BBInfo *CvtBBI = &TrueBBI;
01028   BBInfo *NextBBI = &FalseBBI;
01029 
01030   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
01031   if (Kind == ICSimpleFalse)
01032     std::swap(CvtBBI, NextBBI);
01033 
01034   if (CvtBBI->IsDone ||
01035       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
01036     // Something has changed. It's no longer safe to predicate this block.
01037     BBI.IsAnalyzed = false;
01038     CvtBBI->IsAnalyzed = false;
01039     return false;
01040   }
01041 
01042   if (CvtBBI->BB->hasAddressTaken())
01043     // Conservatively abort if-conversion if BB's address is taken.
01044     return false;
01045 
01046   if (Kind == ICSimpleFalse)
01047     if (TII->ReverseBranchCondition(Cond))
01048       llvm_unreachable("Unable to reverse branch condition!");
01049 
01050   // Initialize liveins to the first BB. These are potentiall redefined by
01051   // predicated instructions.
01052   Redefs.init(TRI);
01053   Redefs.addLiveIns(CvtBBI->BB);
01054   Redefs.addLiveIns(NextBBI->BB);
01055 
01056   // Compute a set of registers which must not be killed by instructions in
01057   // BB1: This is everything live-in to BB2.
01058   DontKill.init(TRI);
01059   DontKill.addLiveIns(NextBBI->BB);
01060 
01061   if (CvtBBI->BB->pred_size() > 1) {
01062     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
01063     // Copy instructions in the true block, predicate them, and add them to
01064     // the entry block.
01065     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
01066 
01067     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
01068     // explicitly remove CvtBBI as a successor.
01069     BBI.BB->removeSuccessor(CvtBBI->BB);
01070   } else {
01071     RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
01072     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
01073 
01074     // Merge converted block into entry block.
01075     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
01076     MergeBlocks(BBI, *CvtBBI);
01077   }
01078 
01079   bool IterIfcvt = true;
01080   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
01081     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
01082     BBI.HasFallThrough = false;
01083     // Now ifcvt'd block will look like this:
01084     // BB:
01085     // ...
01086     // t, f = cmp
01087     // if t op
01088     // b BBf
01089     //
01090     // We cannot further ifcvt this block because the unconditional branch
01091     // will have to be predicated on the new condition, that will not be
01092     // available if cmp executes.
01093     IterIfcvt = false;
01094   }
01095 
01096   RemoveExtraEdges(BBI);
01097 
01098   // Update block info. BB can be iteratively if-converted.
01099   if (!IterIfcvt)
01100     BBI.IsDone = true;
01101   InvalidatePreds(BBI.BB);
01102   CvtBBI->IsDone = true;
01103 
01104   // FIXME: Must maintain LiveIns.
01105   return true;
01106 }
01107 
01108 /// Scale down weights to fit into uint32_t. NewTrue is the new weight
01109 /// for successor TrueBB, and NewFalse is the new weight for successor
01110 /// FalseBB.
01111 static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
01112                          MachineBasicBlock *MBB,
01113                          const MachineBasicBlock *TrueBB,
01114                          const MachineBasicBlock *FalseBB,
01115                          const MachineBranchProbabilityInfo *MBPI) {
01116   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
01117   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
01118   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
01119                                         SE = MBB->succ_end();
01120        SI != SE; ++SI) {
01121     if (*SI == TrueBB)
01122       MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
01123     else if (*SI == FalseBB)
01124       MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
01125     else
01126       MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
01127   }
01128 }
01129 
01130 /// IfConvertTriangle - If convert a triangle sub-CFG.
01131 ///
01132 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
01133   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
01134   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
01135   BBInfo *CvtBBI = &TrueBBI;
01136   BBInfo *NextBBI = &FalseBBI;
01137   DebugLoc dl;  // FIXME: this is nowhere
01138 
01139   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
01140   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
01141     std::swap(CvtBBI, NextBBI);
01142 
01143   if (CvtBBI->IsDone ||
01144       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
01145     // Something has changed. It's no longer safe to predicate this block.
01146     BBI.IsAnalyzed = false;
01147     CvtBBI->IsAnalyzed = false;
01148     return false;
01149   }
01150 
01151   if (CvtBBI->BB->hasAddressTaken())
01152     // Conservatively abort if-conversion if BB's address is taken.
01153     return false;
01154 
01155   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
01156     if (TII->ReverseBranchCondition(Cond))
01157       llvm_unreachable("Unable to reverse branch condition!");
01158 
01159   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
01160     if (ReverseBranchCondition(*CvtBBI)) {
01161       // BB has been changed, modify its predecessors (except for this
01162       // one) so they don't get ifcvt'ed based on bad intel.
01163       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
01164              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
01165         MachineBasicBlock *PBB = *PI;
01166         if (PBB == BBI.BB)
01167           continue;
01168         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
01169         if (PBBI.IsEnqueued) {
01170           PBBI.IsAnalyzed = false;
01171           PBBI.IsEnqueued = false;
01172         }
01173       }
01174     }
01175   }
01176 
01177   // Initialize liveins to the first BB. These are potentially redefined by
01178   // predicated instructions.
01179   Redefs.init(TRI);
01180   Redefs.addLiveIns(CvtBBI->BB);
01181   Redefs.addLiveIns(NextBBI->BB);
01182 
01183   DontKill.clear();
01184 
01185   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
01186   uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
01187   uint32_t WeightScale = 0;
01188 
01189   if (HasEarlyExit) {
01190     // Get weights before modifying CvtBBI->BB and BBI.BB.
01191     CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
01192     CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
01193     BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
01194     BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
01195     SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
01196   }
01197 
01198   if (CvtBBI->BB->pred_size() > 1) {
01199     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
01200     // Copy instructions in the true block, predicate them, and add them to
01201     // the entry block.
01202     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
01203 
01204     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
01205     // explicitly remove CvtBBI as a successor.
01206     BBI.BB->removeSuccessor(CvtBBI->BB);
01207   } else {
01208     // Predicate the 'true' block after removing its branch.
01209     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
01210     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
01211 
01212     // Now merge the entry of the triangle with the true block.
01213     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
01214     MergeBlocks(BBI, *CvtBBI, false);
01215   }
01216 
01217   // If 'true' block has a 'false' successor, add an exit branch to it.
01218   if (HasEarlyExit) {
01219     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
01220                                            CvtBBI->BrCond.end());
01221     if (TII->ReverseBranchCondition(RevCond))
01222       llvm_unreachable("Unable to reverse branch condition!");
01223     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
01224     BBI.BB->addSuccessor(CvtBBI->FalseBB);
01225     // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
01226     // New_Weight(BBI.BB, NextBBI->BB) =
01227     //   Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
01228     //   Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
01229     // New_Weight(BBI.BB, CvtBBI->FalseBB) =
01230     //   Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
01231 
01232     uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
01233     uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
01234     // We need to scale down all weights of BBI.BB to fit uint32_t.
01235     // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
01236     // the next block.
01237     ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
01238                  CvtBBI->FalseBB, MBPI);
01239   }
01240 
01241   // Merge in the 'false' block if the 'false' block has no other
01242   // predecessors. Otherwise, add an unconditional branch to 'false'.
01243   bool FalseBBDead = false;
01244   bool IterIfcvt = true;
01245   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
01246   if (!isFallThrough) {
01247     // Only merge them if the true block does not fallthrough to the false
01248     // block. By not merging them, we make it possible to iteratively
01249     // ifcvt the blocks.
01250     if (!HasEarlyExit &&
01251         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
01252         !NextBBI->BB->hasAddressTaken()) {
01253       MergeBlocks(BBI, *NextBBI);
01254       FalseBBDead = true;
01255     } else {
01256       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
01257       BBI.HasFallThrough = false;
01258     }
01259     // Mixed predicated and unpredicated code. This cannot be iteratively
01260     // predicated.
01261     IterIfcvt = false;
01262   }
01263 
01264   RemoveExtraEdges(BBI);
01265 
01266   // Update block info. BB can be iteratively if-converted.
01267   if (!IterIfcvt)
01268     BBI.IsDone = true;
01269   InvalidatePreds(BBI.BB);
01270   CvtBBI->IsDone = true;
01271   if (FalseBBDead)
01272     NextBBI->IsDone = true;
01273 
01274   // FIXME: Must maintain LiveIns.
01275   return true;
01276 }
01277 
01278 /// IfConvertDiamond - If convert a diamond sub-CFG.
01279 ///
01280 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
01281                                    unsigned NumDups1, unsigned NumDups2) {
01282   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
01283   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
01284   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
01285   // True block must fall through or end with an unanalyzable terminator.
01286   if (!TailBB) {
01287     if (blockAlwaysFallThrough(TrueBBI))
01288       TailBB = FalseBBI.TrueBB;
01289     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
01290   }
01291 
01292   if (TrueBBI.IsDone || FalseBBI.IsDone ||
01293       TrueBBI.BB->pred_size() > 1 ||
01294       FalseBBI.BB->pred_size() > 1) {
01295     // Something has changed. It's no longer safe to predicate these blocks.
01296     BBI.IsAnalyzed = false;
01297     TrueBBI.IsAnalyzed = false;
01298     FalseBBI.IsAnalyzed = false;
01299     return false;
01300   }
01301 
01302   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
01303     // Conservatively abort if-conversion if either BB has its address taken.
01304     return false;
01305 
01306   // Put the predicated instructions from the 'true' block before the
01307   // instructions from the 'false' block, unless the true block would clobber
01308   // the predicate, in which case, do the opposite.
01309   BBInfo *BBI1 = &TrueBBI;
01310   BBInfo *BBI2 = &FalseBBI;
01311   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
01312   if (TII->ReverseBranchCondition(RevCond))
01313     llvm_unreachable("Unable to reverse branch condition!");
01314   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
01315   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
01316 
01317   // Figure out the more profitable ordering.
01318   bool DoSwap = false;
01319   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
01320     DoSwap = true;
01321   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
01322     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
01323       DoSwap = true;
01324   }
01325   if (DoSwap) {
01326     std::swap(BBI1, BBI2);
01327     std::swap(Cond1, Cond2);
01328   }
01329 
01330   // Remove the conditional branch from entry to the blocks.
01331   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
01332 
01333   // Initialize liveins to the first BB. These are potentially redefined by
01334   // predicated instructions.
01335   Redefs.init(TRI);
01336   Redefs.addLiveIns(BBI1->BB);
01337 
01338   // Remove the duplicated instructions at the beginnings of both paths.
01339   MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
01340   MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
01341   MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
01342   MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
01343   // Skip dbg_value instructions
01344   while (DI1 != DIE1 && DI1->isDebugValue())
01345     ++DI1;
01346   while (DI2 != DIE2 && DI2->isDebugValue())
01347     ++DI2;
01348   BBI1->NonPredSize -= NumDups1;
01349   BBI2->NonPredSize -= NumDups1;
01350 
01351   // Skip past the dups on each side separately since there may be
01352   // differing dbg_value entries.
01353   for (unsigned i = 0; i < NumDups1; ++DI1) {
01354     if (!DI1->isDebugValue())
01355       ++i;
01356   }
01357   while (NumDups1 != 0) {
01358     ++DI2;
01359     if (!DI2->isDebugValue())
01360       --NumDups1;
01361   }
01362 
01363   // Compute a set of registers which must not be killed by instructions in BB1:
01364   // This is everything used+live in BB2 after the duplicated instructions. We
01365   // can compute this set by simulating liveness backwards from the end of BB2.
01366   DontKill.init(TRI);
01367   for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
01368        E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
01369     DontKill.stepBackward(*I);
01370   }
01371 
01372   for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
01373        ++I) {
01374     Redefs.stepForward(*I);
01375   }
01376   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
01377   BBI2->BB->erase(BBI2->BB->begin(), DI2);
01378 
01379   // Remove branch from 'true' block and remove duplicated instructions.
01380   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
01381   DI1 = BBI1->BB->end();
01382   for (unsigned i = 0; i != NumDups2; ) {
01383     // NumDups2 only counted non-dbg_value instructions, so this won't
01384     // run off the head of the list.
01385     assert (DI1 != BBI1->BB->begin());
01386     --DI1;
01387     // skip dbg_value instructions
01388     if (!DI1->isDebugValue())
01389       ++i;
01390   }
01391   BBI1->BB->erase(DI1, BBI1->BB->end());
01392 
01393   // Kill flags in the true block for registers living into the false block
01394   // must be removed.
01395   RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
01396 
01397   // Remove 'false' block branch and find the last instruction to predicate.
01398   BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
01399   DI2 = BBI2->BB->end();
01400   while (NumDups2 != 0) {
01401     // NumDups2 only counted non-dbg_value instructions, so this won't
01402     // run off the head of the list.
01403     assert (DI2 != BBI2->BB->begin());
01404     --DI2;
01405     // skip dbg_value instructions
01406     if (!DI2->isDebugValue())
01407       --NumDups2;
01408   }
01409 
01410   // Remember which registers would later be defined by the false block.
01411   // This allows us not to predicate instructions in the true block that would
01412   // later be re-defined. That is, rather than
01413   //   subeq  r0, r1, #1
01414   //   addne  r0, r1, #1
01415   // generate:
01416   //   sub    r0, r1, #1
01417   //   addne  r0, r1, #1
01418   SmallSet<unsigned, 4> RedefsByFalse;
01419   SmallSet<unsigned, 4> ExtUses;
01420   if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
01421     for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
01422       if (FI->isDebugValue())
01423         continue;
01424       SmallVector<unsigned, 4> Defs;
01425       for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
01426         const MachineOperand &MO = FI->getOperand(i);
01427         if (!MO.isReg())
01428           continue;
01429         unsigned Reg = MO.getReg();
01430         if (!Reg)
01431           continue;
01432         if (MO.isDef()) {
01433           Defs.push_back(Reg);
01434         } else if (!RedefsByFalse.count(Reg)) {
01435           // These are defined before ctrl flow reach the 'false' instructions.
01436           // They cannot be modified by the 'true' instructions.
01437           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01438                SubRegs.isValid(); ++SubRegs)
01439             ExtUses.insert(*SubRegs);
01440         }
01441       }
01442 
01443       for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
01444         unsigned Reg = Defs[i];
01445         if (!ExtUses.count(Reg)) {
01446           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01447                SubRegs.isValid(); ++SubRegs)
01448             RedefsByFalse.insert(*SubRegs);
01449         }
01450       }
01451     }
01452   }
01453 
01454   // Predicate the 'true' block.
01455   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
01456 
01457   // Predicate the 'false' block.
01458   PredicateBlock(*BBI2, DI2, *Cond2);
01459 
01460   // Merge the true block into the entry of the diamond.
01461   MergeBlocks(BBI, *BBI1, TailBB == nullptr);
01462   MergeBlocks(BBI, *BBI2, TailBB == nullptr);
01463 
01464   // If the if-converted block falls through or unconditionally branches into
01465   // the tail block, and the tail block does not have other predecessors, then
01466   // fold the tail block in as well. Otherwise, unless it falls through to the
01467   // tail, add a unconditional branch to it.
01468   if (TailBB) {
01469     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
01470     bool CanMergeTail = !TailBBI.HasFallThrough &&
01471       !TailBBI.BB->hasAddressTaken();
01472     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
01473     // check if there are any other predecessors besides those.
01474     unsigned NumPreds = TailBB->pred_size();
01475     if (NumPreds > 1)
01476       CanMergeTail = false;
01477     else if (NumPreds == 1 && CanMergeTail) {
01478       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
01479       if (*PI != BBI1->BB && *PI != BBI2->BB)
01480         CanMergeTail = false;
01481     }
01482     if (CanMergeTail) {
01483       MergeBlocks(BBI, TailBBI);
01484       TailBBI.IsDone = true;
01485     } else {
01486       BBI.BB->addSuccessor(TailBB);
01487       InsertUncondBranch(BBI.BB, TailBB, TII);
01488       BBI.HasFallThrough = false;
01489     }
01490   }
01491 
01492   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
01493   // which can happen here if TailBB is unanalyzable and is merged, so
01494   // explicitly remove BBI1 and BBI2 as successors.
01495   BBI.BB->removeSuccessor(BBI1->BB);
01496   BBI.BB->removeSuccessor(BBI2->BB);
01497   RemoveExtraEdges(BBI);
01498 
01499   // Update block info.
01500   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
01501   InvalidatePreds(BBI.BB);
01502 
01503   // FIXME: Must maintain LiveIns.
01504   return true;
01505 }
01506 
01507 static bool MaySpeculate(const MachineInstr *MI,
01508                          SmallSet<unsigned, 4> &LaterRedefs,
01509                          const TargetInstrInfo *TII) {
01510   bool SawStore = true;
01511   if (!MI->isSafeToMove(TII, nullptr, SawStore))
01512     return false;
01513 
01514   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01515     const MachineOperand &MO = MI->getOperand(i);
01516     if (!MO.isReg())
01517       continue;
01518     unsigned Reg = MO.getReg();
01519     if (!Reg)
01520       continue;
01521     if (MO.isDef() && !LaterRedefs.count(Reg))
01522       return false;
01523   }
01524 
01525   return true;
01526 }
01527 
01528 /// PredicateBlock - Predicate instructions from the start of the block to the
01529 /// specified end with the specified condition.
01530 void IfConverter::PredicateBlock(BBInfo &BBI,
01531                                  MachineBasicBlock::iterator E,
01532                                  SmallVectorImpl<MachineOperand> &Cond,
01533                                  SmallSet<unsigned, 4> *LaterRedefs) {
01534   bool AnyUnpred = false;
01535   bool MaySpec = LaterRedefs != nullptr;
01536   for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
01537     if (I->isDebugValue() || TII->isPredicated(I))
01538       continue;
01539     // It may be possible not to predicate an instruction if it's the 'true'
01540     // side of a diamond and the 'false' side may re-define the instruction's
01541     // defs.
01542     if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
01543       AnyUnpred = true;
01544       continue;
01545     }
01546     // If any instruction is predicated, then every instruction after it must
01547     // be predicated.
01548     MaySpec = false;
01549     if (!TII->PredicateInstruction(I, Cond)) {
01550 #ifndef NDEBUG
01551       dbgs() << "Unable to predicate " << *I << "!\n";
01552 #endif
01553       llvm_unreachable(nullptr);
01554     }
01555 
01556     // If the predicated instruction now redefines a register as the result of
01557     // if-conversion, add an implicit kill.
01558     UpdatePredRedefs(I, Redefs);
01559   }
01560 
01561   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
01562 
01563   BBI.IsAnalyzed = false;
01564   BBI.NonPredSize = 0;
01565 
01566   ++NumIfConvBBs;
01567   if (AnyUnpred)
01568     ++NumUnpred;
01569 }
01570 
01571 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
01572 /// the destination block. Skip end of block branches if IgnoreBr is true.
01573 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
01574                                         SmallVectorImpl<MachineOperand> &Cond,
01575                                         bool IgnoreBr) {
01576   MachineFunction &MF = *ToBBI.BB->getParent();
01577 
01578   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
01579          E = FromBBI.BB->end(); I != E; ++I) {
01580     // Do not copy the end of the block branches.
01581     if (IgnoreBr && I->isBranch())
01582       break;
01583 
01584     MachineInstr *MI = MF.CloneMachineInstr(I);
01585     ToBBI.BB->insert(ToBBI.BB->end(), MI);
01586     ToBBI.NonPredSize++;
01587     unsigned ExtraPredCost = TII->getPredicationCost(&*I);
01588     unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
01589     if (NumCycles > 1)
01590       ToBBI.ExtraCost += NumCycles-1;
01591     ToBBI.ExtraCost2 += ExtraPredCost;
01592 
01593     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
01594       if (!TII->PredicateInstruction(MI, Cond)) {
01595 #ifndef NDEBUG
01596         dbgs() << "Unable to predicate " << *I << "!\n";
01597 #endif
01598         llvm_unreachable(nullptr);
01599       }
01600     }
01601 
01602     // If the predicated instruction now redefines a register as the result of
01603     // if-conversion, add an implicit kill.
01604     UpdatePredRedefs(MI, Redefs);
01605 
01606     // Some kill flags may not be correct anymore.
01607     if (!DontKill.empty())
01608       RemoveKills(*MI, DontKill);
01609   }
01610 
01611   if (!IgnoreBr) {
01612     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
01613                                            FromBBI.BB->succ_end());
01614     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
01615     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
01616 
01617     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
01618       MachineBasicBlock *Succ = Succs[i];
01619       // Fallthrough edge can't be transferred.
01620       if (Succ == FallThrough)
01621         continue;
01622       ToBBI.BB->addSuccessor(Succ);
01623     }
01624   }
01625 
01626   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
01627             std::back_inserter(ToBBI.Predicate));
01628   std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
01629 
01630   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
01631   ToBBI.IsAnalyzed = false;
01632 
01633   ++NumDupBBs;
01634 }
01635 
01636 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
01637 /// This will leave FromBB as an empty block, so remove all of its
01638 /// successor edges except for the fall-through edge.  If AddEdges is true,
01639 /// i.e., when FromBBI's branch is being moved, add those successor edges to
01640 /// ToBBI.
01641 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
01642   assert(!FromBBI.BB->hasAddressTaken() &&
01643          "Removing a BB whose address is taken!");
01644 
01645   ToBBI.BB->splice(ToBBI.BB->end(),
01646                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
01647 
01648   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
01649                                          FromBBI.BB->succ_end());
01650   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
01651   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
01652 
01653   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
01654     MachineBasicBlock *Succ = Succs[i];
01655     // Fallthrough edge can't be transferred.
01656     if (Succ == FallThrough)
01657       continue;
01658     FromBBI.BB->removeSuccessor(Succ);
01659     if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
01660       ToBBI.BB->addSuccessor(Succ);
01661   }
01662 
01663   // Now FromBBI always falls through to the next block!
01664   if (NBB && !FromBBI.BB->isSuccessor(NBB))
01665     FromBBI.BB->addSuccessor(NBB);
01666 
01667   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
01668             std::back_inserter(ToBBI.Predicate));
01669   FromBBI.Predicate.clear();
01670 
01671   ToBBI.NonPredSize += FromBBI.NonPredSize;
01672   ToBBI.ExtraCost += FromBBI.ExtraCost;
01673   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
01674   FromBBI.NonPredSize = 0;
01675   FromBBI.ExtraCost = 0;
01676   FromBBI.ExtraCost2 = 0;
01677 
01678   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
01679   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
01680   ToBBI.IsAnalyzed = false;
01681   FromBBI.IsAnalyzed = false;
01682 }