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