xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/IfConversion.cpp (revision f976241773df2260e6170317080761d1c5814fe5)
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.IsBeingAnalyzed || TrueBBI.IsDone)
573     return false;
574 
575   if (TrueBBI.BB->pred_size() > 1) {
576     if (TrueBBI.CannotBeCopied)
577       return false;
578 
579     unsigned Size = TrueBBI.NonPredSize;
580     if (TrueBBI.IsBrAnalyzable) {
581       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
582         // Ends with an unconditional branch. It will be removed.
583         --Size;
584       else {
585         MachineBasicBlock *FExit = FalseBranch
586           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
587         if (FExit)
588           // Require a conditional branch
589           ++Size;
590       }
591     }
592     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
593       return false;
594     Dups = Size;
595   }
596 
597   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
598   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
599     MachineFunction::iterator I = TrueBBI.BB->getIterator();
600     if (++I == TrueBBI.BB->getParent()->end())
601       return false;
602     TExit = &*I;
603   }
604   return TExit && TExit == FalseBBI.BB;
605 }
606 
607 /// Count duplicated instructions and move the iterators to show where they
608 /// are.
609 /// @param TIB True Iterator Begin
610 /// @param FIB False Iterator Begin
611 /// These two iterators initially point to the first instruction of the two
612 /// blocks, and finally point to the first non-shared instruction.
613 /// @param TIE True Iterator End
614 /// @param FIE False Iterator End
615 /// These two iterators initially point to End() for the two blocks() and
616 /// finally point to the first shared instruction in the tail.
617 /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
618 /// two blocks.
619 /// @param Dups1 count of duplicated instructions at the beginning of the 2
620 /// blocks.
621 /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
622 /// @param SkipUnconditionalBranches if true, Don't make sure that
623 /// unconditional branches at the end of the blocks are the same. True is
624 /// passed when the blocks are analyzable to allow for fallthrough to be
625 /// handled.
626 /// @return false if the shared portion prevents if conversion.
627 bool IfConverter::CountDuplicatedInstructions(
628     MachineBasicBlock::iterator &TIB,
629     MachineBasicBlock::iterator &FIB,
630     MachineBasicBlock::iterator &TIE,
631     MachineBasicBlock::iterator &FIE,
632     unsigned &Dups1, unsigned &Dups2,
633     MachineBasicBlock &TBB, MachineBasicBlock &FBB,
634     bool SkipUnconditionalBranches) const {
635   while (TIB != TIE && FIB != FIE) {
636     // Skip dbg_value instructions. These do not count.
637     TIB = skipDebugInstructionsForward(TIB, TIE);
638     FIB = skipDebugInstructionsForward(FIB, FIE);
639     if (TIB == TIE || FIB == FIE)
640       break;
641     if (!TIB->isIdenticalTo(*FIB))
642       break;
643     // A pred-clobbering instruction in the shared portion prevents
644     // if-conversion.
645     std::vector<MachineOperand> PredDefs;
646     if (TII->DefinesPredicate(*TIB, PredDefs))
647       return false;
648     // If we get all the way to the branch instructions, don't count them.
649     if (!TIB->isBranch())
650       ++Dups1;
651     ++TIB;
652     ++FIB;
653   }
654 
655   // Check for already containing all of the block.
656   if (TIB == TIE || FIB == FIE)
657     return true;
658   // Now, in preparation for counting duplicate instructions at the ends of the
659   // blocks, switch to reverse_iterators. Note that getReverse() returns an
660   // iterator that points to the same instruction, unlike std::reverse_iterator.
661   // We have to do our own shifting so that we get the same range.
662   MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
663   MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
664   const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
665   const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
666 
667   if (!TBB.succ_empty() || !FBB.succ_empty()) {
668     if (SkipUnconditionalBranches) {
669       while (RTIE != RTIB && RTIE->isUnconditionalBranch())
670         ++RTIE;
671       while (RFIE != RFIB && RFIE->isUnconditionalBranch())
672         ++RFIE;
673     }
674   }
675 
676   // Count duplicate instructions at the ends of the blocks.
677   while (RTIE != RTIB && RFIE != RFIB) {
678     // Skip dbg_value instructions. These do not count.
679     // Note that these are reverse iterators going forward.
680     RTIE = skipDebugInstructionsForward(RTIE, RTIB);
681     RFIE = skipDebugInstructionsForward(RFIE, RFIB);
682     if (RTIE == RTIB || RFIE == RFIB)
683       break;
684     if (!RTIE->isIdenticalTo(*RFIE))
685       break;
686     // We have to verify that any branch instructions are the same, and then we
687     // don't count them toward the # of duplicate instructions.
688     if (!RTIE->isBranch())
689       ++Dups2;
690     ++RTIE;
691     ++RFIE;
692   }
693   TIE = std::next(RTIE.getReverse());
694   FIE = std::next(RFIE.getReverse());
695   return true;
696 }
697 
698 /// RescanInstructions - Run ScanInstructions on a pair of blocks.
699 /// @param TIB - True Iterator Begin, points to first non-shared instruction
700 /// @param FIB - False Iterator Begin, points to first non-shared instruction
701 /// @param TIE - True Iterator End, points past last non-shared instruction
702 /// @param FIE - False Iterator End, points past last non-shared instruction
703 /// @param TrueBBI  - BBInfo to update for the true block.
704 /// @param FalseBBI - BBInfo to update for the false block.
705 /// @returns - false if either block cannot be predicated or if both blocks end
706 ///   with a predicate-clobbering instruction.
707 bool IfConverter::RescanInstructions(
708     MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
709     MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
710     BBInfo &TrueBBI, BBInfo &FalseBBI) const {
711   bool BranchUnpredicable = true;
712   TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
713   ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
714   if (TrueBBI.IsUnpredicable)
715     return false;
716   ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
717   if (FalseBBI.IsUnpredicable)
718     return false;
719   if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
720     return false;
721   return true;
722 }
723 
724 #ifndef NDEBUG
725 static void verifySameBranchInstructions(
726     MachineBasicBlock *MBB1,
727     MachineBasicBlock *MBB2) {
728   const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
729   const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
730   MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
731   MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
732   while (E1 != B1 && E2 != B2) {
733     skipDebugInstructionsForward(E1, B1);
734     skipDebugInstructionsForward(E2, B2);
735     if (E1 == B1 && E2 == B2)
736       break;
737 
738     if (E1 == B1) {
739       assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
740       break;
741     }
742     if (E2 == B2) {
743       assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
744       break;
745     }
746 
747     if (E1->isBranch() || E2->isBranch())
748       assert(E1->isIdenticalTo(*E2) &&
749              "Branch mis-match, branch instructions don't match.");
750     else
751       break;
752     ++E1;
753     ++E2;
754   }
755 }
756 #endif
757 
758 /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
759 /// with their common predecessor) form a diamond if a common tail block is
760 /// extracted.
761 /// While not strictly a diamond, this pattern would form a diamond if
762 /// tail-merging had merged the shared tails.
763 ///           EBB
764 ///         _/   \_
765 ///         |     |
766 ///        TBB   FBB
767 ///        /  \ /   \
768 ///  FalseBB TrueBB FalseBB
769 /// Currently only handles analyzable branches.
770 /// Specifically excludes actual diamonds to avoid overlap.
771 bool IfConverter::ValidForkedDiamond(
772     BBInfo &TrueBBI, BBInfo &FalseBBI,
773     unsigned &Dups1, unsigned &Dups2,
774     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
775   Dups1 = Dups2 = 0;
776   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
777       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
778     return false;
779 
780   if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
781     return false;
782   // Don't IfConvert blocks that can't be folded into their predecessor.
783   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
784     return false;
785 
786   // This function is specifically looking for conditional tails, as
787   // unconditional tails are already handled by the standard diamond case.
788   if (TrueBBI.BrCond.size() == 0 ||
789       FalseBBI.BrCond.size() == 0)
790     return false;
791 
792   MachineBasicBlock *TT = TrueBBI.TrueBB;
793   MachineBasicBlock *TF = TrueBBI.FalseBB;
794   MachineBasicBlock *FT = FalseBBI.TrueBB;
795   MachineBasicBlock *FF = FalseBBI.FalseBB;
796 
797   if (!TT)
798     TT = getNextBlock(*TrueBBI.BB);
799   if (!TF)
800     TF = getNextBlock(*TrueBBI.BB);
801   if (!FT)
802     FT = getNextBlock(*FalseBBI.BB);
803   if (!FF)
804     FF = getNextBlock(*FalseBBI.BB);
805 
806   if (!TT || !TF)
807     return false;
808 
809   // Check successors. If they don't match, bail.
810   if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
811     return false;
812 
813   bool FalseReversed = false;
814   if (TF == FT && TT == FF) {
815     // If the branches are opposing, but we can't reverse, don't do it.
816     if (!FalseBBI.IsBrReversible)
817       return false;
818     FalseReversed = true;
819     reverseBranchCondition(FalseBBI);
820   }
821   auto UnReverseOnExit = make_scope_exit([&]() {
822     if (FalseReversed)
823       reverseBranchCondition(FalseBBI);
824   });
825 
826   // Count duplicate instructions at the beginning of the true and false blocks.
827   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
828   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
829   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
830   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
831   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
832                                   *TrueBBI.BB, *FalseBBI.BB,
833                                   /* SkipUnconditionalBranches */ true))
834     return false;
835 
836   TrueBBICalc.BB = TrueBBI.BB;
837   FalseBBICalc.BB = FalseBBI.BB;
838   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
839     return false;
840 
841   // The size is used to decide whether to if-convert, and the shared portions
842   // are subtracted off. Because of the subtraction, we just use the size that
843   // was calculated by the original ScanInstructions, as it is correct.
844   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
845   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
846   return true;
847 }
848 
849 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
850 /// with their common predecessor) forms a valid diamond shape for ifcvt.
851 bool IfConverter::ValidDiamond(
852     BBInfo &TrueBBI, BBInfo &FalseBBI,
853     unsigned &Dups1, unsigned &Dups2,
854     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
855   Dups1 = Dups2 = 0;
856   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
857       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
858     return false;
859 
860   MachineBasicBlock *TT = TrueBBI.TrueBB;
861   MachineBasicBlock *FT = FalseBBI.TrueBB;
862 
863   if (!TT && blockAlwaysFallThrough(TrueBBI))
864     TT = getNextBlock(*TrueBBI.BB);
865   if (!FT && blockAlwaysFallThrough(FalseBBI))
866     FT = getNextBlock(*FalseBBI.BB);
867   if (TT != FT)
868     return false;
869   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
870     return false;
871   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
872     return false;
873 
874   // FIXME: Allow true block to have an early exit?
875   if (TrueBBI.FalseBB || FalseBBI.FalseBB)
876     return false;
877 
878   // Count duplicate instructions at the beginning and end of the true and
879   // false blocks.
880   // Skip unconditional branches only if we are considering an analyzable
881   // diamond. Otherwise the branches must be the same.
882   bool SkipUnconditionalBranches =
883       TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
884   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
885   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
886   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
887   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
888   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
889                                   *TrueBBI.BB, *FalseBBI.BB,
890                                   SkipUnconditionalBranches))
891     return false;
892 
893   TrueBBICalc.BB = TrueBBI.BB;
894   FalseBBICalc.BB = FalseBBI.BB;
895   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
896     return false;
897   // The size is used to decide whether to if-convert, and the shared portions
898   // are subtracted off. Because of the subtraction, we just use the size that
899   // was calculated by the original ScanInstructions, as it is correct.
900   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
901   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
902   return true;
903 }
904 
905 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
906 /// the block is predicable.
907 void IfConverter::AnalyzeBranches(BBInfo &BBI) {
908   if (BBI.IsDone)
909     return;
910 
911   BBI.TrueBB = BBI.FalseBB = nullptr;
912   BBI.BrCond.clear();
913   BBI.IsBrAnalyzable =
914       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
915   if (!BBI.IsBrAnalyzable) {
916     BBI.TrueBB = nullptr;
917     BBI.FalseBB = nullptr;
918     BBI.BrCond.clear();
919   }
920 
921   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
922   BBI.IsBrReversible = (RevCond.size() == 0) ||
923       !TII->reverseBranchCondition(RevCond);
924   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
925 
926   if (BBI.BrCond.size()) {
927     // No false branch. This BB must end with a conditional branch and a
928     // fallthrough.
929     if (!BBI.FalseBB)
930       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
931     if (!BBI.FalseBB) {
932       // Malformed bcc? True and false blocks are the same?
933       BBI.IsUnpredicable = true;
934     }
935   }
936 }
937 
938 /// ScanInstructions - Scan all the instructions in the block to determine if
939 /// the block is predicable. In most cases, that means all the instructions
940 /// in the block are isPredicable(). Also checks if the block contains any
941 /// instruction which can clobber a predicate (e.g. condition code register).
942 /// If so, the block is not predicable unless it's the last instruction.
943 void IfConverter::ScanInstructions(BBInfo &BBI,
944                                    MachineBasicBlock::iterator &Begin,
945                                    MachineBasicBlock::iterator &End,
946                                    bool BranchUnpredicable) const {
947   if (BBI.IsDone || BBI.IsUnpredicable)
948     return;
949 
950   bool AlreadyPredicated = !BBI.Predicate.empty();
951 
952   BBI.NonPredSize = 0;
953   BBI.ExtraCost = 0;
954   BBI.ExtraCost2 = 0;
955   BBI.ClobbersPred = false;
956   for (MachineInstr &MI : make_range(Begin, End)) {
957     if (MI.isDebugInstr())
958       continue;
959 
960     // It's unsafe to duplicate convergent instructions in this context, so set
961     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
962     // following CFG, which is subject to our "simple" transformation.
963     //
964     //    BB0     // if (c1) goto BB1; else goto BB2;
965     //   /   \
966     //  BB1   |
967     //   |   BB2  // if (c2) goto TBB; else goto FBB;
968     //   |   / |
969     //   |  /  |
970     //   TBB   |
971     //    |    |
972     //    |   FBB
973     //    |
974     //    exit
975     //
976     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
977     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
978     // TBB contains a convergent instruction.  This is safe iff doing so does
979     // not add a control-flow dependency to the convergent instruction -- i.e.,
980     // it's safe iff the set of control flows that leads us to the convergent
981     // instruction does not get smaller after the transformation.
982     //
983     // Originally we executed TBB if c1 || c2.  After the transformation, there
984     // are two copies of TBB's instructions.  We get to the first if c1, and we
985     // get to the second if !c1 && c2.
986     //
987     // There are clearly fewer ways to satisfy the condition "c1" than
988     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
989     // our convergent instruction, the transformation is unsafe.
990     if (MI.isNotDuplicable() || MI.isConvergent())
991       BBI.CannotBeCopied = true;
992 
993     bool isPredicated = TII->isPredicated(MI);
994     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
995 
996     if (BranchUnpredicable && MI.isBranch()) {
997       BBI.IsUnpredicable = true;
998       return;
999     }
1000 
1001     // A conditional branch is not predicable, but it may be eliminated.
1002     if (isCondBr)
1003       continue;
1004 
1005     if (!isPredicated) {
1006       BBI.NonPredSize++;
1007       unsigned ExtraPredCost = TII->getPredicationCost(MI);
1008       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1009       if (NumCycles > 1)
1010         BBI.ExtraCost += NumCycles-1;
1011       BBI.ExtraCost2 += ExtraPredCost;
1012     } else if (!AlreadyPredicated) {
1013       // FIXME: This instruction is already predicated before the
1014       // if-conversion pass. It's probably something like a conditional move.
1015       // Mark this block unpredicable for now.
1016       BBI.IsUnpredicable = true;
1017       return;
1018     }
1019 
1020     if (BBI.ClobbersPred && !isPredicated) {
1021       // Predicate modification instruction should end the block (except for
1022       // already predicated instructions and end of block branches).
1023       // Predicate may have been modified, the subsequent (currently)
1024       // unpredicated instructions cannot be correctly predicated.
1025       BBI.IsUnpredicable = true;
1026       return;
1027     }
1028 
1029     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1030     // still potentially predicable.
1031     std::vector<MachineOperand> PredDefs;
1032     if (TII->DefinesPredicate(MI, PredDefs))
1033       BBI.ClobbersPred = true;
1034 
1035     if (!TII->isPredicable(MI)) {
1036       BBI.IsUnpredicable = true;
1037       return;
1038     }
1039   }
1040 }
1041 
1042 /// Determine if the block is a suitable candidate to be predicated by the
1043 /// specified predicate.
1044 /// @param BBI BBInfo for the block to check
1045 /// @param Pred Predicate array for the branch that leads to BBI
1046 /// @param isTriangle true if the Analysis is for a triangle
1047 /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1048 ///        case
1049 /// @param hasCommonTail true if BBI shares a tail with a sibling block that
1050 ///        contains any instruction that would make the block unpredicable.
1051 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1052                                       SmallVectorImpl<MachineOperand> &Pred,
1053                                       bool isTriangle, bool RevBranch,
1054                                       bool hasCommonTail) {
1055   // If the block is dead or unpredicable, then it cannot be predicated.
1056   // Two blocks may share a common unpredicable tail, but this doesn't prevent
1057   // them from being if-converted. The non-shared portion is assumed to have
1058   // been checked
1059   if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1060     return false;
1061 
1062   // If it is already predicated but we couldn't analyze its terminator, the
1063   // latter might fallthrough, but we can't determine where to.
1064   // Conservatively avoid if-converting again.
1065   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1066     return false;
1067 
1068   // If it is already predicated, check if the new predicate subsumes
1069   // its predicate.
1070   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1071     return false;
1072 
1073   if (!hasCommonTail && BBI.BrCond.size()) {
1074     if (!isTriangle)
1075       return false;
1076 
1077     // Test predicate subsumption.
1078     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1079     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1080     if (RevBranch) {
1081       if (TII->reverseBranchCondition(Cond))
1082         return false;
1083     }
1084     if (TII->reverseBranchCondition(RevPred) ||
1085         !TII->SubsumesPredicate(Cond, RevPred))
1086       return false;
1087   }
1088 
1089   return true;
1090 }
1091 
1092 /// Analyze the structure of the sub-CFG starting from the specified block.
1093 /// Record its successors and whether it looks like an if-conversion candidate.
1094 void IfConverter::AnalyzeBlock(
1095     MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1096   struct BBState {
1097     BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
1098     MachineBasicBlock *MBB;
1099 
1100     /// This flag is true if MBB's successors have been analyzed.
1101     bool SuccsAnalyzed;
1102   };
1103 
1104   // Push MBB to the stack.
1105   SmallVector<BBState, 16> BBStack(1, MBB);
1106 
1107   while (!BBStack.empty()) {
1108     BBState &State = BBStack.back();
1109     MachineBasicBlock *BB = State.MBB;
1110     BBInfo &BBI = BBAnalysis[BB->getNumber()];
1111 
1112     if (!State.SuccsAnalyzed) {
1113       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1114         BBStack.pop_back();
1115         continue;
1116       }
1117 
1118       BBI.BB = BB;
1119       BBI.IsBeingAnalyzed = true;
1120 
1121       AnalyzeBranches(BBI);
1122       MachineBasicBlock::iterator Begin = BBI.BB->begin();
1123       MachineBasicBlock::iterator End = BBI.BB->end();
1124       ScanInstructions(BBI, Begin, End);
1125 
1126       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1127       // not considered for ifcvt anymore.
1128       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1129         BBI.IsBeingAnalyzed = false;
1130         BBI.IsAnalyzed = true;
1131         BBStack.pop_back();
1132         continue;
1133       }
1134 
1135       // Do not ifcvt if either path is a back edge to the entry block.
1136       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1137         BBI.IsBeingAnalyzed = false;
1138         BBI.IsAnalyzed = true;
1139         BBStack.pop_back();
1140         continue;
1141       }
1142 
1143       // Do not ifcvt if true and false fallthrough blocks are the same.
1144       if (!BBI.FalseBB) {
1145         BBI.IsBeingAnalyzed = false;
1146         BBI.IsAnalyzed = true;
1147         BBStack.pop_back();
1148         continue;
1149       }
1150 
1151       // Push the False and True blocks to the stack.
1152       State.SuccsAnalyzed = true;
1153       BBStack.push_back(*BBI.FalseBB);
1154       BBStack.push_back(*BBI.TrueBB);
1155       continue;
1156     }
1157 
1158     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1159     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1160 
1161     if (TrueBBI.IsDone && FalseBBI.IsDone) {
1162       BBI.IsBeingAnalyzed = false;
1163       BBI.IsAnalyzed = true;
1164       BBStack.pop_back();
1165       continue;
1166     }
1167 
1168     SmallVector<MachineOperand, 4>
1169         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1170     bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1171 
1172     unsigned Dups = 0;
1173     unsigned Dups2 = 0;
1174     bool TNeedSub = !TrueBBI.Predicate.empty();
1175     bool FNeedSub = !FalseBBI.Predicate.empty();
1176     bool Enqueued = false;
1177 
1178     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1179 
1180     if (CanRevCond) {
1181       BBInfo TrueBBICalc, FalseBBICalc;
1182       auto feasibleDiamond = [&]() {
1183         bool MeetsSize = MeetIfcvtSizeLimit(
1184             *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1185                           TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1186             *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1187                            FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1188             Prediction);
1189         bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1190                                                 /* IsTriangle */ false, /* RevCond */ false,
1191                                                 /* hasCommonTail */ true);
1192         bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1193                                                  /* IsTriangle */ false, /* RevCond */ false,
1194                                                  /* hasCommonTail */ true);
1195         return MeetsSize && TrueFeasible && FalseFeasible;
1196       };
1197 
1198       if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1199                        TrueBBICalc, FalseBBICalc)) {
1200         if (feasibleDiamond()) {
1201           // Diamond:
1202           //   EBB
1203           //   / \_
1204           //  |   |
1205           // TBB FBB
1206           //   \ /
1207           //  TailBB
1208           // Note TailBB can be empty.
1209           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1210               BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1211               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1212           Enqueued = true;
1213         }
1214       } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1215                                     TrueBBICalc, FalseBBICalc)) {
1216         if (feasibleDiamond()) {
1217           // ForkedDiamond:
1218           // if TBB and FBB have a common tail that includes their conditional
1219           // branch instructions, then we can If Convert this pattern.
1220           //          EBB
1221           //         _/ \_
1222           //         |   |
1223           //        TBB  FBB
1224           //        / \ /   \
1225           //  FalseBB TrueBB FalseBB
1226           //
1227           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1228               BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1229               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1230           Enqueued = true;
1231         }
1232       }
1233     }
1234 
1235     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1236         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1237                            TrueBBI.ExtraCost2, Prediction) &&
1238         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1239       // Triangle:
1240       //   EBB
1241       //   | \_
1242       //   |  |
1243       //   | TBB
1244       //   |  /
1245       //   FBB
1246       Tokens.push_back(
1247           llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1248       Enqueued = true;
1249     }
1250 
1251     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1252         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1253                            TrueBBI.ExtraCost2, Prediction) &&
1254         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1255       Tokens.push_back(
1256           llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1257       Enqueued = true;
1258     }
1259 
1260     if (ValidSimple(TrueBBI, Dups, Prediction) &&
1261         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1262                            TrueBBI.ExtraCost2, Prediction) &&
1263         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1264       // Simple (split, no rejoin):
1265       //   EBB
1266       //   | \_
1267       //   |  |
1268       //   | TBB---> exit
1269       //   |
1270       //   FBB
1271       Tokens.push_back(
1272           llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1273       Enqueued = true;
1274     }
1275 
1276     if (CanRevCond) {
1277       // Try the other path...
1278       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1279                         Prediction.getCompl()) &&
1280           MeetIfcvtSizeLimit(*FalseBBI.BB,
1281                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1282                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1283           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1284         Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1285                                                        FNeedSub, Dups));
1286         Enqueued = true;
1287       }
1288 
1289       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1290                         Prediction.getCompl()) &&
1291           MeetIfcvtSizeLimit(*FalseBBI.BB,
1292                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1293                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1294         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1295         Tokens.push_back(
1296             llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1297         Enqueued = true;
1298       }
1299 
1300       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1301           MeetIfcvtSizeLimit(*FalseBBI.BB,
1302                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1303                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1304           FeasibilityAnalysis(FalseBBI, RevCond)) {
1305         Tokens.push_back(
1306             llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1307         Enqueued = true;
1308       }
1309     }
1310 
1311     BBI.IsEnqueued = Enqueued;
1312     BBI.IsBeingAnalyzed = false;
1313     BBI.IsAnalyzed = true;
1314     BBStack.pop_back();
1315   }
1316 }
1317 
1318 /// Analyze all blocks and find entries for all if-conversion candidates.
1319 void IfConverter::AnalyzeBlocks(
1320     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1321   for (MachineBasicBlock &MBB : MF)
1322     AnalyzeBlock(MBB, Tokens);
1323 
1324   // Sort to favor more complex ifcvt scheme.
1325   llvm::stable_sort(Tokens, IfcvtTokenCmp);
1326 }
1327 
1328 /// Returns true either if ToMBB is the next block after MBB or that all the
1329 /// intervening blocks are empty (given MBB can fall through to its next block).
1330 static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1331   MachineFunction::iterator PI = MBB.getIterator();
1332   MachineFunction::iterator I = std::next(PI);
1333   MachineFunction::iterator TI = ToMBB.getIterator();
1334   MachineFunction::iterator E = MBB.getParent()->end();
1335   while (I != TI) {
1336     // Check isSuccessor to avoid case where the next block is empty, but
1337     // it's not a successor.
1338     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1339       return false;
1340     PI = I++;
1341   }
1342   // Finally see if the last I is indeed a successor to PI.
1343   return PI->isSuccessor(&*I);
1344 }
1345 
1346 /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1347 /// can be if-converted. If predecessor is already enqueued, dequeue it!
1348 void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1349   for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1350     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1351     if (PBBI.IsDone || PBBI.BB == &MBB)
1352       continue;
1353     PBBI.IsAnalyzed = false;
1354     PBBI.IsEnqueued = false;
1355   }
1356 }
1357 
1358 /// Inserts an unconditional branch from \p MBB to \p ToMBB.
1359 static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
1360                                const TargetInstrInfo *TII) {
1361   DebugLoc dl;  // FIXME: this is nowhere
1362   SmallVector<MachineOperand, 0> NoCond;
1363   TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1364 }
1365 
1366 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1367 /// values defined in MI which are also live/used by MI.
1368 static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1369   const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
1370 
1371   // Before stepping forward past MI, remember which regs were live
1372   // before MI. This is needed to set the Undef flag only when reg is
1373   // dead.
1374   SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
1375   LiveBeforeMI.setUniverse(TRI->getNumRegs());
1376   for (unsigned Reg : Redefs)
1377     LiveBeforeMI.insert(Reg);
1378 
1379   SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
1380   Redefs.stepForward(MI, Clobbers);
1381 
1382   // Now add the implicit uses for each of the clobbered values.
1383   for (auto Clobber : Clobbers) {
1384     // FIXME: Const cast here is nasty, but better than making StepForward
1385     // take a mutable instruction instead of const.
1386     unsigned Reg = Clobber.first;
1387     MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1388     MachineInstr *OpMI = Op.getParent();
1389     MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
1390     if (Op.isRegMask()) {
1391       // First handle regmasks.  They clobber any entries in the mask which
1392       // means that we need a def for those registers.
1393       if (LiveBeforeMI.count(Reg))
1394         MIB.addReg(Reg, RegState::Implicit);
1395 
1396       // We also need to add an implicit def of this register for the later
1397       // use to read from.
1398       // For the register allocator to have allocated a register clobbered
1399       // by the call which is used later, it must be the case that
1400       // the call doesn't return.
1401       MIB.addReg(Reg, RegState::Implicit | RegState::Define);
1402       continue;
1403     }
1404     if (LiveBeforeMI.count(Reg))
1405       MIB.addReg(Reg, RegState::Implicit);
1406     else {
1407       bool HasLiveSubReg = false;
1408       for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1409         if (!LiveBeforeMI.count(*S))
1410           continue;
1411         HasLiveSubReg = true;
1412         break;
1413       }
1414       if (HasLiveSubReg)
1415         MIB.addReg(Reg, RegState::Implicit);
1416     }
1417   }
1418 }
1419 
1420 /// If convert a simple (split, no rejoin) sub-CFG.
1421 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1422   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1423   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1424   BBInfo *CvtBBI = &TrueBBI;
1425   BBInfo *NextBBI = &FalseBBI;
1426 
1427   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1428   if (Kind == ICSimpleFalse)
1429     std::swap(CvtBBI, NextBBI);
1430 
1431   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1432   MachineBasicBlock &NextMBB = *NextBBI->BB;
1433   if (CvtBBI->IsDone ||
1434       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1435     // Something has changed. It's no longer safe to predicate this block.
1436     BBI.IsAnalyzed = false;
1437     CvtBBI->IsAnalyzed = false;
1438     return false;
1439   }
1440 
1441   if (CvtMBB.hasAddressTaken())
1442     // Conservatively abort if-conversion if BB's address is taken.
1443     return false;
1444 
1445   if (Kind == ICSimpleFalse)
1446     if (TII->reverseBranchCondition(Cond))
1447       llvm_unreachable("Unable to reverse branch condition!");
1448 
1449   Redefs.init(*TRI);
1450 
1451   if (MRI->tracksLiveness()) {
1452     // Initialize liveins to the first BB. These are potentially redefined by
1453     // predicated instructions.
1454     Redefs.addLiveIns(CvtMBB);
1455     Redefs.addLiveIns(NextMBB);
1456   }
1457 
1458   // Remove the branches from the entry so we can add the contents of the true
1459   // block to it.
1460   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1461 
1462   if (CvtMBB.pred_size() > 1) {
1463     // Copy instructions in the true block, predicate them, and add them to
1464     // the entry block.
1465     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1466 
1467     // Keep the CFG updated.
1468     BBI.BB->removeSuccessor(&CvtMBB, true);
1469   } else {
1470     // Predicate the instructions in the true block.
1471     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1472 
1473     // Merge converted block into entry block. The BB to Cvt edge is removed
1474     // by MergeBlocks.
1475     MergeBlocks(BBI, *CvtBBI);
1476   }
1477 
1478   bool IterIfcvt = true;
1479   if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1480     InsertUncondBranch(*BBI.BB, NextMBB, TII);
1481     BBI.HasFallThrough = false;
1482     // Now ifcvt'd block will look like this:
1483     // BB:
1484     // ...
1485     // t, f = cmp
1486     // if t op
1487     // b BBf
1488     //
1489     // We cannot further ifcvt this block because the unconditional branch
1490     // will have to be predicated on the new condition, that will not be
1491     // available if cmp executes.
1492     IterIfcvt = false;
1493   }
1494 
1495   // Update block info. BB can be iteratively if-converted.
1496   if (!IterIfcvt)
1497     BBI.IsDone = true;
1498   InvalidatePreds(*BBI.BB);
1499   CvtBBI->IsDone = true;
1500 
1501   // FIXME: Must maintain LiveIns.
1502   return true;
1503 }
1504 
1505 /// If convert a triangle sub-CFG.
1506 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1507   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1508   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1509   BBInfo *CvtBBI = &TrueBBI;
1510   BBInfo *NextBBI = &FalseBBI;
1511   DebugLoc dl;  // FIXME: this is nowhere
1512 
1513   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1514   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1515     std::swap(CvtBBI, NextBBI);
1516 
1517   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1518   MachineBasicBlock &NextMBB = *NextBBI->BB;
1519   if (CvtBBI->IsDone ||
1520       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1521     // Something has changed. It's no longer safe to predicate this block.
1522     BBI.IsAnalyzed = false;
1523     CvtBBI->IsAnalyzed = false;
1524     return false;
1525   }
1526 
1527   if (CvtMBB.hasAddressTaken())
1528     // Conservatively abort if-conversion if BB's address is taken.
1529     return false;
1530 
1531   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1532     if (TII->reverseBranchCondition(Cond))
1533       llvm_unreachable("Unable to reverse branch condition!");
1534 
1535   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1536     if (reverseBranchCondition(*CvtBBI)) {
1537       // BB has been changed, modify its predecessors (except for this
1538       // one) so they don't get ifcvt'ed based on bad intel.
1539       for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1540         if (PBB == BBI.BB)
1541           continue;
1542         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1543         if (PBBI.IsEnqueued) {
1544           PBBI.IsAnalyzed = false;
1545           PBBI.IsEnqueued = false;
1546         }
1547       }
1548     }
1549   }
1550 
1551   // Initialize liveins to the first BB. These are potentially redefined by
1552   // predicated instructions.
1553   Redefs.init(*TRI);
1554   if (MRI->tracksLiveness()) {
1555     Redefs.addLiveIns(CvtMBB);
1556     Redefs.addLiveIns(NextMBB);
1557   }
1558 
1559   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1560   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1561 
1562   if (HasEarlyExit) {
1563     // Get probabilities before modifying CvtMBB and BBI.BB.
1564     CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1565     CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1566     BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1567     BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1568   }
1569 
1570   // Remove the branches from the entry so we can add the contents of the true
1571   // block to it.
1572   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1573 
1574   if (CvtMBB.pred_size() > 1) {
1575     // Copy instructions in the true block, predicate them, and add them to
1576     // the entry block.
1577     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1578   } else {
1579     // Predicate the 'true' block after removing its branch.
1580     CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1581     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1582 
1583     // Now merge the entry of the triangle with the true block.
1584     MergeBlocks(BBI, *CvtBBI, false);
1585   }
1586 
1587   // Keep the CFG updated.
1588   BBI.BB->removeSuccessor(&CvtMBB, true);
1589 
1590   // If 'true' block has a 'false' successor, add an exit branch to it.
1591   if (HasEarlyExit) {
1592     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1593                                            CvtBBI->BrCond.end());
1594     if (TII->reverseBranchCondition(RevCond))
1595       llvm_unreachable("Unable to reverse branch condition!");
1596 
1597     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1598     // NewNext = New_Prob(BBI.BB, NextMBB) =
1599     //   Prob(BBI.BB, NextMBB) +
1600     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1601     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1602     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1603     auto NewTrueBB = getNextBlock(*BBI.BB);
1604     auto NewNext = BBNext + BBCvt * CvtNext;
1605     auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1606     if (NewTrueBBIter != BBI.BB->succ_end())
1607       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1608 
1609     auto NewFalse = BBCvt * CvtFalse;
1610     TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1611     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1612   }
1613 
1614   // Merge in the 'false' block if the 'false' block has no other
1615   // predecessors. Otherwise, add an unconditional branch to 'false'.
1616   bool FalseBBDead = false;
1617   bool IterIfcvt = true;
1618   bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1619   if (!isFallThrough) {
1620     // Only merge them if the true block does not fallthrough to the false
1621     // block. By not merging them, we make it possible to iteratively
1622     // ifcvt the blocks.
1623     if (!HasEarlyExit &&
1624         NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1625         !NextMBB.hasAddressTaken()) {
1626       MergeBlocks(BBI, *NextBBI);
1627       FalseBBDead = true;
1628     } else {
1629       InsertUncondBranch(*BBI.BB, NextMBB, TII);
1630       BBI.HasFallThrough = false;
1631     }
1632     // Mixed predicated and unpredicated code. This cannot be iteratively
1633     // predicated.
1634     IterIfcvt = false;
1635   }
1636 
1637   // Update block info. BB can be iteratively if-converted.
1638   if (!IterIfcvt)
1639     BBI.IsDone = true;
1640   InvalidatePreds(*BBI.BB);
1641   CvtBBI->IsDone = true;
1642   if (FalseBBDead)
1643     NextBBI->IsDone = true;
1644 
1645   // FIXME: Must maintain LiveIns.
1646   return true;
1647 }
1648 
1649 /// Common code shared between diamond conversions.
1650 /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1651 /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1652 ///               and FalseBBI
1653 /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1654 ///               and \p FalseBBI
1655 /// \p RemoveBranch - Remove the common branch of the two blocks before
1656 ///                   predicating. Only false for unanalyzable fallthrough
1657 ///                   cases. The caller will replace the branch if necessary.
1658 /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1659 ///                    unanalyzable fallthrough
1660 bool IfConverter::IfConvertDiamondCommon(
1661     BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1662     unsigned NumDups1, unsigned NumDups2,
1663     bool TClobbersPred, bool FClobbersPred,
1664     bool RemoveBranch, bool MergeAddEdges) {
1665 
1666   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1667       TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1668     // Something has changed. It's no longer safe to predicate these blocks.
1669     BBI.IsAnalyzed = false;
1670     TrueBBI.IsAnalyzed = false;
1671     FalseBBI.IsAnalyzed = false;
1672     return false;
1673   }
1674 
1675   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1676     // Conservatively abort if-conversion if either BB has its address taken.
1677     return false;
1678 
1679   // Put the predicated instructions from the 'true' block before the
1680   // instructions from the 'false' block, unless the true block would clobber
1681   // the predicate, in which case, do the opposite.
1682   BBInfo *BBI1 = &TrueBBI;
1683   BBInfo *BBI2 = &FalseBBI;
1684   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1685   if (TII->reverseBranchCondition(RevCond))
1686     llvm_unreachable("Unable to reverse branch condition!");
1687   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1688   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1689 
1690   // Figure out the more profitable ordering.
1691   bool DoSwap = false;
1692   if (TClobbersPred && !FClobbersPred)
1693     DoSwap = true;
1694   else if (!TClobbersPred && !FClobbersPred) {
1695     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1696       DoSwap = true;
1697   } else if (TClobbersPred && FClobbersPred)
1698     llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1699   if (DoSwap) {
1700     std::swap(BBI1, BBI2);
1701     std::swap(Cond1, Cond2);
1702   }
1703 
1704   // Remove the conditional branch from entry to the blocks.
1705   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1706 
1707   MachineBasicBlock &MBB1 = *BBI1->BB;
1708   MachineBasicBlock &MBB2 = *BBI2->BB;
1709 
1710   // Initialize the Redefs:
1711   // - BB2 live-in regs need implicit uses before being redefined by BB1
1712   //   instructions.
1713   // - BB1 live-out regs need implicit uses before being redefined by BB2
1714   //   instructions. We start with BB1 live-ins so we have the live-out regs
1715   //   after tracking the BB1 instructions.
1716   Redefs.init(*TRI);
1717   if (MRI->tracksLiveness()) {
1718     Redefs.addLiveIns(MBB1);
1719     Redefs.addLiveIns(MBB2);
1720   }
1721 
1722   // Remove the duplicated instructions at the beginnings of both paths.
1723   // Skip dbg_value instructions.
1724   MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1725   MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
1726   BBI1->NonPredSize -= NumDups1;
1727   BBI2->NonPredSize -= NumDups1;
1728 
1729   // Skip past the dups on each side separately since there may be
1730   // differing dbg_value entries. NumDups1 can include a "return"
1731   // instruction, if it's not marked as "branch".
1732   for (unsigned i = 0; i < NumDups1; ++DI1) {
1733     if (DI1 == MBB1.end())
1734       break;
1735     if (!DI1->isDebugInstr())
1736       ++i;
1737   }
1738   while (NumDups1 != 0) {
1739     ++DI2;
1740     if (DI2 == MBB2.end())
1741       break;
1742     if (!DI2->isDebugInstr())
1743       --NumDups1;
1744   }
1745 
1746   if (MRI->tracksLiveness()) {
1747     for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1748       SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
1749       Redefs.stepForward(MI, Dummy);
1750     }
1751   }
1752 
1753   BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1754   MBB2.erase(MBB2.begin(), DI2);
1755 
1756   // The branches have been checked to match, so it is safe to remove the
1757   // branch in BB1 and rely on the copy in BB2. The complication is that
1758   // the blocks may end with a return instruction, which may or may not
1759   // be marked as "branch". If it's not, then it could be included in
1760   // "dups1", leaving the blocks potentially empty after moving the common
1761   // duplicates.
1762 #ifndef NDEBUG
1763   // Unanalyzable branches must match exactly. Check that now.
1764   if (!BBI1->IsBrAnalyzable)
1765     verifySameBranchInstructions(&MBB1, &MBB2);
1766 #endif
1767   // Remove duplicated instructions from the tail of MBB1: any branch
1768   // instructions, and the common instructions counted by NumDups2.
1769   DI1 = MBB1.end();
1770   while (DI1 != MBB1.begin()) {
1771     MachineBasicBlock::iterator Prev = std::prev(DI1);
1772     if (!Prev->isBranch() && !Prev->isDebugInstr())
1773       break;
1774     DI1 = Prev;
1775   }
1776   for (unsigned i = 0; i != NumDups2; ) {
1777     // NumDups2 only counted non-dbg_value instructions, so this won't
1778     // run off the head of the list.
1779     assert(DI1 != MBB1.begin());
1780     --DI1;
1781     // skip dbg_value instructions
1782     if (!DI1->isDebugInstr())
1783       ++i;
1784   }
1785   MBB1.erase(DI1, MBB1.end());
1786 
1787   DI2 = BBI2->BB->end();
1788   // The branches have been checked to match. Skip over the branch in the false
1789   // block so that we don't try to predicate it.
1790   if (RemoveBranch)
1791     BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1792   else {
1793     // Make DI2 point to the end of the range where the common "tail"
1794     // instructions could be found.
1795     while (DI2 != MBB2.begin()) {
1796       MachineBasicBlock::iterator Prev = std::prev(DI2);
1797       if (!Prev->isBranch() && !Prev->isDebugInstr())
1798         break;
1799       DI2 = Prev;
1800     }
1801   }
1802   while (NumDups2 != 0) {
1803     // NumDups2 only counted non-dbg_value instructions, so this won't
1804     // run off the head of the list.
1805     assert(DI2 != MBB2.begin());
1806     --DI2;
1807     // skip dbg_value instructions
1808     if (!DI2->isDebugInstr())
1809       --NumDups2;
1810   }
1811 
1812   // Remember which registers would later be defined by the false block.
1813   // This allows us not to predicate instructions in the true block that would
1814   // later be re-defined. That is, rather than
1815   //   subeq  r0, r1, #1
1816   //   addne  r0, r1, #1
1817   // generate:
1818   //   sub    r0, r1, #1
1819   //   addne  r0, r1, #1
1820   SmallSet<MCPhysReg, 4> RedefsByFalse;
1821   SmallSet<MCPhysReg, 4> ExtUses;
1822   if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1823     for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1824       if (FI.isDebugInstr())
1825         continue;
1826       SmallVector<MCPhysReg, 4> Defs;
1827       for (const MachineOperand &MO : FI.operands()) {
1828         if (!MO.isReg())
1829           continue;
1830         unsigned Reg = MO.getReg();
1831         if (!Reg)
1832           continue;
1833         if (MO.isDef()) {
1834           Defs.push_back(Reg);
1835         } else if (!RedefsByFalse.count(Reg)) {
1836           // These are defined before ctrl flow reach the 'false' instructions.
1837           // They cannot be modified by the 'true' instructions.
1838           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1839                SubRegs.isValid(); ++SubRegs)
1840             ExtUses.insert(*SubRegs);
1841         }
1842       }
1843 
1844       for (MCPhysReg Reg : Defs) {
1845         if (!ExtUses.count(Reg)) {
1846           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1847                SubRegs.isValid(); ++SubRegs)
1848             RedefsByFalse.insert(*SubRegs);
1849         }
1850       }
1851     }
1852   }
1853 
1854   // Predicate the 'true' block.
1855   PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1856 
1857   // After predicating BBI1, if there is a predicated terminator in BBI1 and
1858   // a non-predicated in BBI2, then we don't want to predicate the one from
1859   // BBI2. The reason is that if we merged these blocks, we would end up with
1860   // two predicated terminators in the same block.
1861   // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1862   // predicate them either. They were checked to be identical, and so the
1863   // same branch would happen regardless of which path was taken.
1864   if (!MBB2.empty() && (DI2 == MBB2.end())) {
1865     MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1866     MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1867     bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
1868     bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
1869     if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
1870       --DI2;
1871   }
1872 
1873   // Predicate the 'false' block.
1874   PredicateBlock(*BBI2, DI2, *Cond2);
1875 
1876   // Merge the true block into the entry of the diamond.
1877   MergeBlocks(BBI, *BBI1, MergeAddEdges);
1878   MergeBlocks(BBI, *BBI2, MergeAddEdges);
1879   return true;
1880 }
1881 
1882 /// If convert an almost-diamond sub-CFG where the true
1883 /// and false blocks share a common tail.
1884 bool IfConverter::IfConvertForkedDiamond(
1885     BBInfo &BBI, IfcvtKind Kind,
1886     unsigned NumDups1, unsigned NumDups2,
1887     bool TClobbersPred, bool FClobbersPred) {
1888   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1889   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1890 
1891   // Save the debug location for later.
1892   DebugLoc dl;
1893   MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1894   if (TIE != TrueBBI.BB->end())
1895     dl = TIE->getDebugLoc();
1896   // Removing branches from both blocks is safe, because we have already
1897   // determined that both blocks have the same branch instructions. The branch
1898   // will be added back at the end, unpredicated.
1899   if (!IfConvertDiamondCommon(
1900       BBI, TrueBBI, FalseBBI,
1901       NumDups1, NumDups2,
1902       TClobbersPred, FClobbersPred,
1903       /* RemoveBranch */ true, /* MergeAddEdges */ true))
1904     return false;
1905 
1906   // Add back the branch.
1907   // Debug location saved above when removing the branch from BBI2
1908   TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1909                     TrueBBI.BrCond, dl);
1910 
1911   // Update block info.
1912   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1913   InvalidatePreds(*BBI.BB);
1914 
1915   // FIXME: Must maintain LiveIns.
1916   return true;
1917 }
1918 
1919 /// If convert a diamond sub-CFG.
1920 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1921                                    unsigned NumDups1, unsigned NumDups2,
1922                                    bool TClobbersPred, bool FClobbersPred) {
1923   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1924   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1925   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1926 
1927   // True block must fall through or end with an unanalyzable terminator.
1928   if (!TailBB) {
1929     if (blockAlwaysFallThrough(TrueBBI))
1930       TailBB = FalseBBI.TrueBB;
1931     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1932   }
1933 
1934   if (!IfConvertDiamondCommon(
1935       BBI, TrueBBI, FalseBBI,
1936       NumDups1, NumDups2,
1937       TClobbersPred, FClobbersPred,
1938       /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
1939       /* MergeAddEdges */ TailBB == nullptr))
1940     return false;
1941 
1942   // If the if-converted block falls through or unconditionally branches into
1943   // the tail block, and the tail block does not have other predecessors, then
1944   // fold the tail block in as well. Otherwise, unless it falls through to the
1945   // tail, add a unconditional branch to it.
1946   if (TailBB) {
1947     // We need to remove the edges to the true and false blocks manually since
1948     // we didn't let IfConvertDiamondCommon update the CFG.
1949     BBI.BB->removeSuccessor(TrueBBI.BB);
1950     BBI.BB->removeSuccessor(FalseBBI.BB, true);
1951 
1952     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1953     bool CanMergeTail = !TailBBI.HasFallThrough &&
1954       !TailBBI.BB->hasAddressTaken();
1955     // The if-converted block can still have a predicated terminator
1956     // (e.g. a predicated return). If that is the case, we cannot merge
1957     // it with the tail block.
1958     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1959     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1960       CanMergeTail = false;
1961     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1962     // check if there are any other predecessors besides those.
1963     unsigned NumPreds = TailBB->pred_size();
1964     if (NumPreds > 1)
1965       CanMergeTail = false;
1966     else if (NumPreds == 1 && CanMergeTail) {
1967       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1968       if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
1969         CanMergeTail = false;
1970     }
1971     if (CanMergeTail) {
1972       MergeBlocks(BBI, TailBBI);
1973       TailBBI.IsDone = true;
1974     } else {
1975       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1976       InsertUncondBranch(*BBI.BB, *TailBB, TII);
1977       BBI.HasFallThrough = false;
1978     }
1979   }
1980 
1981   // Update block info.
1982   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1983   InvalidatePreds(*BBI.BB);
1984 
1985   // FIXME: Must maintain LiveIns.
1986   return true;
1987 }
1988 
1989 static bool MaySpeculate(const MachineInstr &MI,
1990                          SmallSet<MCPhysReg, 4> &LaterRedefs) {
1991   bool SawStore = true;
1992   if (!MI.isSafeToMove(nullptr, SawStore))
1993     return false;
1994 
1995   for (const MachineOperand &MO : MI.operands()) {
1996     if (!MO.isReg())
1997       continue;
1998     unsigned Reg = MO.getReg();
1999     if (!Reg)
2000       continue;
2001     if (MO.isDef() && !LaterRedefs.count(Reg))
2002       return false;
2003   }
2004 
2005   return true;
2006 }
2007 
2008 /// Predicate instructions from the start of the block to the specified end with
2009 /// the specified condition.
2010 void IfConverter::PredicateBlock(BBInfo &BBI,
2011                                  MachineBasicBlock::iterator E,
2012                                  SmallVectorImpl<MachineOperand> &Cond,
2013                                  SmallSet<MCPhysReg, 4> *LaterRedefs) {
2014   bool AnyUnpred = false;
2015   bool MaySpec = LaterRedefs != nullptr;
2016   for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2017     if (I.isDebugInstr() || TII->isPredicated(I))
2018       continue;
2019     // It may be possible not to predicate an instruction if it's the 'true'
2020     // side of a diamond and the 'false' side may re-define the instruction's
2021     // defs.
2022     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
2023       AnyUnpred = true;
2024       continue;
2025     }
2026     // If any instruction is predicated, then every instruction after it must
2027     // be predicated.
2028     MaySpec = false;
2029     if (!TII->PredicateInstruction(I, Cond)) {
2030 #ifndef NDEBUG
2031       dbgs() << "Unable to predicate " << I << "!\n";
2032 #endif
2033       llvm_unreachable(nullptr);
2034     }
2035 
2036     // If the predicated instruction now redefines a register as the result of
2037     // if-conversion, add an implicit kill.
2038     UpdatePredRedefs(I, Redefs);
2039   }
2040 
2041   BBI.Predicate.append(Cond.begin(), Cond.end());
2042 
2043   BBI.IsAnalyzed = false;
2044   BBI.NonPredSize = 0;
2045 
2046   ++NumIfConvBBs;
2047   if (AnyUnpred)
2048     ++NumUnpred;
2049 }
2050 
2051 /// Copy and predicate instructions from source BB to the destination block.
2052 /// Skip end of block branches if IgnoreBr is true.
2053 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2054                                         SmallVectorImpl<MachineOperand> &Cond,
2055                                         bool IgnoreBr) {
2056   MachineFunction &MF = *ToBBI.BB->getParent();
2057 
2058   MachineBasicBlock &FromMBB = *FromBBI.BB;
2059   for (MachineInstr &I : FromMBB) {
2060     // Do not copy the end of the block branches.
2061     if (IgnoreBr && I.isBranch())
2062       break;
2063 
2064     MachineInstr *MI = MF.CloneMachineInstr(&I);
2065     ToBBI.BB->insert(ToBBI.BB->end(), MI);
2066     ToBBI.NonPredSize++;
2067     unsigned ExtraPredCost = TII->getPredicationCost(I);
2068     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2069     if (NumCycles > 1)
2070       ToBBI.ExtraCost += NumCycles-1;
2071     ToBBI.ExtraCost2 += ExtraPredCost;
2072 
2073     if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
2074       if (!TII->PredicateInstruction(*MI, Cond)) {
2075 #ifndef NDEBUG
2076         dbgs() << "Unable to predicate " << I << "!\n";
2077 #endif
2078         llvm_unreachable(nullptr);
2079       }
2080     }
2081 
2082     // If the predicated instruction now redefines a register as the result of
2083     // if-conversion, add an implicit kill.
2084     UpdatePredRedefs(*MI, Redefs);
2085   }
2086 
2087   if (!IgnoreBr) {
2088     std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2089                                            FromMBB.succ_end());
2090     MachineBasicBlock *NBB = getNextBlock(FromMBB);
2091     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2092 
2093     for (MachineBasicBlock *Succ : Succs) {
2094       // Fallthrough edge can't be transferred.
2095       if (Succ == FallThrough)
2096         continue;
2097       ToBBI.BB->addSuccessor(Succ);
2098     }
2099   }
2100 
2101   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2102   ToBBI.Predicate.append(Cond.begin(), Cond.end());
2103 
2104   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2105   ToBBI.IsAnalyzed = false;
2106 
2107   ++NumDupBBs;
2108 }
2109 
2110 /// Move all instructions from FromBB to the end of ToBB.  This will leave
2111 /// FromBB as an empty block, so remove all of its successor edges except for
2112 /// the fall-through edge.  If AddEdges is true, i.e., when FromBBI's branch is
2113 /// being moved, add those successor edges to ToBBI and remove the old edge
2114 /// from ToBBI to FromBBI.
2115 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2116   MachineBasicBlock &FromMBB = *FromBBI.BB;
2117   assert(!FromMBB.hasAddressTaken() &&
2118          "Removing a BB whose address is taken!");
2119 
2120   // In case FromMBB contains terminators (e.g. return instruction),
2121   // first move the non-terminator instructions, then the terminators.
2122   MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
2123   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2124   ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2125 
2126   // If FromBB has non-predicated terminator we should copy it at the end.
2127   if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
2128     ToTI = ToBBI.BB->end();
2129   ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2130 
2131   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2132   // unknown probabilities into known ones.
2133   // FIXME: This usage is too tricky and in the future we would like to
2134   // eliminate all unknown probabilities in MBB.
2135   if (ToBBI.IsBrAnalyzable)
2136     ToBBI.BB->normalizeSuccProbs();
2137 
2138   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2139                                                 FromMBB.succ_end());
2140   MachineBasicBlock *NBB = getNextBlock(FromMBB);
2141   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2142   // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2143   // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2144   auto To2FromProb = BranchProbability::getZero();
2145   if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2146     // Remove the old edge but remember the edge probability so we can calculate
2147     // the correct weights on the new edges being added further down.
2148     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2149     ToBBI.BB->removeSuccessor(&FromMBB);
2150   }
2151 
2152   for (MachineBasicBlock *Succ : FromSuccs) {
2153     // Fallthrough edge can't be transferred.
2154     if (Succ == FallThrough)
2155       continue;
2156 
2157     auto NewProb = BranchProbability::getZero();
2158     if (AddEdges) {
2159       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2160       // which is a portion of the edge probability from FromMBB to Succ. The
2161       // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2162       // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2163       NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2164 
2165       // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2166       // only happens when if-converting a diamond CFG and FromMBB is the
2167       // tail BB.  In this case FromMBB post-dominates ToBBI.BB and hence we
2168       // could just use the probabilities on FromMBB's out-edges when adding
2169       // new successors.
2170       if (!To2FromProb.isZero())
2171         NewProb *= To2FromProb;
2172     }
2173 
2174     FromMBB.removeSuccessor(Succ);
2175 
2176     if (AddEdges) {
2177       // If the edge from ToBBI.BB to Succ already exists, update the
2178       // probability of this edge by adding NewProb to it. An example is shown
2179       // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2180       // don't have to set C as A's successor as it already is. We only need to
2181       // update the edge probability on A->C. Note that B will not be
2182       // immediately removed from A's successors. It is possible that B->D is
2183       // not removed either if D is a fallthrough of B. Later the edge A->D
2184       // (generated here) and B->D will be combined into one edge. To maintain
2185       // correct edge probability of this combined edge, we need to set the edge
2186       // probability of A->B to zero, which is already done above. The edge
2187       // probability on A->D is calculated by scaling the original probability
2188       // on A->B by the probability of B->D.
2189       //
2190       // Before ifcvt:      After ifcvt (assume B->D is kept):
2191       //
2192       //       A                A
2193       //      /|               /|\
2194       //     / B              / B|
2195       //    | /|             |  ||
2196       //    |/ |             |  |/
2197       //    C  D             C  D
2198       //
2199       if (ToBBI.BB->isSuccessor(Succ))
2200         ToBBI.BB->setSuccProbability(
2201             find(ToBBI.BB->successors(), Succ),
2202             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2203       else
2204         ToBBI.BB->addSuccessor(Succ, NewProb);
2205     }
2206   }
2207 
2208   // Move the now empty FromMBB out of the way to the end of the function so
2209   // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2210   MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2211   if (Last != &FromMBB)
2212     FromMBB.moveAfter(Last);
2213 
2214   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2215   // we've done above.
2216   if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2217     ToBBI.BB->normalizeSuccProbs();
2218 
2219   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2220   FromBBI.Predicate.clear();
2221 
2222   ToBBI.NonPredSize += FromBBI.NonPredSize;
2223   ToBBI.ExtraCost += FromBBI.ExtraCost;
2224   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2225   FromBBI.NonPredSize = 0;
2226   FromBBI.ExtraCost = 0;
2227   FromBBI.ExtraCost2 = 0;
2228 
2229   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2230   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2231   ToBBI.IsAnalyzed = false;
2232   FromBBI.IsAnalyzed = false;
2233 }
2234 
2235 FunctionPass *
2236 llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
2237   return new IfConverter(std::move(Ftor));
2238 }
2239