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