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