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