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