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