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, which
11 // tries to convert conditional branches into predicated instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/Passes.h"
16 #include "BranchFolding.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/ScopeExit.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/LivePhysRegs.h"
22 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetSchedule.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include <algorithm>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "ifcvt"
43 
44 // Hidden options for help debugging.
45 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
48 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
49                                    cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
51                                     cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
53                                      cl::init(false), cl::Hidden);
54 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
55                                       cl::init(false), cl::Hidden);
56 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
57                                       cl::init(false), cl::Hidden);
58 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
59                                        cl::init(false), cl::Hidden);
60 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
61                                     cl::init(false), cl::Hidden);
62 static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
63                                         cl::init(false), cl::Hidden);
64 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
65                                      cl::init(true), cl::Hidden);
66 
67 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
68 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
69 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
70 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
71 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
72 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
73 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
74 STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
75 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
76 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
77 STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
78 
79 namespace {
80   class IfConverter : public MachineFunctionPass {
81     enum IfcvtKind {
82       ICNotClassfied,  // BB data valid, but not classified.
83       ICSimpleFalse,   // Same as ICSimple, but on the false path.
84       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
85       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
86       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
87       ICTriangleFalse, // Same as ICTriangle, but on the false path.
88       ICTriangle,      // BB is entry of a triangle sub-CFG.
89       ICDiamond,       // BB is entry of a diamond sub-CFG.
90       ICForkedDiamond  // BB is entry of an almost diamond sub-CFG, with a
91                        // common tail that can be shared.
92     };
93 
94     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
95     /// if-conversion feasibility analysis. This includes results from
96     /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
97     /// classification, and common tail block of its successors (if it's a
98     /// diamond shape), its size, whether it's predicable, and whether any
99     /// instruction can clobber the 'would-be' predicate.
100     ///
101     /// IsDone          - True if BB is not to be considered for ifcvt.
102     /// IsBeingAnalyzed - True if BB is currently being analyzed.
103     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
104     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
105     /// IsBrAnalyzable  - True if analyzeBranch() returns false.
106     /// HasFallThrough  - True if BB may fallthrough to the following BB.
107     /// IsUnpredicable  - True if BB is known to be unpredicable.
108     /// ClobbersPred    - True if BB could modify predicates (e.g. has
109     ///                   cmp, call, etc.)
110     /// NonPredSize     - Number of non-predicated instructions.
111     /// ExtraCost       - Extra cost for multi-cycle instructions.
112     /// ExtraCost2      - Some instructions are slower when predicated
113     /// BB              - Corresponding MachineBasicBlock.
114     /// TrueBB / FalseBB- See analyzeBranch().
115     /// BrCond          - Conditions for end of block conditional branches.
116     /// Predicate       - Predicate used in the BB.
117     struct BBInfo {
118       bool IsDone          : 1;
119       bool IsBeingAnalyzed : 1;
120       bool IsAnalyzed      : 1;
121       bool IsEnqueued      : 1;
122       bool IsBrAnalyzable  : 1;
123       bool IsBrReversible  : 1;
124       bool HasFallThrough  : 1;
125       bool IsUnpredicable  : 1;
126       bool CannotBeCopied  : 1;
127       bool ClobbersPred    : 1;
128       unsigned NonPredSize;
129       unsigned ExtraCost;
130       unsigned ExtraCost2;
131       MachineBasicBlock *BB;
132       MachineBasicBlock *TrueBB;
133       MachineBasicBlock *FalseBB;
134       SmallVector<MachineOperand, 4> BrCond;
135       SmallVector<MachineOperand, 4> Predicate;
136       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
137                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
138                  IsBrReversible(false), HasFallThrough(false),
139                  IsUnpredicable(false), CannotBeCopied(false),
140                  ClobbersPred(false), NonPredSize(0), ExtraCost(0),
141                  ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
142                  FalseBB(nullptr) {}
143     };
144 
145     /// IfcvtToken - Record information about pending if-conversions to attempt:
146     /// BBI             - Corresponding BBInfo.
147     /// Kind            - Type of block. See IfcvtKind.
148     /// NeedSubsumption - True if the to-be-predicated BB has already been
149     ///                   predicated.
150     /// NumDups      - Number of instructions that would be duplicated due
151     ///                   to this if-conversion. (For diamonds, the number of
152     ///                   identical instructions at the beginnings of both
153     ///                   paths).
154     /// NumDups2     - For diamonds, the number of identical instructions
155     ///                   at the ends of both paths.
156     struct IfcvtToken {
157       BBInfo &BBI;
158       IfcvtKind Kind;
159       unsigned NumDups;
160       unsigned NumDups2;
161       bool NeedSubsumption : 1;
162       bool TClobbersPred : 1;
163       bool FClobbersPred : 1;
164       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
165                  bool tc = false, bool fc = false)
166         : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
167           TClobbersPred(tc), FClobbersPred(fc) {}
168     };
169 
170     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
171     /// basic block number.
172     std::vector<BBInfo> BBAnalysis;
173     TargetSchedModel SchedModel;
174 
175     const TargetLoweringBase *TLI;
176     const TargetInstrInfo *TII;
177     const TargetRegisterInfo *TRI;
178     const MachineBranchProbabilityInfo *MBPI;
179     MachineRegisterInfo *MRI;
180 
181     LivePhysRegs Redefs;
182     LivePhysRegs DontKill;
183 
184     bool PreRegAlloc;
185     bool MadeChange;
186     int FnNum;
187     std::function<bool(const Function &)> PredicateFtor;
188 
189   public:
190     static char ID;
191     IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
192         : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
193       initializeIfConverterPass(*PassRegistry::getPassRegistry());
194     }
195 
196     void getAnalysisUsage(AnalysisUsage &AU) const override {
197       AU.addRequired<MachineBlockFrequencyInfo>();
198       AU.addRequired<MachineBranchProbabilityInfo>();
199       MachineFunctionPass::getAnalysisUsage(AU);
200     }
201 
202     bool runOnMachineFunction(MachineFunction &MF) override;
203 
204     MachineFunctionProperties getRequiredProperties() const override {
205       return MachineFunctionProperties().set(
206           MachineFunctionProperties::Property::AllVRegsAllocated);
207     }
208 
209   private:
210     bool ReverseBranchCondition(BBInfo &BBI) const;
211     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
212                      BranchProbability Prediction) const;
213     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
214                        bool FalseBranch, unsigned &Dups,
215                        BranchProbability Prediction) const;
216     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
217                       unsigned &Dups1, unsigned &Dups2,
218                       BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
219     bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
220                             unsigned &Dups1, unsigned &Dups2,
221                             BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
222     void AnalyzeBranches(BBInfo &BBI);
223     void ScanInstructions(BBInfo &BBI,
224                           MachineBasicBlock::iterator &Begin,
225                           MachineBasicBlock::iterator &End) const;
226     bool RescanInstructions(
227         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
228         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
229         BBInfo &TrueBBI, BBInfo &FalseBBI) const;
230     void AnalyzeBlock(MachineBasicBlock *MBB,
231                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
232     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
233                              bool isTriangle = false, bool RevBranch = false,
234                              bool hasCommonTail = false);
235     void AnalyzeBlocks(MachineFunction &MF,
236                        std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
237     void InvalidatePreds(MachineBasicBlock *BB);
238     void RemoveExtraEdges(BBInfo &BBI);
239     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
240     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
241     bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
242                                 unsigned NumDups1, unsigned NumDups2,
243                                 bool TClobbersPred, bool FClobbersPred,
244                                 bool RemoveTrueBranch, bool RemoveFalseBranch,
245                                 bool MergeAddEdges);
246     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
247                           unsigned NumDups1, unsigned NumDups2);
248     bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
249                               unsigned NumDups1, unsigned NumDups2,
250                               bool TClobbers, bool FClobbers);
251     void PredicateBlock(BBInfo &BBI,
252                         MachineBasicBlock::iterator E,
253                         SmallVectorImpl<MachineOperand> &Cond,
254                         SmallSet<unsigned, 4> *LaterRedefs = nullptr);
255     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
256                                SmallVectorImpl<MachineOperand> &Cond,
257                                bool IgnoreBr = false);
258     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
259 
260     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
261                             unsigned Cycle, unsigned Extra,
262                             BranchProbability Prediction) const {
263       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
264                                                    Prediction);
265     }
266 
267     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
268                             unsigned TCycle, unsigned TExtra,
269                             MachineBasicBlock &FBB,
270                             unsigned FCycle, unsigned FExtra,
271                             BranchProbability Prediction) const {
272       return TCycle > 0 && FCycle > 0 &&
273         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
274                                  Prediction);
275     }
276 
277     // blockAlwaysFallThrough - Block ends without a terminator.
278     bool blockAlwaysFallThrough(BBInfo &BBI) const {
279       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
280     }
281 
282     // IfcvtTokenCmp - Used to sort if-conversion candidates.
283     static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
284                               const std::unique_ptr<IfcvtToken> &C2) {
285       int Incr1 = (C1->Kind == ICDiamond)
286         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
287       int Incr2 = (C2->Kind == ICDiamond)
288         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
289       if (Incr1 > Incr2)
290         return true;
291       else if (Incr1 == Incr2) {
292         // Favors subsumption.
293         if (!C1->NeedSubsumption && C2->NeedSubsumption)
294           return true;
295         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
296           // Favors diamond over triangle, etc.
297           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
298             return true;
299           else if (C1->Kind == C2->Kind)
300             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
301         }
302       }
303       return false;
304     }
305   };
306 
307   char IfConverter::ID = 0;
308 }
309 
310 char &llvm::IfConverterID = IfConverter::ID;
311 
312 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
313 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
314 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
315 
316 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
317   if (skipFunction(*MF.getFunction()) ||
318       (PredicateFtor && !PredicateFtor(*MF.getFunction())))
319     return false;
320 
321   const TargetSubtargetInfo &ST = MF.getSubtarget();
322   TLI = ST.getTargetLowering();
323   TII = ST.getInstrInfo();
324   TRI = ST.getRegisterInfo();
325   BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
326   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
327   MRI = &MF.getRegInfo();
328   SchedModel.init(ST.getSchedModel(), &ST, TII);
329 
330   if (!TII) return false;
331 
332   PreRegAlloc = MRI->isSSA();
333 
334   bool BFChange = false;
335   if (!PreRegAlloc) {
336     // Tail merge tend to expose more if-conversion opportunities.
337     BranchFolder BF(true, false, MBFI, *MBPI);
338     BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
339                                    getAnalysisIfAvailable<MachineModuleInfo>());
340   }
341 
342   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
343                << MF.getName() << "\'");
344 
345   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
346     DEBUG(dbgs() << " skipped\n");
347     return false;
348   }
349   DEBUG(dbgs() << "\n");
350 
351   MF.RenumberBlocks();
352   BBAnalysis.resize(MF.getNumBlockIDs());
353 
354   std::vector<std::unique_ptr<IfcvtToken>> Tokens;
355   MadeChange = false;
356   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
357     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
358   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
359     // Do an initial analysis for each basic block and find all the potential
360     // candidates to perform if-conversion.
361     bool Change = false;
362     AnalyzeBlocks(MF, Tokens);
363     while (!Tokens.empty()) {
364       std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
365       Tokens.pop_back();
366       BBInfo &BBI = Token->BBI;
367       IfcvtKind Kind = Token->Kind;
368       unsigned NumDups = Token->NumDups;
369       unsigned NumDups2 = Token->NumDups2;
370 
371       // If the block has been evicted out of the queue or it has already been
372       // marked dead (due to it being predicated), then skip it.
373       if (BBI.IsDone)
374         BBI.IsEnqueued = false;
375       if (!BBI.IsEnqueued)
376         continue;
377 
378       BBI.IsEnqueued = false;
379 
380       bool RetVal = false;
381       switch (Kind) {
382       default: llvm_unreachable("Unexpected!");
383       case ICSimple:
384       case ICSimpleFalse: {
385         bool isFalse = Kind == ICSimpleFalse;
386         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
387         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
388                                             " false" : "")
389                      << "): BB#" << BBI.BB->getNumber() << " ("
390                      << ((Kind == ICSimpleFalse)
391                          ? BBI.FalseBB->getNumber()
392                          : BBI.TrueBB->getNumber()) << ") ");
393         RetVal = IfConvertSimple(BBI, Kind);
394         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
395         if (RetVal) {
396           if (isFalse) ++NumSimpleFalse;
397           else         ++NumSimple;
398         }
399        break;
400       }
401       case ICTriangle:
402       case ICTriangleRev:
403       case ICTriangleFalse:
404       case ICTriangleFRev: {
405         bool isFalse = Kind == ICTriangleFalse;
406         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
407         if (DisableTriangle && !isFalse && !isRev) break;
408         if (DisableTriangleR && !isFalse && isRev) break;
409         if (DisableTriangleF && isFalse && !isRev) break;
410         if (DisableTriangleFR && isFalse && isRev) break;
411         DEBUG(dbgs() << "Ifcvt (Triangle");
412         if (isFalse)
413           DEBUG(dbgs() << " false");
414         if (isRev)
415           DEBUG(dbgs() << " rev");
416         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
417                      << BBI.TrueBB->getNumber() << ",F:"
418                      << BBI.FalseBB->getNumber() << ") ");
419         RetVal = IfConvertTriangle(BBI, Kind);
420         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
421         if (RetVal) {
422           if (isFalse) {
423             if (isRev) ++NumTriangleFRev;
424             else       ++NumTriangleFalse;
425           } else {
426             if (isRev) ++NumTriangleRev;
427             else       ++NumTriangle;
428           }
429         }
430         break;
431       }
432       case ICDiamond: {
433         if (DisableDiamond) break;
434         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
435                      << BBI.TrueBB->getNumber() << ",F:"
436                      << BBI.FalseBB->getNumber() << ") ");
437         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
438         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
439         if (RetVal) ++NumDiamonds;
440         break;
441       }
442       case ICForkedDiamond: {
443         if (DisableForkedDiamond) break;
444         DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
445                      << BBI.BB->getNumber() << " (T:"
446                      << BBI.TrueBB->getNumber() << ",F:"
447                      << BBI.FalseBB->getNumber() << ") ");
448         RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
449                                       Token->TClobbersPred,
450                                       Token->FClobbersPred);
451         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
452         if (RetVal) ++NumForkedDiamonds;
453         break;
454       }
455       }
456 
457       Change |= RetVal;
458 
459       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
460         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
461       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
462         break;
463     }
464 
465     if (!Change)
466       break;
467     MadeChange |= Change;
468   }
469 
470   Tokens.clear();
471   BBAnalysis.clear();
472 
473   if (MadeChange && IfCvtBranchFold) {
474     BranchFolder BF(false, false, MBFI, *MBPI);
475     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
476                         getAnalysisIfAvailable<MachineModuleInfo>());
477   }
478 
479   MadeChange |= BFChange;
480   return MadeChange;
481 }
482 
483 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
484 /// its 'true' successor.
485 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
486                                          MachineBasicBlock *TrueBB) {
487   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
488          E = BB->succ_end(); SI != E; ++SI) {
489     MachineBasicBlock *SuccBB = *SI;
490     if (SuccBB != TrueBB)
491       return SuccBB;
492   }
493   return nullptr;
494 }
495 
496 /// ReverseBranchCondition - Reverse the condition of the end of the block
497 /// branch. Swap block's 'true' and 'false' successors.
498 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
499   DebugLoc dl;  // FIXME: this is nowhere
500   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
501     TII->RemoveBranch(*BBI.BB);
502     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
503     std::swap(BBI.TrueBB, BBI.FalseBB);
504     return true;
505   }
506   return false;
507 }
508 
509 /// getNextBlock - Returns the next block in the function blocks ordering. If
510 /// it is the end, returns NULL.
511 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
512   MachineFunction::iterator I = BB->getIterator();
513   MachineFunction::iterator E = BB->getParent()->end();
514   if (++I == E)
515     return nullptr;
516   return &*I;
517 }
518 
519 /// ValidSimple - Returns true if the 'true' block (along with its
520 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
521 /// number of instructions that the ifcvt would need to duplicate if performed
522 /// in Dups.
523 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
524                               BranchProbability Prediction) const {
525   Dups = 0;
526   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
527     return false;
528 
529   if (TrueBBI.IsBrAnalyzable)
530     return false;
531 
532   if (TrueBBI.BB->pred_size() > 1) {
533     if (TrueBBI.CannotBeCopied ||
534         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
535                                         Prediction))
536       return false;
537     Dups = TrueBBI.NonPredSize;
538   }
539 
540   return true;
541 }
542 
543 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
544 /// with their common predecessor) forms a valid triangle shape for ifcvt.
545 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
546 /// branches to the 'false' block rather than the other way around. It also
547 /// returns the number of instructions that the ifcvt would need to duplicate
548 /// if performed in 'Dups'.
549 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
550                                 bool FalseBranch, unsigned &Dups,
551                                 BranchProbability Prediction) const {
552   Dups = 0;
553   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
554     return false;
555 
556   if (TrueBBI.BB->pred_size() > 1) {
557     if (TrueBBI.CannotBeCopied)
558       return false;
559 
560     unsigned Size = TrueBBI.NonPredSize;
561     if (TrueBBI.IsBrAnalyzable) {
562       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
563         // Ends with an unconditional branch. It will be removed.
564         --Size;
565       else {
566         MachineBasicBlock *FExit = FalseBranch
567           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
568         if (FExit)
569           // Require a conditional branch
570           ++Size;
571       }
572     }
573     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
574       return false;
575     Dups = Size;
576   }
577 
578   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
579   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
580     MachineFunction::iterator I = TrueBBI.BB->getIterator();
581     if (++I == TrueBBI.BB->getParent()->end())
582       return false;
583     TExit = &*I;
584   }
585   return TExit && TExit == FalseBBI.BB;
586 }
587 
588 /// Increment It until it points to a non-debug instruction or to End.
589 /// @param It Iterator to increment
590 /// @param End Iterator that points to end. Will be compared to It
591 /// @returns true if It == End, false otherwise.
592 static inline bool skipDebugInstructionsForward(
593     MachineBasicBlock::iterator &It,
594     MachineBasicBlock::iterator &End) {
595   while (It != End && It->isDebugValue())
596     It++;
597   return It == End;
598 }
599 
600 /// Decrement It until it points to a non-debug instruction or to Begin.
601 /// @param It Iterator to decrement.
602 /// @param Begin Iterator that points to beginning. Will be compared to It
603 /// @returns true if It == Begin, false otherwise.
604 static inline bool skipDebugInstructionsBackward(
605     MachineBasicBlock::iterator &It,
606     MachineBasicBlock::iterator &Begin) {
607   while (It != Begin && It->isDebugValue())
608     It--;
609   return It == Begin;
610 }
611 
612 /// Count duplicated instructions and move the iterators to show where they
613 /// are.
614 /// @param TIB True Iterator Begin
615 /// @param FIB False Iterator Begin
616 /// These two iterators initially point to the first instruction of the two
617 /// blocks, and finally point to the first non-shared instruction.
618 /// @param TIE True Iterator End
619 /// @param FIE False Iterator End
620 /// These two iterators initially point to End() for the two blocks() and
621 /// finally point to the first shared instruction in the tail.
622 /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
623 /// two blocks.
624 static void countDuplicatedInstructions(
625     MachineBasicBlock::iterator &TIB,
626     MachineBasicBlock::iterator &FIB,
627     MachineBasicBlock::iterator &TIE,
628     MachineBasicBlock::iterator &FIE,
629     unsigned &Dups1, unsigned &Dups2,
630     MachineBasicBlock &TBB, MachineBasicBlock &FBB,
631     bool SkipConditionalBranches) {
632 
633   while (TIB != TIE && FIB != FIE) {
634     // Skip dbg_value instructions. These do not count.
635     if(skipDebugInstructionsForward(TIB, TIE))
636       break;
637     if(skipDebugInstructionsForward(FIB, FIE))
638       break;
639     if (!TIB->isIdenticalTo(*FIB))
640       break;
641     ++Dups1;
642     ++TIB;
643     ++FIB;
644   }
645 
646   // Now, in preparation for counting duplicate instructions at the ends of the
647   // blocks, move the end iterators up past any branch instructions.
648   // If both blocks are returning don't skip the branches, since they will
649   // likely be both identical return instructions. In such cases the return
650   // can be left unpredicated.
651   // Check for already containing all of the block.
652   if (TIB == TIE || FIB == FIE)
653     return;
654   --TIE;
655   --FIE;
656   // Upon exit TIE and FIE will both point at the last non-shared instruction,
657   // they need to be moved forward to point past the last non-shared
658   // instruction.
659   auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
660     ++TIE; ++FIE;
661   });
662 
663   if (!TBB.succ_empty() || !FBB.succ_empty()) {
664     if (SkipConditionalBranches) {
665       while (TIE != TIB && TIE->isBranch())
666         --TIE;
667       while (FIE != FIB && FIE->isBranch())
668         --FIE;
669     } else {
670       while (TIE != TIB && TIE->isUnconditionalBranch())
671         --TIE;
672       while (FIE != FIB && FIE->isUnconditionalBranch())
673         --FIE;
674     }
675   }
676 
677   // If Dups1 includes all of a block, then don't count duplicate
678   // instructions at the end of the blocks.
679   if (TIB == TIE || FIB == FIE)
680     return;
681 
682   // Count duplicate instructions at the ends of the blocks.
683   while (TIE != TIB && FIE != FIB) {
684     // Skip dbg_value instructions. These do not count.
685     if (skipDebugInstructionsBackward(TIE, TIB))
686       break;
687     if (skipDebugInstructionsBackward(FIE, FIB))
688       break;
689     if (!TIE->isIdenticalTo(*FIE))
690       break;
691     // If we are trying to make sure the conditional branches are the same, we
692     // still don't want to count them.
693     if (SkipConditionalBranches || !TIE->isBranch())
694       ++Dups2;
695     --TIE;
696     --FIE;
697   }
698 }
699 
700 /// RescanInstructions - Run ScanInstructions on a pair of blocks.
701 /// @param TIB - True Iterator Begin, points to first non-shared instruction
702 /// @param FIB - False Iterator Begin, points to first non-shared instruction
703 /// @param TIE - True Iterator End, points past last non-shared instruction
704 /// @param FIE - False Iterator End, points past last non-shared instruction
705 /// @param TrueBBI  - BBInfo to update for the true block.
706 /// @param FalseBBI - BBInfo to update for the false block.
707 /// @returns - false if either block cannot be predicated or if both blocks end
708 ///   with a predicate-clobbering instruction.
709 bool IfConverter::RescanInstructions(
710     MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
711     MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
712     BBInfo &TrueBBI, BBInfo &FalseBBI) const {
713   ScanInstructions(TrueBBI, TIB, TIE);
714   if (TrueBBI.IsUnpredicable)
715     return false;
716   ScanInstructions(FalseBBI, FIB, FIE);
717   if (FalseBBI.IsUnpredicable)
718     return false;
719   if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
720     return false;
721   return true;
722 }
723 
724 /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
725 /// with their common predecessor) form a diamond if a common tail block is
726 /// extracted.
727 /// While not strictly a diamond, this pattern would form a diamond if
728 /// tail-merging had merged the shared tails.
729 ///           EBB
730 ///         _/   \_
731 ///         |     |
732 ///        TBB   FBB
733 ///        /  \ /   \
734 ///  FalseBB TrueBB FalseBB
735 /// Currently only handles analyzable branches.
736 /// Specifically excludes actual diamonds to avoid overlap.
737 bool IfConverter::ValidForkedDiamond(
738     BBInfo &TrueBBI, BBInfo &FalseBBI,
739     unsigned &Dups1, unsigned &Dups2,
740     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
741   Dups1 = Dups2 = 0;
742   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
743       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
744     return false;
745 
746   if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
747     return false;
748   // Don't IfConvert blocks that can't be folded into their predecessor.
749   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
750     return false;
751 
752   // This function is specifically looking for conditional tails, as
753   // unconditional tails are already handled by the standard diamond case.
754   if (TrueBBI.BrCond.size() == 0 ||
755       FalseBBI.BrCond.size() == 0)
756     return false;
757 
758   MachineBasicBlock *TT = TrueBBI.TrueBB;
759   MachineBasicBlock *TF = TrueBBI.FalseBB;
760   MachineBasicBlock *FT = FalseBBI.TrueBB;
761   MachineBasicBlock *FF = FalseBBI.FalseBB;
762 
763   if (!TT)
764     TT = getNextBlock(TrueBBI.BB);
765   if (!TF)
766     TF = getNextBlock(TrueBBI.BB);
767   if (!FT)
768     FT = getNextBlock(FalseBBI.BB);
769   if (!FF)
770     FF = getNextBlock(FalseBBI.BB);
771 
772   if (!TT || !TF)
773     return false;
774 
775   // Check successors. If they don't match, bail.
776   if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
777     return false;
778 
779   bool FalseReversed = false;
780   if (TF == FT && TT == FF) {
781     // If the branches are opposing, but we can't reverse, don't do it.
782     if (!FalseBBI.IsBrReversible)
783       return false;
784     FalseReversed = true;
785     ReverseBranchCondition(FalseBBI);
786   }
787   auto UnReverseOnExit = make_scope_exit([&]() {
788     if (FalseReversed)
789       ReverseBranchCondition(FalseBBI);
790   });
791 
792   // Count duplicate instructions at the beginning of the true and false blocks.
793   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
794   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
795   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
796   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
797   countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
798                               *TrueBBI.BB, *FalseBBI.BB,
799                               /* SkipConditionalBranches */ false);
800 
801   TrueBBICalc.BB = TrueBBI.BB;
802   FalseBBICalc.BB = FalseBBI.BB;
803   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
804     return false;
805   // The size is used to decide whether to if-convert, and the shared portions
806   // are subtracted off. Because of the subtraction, we just use the size that
807   // was calculated by the original ScanInstructions, as it is correct.
808   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
809   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
810   return true;
811 }
812 
813 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
814 /// with their common predecessor) forms a valid diamond shape for ifcvt.
815 bool IfConverter::ValidDiamond(
816     BBInfo &TrueBBI, BBInfo &FalseBBI,
817     unsigned &Dups1, unsigned &Dups2,
818     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
819   Dups1 = Dups2 = 0;
820   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
821       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
822     return false;
823 
824   MachineBasicBlock *TT = TrueBBI.TrueBB;
825   MachineBasicBlock *FT = FalseBBI.TrueBB;
826 
827   if (!TT && blockAlwaysFallThrough(TrueBBI))
828     TT = getNextBlock(TrueBBI.BB);
829   if (!FT && blockAlwaysFallThrough(FalseBBI))
830     FT = getNextBlock(FalseBBI.BB);
831   if (TT != FT)
832     return false;
833   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
834     return false;
835   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
836     return false;
837 
838   // FIXME: Allow true block to have an early exit?
839   if (TrueBBI.FalseBB || FalseBBI.FalseBB)
840     return false;
841 
842   // Count duplicate instructions at the beginning and end of the true and
843   // false blocks.
844   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
845   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
846   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
847   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
848   countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
849                               *TrueBBI.BB, *FalseBBI.BB,
850                               /* SkipConditionalBranches */ true);
851 
852   TrueBBICalc.BB = TrueBBI.BB;
853   FalseBBICalc.BB = FalseBBI.BB;
854   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
855     return false;
856   // The size is used to decide whether to if-convert, and the shared portions
857   // are subtracted off. Because of the subtraction, we just use the size that
858   // was calculated by the original ScanInstructions, as it is correct.
859   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
860   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
861   return true;
862 }
863 
864 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
865 /// the block is predicable.
866 void IfConverter::AnalyzeBranches(BBInfo &BBI) {
867   if (BBI.IsDone)
868     return;
869 
870   BBI.TrueBB = BBI.FalseBB = nullptr;
871   BBI.BrCond.clear();
872   BBI.IsBrAnalyzable =
873       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
874   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
875   BBI.IsBrReversible = (RevCond.size() == 0) ||
876       !TII->ReverseBranchCondition(RevCond);
877   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
878 
879   if (BBI.BrCond.size()) {
880     // No false branch. This BB must end with a conditional branch and a
881     // fallthrough.
882     if (!BBI.FalseBB)
883       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
884     if (!BBI.FalseBB) {
885       // Malformed bcc? True and false blocks are the same?
886       BBI.IsUnpredicable = true;
887     }
888   }
889 }
890 
891 /// ScanInstructions - Scan all the instructions in the block to determine if
892 /// the block is predicable. In most cases, that means all the instructions
893 /// in the block are isPredicable(). Also checks if the block contains any
894 /// instruction which can clobber a predicate (e.g. condition code register).
895 /// If so, the block is not predicable unless it's the last instruction.
896 void IfConverter::ScanInstructions(BBInfo &BBI,
897                                    MachineBasicBlock::iterator &Begin,
898                                    MachineBasicBlock::iterator &End) const {
899   if (BBI.IsDone || BBI.IsUnpredicable)
900     return;
901 
902   bool AlreadyPredicated = !BBI.Predicate.empty();
903 
904   BBI.NonPredSize = 0;
905   BBI.ExtraCost = 0;
906   BBI.ExtraCost2 = 0;
907   BBI.ClobbersPred = false;
908   for (; Begin != End; ++Begin) {
909     auto &MI = *Begin;
910     if (MI.isDebugValue())
911       continue;
912 
913     // It's unsafe to duplicate convergent instructions in this context, so set
914     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
915     // following CFG, which is subject to our "simple" transformation.
916     //
917     //    BB0     // if (c1) goto BB1; else goto BB2;
918     //   /   \
919     //  BB1   |
920     //   |   BB2  // if (c2) goto TBB; else goto FBB;
921     //   |   / |
922     //   |  /  |
923     //   TBB   |
924     //    |    |
925     //    |   FBB
926     //    |
927     //    exit
928     //
929     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
930     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
931     // TBB contains a convergent instruction.  This is safe iff doing so does
932     // not add a control-flow dependency to the convergent instruction -- i.e.,
933     // it's safe iff the set of control flows that leads us to the convergent
934     // instruction does not get smaller after the transformation.
935     //
936     // Originally we executed TBB if c1 || c2.  After the transformation, there
937     // are two copies of TBB's instructions.  We get to the first if c1, and we
938     // get to the second if !c1 && c2.
939     //
940     // There are clearly fewer ways to satisfy the condition "c1" than
941     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
942     // our convergent instruction, the transformation is unsafe.
943     if (MI.isNotDuplicable() || MI.isConvergent())
944       BBI.CannotBeCopied = true;
945 
946     bool isPredicated = TII->isPredicated(MI);
947     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
948 
949     // A conditional branch is not predicable, but it may be eliminated.
950     if (isCondBr)
951       continue;
952 
953     if (!isPredicated) {
954       BBI.NonPredSize++;
955       unsigned ExtraPredCost = TII->getPredicationCost(MI);
956       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
957       if (NumCycles > 1)
958         BBI.ExtraCost += NumCycles-1;
959       BBI.ExtraCost2 += ExtraPredCost;
960     } else if (!AlreadyPredicated) {
961       // FIXME: This instruction is already predicated before the
962       // if-conversion pass. It's probably something like a conditional move.
963       // Mark this block unpredicable for now.
964       BBI.IsUnpredicable = true;
965       return;
966     }
967 
968     if (BBI.ClobbersPred && !isPredicated) {
969       // Predicate modification instruction should end the block (except for
970       // already predicated instructions and end of block branches).
971       // Predicate may have been modified, the subsequent (currently)
972       // unpredicated instructions cannot be correctly predicated.
973       BBI.IsUnpredicable = true;
974       return;
975     }
976 
977     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
978     // still potentially predicable.
979     std::vector<MachineOperand> PredDefs;
980     if (TII->DefinesPredicate(MI, PredDefs))
981       BBI.ClobbersPred = true;
982 
983     if (!TII->isPredicable(MI)) {
984       BBI.IsUnpredicable = true;
985       return;
986     }
987   }
988 }
989 
990 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
991 /// predicated by the specified predicate.
992 /// @param BBI BBInfo for the block to check
993 /// @param Pred Predicate array for the branch that leads to BBI
994 /// @param isTriangle true if the Analysis is for a triangle
995 /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
996 ///        case
997 /// @param hasCommonTail true if BBI shares a tail with a sibling block that
998 ///        contains any instruction that would make the block unpredicable.
999 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1000                                       SmallVectorImpl<MachineOperand> &Pred,
1001                                       bool isTriangle, bool RevBranch,
1002                                       bool hasCommonTail) {
1003   // If the block is dead or unpredicable, then it cannot be predicated.
1004   // Two blocks may share a common unpredicable tail, but this doesn't prevent
1005   // them from being if-converted. The non-shared portion is assumed to have
1006   // been checked
1007   if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1008     return false;
1009 
1010   // If it is already predicated but we couldn't analyze its terminator, the
1011   // latter might fallthrough, but we can't determine where to.
1012   // Conservatively avoid if-converting again.
1013   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1014     return false;
1015 
1016   // If it is already predicated, check if the new predicate subsumes
1017   // its predicate.
1018   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1019     return false;
1020 
1021   if (!hasCommonTail && BBI.BrCond.size()) {
1022     if (!isTriangle)
1023       return false;
1024 
1025     // Test predicate subsumption.
1026     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1027     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1028     if (RevBranch) {
1029       if (TII->ReverseBranchCondition(Cond))
1030         return false;
1031     }
1032     if (TII->ReverseBranchCondition(RevPred) ||
1033         !TII->SubsumesPredicate(Cond, RevPred))
1034       return false;
1035   }
1036 
1037   return true;
1038 }
1039 
1040 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
1041 /// the specified block. Record its successors and whether it looks like an
1042 /// if-conversion candidate.
1043 void IfConverter::AnalyzeBlock(
1044     MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1045   struct BBState {
1046     BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
1047     MachineBasicBlock *MBB;
1048 
1049     /// This flag is true if MBB's successors have been analyzed.
1050     bool SuccsAnalyzed;
1051   };
1052 
1053   // Push MBB to the stack.
1054   SmallVector<BBState, 16> BBStack(1, MBB);
1055 
1056   while (!BBStack.empty()) {
1057     BBState &State = BBStack.back();
1058     MachineBasicBlock *BB = State.MBB;
1059     BBInfo &BBI = BBAnalysis[BB->getNumber()];
1060 
1061     if (!State.SuccsAnalyzed) {
1062       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1063         BBStack.pop_back();
1064         continue;
1065       }
1066 
1067       BBI.BB = BB;
1068       BBI.IsBeingAnalyzed = true;
1069 
1070       AnalyzeBranches(BBI);
1071       MachineBasicBlock::iterator Begin = BBI.BB->begin();
1072       MachineBasicBlock::iterator End = BBI.BB->end();
1073       ScanInstructions(BBI, Begin, End);
1074 
1075       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1076       // not considered for ifcvt anymore.
1077       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1078         BBI.IsBeingAnalyzed = false;
1079         BBI.IsAnalyzed = true;
1080         BBStack.pop_back();
1081         continue;
1082       }
1083 
1084       // Do not ifcvt if either path is a back edge to the entry block.
1085       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1086         BBI.IsBeingAnalyzed = false;
1087         BBI.IsAnalyzed = true;
1088         BBStack.pop_back();
1089         continue;
1090       }
1091 
1092       // Do not ifcvt if true and false fallthrough blocks are the same.
1093       if (!BBI.FalseBB) {
1094         BBI.IsBeingAnalyzed = false;
1095         BBI.IsAnalyzed = true;
1096         BBStack.pop_back();
1097         continue;
1098       }
1099 
1100       // Push the False and True blocks to the stack.
1101       State.SuccsAnalyzed = true;
1102       BBStack.push_back(BBI.FalseBB);
1103       BBStack.push_back(BBI.TrueBB);
1104       continue;
1105     }
1106 
1107     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1108     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1109 
1110     if (TrueBBI.IsDone && FalseBBI.IsDone) {
1111       BBI.IsBeingAnalyzed = false;
1112       BBI.IsAnalyzed = true;
1113       BBStack.pop_back();
1114       continue;
1115     }
1116 
1117     SmallVector<MachineOperand, 4>
1118         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1119     bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1120 
1121     unsigned Dups = 0;
1122     unsigned Dups2 = 0;
1123     bool TNeedSub = !TrueBBI.Predicate.empty();
1124     bool FNeedSub = !FalseBBI.Predicate.empty();
1125     bool Enqueued = false;
1126 
1127     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1128 
1129     if (CanRevCond) {
1130       BBInfo TrueBBICalc, FalseBBICalc;
1131       auto feasibleDiamond = [&]() {
1132         return (
1133             MeetIfcvtSizeLimit(
1134                 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1135                               TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1136                 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1137                                FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1138                 Prediction) &&
1139             FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1140                                 /* IsTriangle */ false, /* RevCond */ false,
1141                                 /* hasCommonTail */ true) &&
1142             FeasibilityAnalysis(FalseBBI, RevCond,
1143                                 /* IsTriangle */ false, /* RevCond */ false,
1144                                 /* hasCommonTail */ true));
1145       };
1146 
1147       if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1148                        TrueBBICalc, FalseBBICalc)) {
1149         if (feasibleDiamond()) {
1150           // Diamond:
1151           //   EBB
1152           //   / \_
1153           //  |   |
1154           // TBB FBB
1155           //   \ /
1156           //  TailBB
1157           // Note TailBB can be empty.
1158           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1159               BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
1160           Enqueued = true;
1161         }
1162       } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1163                                     TrueBBICalc, FalseBBICalc)) {
1164         if (feasibleDiamond()) {
1165           // ForkedDiamond:
1166           // if TBB and FBB have a common tail that includes their conditional
1167           // branch instructions, then we can If Convert this pattern.
1168           //          EBB
1169           //         _/ \_
1170           //         |   |
1171           //        TBB  FBB
1172           //        / \ /   \
1173           //  FalseBB TrueBB FalseBB
1174           //
1175           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1176               BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1177               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1178           Enqueued = true;
1179         }
1180       }
1181     }
1182 
1183     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1184         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1185                            TrueBBI.ExtraCost2, Prediction) &&
1186         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1187       // Triangle:
1188       //   EBB
1189       //   | \_
1190       //   |  |
1191       //   | TBB
1192       //   |  /
1193       //   FBB
1194       Tokens.push_back(
1195           llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1196       Enqueued = true;
1197     }
1198 
1199     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1200         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1201                            TrueBBI.ExtraCost2, Prediction) &&
1202         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1203       Tokens.push_back(
1204           llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1205       Enqueued = true;
1206     }
1207 
1208     if (ValidSimple(TrueBBI, Dups, Prediction) &&
1209         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1210                            TrueBBI.ExtraCost2, Prediction) &&
1211         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1212       // Simple (split, no rejoin):
1213       //   EBB
1214       //   | \_
1215       //   |  |
1216       //   | TBB---> exit
1217       //   |
1218       //   FBB
1219       Tokens.push_back(
1220           llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1221       Enqueued = true;
1222     }
1223 
1224     if (CanRevCond) {
1225       // Try the other path...
1226       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1227                         Prediction.getCompl()) &&
1228           MeetIfcvtSizeLimit(*FalseBBI.BB,
1229                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1230                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1231           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1232         Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1233                                                        FNeedSub, Dups));
1234         Enqueued = true;
1235       }
1236 
1237       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1238                         Prediction.getCompl()) &&
1239           MeetIfcvtSizeLimit(*FalseBBI.BB,
1240                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1241                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1242         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1243         Tokens.push_back(
1244             llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1245         Enqueued = true;
1246       }
1247 
1248       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1249           MeetIfcvtSizeLimit(*FalseBBI.BB,
1250                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1251                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1252           FeasibilityAnalysis(FalseBBI, RevCond)) {
1253         Tokens.push_back(
1254             llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1255         Enqueued = true;
1256       }
1257     }
1258 
1259     BBI.IsEnqueued = Enqueued;
1260     BBI.IsBeingAnalyzed = false;
1261     BBI.IsAnalyzed = true;
1262     BBStack.pop_back();
1263   }
1264 }
1265 
1266 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
1267 /// candidates.
1268 void IfConverter::AnalyzeBlocks(
1269     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1270   for (auto &BB : MF)
1271     AnalyzeBlock(&BB, Tokens);
1272 
1273   // Sort to favor more complex ifcvt scheme.
1274   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
1275 }
1276 
1277 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1278 /// that all the intervening blocks are empty (given BB can fall through to its
1279 /// next block).
1280 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
1281   MachineFunction::iterator PI = BB->getIterator();
1282   MachineFunction::iterator I = std::next(PI);
1283   MachineFunction::iterator TI = ToBB->getIterator();
1284   MachineFunction::iterator E = BB->getParent()->end();
1285   while (I != TI) {
1286     // Check isSuccessor to avoid case where the next block is empty, but
1287     // it's not a successor.
1288     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1289       return false;
1290     PI = I++;
1291   }
1292   return true;
1293 }
1294 
1295 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1296 /// to determine if it can be if-converted. If predecessor is already enqueued,
1297 /// dequeue it!
1298 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
1299   for (const auto &Predecessor : BB->predecessors()) {
1300     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1301     if (PBBI.IsDone || PBBI.BB == BB)
1302       continue;
1303     PBBI.IsAnalyzed = false;
1304     PBBI.IsEnqueued = false;
1305   }
1306 }
1307 
1308 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1309 ///
1310 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1311                                const TargetInstrInfo *TII) {
1312   DebugLoc dl;  // FIXME: this is nowhere
1313   SmallVector<MachineOperand, 0> NoCond;
1314   TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
1315 }
1316 
1317 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1318 /// successors.
1319 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
1320   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1321   SmallVector<MachineOperand, 4> Cond;
1322   if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
1323     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
1324 }
1325 
1326 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1327 /// values defined in MI which are also live/used by MI.
1328 static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1329   const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1330     ->getSubtarget().getRegisterInfo();
1331 
1332   // Before stepping forward past MI, remember which regs were live
1333   // before MI. This is needed to set the Undef flag only when reg is
1334   // dead.
1335   SparseSet<unsigned> LiveBeforeMI;
1336   LiveBeforeMI.setUniverse(TRI->getNumRegs());
1337   for (auto &Reg : Redefs)
1338     LiveBeforeMI.insert(Reg);
1339 
1340   SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1341   Redefs.stepForward(MI, Clobbers);
1342 
1343   // Now add the implicit uses for each of the clobbered values.
1344   for (auto Reg : Clobbers) {
1345     // FIXME: Const cast here is nasty, but better than making StepForward
1346     // take a mutable instruction instead of const.
1347     MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1348     MachineInstr *OpMI = Op.getParent();
1349     MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1350     if (Op.isRegMask()) {
1351       // First handle regmasks.  They clobber any entries in the mask which
1352       // means that we need a def for those registers.
1353       if (LiveBeforeMI.count(Reg.first))
1354         MIB.addReg(Reg.first, RegState::Implicit);
1355 
1356       // We also need to add an implicit def of this register for the later
1357       // use to read from.
1358       // For the register allocator to have allocated a register clobbered
1359       // by the call which is used later, it must be the case that
1360       // the call doesn't return.
1361       MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1362       continue;
1363     }
1364     assert(Op.isReg() && "Register operand required");
1365     if (Op.isDead()) {
1366       // If we found a dead def, but it needs to be live, then remove the dead
1367       // flag.
1368       if (Redefs.contains(Op.getReg()))
1369         Op.setIsDead(false);
1370     }
1371     if (LiveBeforeMI.count(Reg.first))
1372       MIB.addReg(Reg.first, RegState::Implicit);
1373   }
1374 }
1375 
1376 /**
1377  * Remove kill flags from operands with a registers in the @p DontKill set.
1378  */
1379 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
1380   for (MIBundleOperands O(MI); O.isValid(); ++O) {
1381     if (!O->isReg() || !O->isKill())
1382       continue;
1383     if (DontKill.contains(O->getReg()))
1384       O->setIsKill(false);
1385   }
1386 }
1387 
1388 /**
1389  * Walks a range of machine instructions and removes kill flags for registers
1390  * in the @p DontKill set.
1391  */
1392 static void RemoveKills(MachineBasicBlock::iterator I,
1393                         MachineBasicBlock::iterator E,
1394                         const LivePhysRegs &DontKill,
1395                         const MCRegisterInfo &MCRI) {
1396   for ( ; I != E; ++I)
1397     RemoveKills(*I, DontKill);
1398 }
1399 
1400 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1401 ///
1402 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1403   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1404   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1405   BBInfo *CvtBBI = &TrueBBI;
1406   BBInfo *NextBBI = &FalseBBI;
1407 
1408   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1409   if (Kind == ICSimpleFalse)
1410     std::swap(CvtBBI, NextBBI);
1411 
1412   if (CvtBBI->IsDone ||
1413       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1414     // Something has changed. It's no longer safe to predicate this block.
1415     BBI.IsAnalyzed = false;
1416     CvtBBI->IsAnalyzed = false;
1417     return false;
1418   }
1419 
1420   if (CvtBBI->BB->hasAddressTaken())
1421     // Conservatively abort if-conversion if BB's address is taken.
1422     return false;
1423 
1424   if (Kind == ICSimpleFalse)
1425     if (TII->ReverseBranchCondition(Cond))
1426       llvm_unreachable("Unable to reverse branch condition!");
1427 
1428   // Initialize liveins to the first BB. These are potentiall redefined by
1429   // predicated instructions.
1430   Redefs.init(TRI);
1431   Redefs.addLiveIns(*CvtBBI->BB);
1432   Redefs.addLiveIns(*NextBBI->BB);
1433 
1434   // Compute a set of registers which must not be killed by instructions in
1435   // BB1: This is everything live-in to BB2.
1436   DontKill.init(TRI);
1437   DontKill.addLiveIns(*NextBBI->BB);
1438 
1439   if (CvtBBI->BB->pred_size() > 1) {
1440     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1441     // Copy instructions in the true block, predicate them, and add them to
1442     // the entry block.
1443     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1444 
1445     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1446     // explicitly remove CvtBBI as a successor.
1447     BBI.BB->removeSuccessor(CvtBBI->BB, true);
1448   } else {
1449     RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
1450     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1451 
1452     // Merge converted block into entry block.
1453     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1454     MergeBlocks(BBI, *CvtBBI);
1455   }
1456 
1457   bool IterIfcvt = true;
1458   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1459     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1460     BBI.HasFallThrough = false;
1461     // Now ifcvt'd block will look like this:
1462     // BB:
1463     // ...
1464     // t, f = cmp
1465     // if t op
1466     // b BBf
1467     //
1468     // We cannot further ifcvt this block because the unconditional branch
1469     // will have to be predicated on the new condition, that will not be
1470     // available if cmp executes.
1471     IterIfcvt = false;
1472   }
1473 
1474   RemoveExtraEdges(BBI);
1475 
1476   // Update block info. BB can be iteratively if-converted.
1477   if (!IterIfcvt)
1478     BBI.IsDone = true;
1479   InvalidatePreds(BBI.BB);
1480   CvtBBI->IsDone = true;
1481 
1482   // FIXME: Must maintain LiveIns.
1483   return true;
1484 }
1485 
1486 /// IfConvertTriangle - If convert a triangle sub-CFG.
1487 ///
1488 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1489   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1490   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1491   BBInfo *CvtBBI = &TrueBBI;
1492   BBInfo *NextBBI = &FalseBBI;
1493   DebugLoc dl;  // FIXME: this is nowhere
1494 
1495   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1496   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1497     std::swap(CvtBBI, NextBBI);
1498 
1499   if (CvtBBI->IsDone ||
1500       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1501     // Something has changed. It's no longer safe to predicate this block.
1502     BBI.IsAnalyzed = false;
1503     CvtBBI->IsAnalyzed = false;
1504     return false;
1505   }
1506 
1507   if (CvtBBI->BB->hasAddressTaken())
1508     // Conservatively abort if-conversion if BB's address is taken.
1509     return false;
1510 
1511   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1512     if (TII->ReverseBranchCondition(Cond))
1513       llvm_unreachable("Unable to reverse branch condition!");
1514 
1515   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1516     if (ReverseBranchCondition(*CvtBBI)) {
1517       // BB has been changed, modify its predecessors (except for this
1518       // one) so they don't get ifcvt'ed based on bad intel.
1519       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1520              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1521         MachineBasicBlock *PBB = *PI;
1522         if (PBB == BBI.BB)
1523           continue;
1524         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1525         if (PBBI.IsEnqueued) {
1526           PBBI.IsAnalyzed = false;
1527           PBBI.IsEnqueued = false;
1528         }
1529       }
1530     }
1531   }
1532 
1533   // Initialize liveins to the first BB. These are potentially redefined by
1534   // predicated instructions.
1535   Redefs.init(TRI);
1536   Redefs.addLiveIns(*CvtBBI->BB);
1537   Redefs.addLiveIns(*NextBBI->BB);
1538 
1539   DontKill.clear();
1540 
1541   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1542   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1543 
1544   if (HasEarlyExit) {
1545     // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1546     CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1547     CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1548     BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1549     BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
1550   }
1551 
1552   if (CvtBBI->BB->pred_size() > 1) {
1553     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1554     // Copy instructions in the true block, predicate them, and add them to
1555     // the entry block.
1556     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1557 
1558     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1559     // explicitly remove CvtBBI as a successor.
1560     BBI.BB->removeSuccessor(CvtBBI->BB, true);
1561   } else {
1562     // Predicate the 'true' block after removing its branch.
1563     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1564     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1565 
1566     // Now merge the entry of the triangle with the true block.
1567     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1568     MergeBlocks(BBI, *CvtBBI, false);
1569   }
1570 
1571   // If 'true' block has a 'false' successor, add an exit branch to it.
1572   if (HasEarlyExit) {
1573     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1574                                            CvtBBI->BrCond.end());
1575     if (TII->ReverseBranchCondition(RevCond))
1576       llvm_unreachable("Unable to reverse branch condition!");
1577 
1578     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1579     // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1580     //   Prob(BBI.BB, NextBBI->BB) +
1581     //   Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1582     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1583     //   Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1584     auto NewTrueBB = getNextBlock(BBI.BB);
1585     auto NewNext = BBNext + BBCvt * CvtNext;
1586     auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1587     if (NewTrueBBIter != BBI.BB->succ_end())
1588       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1589 
1590     auto NewFalse = BBCvt * CvtFalse;
1591     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1592     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1593   }
1594 
1595   // Merge in the 'false' block if the 'false' block has no other
1596   // predecessors. Otherwise, add an unconditional branch to 'false'.
1597   bool FalseBBDead = false;
1598   bool IterIfcvt = true;
1599   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1600   if (!isFallThrough) {
1601     // Only merge them if the true block does not fallthrough to the false
1602     // block. By not merging them, we make it possible to iteratively
1603     // ifcvt the blocks.
1604     if (!HasEarlyExit &&
1605         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1606         !NextBBI->BB->hasAddressTaken()) {
1607       MergeBlocks(BBI, *NextBBI);
1608       FalseBBDead = true;
1609     } else {
1610       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1611       BBI.HasFallThrough = false;
1612     }
1613     // Mixed predicated and unpredicated code. This cannot be iteratively
1614     // predicated.
1615     IterIfcvt = false;
1616   }
1617 
1618   RemoveExtraEdges(BBI);
1619 
1620   // Update block info. BB can be iteratively if-converted.
1621   if (!IterIfcvt)
1622     BBI.IsDone = true;
1623   InvalidatePreds(BBI.BB);
1624   CvtBBI->IsDone = true;
1625   if (FalseBBDead)
1626     NextBBI->IsDone = true;
1627 
1628   // FIXME: Must maintain LiveIns.
1629   return true;
1630 }
1631 
1632 /// IfConvertDiamondCommon - Common code shared between diamond conversions.
1633 /// BBI, TrueBBI, and FalseBBI form the diamond shape.
1634 /// NumDups1 - number of shared instructions at the beginning of TrueBBI and
1635 ///            FalseBBI
1636 /// NumDups2 - number of shared instructions at the end of TrueBBI and FalseBBI
1637 /// RemoveTrueBranch - Remove the branch of the true block before predicating
1638 ///                    Only false for unanalyzable fallthrough cases.
1639 /// RemoveFalseBranch - Remove the branch of the false block before predicating
1640 ///                     Only false for unanalyzable fallthrough cases.
1641 /// MergeAddEdges - Add successor edges when merging blocks. Only false for
1642 ///                 unanalyzable fallthrough
1643 bool IfConverter::IfConvertDiamondCommon(
1644     BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1645     unsigned NumDups1, unsigned NumDups2,
1646     bool TClobbersPred, bool FClobbersPred,
1647     bool RemoveTrueBranch, bool RemoveFalseBranch,
1648     bool MergeAddEdges) {
1649 
1650   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1651       TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1652     // Something has changed. It's no longer safe to predicate these blocks.
1653     BBI.IsAnalyzed = false;
1654     TrueBBI.IsAnalyzed = false;
1655     FalseBBI.IsAnalyzed = false;
1656     return false;
1657   }
1658 
1659   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1660     // Conservatively abort if-conversion if either BB has its address taken.
1661     return false;
1662 
1663   // Put the predicated instructions from the 'true' block before the
1664   // instructions from the 'false' block, unless the true block would clobber
1665   // the predicate, in which case, do the opposite.
1666   BBInfo *BBI1 = &TrueBBI;
1667   BBInfo *BBI2 = &FalseBBI;
1668   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1669   if (TII->ReverseBranchCondition(RevCond))
1670     llvm_unreachable("Unable to reverse branch condition!");
1671   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1672   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1673 
1674   // Figure out the more profitable ordering.
1675   bool DoSwap = false;
1676   if (TClobbersPred && !FClobbersPred)
1677     DoSwap = true;
1678   else if (TClobbersPred == FClobbersPred) {
1679     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1680       DoSwap = true;
1681   }
1682   if (DoSwap) {
1683     std::swap(BBI1, BBI2);
1684     std::swap(Cond1, Cond2);
1685     std::swap(RemoveTrueBranch, RemoveFalseBranch);
1686   }
1687 
1688   // Remove the conditional branch from entry to the blocks.
1689   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1690 
1691   // Initialize the Redefs:
1692   // - BB2 live-in regs need implicit uses before being redefined by BB1
1693   //   instructions.
1694   // - BB1 live-out regs need implicit uses before being redefined by BB2
1695   //   instructions. We start with BB1 live-ins so we have the live-out regs
1696   //   after tracking the BB1 instructions.
1697   Redefs.init(TRI);
1698   Redefs.addLiveIns(*BBI1->BB);
1699   Redefs.addLiveIns(*BBI2->BB);
1700 
1701   // Remove the duplicated instructions at the beginnings of both paths.
1702   // Skip dbg_value instructions
1703   MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1704   MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
1705   BBI1->NonPredSize -= NumDups1;
1706   BBI2->NonPredSize -= NumDups1;
1707 
1708   // Skip past the dups on each side separately since there may be
1709   // differing dbg_value entries.
1710   for (unsigned i = 0; i < NumDups1; ++DI1) {
1711     if (!DI1->isDebugValue())
1712       ++i;
1713   }
1714   while (NumDups1 != 0) {
1715     ++DI2;
1716     if (!DI2->isDebugValue())
1717       --NumDups1;
1718   }
1719 
1720   // Compute a set of registers which must not be killed by instructions in BB1:
1721   // This is everything used+live in BB2 after the duplicated instructions. We
1722   // can compute this set by simulating liveness backwards from the end of BB2.
1723   DontKill.init(TRI);
1724   for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1725        E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
1726     DontKill.stepBackward(*I);
1727   }
1728 
1729   for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1730        ++I) {
1731     SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1732     Redefs.stepForward(*I, IgnoredClobbers);
1733   }
1734   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1735   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1736 
1737   if (RemoveTrueBranch)
1738     BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1739   // Remove duplicated instructions.
1740   DI1 = BBI1->BB->end();
1741   for (unsigned i = 0; i != NumDups2; ) {
1742     // NumDups2 only counted non-dbg_value instructions, so this won't
1743     // run off the head of the list.
1744     assert (DI1 != BBI1->BB->begin());
1745     --DI1;
1746     // skip dbg_value instructions
1747     if (!DI1->isDebugValue())
1748       ++i;
1749   }
1750   BBI1->BB->erase(DI1, BBI1->BB->end());
1751 
1752   // Kill flags in the true block for registers living into the false block
1753   // must be removed.
1754   RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1755 
1756   // Remove 'false' block branch, and find the last instruction to predicate.
1757   // Save the debug location.
1758   if (RemoveFalseBranch)
1759     BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1760   DI2 = BBI2->BB->end();
1761   while (NumDups2 != 0) {
1762     // NumDups2 only counted non-dbg_value instructions, so this won't
1763     // run off the head of the list.
1764     assert (DI2 != BBI2->BB->begin());
1765     --DI2;
1766     // skip dbg_value instructions
1767     if (!DI2->isDebugValue())
1768       --NumDups2;
1769   }
1770 
1771   // Remember which registers would later be defined by the false block.
1772   // This allows us not to predicate instructions in the true block that would
1773   // later be re-defined. That is, rather than
1774   //   subeq  r0, r1, #1
1775   //   addne  r0, r1, #1
1776   // generate:
1777   //   sub    r0, r1, #1
1778   //   addne  r0, r1, #1
1779   SmallSet<unsigned, 4> RedefsByFalse;
1780   SmallSet<unsigned, 4> ExtUses;
1781   if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1782     for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1783       if (FI->isDebugValue())
1784         continue;
1785       SmallVector<unsigned, 4> Defs;
1786       for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1787         const MachineOperand &MO = FI->getOperand(i);
1788         if (!MO.isReg())
1789           continue;
1790         unsigned Reg = MO.getReg();
1791         if (!Reg)
1792           continue;
1793         if (MO.isDef()) {
1794           Defs.push_back(Reg);
1795         } else if (!RedefsByFalse.count(Reg)) {
1796           // These are defined before ctrl flow reach the 'false' instructions.
1797           // They cannot be modified by the 'true' instructions.
1798           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1799                SubRegs.isValid(); ++SubRegs)
1800             ExtUses.insert(*SubRegs);
1801         }
1802       }
1803 
1804       for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1805         unsigned Reg = Defs[i];
1806         if (!ExtUses.count(Reg)) {
1807           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1808                SubRegs.isValid(); ++SubRegs)
1809             RedefsByFalse.insert(*SubRegs);
1810         }
1811       }
1812     }
1813   }
1814 
1815   // Predicate the 'true' block.
1816   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
1817 
1818   // After predicating BBI1, if there is a predicated terminator in BBI1 and
1819   // a non-predicated in BBI2, then we don't want to predicate the one from
1820   // BBI2. The reason is that if we merged these blocks, we would end up with
1821   // two predicated terminators in the same block.
1822   if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1823     MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1824     MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
1825     if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1826         BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
1827       --DI2;
1828   }
1829 
1830   // Predicate the 'false' block.
1831   PredicateBlock(*BBI2, DI2, *Cond2);
1832 
1833   // Merge the true block into the entry of the diamond.
1834   MergeBlocks(BBI, *BBI1, MergeAddEdges);
1835   MergeBlocks(BBI, *BBI2, MergeAddEdges);
1836   return true;
1837 }
1838 
1839 /// IfConvertForkedDiamond - If convert an almost-diamond sub-CFG where the true
1840 /// and false blocks share a common tail.
1841 bool IfConverter::IfConvertForkedDiamond(
1842     BBInfo &BBI, IfcvtKind Kind,
1843     unsigned NumDups1, unsigned NumDups2,
1844     bool TClobbersPred, bool FClobbersPred) {
1845   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1846   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1847 
1848   // Save the debug location for later.
1849   DebugLoc dl;
1850   MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1851   if (TIE != TrueBBI.BB->end())
1852     dl = TIE->getDebugLoc();
1853   // Removing branches from both blocks is safe, because we have already
1854   // determined that both blocks have the same branch instructions. The branch
1855   // will be added back at the end, unpredicated.
1856   if (!IfConvertDiamondCommon(
1857       BBI, TrueBBI, FalseBBI,
1858       NumDups1, NumDups2,
1859       TClobbersPred, FClobbersPred,
1860       /* RemoveTrueBranch */ true, /* RemoveFalseBranch */ true,
1861       /* MergeAddEdges */ true))
1862     return false;
1863 
1864   // Add back the branch.
1865   // Debug location saved above when removing the branch from BBI2
1866   TII->InsertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1867                     TrueBBI.BrCond, dl);
1868 
1869   RemoveExtraEdges(BBI);
1870 
1871   // Update block info.
1872   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1873   InvalidatePreds(BBI.BB);
1874 
1875   // FIXME: Must maintain LiveIns.
1876   return true;
1877 }
1878 
1879 /// IfConvertDiamond - If convert a diamond sub-CFG.
1880 ///
1881 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1882                                    unsigned NumDups1, unsigned NumDups2) {
1883   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1884   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1885   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1886 
1887   // True block must fall through or end with an unanalyzable terminator.
1888   if (!TailBB) {
1889     if (blockAlwaysFallThrough(TrueBBI))
1890       TailBB = FalseBBI.TrueBB;
1891     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1892   }
1893 
1894   if (!IfConvertDiamondCommon(
1895       BBI, TrueBBI, FalseBBI,
1896       NumDups1, NumDups2,
1897       TrueBBI.ClobbersPred, FalseBBI.ClobbersPred,
1898       /* RemoveTrueBranch */ TrueBBI.IsBrAnalyzable,
1899       /* RemoveFalseBranch */ FalseBBI.IsBrAnalyzable,
1900       /* MergeAddEdges */ TailBB == nullptr))
1901     return false;
1902 
1903   // If the if-converted block falls through or unconditionally branches into
1904   // the tail block, and the tail block does not have other predecessors, then
1905   // fold the tail block in as well. Otherwise, unless it falls through to the
1906   // tail, add a unconditional branch to it.
1907   if (TailBB) {
1908     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1909     bool CanMergeTail = !TailBBI.HasFallThrough &&
1910       !TailBBI.BB->hasAddressTaken();
1911     // The if-converted block can still have a predicated terminator
1912     // (e.g. a predicated return). If that is the case, we cannot merge
1913     // it with the tail block.
1914     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1915     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1916       CanMergeTail = false;
1917     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1918     // check if there are any other predecessors besides those.
1919     unsigned NumPreds = TailBB->pred_size();
1920     if (NumPreds > 1)
1921       CanMergeTail = false;
1922     else if (NumPreds == 1 && CanMergeTail) {
1923       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1924       if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
1925         CanMergeTail = false;
1926     }
1927     if (CanMergeTail) {
1928       MergeBlocks(BBI, TailBBI);
1929       TailBBI.IsDone = true;
1930     } else {
1931       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1932       InsertUncondBranch(BBI.BB, TailBB, TII);
1933       BBI.HasFallThrough = false;
1934     }
1935   }
1936 
1937   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1938   // which can happen here if TailBB is unanalyzable and is merged, so
1939   // explicitly remove BBI1 and BBI2 as successors.
1940   BBI.BB->removeSuccessor(TrueBBI.BB);
1941   BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
1942   RemoveExtraEdges(BBI);
1943 
1944   // Update block info.
1945   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1946   InvalidatePreds(BBI.BB);
1947 
1948   // FIXME: Must maintain LiveIns.
1949   return true;
1950 }
1951 
1952 static bool MaySpeculate(const MachineInstr &MI,
1953                          SmallSet<unsigned, 4> &LaterRedefs) {
1954   bool SawStore = true;
1955   if (!MI.isSafeToMove(nullptr, SawStore))
1956     return false;
1957 
1958   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1959     const MachineOperand &MO = MI.getOperand(i);
1960     if (!MO.isReg())
1961       continue;
1962     unsigned Reg = MO.getReg();
1963     if (!Reg)
1964       continue;
1965     if (MO.isDef() && !LaterRedefs.count(Reg))
1966       return false;
1967   }
1968 
1969   return true;
1970 }
1971 
1972 /// PredicateBlock - Predicate instructions from the start of the block to the
1973 /// specified end with the specified condition.
1974 void IfConverter::PredicateBlock(BBInfo &BBI,
1975                                  MachineBasicBlock::iterator E,
1976                                  SmallVectorImpl<MachineOperand> &Cond,
1977                                  SmallSet<unsigned, 4> *LaterRedefs) {
1978   bool AnyUnpred = false;
1979   bool MaySpec = LaterRedefs != nullptr;
1980   for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1981     if (I.isDebugValue() || TII->isPredicated(I))
1982       continue;
1983     // It may be possible not to predicate an instruction if it's the 'true'
1984     // side of a diamond and the 'false' side may re-define the instruction's
1985     // defs.
1986     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
1987       AnyUnpred = true;
1988       continue;
1989     }
1990     // If any instruction is predicated, then every instruction after it must
1991     // be predicated.
1992     MaySpec = false;
1993     if (!TII->PredicateInstruction(I, Cond)) {
1994 #ifndef NDEBUG
1995       dbgs() << "Unable to predicate " << I << "!\n";
1996 #endif
1997       llvm_unreachable(nullptr);
1998     }
1999 
2000     // If the predicated instruction now redefines a register as the result of
2001     // if-conversion, add an implicit kill.
2002     UpdatePredRedefs(I, Redefs);
2003   }
2004 
2005   BBI.Predicate.append(Cond.begin(), Cond.end());
2006 
2007   BBI.IsAnalyzed = false;
2008   BBI.NonPredSize = 0;
2009 
2010   ++NumIfConvBBs;
2011   if (AnyUnpred)
2012     ++NumUnpred;
2013 }
2014 
2015 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
2016 /// the destination block. Skip end of block branches if IgnoreBr is true.
2017 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2018                                         SmallVectorImpl<MachineOperand> &Cond,
2019                                         bool IgnoreBr) {
2020   MachineFunction &MF = *ToBBI.BB->getParent();
2021 
2022   for (auto &I : *FromBBI.BB) {
2023     // Do not copy the end of the block branches.
2024     if (IgnoreBr && I.isBranch())
2025       break;
2026 
2027     MachineInstr *MI = MF.CloneMachineInstr(&I);
2028     ToBBI.BB->insert(ToBBI.BB->end(), MI);
2029     ToBBI.NonPredSize++;
2030     unsigned ExtraPredCost = TII->getPredicationCost(I);
2031     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2032     if (NumCycles > 1)
2033       ToBBI.ExtraCost += NumCycles-1;
2034     ToBBI.ExtraCost2 += ExtraPredCost;
2035 
2036     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
2037       if (!TII->PredicateInstruction(*MI, Cond)) {
2038 #ifndef NDEBUG
2039         dbgs() << "Unable to predicate " << I << "!\n";
2040 #endif
2041         llvm_unreachable(nullptr);
2042       }
2043     }
2044 
2045     // If the predicated instruction now redefines a register as the result of
2046     // if-conversion, add an implicit kill.
2047     UpdatePredRedefs(*MI, Redefs);
2048 
2049     // Some kill flags may not be correct anymore.
2050     if (!DontKill.empty())
2051       RemoveKills(*MI, DontKill);
2052   }
2053 
2054   if (!IgnoreBr) {
2055     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
2056                                            FromBBI.BB->succ_end());
2057     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
2058     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2059 
2060     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
2061       MachineBasicBlock *Succ = Succs[i];
2062       // Fallthrough edge can't be transferred.
2063       if (Succ == FallThrough)
2064         continue;
2065       ToBBI.BB->addSuccessor(Succ);
2066     }
2067   }
2068 
2069   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2070   ToBBI.Predicate.append(Cond.begin(), Cond.end());
2071 
2072   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2073   ToBBI.IsAnalyzed = false;
2074 
2075   ++NumDupBBs;
2076 }
2077 
2078 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
2079 /// This will leave FromBB as an empty block, so remove all of its
2080 /// successor edges except for the fall-through edge.  If AddEdges is true,
2081 /// i.e., when FromBBI's branch is being moved, add those successor edges to
2082 /// ToBBI.
2083 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2084   assert(!FromBBI.BB->hasAddressTaken() &&
2085          "Removing a BB whose address is taken!");
2086 
2087   // In case FromBBI.BB contains terminators (e.g. return instruction),
2088   // first move the non-terminator instructions, then the terminators.
2089   MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
2090   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2091   ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
2092 
2093   // If FromBB has non-predicated terminator we should copy it at the end.
2094   if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
2095     ToTI = ToBBI.BB->end();
2096   ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
2097 
2098   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2099   // unknown probabilities into known ones.
2100   // FIXME: This usage is too tricky and in the future we would like to
2101   // eliminate all unknown probabilities in MBB.
2102   ToBBI.BB->normalizeSuccProbs();
2103 
2104   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
2105                                                 FromBBI.BB->succ_end());
2106   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
2107   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2108   // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
2109   // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
2110   auto To2FromProb = BranchProbability::getZero();
2111   if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
2112     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
2113     // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
2114     // edge probability being merged to other edges when this edge is removed
2115     // later.
2116     ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), FromBBI.BB),
2117                                  BranchProbability::getZero());
2118   }
2119 
2120   for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
2121     MachineBasicBlock *Succ = FromSuccs[i];
2122     // Fallthrough edge can't be transferred.
2123     if (Succ == FallThrough)
2124       continue;
2125 
2126     auto NewProb = BranchProbability::getZero();
2127     if (AddEdges) {
2128       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2129       // which is a portion of the edge probability from FromBBI.BB to Succ. The
2130       // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
2131       // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
2132       NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
2133 
2134       // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
2135       // only happens when if-converting a diamond CFG and FromBBI.BB is the
2136       // tail BB.  In this case FromBBI.BB post-dominates ToBBI.BB and hence we
2137       // could just use the probabilities on FromBBI.BB's out-edges when adding
2138       // new successors.
2139       if (!To2FromProb.isZero())
2140         NewProb *= To2FromProb;
2141     }
2142 
2143     FromBBI.BB->removeSuccessor(Succ);
2144 
2145     if (AddEdges) {
2146       // If the edge from ToBBI.BB to Succ already exists, update the
2147       // probability of this edge by adding NewProb to it. An example is shown
2148       // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
2149       // don't have to set C as A's successor as it already is. We only need to
2150       // update the edge probability on A->C. Note that B will not be
2151       // immediately removed from A's successors. It is possible that B->D is
2152       // not removed either if D is a fallthrough of B. Later the edge A->D
2153       // (generated here) and B->D will be combined into one edge. To maintain
2154       // correct edge probability of this combined edge, we need to set the edge
2155       // probability of A->B to zero, which is already done above. The edge
2156       // probability on A->D is calculated by scaling the original probability
2157       // on A->B by the probability of B->D.
2158       //
2159       // Before ifcvt:      After ifcvt (assume B->D is kept):
2160       //
2161       //       A                A
2162       //      /|               /|\
2163       //     / B              / B|
2164       //    | /|             |  ||
2165       //    |/ |             |  |/
2166       //    C  D             C  D
2167       //
2168       if (ToBBI.BB->isSuccessor(Succ))
2169         ToBBI.BB->setSuccProbability(
2170             find(ToBBI.BB->successors(), Succ),
2171             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2172       else
2173         ToBBI.BB->addSuccessor(Succ, NewProb);
2174     }
2175   }
2176 
2177   // Now FromBBI always falls through to the next block!
2178   if (NBB && !FromBBI.BB->isSuccessor(NBB))
2179     FromBBI.BB->addSuccessor(NBB);
2180 
2181   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2182   // we've done above.
2183   ToBBI.BB->normalizeSuccProbs();
2184 
2185   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2186   FromBBI.Predicate.clear();
2187 
2188   ToBBI.NonPredSize += FromBBI.NonPredSize;
2189   ToBBI.ExtraCost += FromBBI.ExtraCost;
2190   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2191   FromBBI.NonPredSize = 0;
2192   FromBBI.ExtraCost = 0;
2193   FromBBI.ExtraCost2 = 0;
2194 
2195   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2196   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2197   ToBBI.IsAnalyzed = false;
2198   FromBBI.IsAnalyzed = false;
2199 }
2200 
2201 FunctionPass *
2202 llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
2203   return new IfConverter(std::move(Ftor));
2204 }
2205