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