10b57cec5SDimitry Andric //===- IfConversion.cpp - Machine code if conversion pass -----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the machine instruction level if-conversion pass, which
100b57cec5SDimitry Andric // tries to convert conditional branches into predicated instructions.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "BranchFolding.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SparseSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
210b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
22480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
345ffd83dbSDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
40480093f4SDimitry Andric #include "llvm/IR/Attributes.h"
410b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
42480093f4SDimitry Andric #include "llvm/InitializePasses.h"
430b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
440b57cec5SDimitry Andric #include "llvm/Pass.h"
450b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
460b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
470b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
480b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
490b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
500b57cec5SDimitry Andric #include <algorithm>
510b57cec5SDimitry Andric #include <cassert>
520b57cec5SDimitry Andric #include <functional>
530b57cec5SDimitry Andric #include <iterator>
540b57cec5SDimitry Andric #include <memory>
550b57cec5SDimitry Andric #include <utility>
560b57cec5SDimitry Andric #include <vector>
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric using namespace llvm;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric #define DEBUG_TYPE "if-converter"
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric // Hidden options for help debugging.
630b57cec5SDimitry Andric static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
640b57cec5SDimitry Andric static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
650b57cec5SDimitry Andric static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
660b57cec5SDimitry Andric static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
670b57cec5SDimitry Andric                                    cl::init(false), cl::Hidden);
680b57cec5SDimitry Andric static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
690b57cec5SDimitry Andric                                     cl::init(false), cl::Hidden);
700b57cec5SDimitry Andric static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
710b57cec5SDimitry Andric                                      cl::init(false), cl::Hidden);
720b57cec5SDimitry Andric static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
730b57cec5SDimitry Andric                                       cl::init(false), cl::Hidden);
740b57cec5SDimitry Andric static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
750b57cec5SDimitry Andric                                       cl::init(false), cl::Hidden);
760b57cec5SDimitry Andric static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
770b57cec5SDimitry Andric                                        cl::init(false), cl::Hidden);
780b57cec5SDimitry Andric static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
790b57cec5SDimitry Andric                                     cl::init(false), cl::Hidden);
800b57cec5SDimitry Andric static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
810b57cec5SDimitry Andric                                         cl::init(false), cl::Hidden);
820b57cec5SDimitry Andric static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
830b57cec5SDimitry Andric                                      cl::init(true), cl::Hidden);
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric STATISTIC(NumSimple,       "Number of simple if-conversions performed");
860b57cec5SDimitry Andric STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
870b57cec5SDimitry Andric STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
880b57cec5SDimitry Andric STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
890b57cec5SDimitry Andric STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
900b57cec5SDimitry Andric STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
910b57cec5SDimitry Andric STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
920b57cec5SDimitry Andric STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
930b57cec5SDimitry Andric STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
940b57cec5SDimitry Andric STATISTIC(NumDupBBs,       "Number of duplicated blocks");
950b57cec5SDimitry Andric STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric namespace {
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   class IfConverter : public MachineFunctionPass {
1000b57cec5SDimitry Andric     enum IfcvtKind {
1010b57cec5SDimitry Andric       ICNotClassfied,  // BB data valid, but not classified.
1020b57cec5SDimitry Andric       ICSimpleFalse,   // Same as ICSimple, but on the false path.
1030b57cec5SDimitry Andric       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
1040b57cec5SDimitry Andric       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
1050b57cec5SDimitry Andric       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
1060b57cec5SDimitry Andric       ICTriangleFalse, // Same as ICTriangle, but on the false path.
1070b57cec5SDimitry Andric       ICTriangle,      // BB is entry of a triangle sub-CFG.
1080b57cec5SDimitry Andric       ICDiamond,       // BB is entry of a diamond sub-CFG.
1090b57cec5SDimitry Andric       ICForkedDiamond  // BB is entry of an almost diamond sub-CFG, with a
1100b57cec5SDimitry Andric                        // common tail that can be shared.
1110b57cec5SDimitry Andric     };
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric     /// One per MachineBasicBlock, this is used to cache the result
1140b57cec5SDimitry Andric     /// if-conversion feasibility analysis. This includes results from
1150b57cec5SDimitry Andric     /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
1160b57cec5SDimitry Andric     /// classification, and common tail block of its successors (if it's a
1170b57cec5SDimitry Andric     /// diamond shape), its size, whether it's predicable, and whether any
1180b57cec5SDimitry Andric     /// instruction can clobber the 'would-be' predicate.
1190b57cec5SDimitry Andric     ///
1200b57cec5SDimitry Andric     /// IsDone          - True if BB is not to be considered for ifcvt.
1210b57cec5SDimitry Andric     /// IsBeingAnalyzed - True if BB is currently being analyzed.
1220b57cec5SDimitry Andric     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
1230b57cec5SDimitry Andric     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
1240b57cec5SDimitry Andric     /// IsBrAnalyzable  - True if analyzeBranch() returns false.
1250b57cec5SDimitry Andric     /// HasFallThrough  - True if BB may fallthrough to the following BB.
1260b57cec5SDimitry Andric     /// IsUnpredicable  - True if BB is known to be unpredicable.
1270b57cec5SDimitry Andric     /// ClobbersPred    - True if BB could modify predicates (e.g. has
1280b57cec5SDimitry Andric     ///                   cmp, call, etc.)
1290b57cec5SDimitry Andric     /// NonPredSize     - Number of non-predicated instructions.
1300b57cec5SDimitry Andric     /// ExtraCost       - Extra cost for multi-cycle instructions.
1310b57cec5SDimitry Andric     /// ExtraCost2      - Some instructions are slower when predicated
1320b57cec5SDimitry Andric     /// BB              - Corresponding MachineBasicBlock.
1330b57cec5SDimitry Andric     /// TrueBB / FalseBB- See analyzeBranch().
1340b57cec5SDimitry Andric     /// BrCond          - Conditions for end of block conditional branches.
1350b57cec5SDimitry Andric     /// Predicate       - Predicate used in the BB.
1360b57cec5SDimitry Andric     struct BBInfo {
1370b57cec5SDimitry Andric       bool IsDone          : 1;
1380b57cec5SDimitry Andric       bool IsBeingAnalyzed : 1;
1390b57cec5SDimitry Andric       bool IsAnalyzed      : 1;
1400b57cec5SDimitry Andric       bool IsEnqueued      : 1;
1410b57cec5SDimitry Andric       bool IsBrAnalyzable  : 1;
1420b57cec5SDimitry Andric       bool IsBrReversible  : 1;
1430b57cec5SDimitry Andric       bool HasFallThrough  : 1;
1440b57cec5SDimitry Andric       bool IsUnpredicable  : 1;
1450b57cec5SDimitry Andric       bool CannotBeCopied  : 1;
1460b57cec5SDimitry Andric       bool ClobbersPred    : 1;
1470b57cec5SDimitry Andric       unsigned NonPredSize = 0;
1480b57cec5SDimitry Andric       unsigned ExtraCost = 0;
1490b57cec5SDimitry Andric       unsigned ExtraCost2 = 0;
1500b57cec5SDimitry Andric       MachineBasicBlock *BB = nullptr;
1510b57cec5SDimitry Andric       MachineBasicBlock *TrueBB = nullptr;
1520b57cec5SDimitry Andric       MachineBasicBlock *FalseBB = nullptr;
1530b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> BrCond;
1540b57cec5SDimitry Andric       SmallVector<MachineOperand, 4> Predicate;
1550b57cec5SDimitry Andric 
BBInfo__anoncaa57e1d0111::IfConverter::BBInfo1560b57cec5SDimitry Andric       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
1570b57cec5SDimitry Andric                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
1580b57cec5SDimitry Andric                  IsBrReversible(false), HasFallThrough(false),
1590b57cec5SDimitry Andric                  IsUnpredicable(false), CannotBeCopied(false),
1600b57cec5SDimitry Andric                  ClobbersPred(false) {}
1610b57cec5SDimitry Andric     };
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric     /// Record information about pending if-conversions to attempt:
1640b57cec5SDimitry Andric     /// BBI             - Corresponding BBInfo.
1650b57cec5SDimitry Andric     /// Kind            - Type of block. See IfcvtKind.
1660b57cec5SDimitry Andric     /// NeedSubsumption - True if the to-be-predicated BB has already been
1670b57cec5SDimitry Andric     ///                   predicated.
1680b57cec5SDimitry Andric     /// NumDups      - Number of instructions that would be duplicated due
1690b57cec5SDimitry Andric     ///                   to this if-conversion. (For diamonds, the number of
1700b57cec5SDimitry Andric     ///                   identical instructions at the beginnings of both
1710b57cec5SDimitry Andric     ///                   paths).
1720b57cec5SDimitry Andric     /// NumDups2     - For diamonds, the number of identical instructions
1730b57cec5SDimitry Andric     ///                   at the ends of both paths.
1740b57cec5SDimitry Andric     struct IfcvtToken {
1750b57cec5SDimitry Andric       BBInfo &BBI;
1760b57cec5SDimitry Andric       IfcvtKind Kind;
1770b57cec5SDimitry Andric       unsigned NumDups;
1780b57cec5SDimitry Andric       unsigned NumDups2;
1790b57cec5SDimitry Andric       bool NeedSubsumption : 1;
1800b57cec5SDimitry Andric       bool TClobbersPred : 1;
1810b57cec5SDimitry Andric       bool FClobbersPred : 1;
1820b57cec5SDimitry Andric 
IfcvtToken__anoncaa57e1d0111::IfConverter::IfcvtToken1830b57cec5SDimitry Andric       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
1840b57cec5SDimitry Andric                  bool tc = false, bool fc = false)
1850b57cec5SDimitry Andric         : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
1860b57cec5SDimitry Andric           TClobbersPred(tc), FClobbersPred(fc) {}
1870b57cec5SDimitry Andric     };
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric     /// Results of if-conversion feasibility analysis indexed by basic block
1900b57cec5SDimitry Andric     /// number.
1910b57cec5SDimitry Andric     std::vector<BBInfo> BBAnalysis;
1920b57cec5SDimitry Andric     TargetSchedModel SchedModel;
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric     const TargetLoweringBase *TLI;
1950b57cec5SDimitry Andric     const TargetInstrInfo *TII;
1960b57cec5SDimitry Andric     const TargetRegisterInfo *TRI;
1970b57cec5SDimitry Andric     const MachineBranchProbabilityInfo *MBPI;
1980b57cec5SDimitry Andric     MachineRegisterInfo *MRI;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric     LivePhysRegs Redefs;
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric     bool PreRegAlloc;
2030b57cec5SDimitry Andric     bool MadeChange;
2040b57cec5SDimitry Andric     int FnNum = -1;
2050b57cec5SDimitry Andric     std::function<bool(const MachineFunction &)> PredicateFtor;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   public:
2080b57cec5SDimitry Andric     static char ID;
2090b57cec5SDimitry Andric 
IfConverter(std::function<bool (const MachineFunction &)> Ftor=nullptr)2100b57cec5SDimitry Andric     IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
2110b57cec5SDimitry Andric         : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
2120b57cec5SDimitry Andric       initializeIfConverterPass(*PassRegistry::getPassRegistry());
2130b57cec5SDimitry Andric     }
2140b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const2150b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
2160b57cec5SDimitry Andric       AU.addRequired<MachineBlockFrequencyInfo>();
2170b57cec5SDimitry Andric       AU.addRequired<MachineBranchProbabilityInfo>();
218480093f4SDimitry Andric       AU.addRequired<ProfileSummaryInfoWrapperPass>();
2190b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
2200b57cec5SDimitry Andric     }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
2230b57cec5SDimitry Andric 
getRequiredProperties() const2240b57cec5SDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
2250b57cec5SDimitry Andric       return MachineFunctionProperties().set(
2260b57cec5SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
2270b57cec5SDimitry Andric     }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   private:
2300b57cec5SDimitry Andric     bool reverseBranchCondition(BBInfo &BBI) const;
2310b57cec5SDimitry Andric     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
2320b57cec5SDimitry Andric                      BranchProbability Prediction) const;
2330b57cec5SDimitry Andric     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
2340b57cec5SDimitry Andric                        bool FalseBranch, unsigned &Dups,
2350b57cec5SDimitry Andric                        BranchProbability Prediction) const;
2360b57cec5SDimitry Andric     bool CountDuplicatedInstructions(
2370b57cec5SDimitry Andric         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
2380b57cec5SDimitry Andric         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
2390b57cec5SDimitry Andric         unsigned &Dups1, unsigned &Dups2,
2400b57cec5SDimitry Andric         MachineBasicBlock &TBB, MachineBasicBlock &FBB,
2410b57cec5SDimitry Andric         bool SkipUnconditionalBranches) const;
2420b57cec5SDimitry Andric     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
2430b57cec5SDimitry Andric                       unsigned &Dups1, unsigned &Dups2,
2440b57cec5SDimitry Andric                       BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
2450b57cec5SDimitry Andric     bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
2460b57cec5SDimitry Andric                             unsigned &Dups1, unsigned &Dups2,
2470b57cec5SDimitry Andric                             BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
2480b57cec5SDimitry Andric     void AnalyzeBranches(BBInfo &BBI);
2490b57cec5SDimitry Andric     void ScanInstructions(BBInfo &BBI,
2500b57cec5SDimitry Andric                           MachineBasicBlock::iterator &Begin,
2510b57cec5SDimitry Andric                           MachineBasicBlock::iterator &End,
2520b57cec5SDimitry Andric                           bool BranchUnpredicable = false) const;
2530b57cec5SDimitry Andric     bool RescanInstructions(
2540b57cec5SDimitry Andric         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
2550b57cec5SDimitry Andric         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
2560b57cec5SDimitry Andric         BBInfo &TrueBBI, BBInfo &FalseBBI) const;
2570b57cec5SDimitry Andric     void AnalyzeBlock(MachineBasicBlock &MBB,
2580b57cec5SDimitry Andric                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
2590b57cec5SDimitry Andric     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
2600b57cec5SDimitry Andric                              bool isTriangle = false, bool RevBranch = false,
2610b57cec5SDimitry Andric                              bool hasCommonTail = false);
2620b57cec5SDimitry Andric     void AnalyzeBlocks(MachineFunction &MF,
2630b57cec5SDimitry Andric                        std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
2640b57cec5SDimitry Andric     void InvalidatePreds(MachineBasicBlock &MBB);
2650b57cec5SDimitry Andric     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
2660b57cec5SDimitry Andric     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
2670b57cec5SDimitry Andric     bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
2680b57cec5SDimitry Andric                                 unsigned NumDups1, unsigned NumDups2,
2690b57cec5SDimitry Andric                                 bool TClobbersPred, bool FClobbersPred,
2700b57cec5SDimitry Andric                                 bool RemoveBranch, bool MergeAddEdges);
2710b57cec5SDimitry Andric     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
2720b57cec5SDimitry Andric                           unsigned NumDups1, unsigned NumDups2,
2730b57cec5SDimitry Andric                           bool TClobbers, bool FClobbers);
2740b57cec5SDimitry Andric     bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
2750b57cec5SDimitry Andric                               unsigned NumDups1, unsigned NumDups2,
2760b57cec5SDimitry Andric                               bool TClobbers, bool FClobbers);
2770b57cec5SDimitry Andric     void PredicateBlock(BBInfo &BBI,
2780b57cec5SDimitry Andric                         MachineBasicBlock::iterator E,
2790b57cec5SDimitry Andric                         SmallVectorImpl<MachineOperand> &Cond,
2800b57cec5SDimitry Andric                         SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
2810b57cec5SDimitry Andric     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2820b57cec5SDimitry Andric                                SmallVectorImpl<MachineOperand> &Cond,
2830b57cec5SDimitry Andric                                bool IgnoreBr = false);
2840b57cec5SDimitry Andric     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
2850b57cec5SDimitry Andric 
MeetIfcvtSizeLimit(MachineBasicBlock & BB,unsigned Cycle,unsigned Extra,BranchProbability Prediction) const2860b57cec5SDimitry Andric     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
2870b57cec5SDimitry Andric                             unsigned Cycle, unsigned Extra,
2880b57cec5SDimitry Andric                             BranchProbability Prediction) const {
2890b57cec5SDimitry Andric       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
2900b57cec5SDimitry Andric                                                    Prediction);
2910b57cec5SDimitry Andric     }
2920b57cec5SDimitry Andric 
MeetIfcvtSizeLimit(BBInfo & TBBInfo,BBInfo & FBBInfo,MachineBasicBlock & CommBB,unsigned Dups,BranchProbability Prediction,bool Forked) const2938bcb0991SDimitry Andric     bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
2948bcb0991SDimitry Andric                             MachineBasicBlock &CommBB, unsigned Dups,
2958bcb0991SDimitry Andric                             BranchProbability Prediction, bool Forked) const {
2968bcb0991SDimitry Andric       const MachineFunction &MF = *TBBInfo.BB->getParent();
2978bcb0991SDimitry Andric       if (MF.getFunction().hasMinSize()) {
2988bcb0991SDimitry Andric         MachineBasicBlock::iterator TIB = TBBInfo.BB->begin();
2998bcb0991SDimitry Andric         MachineBasicBlock::iterator FIB = FBBInfo.BB->begin();
3008bcb0991SDimitry Andric         MachineBasicBlock::iterator TIE = TBBInfo.BB->end();
3018bcb0991SDimitry Andric         MachineBasicBlock::iterator FIE = FBBInfo.BB->end();
3028bcb0991SDimitry Andric 
303*5f7ddb14SDimitry Andric         unsigned Dups1 = 0, Dups2 = 0;
3048bcb0991SDimitry Andric         if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
3058bcb0991SDimitry Andric                                          *TBBInfo.BB, *FBBInfo.BB,
3068bcb0991SDimitry Andric                                          /*SkipUnconditionalBranches*/ true))
3078bcb0991SDimitry Andric           llvm_unreachable("should already have been checked by ValidDiamond");
3088bcb0991SDimitry Andric 
3098bcb0991SDimitry Andric         unsigned BranchBytes = 0;
3108bcb0991SDimitry Andric         unsigned CommonBytes = 0;
3118bcb0991SDimitry Andric 
3128bcb0991SDimitry Andric         // Count common instructions at the start of the true and false blocks.
3138bcb0991SDimitry Andric         for (auto &I : make_range(TBBInfo.BB->begin(), TIB)) {
3148bcb0991SDimitry Andric           LLVM_DEBUG(dbgs() << "Common inst: " << I);
3158bcb0991SDimitry Andric           CommonBytes += TII->getInstSizeInBytes(I);
3168bcb0991SDimitry Andric         }
3178bcb0991SDimitry Andric         for (auto &I : make_range(FBBInfo.BB->begin(), FIB)) {
3188bcb0991SDimitry Andric           LLVM_DEBUG(dbgs() << "Common inst: " << I);
3198bcb0991SDimitry Andric           CommonBytes += TII->getInstSizeInBytes(I);
3208bcb0991SDimitry Andric         }
3218bcb0991SDimitry Andric 
3228bcb0991SDimitry Andric         // Count instructions at the end of the true and false blocks, after
3238bcb0991SDimitry Andric         // the ones we plan to predicate. Analyzable branches will be removed
3248bcb0991SDimitry Andric         // (unless this is a forked diamond), and all other instructions are
3258bcb0991SDimitry Andric         // common between the two blocks.
3268bcb0991SDimitry Andric         for (auto &I : make_range(TIE, TBBInfo.BB->end())) {
3278bcb0991SDimitry Andric           if (I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
3288bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3298bcb0991SDimitry Andric             BranchBytes += TII->predictBranchSizeForIfCvt(I);
3308bcb0991SDimitry Andric           } else {
3318bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Common inst: " << I);
3328bcb0991SDimitry Andric             CommonBytes += TII->getInstSizeInBytes(I);
3338bcb0991SDimitry Andric           }
3348bcb0991SDimitry Andric         }
3358bcb0991SDimitry Andric         for (auto &I : make_range(FIE, FBBInfo.BB->end())) {
3368bcb0991SDimitry Andric           if (I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
3378bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3388bcb0991SDimitry Andric             BranchBytes += TII->predictBranchSizeForIfCvt(I);
3398bcb0991SDimitry Andric           } else {
3408bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Common inst: " << I);
3418bcb0991SDimitry Andric             CommonBytes += TII->getInstSizeInBytes(I);
3428bcb0991SDimitry Andric           }
3438bcb0991SDimitry Andric         }
3448bcb0991SDimitry Andric         for (auto &I : CommBB.terminators()) {
3458bcb0991SDimitry Andric           if (I.isBranch()) {
3468bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3478bcb0991SDimitry Andric             BranchBytes += TII->predictBranchSizeForIfCvt(I);
3488bcb0991SDimitry Andric           }
3498bcb0991SDimitry Andric         }
3508bcb0991SDimitry Andric 
3518bcb0991SDimitry Andric         // The common instructions in one branch will be eliminated, halving
3528bcb0991SDimitry Andric         // their code size.
3538bcb0991SDimitry Andric         CommonBytes /= 2;
3548bcb0991SDimitry Andric 
3558bcb0991SDimitry Andric         // Count the instructions which we need to predicate.
3568bcb0991SDimitry Andric         unsigned NumPredicatedInstructions = 0;
3578bcb0991SDimitry Andric         for (auto &I : make_range(TIB, TIE)) {
3588bcb0991SDimitry Andric           if (!I.isDebugInstr()) {
3598bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Predicating: " << I);
3608bcb0991SDimitry Andric             NumPredicatedInstructions++;
3618bcb0991SDimitry Andric           }
3628bcb0991SDimitry Andric         }
3638bcb0991SDimitry Andric         for (auto &I : make_range(FIB, FIE)) {
3648bcb0991SDimitry Andric           if (!I.isDebugInstr()) {
3658bcb0991SDimitry Andric             LLVM_DEBUG(dbgs() << "Predicating: " << I);
3668bcb0991SDimitry Andric             NumPredicatedInstructions++;
3678bcb0991SDimitry Andric           }
3688bcb0991SDimitry Andric         }
3698bcb0991SDimitry Andric 
3708bcb0991SDimitry Andric         // Even though we're optimising for size at the expense of performance,
3718bcb0991SDimitry Andric         // avoid creating really long predicated blocks.
3728bcb0991SDimitry Andric         if (NumPredicatedInstructions > 15)
3738bcb0991SDimitry Andric           return false;
3748bcb0991SDimitry Andric 
3758bcb0991SDimitry Andric         // Some targets (e.g. Thumb2) need to insert extra instructions to
3768bcb0991SDimitry Andric         // start predicated blocks.
3778bcb0991SDimitry Andric         unsigned ExtraPredicateBytes = TII->extraSizeToPredicateInstructions(
3788bcb0991SDimitry Andric             MF, NumPredicatedInstructions);
3798bcb0991SDimitry Andric 
3808bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
3818bcb0991SDimitry Andric                           << ", CommonBytes=" << CommonBytes
3828bcb0991SDimitry Andric                           << ", NumPredicatedInstructions="
3838bcb0991SDimitry Andric                           << NumPredicatedInstructions
3848bcb0991SDimitry Andric                           << ", ExtraPredicateBytes=" << ExtraPredicateBytes
3858bcb0991SDimitry Andric                           << ")\n");
3868bcb0991SDimitry Andric         return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
3878bcb0991SDimitry Andric       } else {
3888bcb0991SDimitry Andric         unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
3898bcb0991SDimitry Andric         unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
3908bcb0991SDimitry Andric         bool Res = TCycle > 0 && FCycle > 0 &&
3918bcb0991SDimitry Andric                    TII->isProfitableToIfCvt(
3928bcb0991SDimitry Andric                        *TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
3938bcb0991SDimitry Andric                        FCycle, FBBInfo.ExtraCost2, Prediction);
3948bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle
3958bcb0991SDimitry Andric                           << ", FCycle=" << FCycle
3968bcb0991SDimitry Andric                           << ", TExtra=" << TBBInfo.ExtraCost2 << ", FExtra="
3978bcb0991SDimitry Andric                           << FBBInfo.ExtraCost2 << ") = " << Res << "\n");
3988bcb0991SDimitry Andric         return Res;
3998bcb0991SDimitry Andric       }
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric     /// Returns true if Block ends without a terminator.
blockAlwaysFallThrough(BBInfo & BBI) const4030b57cec5SDimitry Andric     bool blockAlwaysFallThrough(BBInfo &BBI) const {
4040b57cec5SDimitry Andric       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
4050b57cec5SDimitry Andric     }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     /// Used to sort if-conversion candidates.
IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> & C1,const std::unique_ptr<IfcvtToken> & C2)4080b57cec5SDimitry Andric     static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
4090b57cec5SDimitry Andric                               const std::unique_ptr<IfcvtToken> &C2) {
4100b57cec5SDimitry Andric       int Incr1 = (C1->Kind == ICDiamond)
4110b57cec5SDimitry Andric         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
4120b57cec5SDimitry Andric       int Incr2 = (C2->Kind == ICDiamond)
4130b57cec5SDimitry Andric         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
4140b57cec5SDimitry Andric       if (Incr1 > Incr2)
4150b57cec5SDimitry Andric         return true;
4160b57cec5SDimitry Andric       else if (Incr1 == Incr2) {
4170b57cec5SDimitry Andric         // Favors subsumption.
4180b57cec5SDimitry Andric         if (!C1->NeedSubsumption && C2->NeedSubsumption)
4190b57cec5SDimitry Andric           return true;
4200b57cec5SDimitry Andric         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
4210b57cec5SDimitry Andric           // Favors diamond over triangle, etc.
4220b57cec5SDimitry Andric           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
4230b57cec5SDimitry Andric             return true;
4240b57cec5SDimitry Andric           else if (C1->Kind == C2->Kind)
4250b57cec5SDimitry Andric             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
4260b57cec5SDimitry Andric         }
4270b57cec5SDimitry Andric       }
4280b57cec5SDimitry Andric       return false;
4290b57cec5SDimitry Andric     }
4300b57cec5SDimitry Andric   };
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric } // end anonymous namespace
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric char IfConverter::ID = 0;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric char &llvm::IfConverterID = IfConverter::ID;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)4390b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
440480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
4410b57cec5SDimitry Andric INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
4440b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
4450b57cec5SDimitry Andric     return false;
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget();
4480b57cec5SDimitry Andric   TLI = ST.getTargetLowering();
4490b57cec5SDimitry Andric   TII = ST.getInstrInfo();
4500b57cec5SDimitry Andric   TRI = ST.getRegisterInfo();
4515ffd83dbSDimitry Andric   MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
4520b57cec5SDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
453480093f4SDimitry Andric   ProfileSummaryInfo *PSI =
454480093f4SDimitry Andric       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
4550b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
4560b57cec5SDimitry Andric   SchedModel.init(&ST);
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   if (!TII) return false;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   PreRegAlloc = MRI->isSSA();
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   bool BFChange = false;
4630b57cec5SDimitry Andric   if (!PreRegAlloc) {
4640b57cec5SDimitry Andric     // Tail merge tend to expose more if-conversion opportunities.
465480093f4SDimitry Andric     BranchFolder BF(true, false, MBFI, *MBPI, PSI);
4665ffd83dbSDimitry Andric     BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo());
4670b57cec5SDimitry Andric   }
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
4700b57cec5SDimitry Andric                     << MF.getName() << "\'");
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
4730b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " skipped\n");
4740b57cec5SDimitry Andric     return false;
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n");
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   MF.RenumberBlocks();
4790b57cec5SDimitry Andric   BBAnalysis.resize(MF.getNumBlockIDs());
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   std::vector<std::unique_ptr<IfcvtToken>> Tokens;
4820b57cec5SDimitry Andric   MadeChange = false;
4830b57cec5SDimitry Andric   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
4840b57cec5SDimitry Andric     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
4850b57cec5SDimitry Andric   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
4860b57cec5SDimitry Andric     // Do an initial analysis for each basic block and find all the potential
4870b57cec5SDimitry Andric     // candidates to perform if-conversion.
4880b57cec5SDimitry Andric     bool Change = false;
4890b57cec5SDimitry Andric     AnalyzeBlocks(MF, Tokens);
4900b57cec5SDimitry Andric     while (!Tokens.empty()) {
4910b57cec5SDimitry Andric       std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
4920b57cec5SDimitry Andric       Tokens.pop_back();
4930b57cec5SDimitry Andric       BBInfo &BBI = Token->BBI;
4940b57cec5SDimitry Andric       IfcvtKind Kind = Token->Kind;
4950b57cec5SDimitry Andric       unsigned NumDups = Token->NumDups;
4960b57cec5SDimitry Andric       unsigned NumDups2 = Token->NumDups2;
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric       // If the block has been evicted out of the queue or it has already been
4990b57cec5SDimitry Andric       // marked dead (due to it being predicated), then skip it.
5000b57cec5SDimitry Andric       if (BBI.IsDone)
5010b57cec5SDimitry Andric         BBI.IsEnqueued = false;
5020b57cec5SDimitry Andric       if (!BBI.IsEnqueued)
5030b57cec5SDimitry Andric         continue;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric       BBI.IsEnqueued = false;
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric       bool RetVal = false;
5080b57cec5SDimitry Andric       switch (Kind) {
5090b57cec5SDimitry Andric       default: llvm_unreachable("Unexpected!");
5100b57cec5SDimitry Andric       case ICSimple:
5110b57cec5SDimitry Andric       case ICSimpleFalse: {
5120b57cec5SDimitry Andric         bool isFalse = Kind == ICSimpleFalse;
5130b57cec5SDimitry Andric         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
5140b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
5150b57cec5SDimitry Andric                           << (Kind == ICSimpleFalse ? " false" : "")
5160b57cec5SDimitry Andric                           << "): " << printMBBReference(*BBI.BB) << " ("
5170b57cec5SDimitry Andric                           << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
5180b57cec5SDimitry Andric                                                       : BBI.TrueBB->getNumber())
5190b57cec5SDimitry Andric                           << ") ");
5200b57cec5SDimitry Andric         RetVal = IfConvertSimple(BBI, Kind);
5210b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5220b57cec5SDimitry Andric         if (RetVal) {
5230b57cec5SDimitry Andric           if (isFalse) ++NumSimpleFalse;
5240b57cec5SDimitry Andric           else         ++NumSimple;
5250b57cec5SDimitry Andric         }
5260b57cec5SDimitry Andric        break;
5270b57cec5SDimitry Andric       }
5280b57cec5SDimitry Andric       case ICTriangle:
5290b57cec5SDimitry Andric       case ICTriangleRev:
5300b57cec5SDimitry Andric       case ICTriangleFalse:
5310b57cec5SDimitry Andric       case ICTriangleFRev: {
5320b57cec5SDimitry Andric         bool isFalse = Kind == ICTriangleFalse;
5330b57cec5SDimitry Andric         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
5340b57cec5SDimitry Andric         if (DisableTriangle && !isFalse && !isRev) break;
5350b57cec5SDimitry Andric         if (DisableTriangleR && !isFalse && isRev) break;
5360b57cec5SDimitry Andric         if (DisableTriangleF && isFalse && !isRev) break;
5370b57cec5SDimitry Andric         if (DisableTriangleFR && isFalse && isRev) break;
5380b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
5390b57cec5SDimitry Andric         if (isFalse)
5400b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << " false");
5410b57cec5SDimitry Andric         if (isRev)
5420b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << " rev");
5430b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
5440b57cec5SDimitry Andric                           << " (T:" << BBI.TrueBB->getNumber()
5450b57cec5SDimitry Andric                           << ",F:" << BBI.FalseBB->getNumber() << ") ");
5460b57cec5SDimitry Andric         RetVal = IfConvertTriangle(BBI, Kind);
5470b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5480b57cec5SDimitry Andric         if (RetVal) {
5490b57cec5SDimitry Andric           if (isFalse) {
5500b57cec5SDimitry Andric             if (isRev) ++NumTriangleFRev;
5510b57cec5SDimitry Andric             else       ++NumTriangleFalse;
5520b57cec5SDimitry Andric           } else {
5530b57cec5SDimitry Andric             if (isRev) ++NumTriangleRev;
5540b57cec5SDimitry Andric             else       ++NumTriangle;
5550b57cec5SDimitry Andric           }
5560b57cec5SDimitry Andric         }
5570b57cec5SDimitry Andric         break;
5580b57cec5SDimitry Andric       }
5590b57cec5SDimitry Andric       case ICDiamond:
5600b57cec5SDimitry Andric         if (DisableDiamond) break;
5610b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
5620b57cec5SDimitry Andric                           << " (T:" << BBI.TrueBB->getNumber()
5630b57cec5SDimitry Andric                           << ",F:" << BBI.FalseBB->getNumber() << ") ");
5640b57cec5SDimitry Andric         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
5650b57cec5SDimitry Andric                                   Token->TClobbersPred,
5660b57cec5SDimitry Andric                                   Token->FClobbersPred);
5670b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5680b57cec5SDimitry Andric         if (RetVal) ++NumDiamonds;
5690b57cec5SDimitry Andric         break;
5700b57cec5SDimitry Andric       case ICForkedDiamond:
5710b57cec5SDimitry Andric         if (DisableForkedDiamond) break;
5720b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
5730b57cec5SDimitry Andric                           << printMBBReference(*BBI.BB)
5740b57cec5SDimitry Andric                           << " (T:" << BBI.TrueBB->getNumber()
5750b57cec5SDimitry Andric                           << ",F:" << BBI.FalseBB->getNumber() << ") ");
5760b57cec5SDimitry Andric         RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
5770b57cec5SDimitry Andric                                       Token->TClobbersPred,
5780b57cec5SDimitry Andric                                       Token->FClobbersPred);
5790b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5800b57cec5SDimitry Andric         if (RetVal) ++NumForkedDiamonds;
5810b57cec5SDimitry Andric         break;
5820b57cec5SDimitry Andric       }
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric       if (RetVal && MRI->tracksLiveness())
5850b57cec5SDimitry Andric         recomputeLivenessFlags(*BBI.BB);
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric       Change |= RetVal;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
5900b57cec5SDimitry Andric         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
5910b57cec5SDimitry Andric       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
5920b57cec5SDimitry Andric         break;
5930b57cec5SDimitry Andric     }
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric     if (!Change)
5960b57cec5SDimitry Andric       break;
5970b57cec5SDimitry Andric     MadeChange |= Change;
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   Tokens.clear();
6010b57cec5SDimitry Andric   BBAnalysis.clear();
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   if (MadeChange && IfCvtBranchFold) {
604480093f4SDimitry Andric     BranchFolder BF(false, false, MBFI, *MBPI, PSI);
6055ffd83dbSDimitry Andric     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo());
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   MadeChange |= BFChange;
6090b57cec5SDimitry Andric   return MadeChange;
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
findFalseBlock(MachineBasicBlock * BB,MachineBasicBlock * TrueBB)6130b57cec5SDimitry Andric static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
6140b57cec5SDimitry Andric                                          MachineBasicBlock *TrueBB) {
6150b57cec5SDimitry Andric   for (MachineBasicBlock *SuccBB : BB->successors()) {
6160b57cec5SDimitry Andric     if (SuccBB != TrueBB)
6170b57cec5SDimitry Andric       return SuccBB;
6180b57cec5SDimitry Andric   }
6190b57cec5SDimitry Andric   return nullptr;
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric /// Reverse the condition of the end of the block branch. Swap block's 'true'
6230b57cec5SDimitry Andric /// and 'false' successors.
reverseBranchCondition(BBInfo & BBI) const6240b57cec5SDimitry Andric bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
6250b57cec5SDimitry Andric   DebugLoc dl;  // FIXME: this is nowhere
6260b57cec5SDimitry Andric   if (!TII->reverseBranchCondition(BBI.BrCond)) {
6270b57cec5SDimitry Andric     TII->removeBranch(*BBI.BB);
6280b57cec5SDimitry Andric     TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
6290b57cec5SDimitry Andric     std::swap(BBI.TrueBB, BBI.FalseBB);
6300b57cec5SDimitry Andric     return true;
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric   return false;
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric /// Returns the next block in the function blocks ordering. If it is the end,
6360b57cec5SDimitry Andric /// returns NULL.
getNextBlock(MachineBasicBlock & MBB)6370b57cec5SDimitry Andric static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
6380b57cec5SDimitry Andric   MachineFunction::iterator I = MBB.getIterator();
6390b57cec5SDimitry Andric   MachineFunction::iterator E = MBB.getParent()->end();
6400b57cec5SDimitry Andric   if (++I == E)
6410b57cec5SDimitry Andric     return nullptr;
6420b57cec5SDimitry Andric   return &*I;
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric /// Returns true if the 'true' block (along with its predecessor) forms a valid
6460b57cec5SDimitry Andric /// simple shape for ifcvt. It also returns the number of instructions that the
6470b57cec5SDimitry Andric /// ifcvt would need to duplicate if performed in Dups.
ValidSimple(BBInfo & TrueBBI,unsigned & Dups,BranchProbability Prediction) const6480b57cec5SDimitry Andric bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
6490b57cec5SDimitry Andric                               BranchProbability Prediction) const {
6500b57cec5SDimitry Andric   Dups = 0;
6510b57cec5SDimitry Andric   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
6520b57cec5SDimitry Andric     return false;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   if (TrueBBI.IsBrAnalyzable)
6550b57cec5SDimitry Andric     return false;
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   if (TrueBBI.BB->pred_size() > 1) {
6580b57cec5SDimitry Andric     if (TrueBBI.CannotBeCopied ||
6590b57cec5SDimitry Andric         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
6600b57cec5SDimitry Andric                                         Prediction))
6610b57cec5SDimitry Andric       return false;
6620b57cec5SDimitry Andric     Dups = TrueBBI.NonPredSize;
6630b57cec5SDimitry Andric   }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   return true;
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric /// Returns true if the 'true' and 'false' blocks (along with their common
6690b57cec5SDimitry Andric /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
6700b57cec5SDimitry Andric /// true, it checks if 'true' block's false branch branches to the 'false' block
6710b57cec5SDimitry Andric /// rather than the other way around. It also returns the number of instructions
6720b57cec5SDimitry Andric /// that the ifcvt would need to duplicate if performed in 'Dups'.
ValidTriangle(BBInfo & TrueBBI,BBInfo & FalseBBI,bool FalseBranch,unsigned & Dups,BranchProbability Prediction) const6730b57cec5SDimitry Andric bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
6740b57cec5SDimitry Andric                                 bool FalseBranch, unsigned &Dups,
6750b57cec5SDimitry Andric                                 BranchProbability Prediction) const {
6760b57cec5SDimitry Andric   Dups = 0;
6778bcb0991SDimitry Andric   if (TrueBBI.BB == FalseBBI.BB)
6788bcb0991SDimitry Andric     return false;
6798bcb0991SDimitry Andric 
6800b57cec5SDimitry Andric   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
6810b57cec5SDimitry Andric     return false;
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   if (TrueBBI.BB->pred_size() > 1) {
6840b57cec5SDimitry Andric     if (TrueBBI.CannotBeCopied)
6850b57cec5SDimitry Andric       return false;
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric     unsigned Size = TrueBBI.NonPredSize;
6880b57cec5SDimitry Andric     if (TrueBBI.IsBrAnalyzable) {
6890b57cec5SDimitry Andric       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
6900b57cec5SDimitry Andric         // Ends with an unconditional branch. It will be removed.
6910b57cec5SDimitry Andric         --Size;
6920b57cec5SDimitry Andric       else {
6930b57cec5SDimitry Andric         MachineBasicBlock *FExit = FalseBranch
6940b57cec5SDimitry Andric           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
6950b57cec5SDimitry Andric         if (FExit)
6960b57cec5SDimitry Andric           // Require a conditional branch
6970b57cec5SDimitry Andric           ++Size;
6980b57cec5SDimitry Andric       }
6990b57cec5SDimitry Andric     }
7000b57cec5SDimitry Andric     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
7010b57cec5SDimitry Andric       return false;
7020b57cec5SDimitry Andric     Dups = Size;
7030b57cec5SDimitry Andric   }
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
7060b57cec5SDimitry Andric   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
7070b57cec5SDimitry Andric     MachineFunction::iterator I = TrueBBI.BB->getIterator();
7080b57cec5SDimitry Andric     if (++I == TrueBBI.BB->getParent()->end())
7090b57cec5SDimitry Andric       return false;
7100b57cec5SDimitry Andric     TExit = &*I;
7110b57cec5SDimitry Andric   }
7120b57cec5SDimitry Andric   return TExit && TExit == FalseBBI.BB;
7130b57cec5SDimitry Andric }
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric /// Count duplicated instructions and move the iterators to show where they
7160b57cec5SDimitry Andric /// are.
7170b57cec5SDimitry Andric /// @param TIB True Iterator Begin
7180b57cec5SDimitry Andric /// @param FIB False Iterator Begin
7190b57cec5SDimitry Andric /// These two iterators initially point to the first instruction of the two
7200b57cec5SDimitry Andric /// blocks, and finally point to the first non-shared instruction.
7210b57cec5SDimitry Andric /// @param TIE True Iterator End
7220b57cec5SDimitry Andric /// @param FIE False Iterator End
7230b57cec5SDimitry Andric /// These two iterators initially point to End() for the two blocks() and
7240b57cec5SDimitry Andric /// finally point to the first shared instruction in the tail.
7250b57cec5SDimitry Andric /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
7260b57cec5SDimitry Andric /// two blocks.
7270b57cec5SDimitry Andric /// @param Dups1 count of duplicated instructions at the beginning of the 2
7280b57cec5SDimitry Andric /// blocks.
7290b57cec5SDimitry Andric /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
7300b57cec5SDimitry Andric /// @param SkipUnconditionalBranches if true, Don't make sure that
7310b57cec5SDimitry Andric /// unconditional branches at the end of the blocks are the same. True is
7320b57cec5SDimitry Andric /// passed when the blocks are analyzable to allow for fallthrough to be
7330b57cec5SDimitry Andric /// handled.
7340b57cec5SDimitry Andric /// @return false if the shared portion prevents if conversion.
CountDuplicatedInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,unsigned & Dups1,unsigned & Dups2,MachineBasicBlock & TBB,MachineBasicBlock & FBB,bool SkipUnconditionalBranches) const7350b57cec5SDimitry Andric bool IfConverter::CountDuplicatedInstructions(
7360b57cec5SDimitry Andric     MachineBasicBlock::iterator &TIB,
7370b57cec5SDimitry Andric     MachineBasicBlock::iterator &FIB,
7380b57cec5SDimitry Andric     MachineBasicBlock::iterator &TIE,
7390b57cec5SDimitry Andric     MachineBasicBlock::iterator &FIE,
7400b57cec5SDimitry Andric     unsigned &Dups1, unsigned &Dups2,
7410b57cec5SDimitry Andric     MachineBasicBlock &TBB, MachineBasicBlock &FBB,
7420b57cec5SDimitry Andric     bool SkipUnconditionalBranches) const {
7430b57cec5SDimitry Andric   while (TIB != TIE && FIB != FIE) {
7440b57cec5SDimitry Andric     // Skip dbg_value instructions. These do not count.
745*5f7ddb14SDimitry Andric     TIB = skipDebugInstructionsForward(TIB, TIE, false);
746*5f7ddb14SDimitry Andric     FIB = skipDebugInstructionsForward(FIB, FIE, false);
7470b57cec5SDimitry Andric     if (TIB == TIE || FIB == FIE)
7480b57cec5SDimitry Andric       break;
7490b57cec5SDimitry Andric     if (!TIB->isIdenticalTo(*FIB))
7500b57cec5SDimitry Andric       break;
7510b57cec5SDimitry Andric     // A pred-clobbering instruction in the shared portion prevents
7520b57cec5SDimitry Andric     // if-conversion.
7530b57cec5SDimitry Andric     std::vector<MachineOperand> PredDefs;
754af732203SDimitry Andric     if (TII->ClobbersPredicate(*TIB, PredDefs, false))
7550b57cec5SDimitry Andric       return false;
7560b57cec5SDimitry Andric     // If we get all the way to the branch instructions, don't count them.
7570b57cec5SDimitry Andric     if (!TIB->isBranch())
7580b57cec5SDimitry Andric       ++Dups1;
7590b57cec5SDimitry Andric     ++TIB;
7600b57cec5SDimitry Andric     ++FIB;
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   // Check for already containing all of the block.
7640b57cec5SDimitry Andric   if (TIB == TIE || FIB == FIE)
7650b57cec5SDimitry Andric     return true;
7660b57cec5SDimitry Andric   // Now, in preparation for counting duplicate instructions at the ends of the
7670b57cec5SDimitry Andric   // blocks, switch to reverse_iterators. Note that getReverse() returns an
7680b57cec5SDimitry Andric   // iterator that points to the same instruction, unlike std::reverse_iterator.
7690b57cec5SDimitry Andric   // We have to do our own shifting so that we get the same range.
7700b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
7710b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
7720b57cec5SDimitry Andric   const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
7730b57cec5SDimitry Andric   const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   if (!TBB.succ_empty() || !FBB.succ_empty()) {
7760b57cec5SDimitry Andric     if (SkipUnconditionalBranches) {
7770b57cec5SDimitry Andric       while (RTIE != RTIB && RTIE->isUnconditionalBranch())
7780b57cec5SDimitry Andric         ++RTIE;
7790b57cec5SDimitry Andric       while (RFIE != RFIB && RFIE->isUnconditionalBranch())
7800b57cec5SDimitry Andric         ++RFIE;
7810b57cec5SDimitry Andric     }
7820b57cec5SDimitry Andric   }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   // Count duplicate instructions at the ends of the blocks.
7850b57cec5SDimitry Andric   while (RTIE != RTIB && RFIE != RFIB) {
7860b57cec5SDimitry Andric     // Skip dbg_value instructions. These do not count.
7870b57cec5SDimitry Andric     // Note that these are reverse iterators going forward.
788*5f7ddb14SDimitry Andric     RTIE = skipDebugInstructionsForward(RTIE, RTIB, false);
789*5f7ddb14SDimitry Andric     RFIE = skipDebugInstructionsForward(RFIE, RFIB, false);
7900b57cec5SDimitry Andric     if (RTIE == RTIB || RFIE == RFIB)
7910b57cec5SDimitry Andric       break;
7920b57cec5SDimitry Andric     if (!RTIE->isIdenticalTo(*RFIE))
7930b57cec5SDimitry Andric       break;
7940b57cec5SDimitry Andric     // We have to verify that any branch instructions are the same, and then we
7950b57cec5SDimitry Andric     // don't count them toward the # of duplicate instructions.
7960b57cec5SDimitry Andric     if (!RTIE->isBranch())
7970b57cec5SDimitry Andric       ++Dups2;
7980b57cec5SDimitry Andric     ++RTIE;
7990b57cec5SDimitry Andric     ++RFIE;
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric   TIE = std::next(RTIE.getReverse());
8020b57cec5SDimitry Andric   FIE = std::next(RFIE.getReverse());
8030b57cec5SDimitry Andric   return true;
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric /// RescanInstructions - Run ScanInstructions on a pair of blocks.
8070b57cec5SDimitry Andric /// @param TIB - True Iterator Begin, points to first non-shared instruction
8080b57cec5SDimitry Andric /// @param FIB - False Iterator Begin, points to first non-shared instruction
8090b57cec5SDimitry Andric /// @param TIE - True Iterator End, points past last non-shared instruction
8100b57cec5SDimitry Andric /// @param FIE - False Iterator End, points past last non-shared instruction
8110b57cec5SDimitry Andric /// @param TrueBBI  - BBInfo to update for the true block.
8120b57cec5SDimitry Andric /// @param FalseBBI - BBInfo to update for the false block.
8130b57cec5SDimitry Andric /// @returns - false if either block cannot be predicated or if both blocks end
8140b57cec5SDimitry Andric ///   with a predicate-clobbering instruction.
RescanInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,BBInfo & TrueBBI,BBInfo & FalseBBI) const8150b57cec5SDimitry Andric bool IfConverter::RescanInstructions(
8160b57cec5SDimitry Andric     MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
8170b57cec5SDimitry Andric     MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
8180b57cec5SDimitry Andric     BBInfo &TrueBBI, BBInfo &FalseBBI) const {
8190b57cec5SDimitry Andric   bool BranchUnpredicable = true;
8200b57cec5SDimitry Andric   TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
8210b57cec5SDimitry Andric   ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
8220b57cec5SDimitry Andric   if (TrueBBI.IsUnpredicable)
8230b57cec5SDimitry Andric     return false;
8240b57cec5SDimitry Andric   ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
8250b57cec5SDimitry Andric   if (FalseBBI.IsUnpredicable)
8260b57cec5SDimitry Andric     return false;
8270b57cec5SDimitry Andric   if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
8280b57cec5SDimitry Andric     return false;
8290b57cec5SDimitry Andric   return true;
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric #ifndef NDEBUG
verifySameBranchInstructions(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2)8330b57cec5SDimitry Andric static void verifySameBranchInstructions(
8340b57cec5SDimitry Andric     MachineBasicBlock *MBB1,
8350b57cec5SDimitry Andric     MachineBasicBlock *MBB2) {
8360b57cec5SDimitry Andric   const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
8370b57cec5SDimitry Andric   const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
8380b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
8390b57cec5SDimitry Andric   MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
8400b57cec5SDimitry Andric   while (E1 != B1 && E2 != B2) {
841*5f7ddb14SDimitry Andric     skipDebugInstructionsForward(E1, B1, false);
842*5f7ddb14SDimitry Andric     skipDebugInstructionsForward(E2, B2, false);
8430b57cec5SDimitry Andric     if (E1 == B1 && E2 == B2)
8440b57cec5SDimitry Andric       break;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric     if (E1 == B1) {
8470b57cec5SDimitry Andric       assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
8480b57cec5SDimitry Andric       break;
8490b57cec5SDimitry Andric     }
8500b57cec5SDimitry Andric     if (E2 == B2) {
8510b57cec5SDimitry Andric       assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
8520b57cec5SDimitry Andric       break;
8530b57cec5SDimitry Andric     }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     if (E1->isBranch() || E2->isBranch())
8560b57cec5SDimitry Andric       assert(E1->isIdenticalTo(*E2) &&
8570b57cec5SDimitry Andric              "Branch mis-match, branch instructions don't match.");
8580b57cec5SDimitry Andric     else
8590b57cec5SDimitry Andric       break;
8600b57cec5SDimitry Andric     ++E1;
8610b57cec5SDimitry Andric     ++E2;
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric #endif
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
8670b57cec5SDimitry Andric /// with their common predecessor) form a diamond if a common tail block is
8680b57cec5SDimitry Andric /// extracted.
8690b57cec5SDimitry Andric /// While not strictly a diamond, this pattern would form a diamond if
8700b57cec5SDimitry Andric /// tail-merging had merged the shared tails.
8710b57cec5SDimitry Andric ///           EBB
8720b57cec5SDimitry Andric ///         _/   \_
8730b57cec5SDimitry Andric ///         |     |
8740b57cec5SDimitry Andric ///        TBB   FBB
8750b57cec5SDimitry Andric ///        /  \ /   \
8760b57cec5SDimitry Andric ///  FalseBB TrueBB FalseBB
8770b57cec5SDimitry Andric /// Currently only handles analyzable branches.
8780b57cec5SDimitry Andric /// Specifically excludes actual diamonds to avoid overlap.
ValidForkedDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const8790b57cec5SDimitry Andric bool IfConverter::ValidForkedDiamond(
8800b57cec5SDimitry Andric     BBInfo &TrueBBI, BBInfo &FalseBBI,
8810b57cec5SDimitry Andric     unsigned &Dups1, unsigned &Dups2,
8820b57cec5SDimitry Andric     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
8830b57cec5SDimitry Andric   Dups1 = Dups2 = 0;
8840b57cec5SDimitry Andric   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
8850b57cec5SDimitry Andric       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
8860b57cec5SDimitry Andric     return false;
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
8890b57cec5SDimitry Andric     return false;
8900b57cec5SDimitry Andric   // Don't IfConvert blocks that can't be folded into their predecessor.
8910b57cec5SDimitry Andric   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
8920b57cec5SDimitry Andric     return false;
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   // This function is specifically looking for conditional tails, as
8950b57cec5SDimitry Andric   // unconditional tails are already handled by the standard diamond case.
8960b57cec5SDimitry Andric   if (TrueBBI.BrCond.size() == 0 ||
8970b57cec5SDimitry Andric       FalseBBI.BrCond.size() == 0)
8980b57cec5SDimitry Andric     return false;
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric   MachineBasicBlock *TT = TrueBBI.TrueBB;
9010b57cec5SDimitry Andric   MachineBasicBlock *TF = TrueBBI.FalseBB;
9020b57cec5SDimitry Andric   MachineBasicBlock *FT = FalseBBI.TrueBB;
9030b57cec5SDimitry Andric   MachineBasicBlock *FF = FalseBBI.FalseBB;
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   if (!TT)
9060b57cec5SDimitry Andric     TT = getNextBlock(*TrueBBI.BB);
9070b57cec5SDimitry Andric   if (!TF)
9080b57cec5SDimitry Andric     TF = getNextBlock(*TrueBBI.BB);
9090b57cec5SDimitry Andric   if (!FT)
9100b57cec5SDimitry Andric     FT = getNextBlock(*FalseBBI.BB);
9110b57cec5SDimitry Andric   if (!FF)
9120b57cec5SDimitry Andric     FF = getNextBlock(*FalseBBI.BB);
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   if (!TT || !TF)
9150b57cec5SDimitry Andric     return false;
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   // Check successors. If they don't match, bail.
9180b57cec5SDimitry Andric   if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
9190b57cec5SDimitry Andric     return false;
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   bool FalseReversed = false;
9220b57cec5SDimitry Andric   if (TF == FT && TT == FF) {
9230b57cec5SDimitry Andric     // If the branches are opposing, but we can't reverse, don't do it.
9240b57cec5SDimitry Andric     if (!FalseBBI.IsBrReversible)
9250b57cec5SDimitry Andric       return false;
9260b57cec5SDimitry Andric     FalseReversed = true;
9270b57cec5SDimitry Andric     reverseBranchCondition(FalseBBI);
9280b57cec5SDimitry Andric   }
9290b57cec5SDimitry Andric   auto UnReverseOnExit = make_scope_exit([&]() {
9300b57cec5SDimitry Andric     if (FalseReversed)
9310b57cec5SDimitry Andric       reverseBranchCondition(FalseBBI);
9320b57cec5SDimitry Andric   });
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   // Count duplicate instructions at the beginning of the true and false blocks.
9350b57cec5SDimitry Andric   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
9360b57cec5SDimitry Andric   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
9370b57cec5SDimitry Andric   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
9380b57cec5SDimitry Andric   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
9390b57cec5SDimitry Andric   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
9400b57cec5SDimitry Andric                                   *TrueBBI.BB, *FalseBBI.BB,
9410b57cec5SDimitry Andric                                   /* SkipUnconditionalBranches */ true))
9420b57cec5SDimitry Andric     return false;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   TrueBBICalc.BB = TrueBBI.BB;
9450b57cec5SDimitry Andric   FalseBBICalc.BB = FalseBBI.BB;
9468bcb0991SDimitry Andric   TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
9478bcb0991SDimitry Andric   FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
9480b57cec5SDimitry Andric   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
9490b57cec5SDimitry Andric     return false;
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   // The size is used to decide whether to if-convert, and the shared portions
9520b57cec5SDimitry Andric   // are subtracted off. Because of the subtraction, we just use the size that
9530b57cec5SDimitry Andric   // was calculated by the original ScanInstructions, as it is correct.
9540b57cec5SDimitry Andric   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
9550b57cec5SDimitry Andric   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
9560b57cec5SDimitry Andric   return true;
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
9600b57cec5SDimitry Andric /// with their common predecessor) forms a valid diamond shape for ifcvt.
ValidDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const9610b57cec5SDimitry Andric bool IfConverter::ValidDiamond(
9620b57cec5SDimitry Andric     BBInfo &TrueBBI, BBInfo &FalseBBI,
9630b57cec5SDimitry Andric     unsigned &Dups1, unsigned &Dups2,
9640b57cec5SDimitry Andric     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
9650b57cec5SDimitry Andric   Dups1 = Dups2 = 0;
9660b57cec5SDimitry Andric   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
9670b57cec5SDimitry Andric       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
9680b57cec5SDimitry Andric     return false;
9690b57cec5SDimitry Andric 
9705ffd83dbSDimitry Andric   // If the True and False BBs are equal we're dealing with a degenerate case
9715ffd83dbSDimitry Andric   // that we don't treat as a diamond.
9725ffd83dbSDimitry Andric   if (TrueBBI.BB == FalseBBI.BB)
9735ffd83dbSDimitry Andric     return false;
9745ffd83dbSDimitry Andric 
9750b57cec5SDimitry Andric   MachineBasicBlock *TT = TrueBBI.TrueBB;
9760b57cec5SDimitry Andric   MachineBasicBlock *FT = FalseBBI.TrueBB;
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   if (!TT && blockAlwaysFallThrough(TrueBBI))
9790b57cec5SDimitry Andric     TT = getNextBlock(*TrueBBI.BB);
9800b57cec5SDimitry Andric   if (!FT && blockAlwaysFallThrough(FalseBBI))
9810b57cec5SDimitry Andric     FT = getNextBlock(*FalseBBI.BB);
9820b57cec5SDimitry Andric   if (TT != FT)
9830b57cec5SDimitry Andric     return false;
9840b57cec5SDimitry Andric   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
9850b57cec5SDimitry Andric     return false;
9860b57cec5SDimitry Andric   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
9870b57cec5SDimitry Andric     return false;
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric   // FIXME: Allow true block to have an early exit?
9900b57cec5SDimitry Andric   if (TrueBBI.FalseBB || FalseBBI.FalseBB)
9910b57cec5SDimitry Andric     return false;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   // Count duplicate instructions at the beginning and end of the true and
9940b57cec5SDimitry Andric   // false blocks.
9950b57cec5SDimitry Andric   // Skip unconditional branches only if we are considering an analyzable
9960b57cec5SDimitry Andric   // diamond. Otherwise the branches must be the same.
9970b57cec5SDimitry Andric   bool SkipUnconditionalBranches =
9980b57cec5SDimitry Andric       TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
9990b57cec5SDimitry Andric   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
10000b57cec5SDimitry Andric   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
10010b57cec5SDimitry Andric   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
10020b57cec5SDimitry Andric   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
10030b57cec5SDimitry Andric   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
10040b57cec5SDimitry Andric                                   *TrueBBI.BB, *FalseBBI.BB,
10050b57cec5SDimitry Andric                                   SkipUnconditionalBranches))
10060b57cec5SDimitry Andric     return false;
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   TrueBBICalc.BB = TrueBBI.BB;
10090b57cec5SDimitry Andric   FalseBBICalc.BB = FalseBBI.BB;
10108bcb0991SDimitry Andric   TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
10118bcb0991SDimitry Andric   FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
10120b57cec5SDimitry Andric   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
10130b57cec5SDimitry Andric     return false;
10140b57cec5SDimitry Andric   // The size is used to decide whether to if-convert, and the shared portions
10150b57cec5SDimitry Andric   // are subtracted off. Because of the subtraction, we just use the size that
10160b57cec5SDimitry Andric   // was calculated by the original ScanInstructions, as it is correct.
10170b57cec5SDimitry Andric   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
10180b57cec5SDimitry Andric   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
10190b57cec5SDimitry Andric   return true;
10200b57cec5SDimitry Andric }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric /// AnalyzeBranches - Look at the branches at the end of a block to determine if
10230b57cec5SDimitry Andric /// the block is predicable.
AnalyzeBranches(BBInfo & BBI)10240b57cec5SDimitry Andric void IfConverter::AnalyzeBranches(BBInfo &BBI) {
10250b57cec5SDimitry Andric   if (BBI.IsDone)
10260b57cec5SDimitry Andric     return;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   BBI.TrueBB = BBI.FalseBB = nullptr;
10290b57cec5SDimitry Andric   BBI.BrCond.clear();
10300b57cec5SDimitry Andric   BBI.IsBrAnalyzable =
10310b57cec5SDimitry Andric       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
10320b57cec5SDimitry Andric   if (!BBI.IsBrAnalyzable) {
10330b57cec5SDimitry Andric     BBI.TrueBB = nullptr;
10340b57cec5SDimitry Andric     BBI.FalseBB = nullptr;
10350b57cec5SDimitry Andric     BBI.BrCond.clear();
10360b57cec5SDimitry Andric   }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
10390b57cec5SDimitry Andric   BBI.IsBrReversible = (RevCond.size() == 0) ||
10400b57cec5SDimitry Andric       !TII->reverseBranchCondition(RevCond);
10410b57cec5SDimitry Andric   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   if (BBI.BrCond.size()) {
10440b57cec5SDimitry Andric     // No false branch. This BB must end with a conditional branch and a
10450b57cec5SDimitry Andric     // fallthrough.
10460b57cec5SDimitry Andric     if (!BBI.FalseBB)
10470b57cec5SDimitry Andric       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
10480b57cec5SDimitry Andric     if (!BBI.FalseBB) {
10490b57cec5SDimitry Andric       // Malformed bcc? True and false blocks are the same?
10500b57cec5SDimitry Andric       BBI.IsUnpredicable = true;
10510b57cec5SDimitry Andric     }
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric /// ScanInstructions - Scan all the instructions in the block to determine if
10560b57cec5SDimitry Andric /// the block is predicable. In most cases, that means all the instructions
10570b57cec5SDimitry Andric /// in the block are isPredicable(). Also checks if the block contains any
10580b57cec5SDimitry Andric /// instruction which can clobber a predicate (e.g. condition code register).
10590b57cec5SDimitry Andric /// If so, the block is not predicable unless it's the last instruction.
ScanInstructions(BBInfo & BBI,MachineBasicBlock::iterator & Begin,MachineBasicBlock::iterator & End,bool BranchUnpredicable) const10600b57cec5SDimitry Andric void IfConverter::ScanInstructions(BBInfo &BBI,
10610b57cec5SDimitry Andric                                    MachineBasicBlock::iterator &Begin,
10620b57cec5SDimitry Andric                                    MachineBasicBlock::iterator &End,
10630b57cec5SDimitry Andric                                    bool BranchUnpredicable) const {
10640b57cec5SDimitry Andric   if (BBI.IsDone || BBI.IsUnpredicable)
10650b57cec5SDimitry Andric     return;
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   bool AlreadyPredicated = !BBI.Predicate.empty();
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric   BBI.NonPredSize = 0;
10700b57cec5SDimitry Andric   BBI.ExtraCost = 0;
10710b57cec5SDimitry Andric   BBI.ExtraCost2 = 0;
10720b57cec5SDimitry Andric   BBI.ClobbersPred = false;
10730b57cec5SDimitry Andric   for (MachineInstr &MI : make_range(Begin, End)) {
10740b57cec5SDimitry Andric     if (MI.isDebugInstr())
10750b57cec5SDimitry Andric       continue;
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric     // It's unsafe to duplicate convergent instructions in this context, so set
10780b57cec5SDimitry Andric     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
10790b57cec5SDimitry Andric     // following CFG, which is subject to our "simple" transformation.
10800b57cec5SDimitry Andric     //
10810b57cec5SDimitry Andric     //    BB0     // if (c1) goto BB1; else goto BB2;
10820b57cec5SDimitry Andric     //   /   \
10830b57cec5SDimitry Andric     //  BB1   |
10840b57cec5SDimitry Andric     //   |   BB2  // if (c2) goto TBB; else goto FBB;
10850b57cec5SDimitry Andric     //   |   / |
10860b57cec5SDimitry Andric     //   |  /  |
10870b57cec5SDimitry Andric     //   TBB   |
10880b57cec5SDimitry Andric     //    |    |
10890b57cec5SDimitry Andric     //    |   FBB
10900b57cec5SDimitry Andric     //    |
10910b57cec5SDimitry Andric     //    exit
10920b57cec5SDimitry Andric     //
10930b57cec5SDimitry Andric     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
10940b57cec5SDimitry Andric     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
10950b57cec5SDimitry Andric     // TBB contains a convergent instruction.  This is safe iff doing so does
10960b57cec5SDimitry Andric     // not add a control-flow dependency to the convergent instruction -- i.e.,
10970b57cec5SDimitry Andric     // it's safe iff the set of control flows that leads us to the convergent
10980b57cec5SDimitry Andric     // instruction does not get smaller after the transformation.
10990b57cec5SDimitry Andric     //
11000b57cec5SDimitry Andric     // Originally we executed TBB if c1 || c2.  After the transformation, there
11010b57cec5SDimitry Andric     // are two copies of TBB's instructions.  We get to the first if c1, and we
11020b57cec5SDimitry Andric     // get to the second if !c1 && c2.
11030b57cec5SDimitry Andric     //
11040b57cec5SDimitry Andric     // There are clearly fewer ways to satisfy the condition "c1" than
11050b57cec5SDimitry Andric     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
11060b57cec5SDimitry Andric     // our convergent instruction, the transformation is unsafe.
11070b57cec5SDimitry Andric     if (MI.isNotDuplicable() || MI.isConvergent())
11080b57cec5SDimitry Andric       BBI.CannotBeCopied = true;
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric     bool isPredicated = TII->isPredicated(MI);
11110b57cec5SDimitry Andric     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric     if (BranchUnpredicable && MI.isBranch()) {
11140b57cec5SDimitry Andric       BBI.IsUnpredicable = true;
11150b57cec5SDimitry Andric       return;
11160b57cec5SDimitry Andric     }
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric     // A conditional branch is not predicable, but it may be eliminated.
11190b57cec5SDimitry Andric     if (isCondBr)
11200b57cec5SDimitry Andric       continue;
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     if (!isPredicated) {
11230b57cec5SDimitry Andric       BBI.NonPredSize++;
11240b57cec5SDimitry Andric       unsigned ExtraPredCost = TII->getPredicationCost(MI);
11250b57cec5SDimitry Andric       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
11260b57cec5SDimitry Andric       if (NumCycles > 1)
11270b57cec5SDimitry Andric         BBI.ExtraCost += NumCycles-1;
11280b57cec5SDimitry Andric       BBI.ExtraCost2 += ExtraPredCost;
11290b57cec5SDimitry Andric     } else if (!AlreadyPredicated) {
11300b57cec5SDimitry Andric       // FIXME: This instruction is already predicated before the
11310b57cec5SDimitry Andric       // if-conversion pass. It's probably something like a conditional move.
11320b57cec5SDimitry Andric       // Mark this block unpredicable for now.
11330b57cec5SDimitry Andric       BBI.IsUnpredicable = true;
11340b57cec5SDimitry Andric       return;
11350b57cec5SDimitry Andric     }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric     if (BBI.ClobbersPred && !isPredicated) {
11380b57cec5SDimitry Andric       // Predicate modification instruction should end the block (except for
11390b57cec5SDimitry Andric       // already predicated instructions and end of block branches).
11400b57cec5SDimitry Andric       // Predicate may have been modified, the subsequent (currently)
11410b57cec5SDimitry Andric       // unpredicated instructions cannot be correctly predicated.
11420b57cec5SDimitry Andric       BBI.IsUnpredicable = true;
11430b57cec5SDimitry Andric       return;
11440b57cec5SDimitry Andric     }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
11470b57cec5SDimitry Andric     // still potentially predicable.
11480b57cec5SDimitry Andric     std::vector<MachineOperand> PredDefs;
1149af732203SDimitry Andric     if (TII->ClobbersPredicate(MI, PredDefs, true))
11500b57cec5SDimitry Andric       BBI.ClobbersPred = true;
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric     if (!TII->isPredicable(MI)) {
11530b57cec5SDimitry Andric       BBI.IsUnpredicable = true;
11540b57cec5SDimitry Andric       return;
11550b57cec5SDimitry Andric     }
11560b57cec5SDimitry Andric   }
11570b57cec5SDimitry Andric }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric /// Determine if the block is a suitable candidate to be predicated by the
11600b57cec5SDimitry Andric /// specified predicate.
11610b57cec5SDimitry Andric /// @param BBI BBInfo for the block to check
11620b57cec5SDimitry Andric /// @param Pred Predicate array for the branch that leads to BBI
11630b57cec5SDimitry Andric /// @param isTriangle true if the Analysis is for a triangle
11640b57cec5SDimitry Andric /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
11650b57cec5SDimitry Andric ///        case
11660b57cec5SDimitry Andric /// @param hasCommonTail true if BBI shares a tail with a sibling block that
11670b57cec5SDimitry Andric ///        contains any instruction that would make the block unpredicable.
FeasibilityAnalysis(BBInfo & BBI,SmallVectorImpl<MachineOperand> & Pred,bool isTriangle,bool RevBranch,bool hasCommonTail)11680b57cec5SDimitry Andric bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
11690b57cec5SDimitry Andric                                       SmallVectorImpl<MachineOperand> &Pred,
11700b57cec5SDimitry Andric                                       bool isTriangle, bool RevBranch,
11710b57cec5SDimitry Andric                                       bool hasCommonTail) {
11720b57cec5SDimitry Andric   // If the block is dead or unpredicable, then it cannot be predicated.
11730b57cec5SDimitry Andric   // Two blocks may share a common unpredicable tail, but this doesn't prevent
11740b57cec5SDimitry Andric   // them from being if-converted. The non-shared portion is assumed to have
11750b57cec5SDimitry Andric   // been checked
11760b57cec5SDimitry Andric   if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
11770b57cec5SDimitry Andric     return false;
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric   // If it is already predicated but we couldn't analyze its terminator, the
11800b57cec5SDimitry Andric   // latter might fallthrough, but we can't determine where to.
11810b57cec5SDimitry Andric   // Conservatively avoid if-converting again.
11820b57cec5SDimitry Andric   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
11830b57cec5SDimitry Andric     return false;
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   // If it is already predicated, check if the new predicate subsumes
11860b57cec5SDimitry Andric   // its predicate.
11870b57cec5SDimitry Andric   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
11880b57cec5SDimitry Andric     return false;
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric   if (!hasCommonTail && BBI.BrCond.size()) {
11910b57cec5SDimitry Andric     if (!isTriangle)
11920b57cec5SDimitry Andric       return false;
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric     // Test predicate subsumption.
11950b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
11960b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
11970b57cec5SDimitry Andric     if (RevBranch) {
11980b57cec5SDimitry Andric       if (TII->reverseBranchCondition(Cond))
11990b57cec5SDimitry Andric         return false;
12000b57cec5SDimitry Andric     }
12010b57cec5SDimitry Andric     if (TII->reverseBranchCondition(RevPred) ||
12020b57cec5SDimitry Andric         !TII->SubsumesPredicate(Cond, RevPred))
12030b57cec5SDimitry Andric       return false;
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric   return true;
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric /// Analyze the structure of the sub-CFG starting from the specified block.
12100b57cec5SDimitry Andric /// Record its successors and whether it looks like an if-conversion candidate.
AnalyzeBlock(MachineBasicBlock & MBB,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)12110b57cec5SDimitry Andric void IfConverter::AnalyzeBlock(
12120b57cec5SDimitry Andric     MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
12130b57cec5SDimitry Andric   struct BBState {
12140b57cec5SDimitry Andric     BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
12150b57cec5SDimitry Andric     MachineBasicBlock *MBB;
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric     /// This flag is true if MBB's successors have been analyzed.
12180b57cec5SDimitry Andric     bool SuccsAnalyzed;
12190b57cec5SDimitry Andric   };
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   // Push MBB to the stack.
12220b57cec5SDimitry Andric   SmallVector<BBState, 16> BBStack(1, MBB);
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   while (!BBStack.empty()) {
12250b57cec5SDimitry Andric     BBState &State = BBStack.back();
12260b57cec5SDimitry Andric     MachineBasicBlock *BB = State.MBB;
12270b57cec5SDimitry Andric     BBInfo &BBI = BBAnalysis[BB->getNumber()];
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric     if (!State.SuccsAnalyzed) {
12300b57cec5SDimitry Andric       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
12310b57cec5SDimitry Andric         BBStack.pop_back();
12320b57cec5SDimitry Andric         continue;
12330b57cec5SDimitry Andric       }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric       BBI.BB = BB;
12360b57cec5SDimitry Andric       BBI.IsBeingAnalyzed = true;
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric       AnalyzeBranches(BBI);
12390b57cec5SDimitry Andric       MachineBasicBlock::iterator Begin = BBI.BB->begin();
12400b57cec5SDimitry Andric       MachineBasicBlock::iterator End = BBI.BB->end();
12410b57cec5SDimitry Andric       ScanInstructions(BBI, Begin, End);
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
12440b57cec5SDimitry Andric       // not considered for ifcvt anymore.
12450b57cec5SDimitry Andric       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
12460b57cec5SDimitry Andric         BBI.IsBeingAnalyzed = false;
12470b57cec5SDimitry Andric         BBI.IsAnalyzed = true;
12480b57cec5SDimitry Andric         BBStack.pop_back();
12490b57cec5SDimitry Andric         continue;
12500b57cec5SDimitry Andric       }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric       // Do not ifcvt if either path is a back edge to the entry block.
12530b57cec5SDimitry Andric       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
12540b57cec5SDimitry Andric         BBI.IsBeingAnalyzed = false;
12550b57cec5SDimitry Andric         BBI.IsAnalyzed = true;
12560b57cec5SDimitry Andric         BBStack.pop_back();
12570b57cec5SDimitry Andric         continue;
12580b57cec5SDimitry Andric       }
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric       // Do not ifcvt if true and false fallthrough blocks are the same.
12610b57cec5SDimitry Andric       if (!BBI.FalseBB) {
12620b57cec5SDimitry Andric         BBI.IsBeingAnalyzed = false;
12630b57cec5SDimitry Andric         BBI.IsAnalyzed = true;
12640b57cec5SDimitry Andric         BBStack.pop_back();
12650b57cec5SDimitry Andric         continue;
12660b57cec5SDimitry Andric       }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric       // Push the False and True blocks to the stack.
12690b57cec5SDimitry Andric       State.SuccsAnalyzed = true;
12700b57cec5SDimitry Andric       BBStack.push_back(*BBI.FalseBB);
12710b57cec5SDimitry Andric       BBStack.push_back(*BBI.TrueBB);
12720b57cec5SDimitry Andric       continue;
12730b57cec5SDimitry Andric     }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
12760b57cec5SDimitry Andric     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric     if (TrueBBI.IsDone && FalseBBI.IsDone) {
12790b57cec5SDimitry Andric       BBI.IsBeingAnalyzed = false;
12800b57cec5SDimitry Andric       BBI.IsAnalyzed = true;
12810b57cec5SDimitry Andric       BBStack.pop_back();
12820b57cec5SDimitry Andric       continue;
12830b57cec5SDimitry Andric     }
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric     SmallVector<MachineOperand, 4>
12860b57cec5SDimitry Andric         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
12870b57cec5SDimitry Andric     bool CanRevCond = !TII->reverseBranchCondition(RevCond);
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric     unsigned Dups = 0;
12900b57cec5SDimitry Andric     unsigned Dups2 = 0;
12910b57cec5SDimitry Andric     bool TNeedSub = !TrueBBI.Predicate.empty();
12920b57cec5SDimitry Andric     bool FNeedSub = !FalseBBI.Predicate.empty();
12930b57cec5SDimitry Andric     bool Enqueued = false;
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric     if (CanRevCond) {
12980b57cec5SDimitry Andric       BBInfo TrueBBICalc, FalseBBICalc;
12998bcb0991SDimitry Andric       auto feasibleDiamond = [&](bool Forked) {
13008bcb0991SDimitry Andric         bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
13018bcb0991SDimitry Andric                                             Dups + Dups2, Prediction, Forked);
13020b57cec5SDimitry Andric         bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
13030b57cec5SDimitry Andric                                                 /* IsTriangle */ false, /* RevCond */ false,
13040b57cec5SDimitry Andric                                                 /* hasCommonTail */ true);
13050b57cec5SDimitry Andric         bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
13060b57cec5SDimitry Andric                                                  /* IsTriangle */ false, /* RevCond */ false,
13070b57cec5SDimitry Andric                                                  /* hasCommonTail */ true);
13080b57cec5SDimitry Andric         return MeetsSize && TrueFeasible && FalseFeasible;
13090b57cec5SDimitry Andric       };
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric       if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
13120b57cec5SDimitry Andric                        TrueBBICalc, FalseBBICalc)) {
13138bcb0991SDimitry Andric         if (feasibleDiamond(false)) {
13140b57cec5SDimitry Andric           // Diamond:
13150b57cec5SDimitry Andric           //   EBB
13160b57cec5SDimitry Andric           //   / \_
13170b57cec5SDimitry Andric           //  |   |
13180b57cec5SDimitry Andric           // TBB FBB
13190b57cec5SDimitry Andric           //   \ /
13200b57cec5SDimitry Andric           //  TailBB
13210b57cec5SDimitry Andric           // Note TailBB can be empty.
13228bcb0991SDimitry Andric           Tokens.push_back(std::make_unique<IfcvtToken>(
13230b57cec5SDimitry Andric               BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
13240b57cec5SDimitry Andric               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
13250b57cec5SDimitry Andric           Enqueued = true;
13260b57cec5SDimitry Andric         }
13270b57cec5SDimitry Andric       } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
13280b57cec5SDimitry Andric                                     TrueBBICalc, FalseBBICalc)) {
13298bcb0991SDimitry Andric         if (feasibleDiamond(true)) {
13300b57cec5SDimitry Andric           // ForkedDiamond:
13310b57cec5SDimitry Andric           // if TBB and FBB have a common tail that includes their conditional
13320b57cec5SDimitry Andric           // branch instructions, then we can If Convert this pattern.
13330b57cec5SDimitry Andric           //          EBB
13340b57cec5SDimitry Andric           //         _/ \_
13350b57cec5SDimitry Andric           //         |   |
13360b57cec5SDimitry Andric           //        TBB  FBB
13370b57cec5SDimitry Andric           //        / \ /   \
13380b57cec5SDimitry Andric           //  FalseBB TrueBB FalseBB
13390b57cec5SDimitry Andric           //
13408bcb0991SDimitry Andric           Tokens.push_back(std::make_unique<IfcvtToken>(
13410b57cec5SDimitry Andric               BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
13420b57cec5SDimitry Andric               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
13430b57cec5SDimitry Andric           Enqueued = true;
13440b57cec5SDimitry Andric         }
13450b57cec5SDimitry Andric       }
13460b57cec5SDimitry Andric     }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
13490b57cec5SDimitry Andric         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13500b57cec5SDimitry Andric                            TrueBBI.ExtraCost2, Prediction) &&
13510b57cec5SDimitry Andric         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
13520b57cec5SDimitry Andric       // Triangle:
13530b57cec5SDimitry Andric       //   EBB
13540b57cec5SDimitry Andric       //   | \_
13550b57cec5SDimitry Andric       //   |  |
13560b57cec5SDimitry Andric       //   | TBB
13570b57cec5SDimitry Andric       //   |  /
13580b57cec5SDimitry Andric       //   FBB
13590b57cec5SDimitry Andric       Tokens.push_back(
13608bcb0991SDimitry Andric           std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
13610b57cec5SDimitry Andric       Enqueued = true;
13620b57cec5SDimitry Andric     }
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
13650b57cec5SDimitry Andric         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13660b57cec5SDimitry Andric                            TrueBBI.ExtraCost2, Prediction) &&
13670b57cec5SDimitry Andric         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
13680b57cec5SDimitry Andric       Tokens.push_back(
13698bcb0991SDimitry Andric           std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
13700b57cec5SDimitry Andric       Enqueued = true;
13710b57cec5SDimitry Andric     }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     if (ValidSimple(TrueBBI, Dups, Prediction) &&
13740b57cec5SDimitry Andric         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13750b57cec5SDimitry Andric                            TrueBBI.ExtraCost2, Prediction) &&
13760b57cec5SDimitry Andric         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
13770b57cec5SDimitry Andric       // Simple (split, no rejoin):
13780b57cec5SDimitry Andric       //   EBB
13790b57cec5SDimitry Andric       //   | \_
13800b57cec5SDimitry Andric       //   |  |
13810b57cec5SDimitry Andric       //   | TBB---> exit
13820b57cec5SDimitry Andric       //   |
13830b57cec5SDimitry Andric       //   FBB
13840b57cec5SDimitry Andric       Tokens.push_back(
13858bcb0991SDimitry Andric           std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
13860b57cec5SDimitry Andric       Enqueued = true;
13870b57cec5SDimitry Andric     }
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric     if (CanRevCond) {
13900b57cec5SDimitry Andric       // Try the other path...
13910b57cec5SDimitry Andric       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
13920b57cec5SDimitry Andric                         Prediction.getCompl()) &&
13930b57cec5SDimitry Andric           MeetIfcvtSizeLimit(*FalseBBI.BB,
13940b57cec5SDimitry Andric                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
13950b57cec5SDimitry Andric                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
13960b57cec5SDimitry Andric           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
13978bcb0991SDimitry Andric         Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
13980b57cec5SDimitry Andric                                                        FNeedSub, Dups));
13990b57cec5SDimitry Andric         Enqueued = true;
14000b57cec5SDimitry Andric       }
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
14030b57cec5SDimitry Andric                         Prediction.getCompl()) &&
14040b57cec5SDimitry Andric           MeetIfcvtSizeLimit(*FalseBBI.BB,
14050b57cec5SDimitry Andric                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
14060b57cec5SDimitry Andric                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
14070b57cec5SDimitry Andric         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
14080b57cec5SDimitry Andric         Tokens.push_back(
14098bcb0991SDimitry Andric             std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
14100b57cec5SDimitry Andric         Enqueued = true;
14110b57cec5SDimitry Andric       }
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
14140b57cec5SDimitry Andric           MeetIfcvtSizeLimit(*FalseBBI.BB,
14150b57cec5SDimitry Andric                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
14160b57cec5SDimitry Andric                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
14170b57cec5SDimitry Andric           FeasibilityAnalysis(FalseBBI, RevCond)) {
14180b57cec5SDimitry Andric         Tokens.push_back(
14198bcb0991SDimitry Andric             std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
14200b57cec5SDimitry Andric         Enqueued = true;
14210b57cec5SDimitry Andric       }
14220b57cec5SDimitry Andric     }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric     BBI.IsEnqueued = Enqueued;
14250b57cec5SDimitry Andric     BBI.IsBeingAnalyzed = false;
14260b57cec5SDimitry Andric     BBI.IsAnalyzed = true;
14270b57cec5SDimitry Andric     BBStack.pop_back();
14280b57cec5SDimitry Andric   }
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric /// Analyze all blocks and find entries for all if-conversion candidates.
AnalyzeBlocks(MachineFunction & MF,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)14320b57cec5SDimitry Andric void IfConverter::AnalyzeBlocks(
14330b57cec5SDimitry Andric     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
14340b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF)
14350b57cec5SDimitry Andric     AnalyzeBlock(MBB, Tokens);
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   // Sort to favor more complex ifcvt scheme.
14380b57cec5SDimitry Andric   llvm::stable_sort(Tokens, IfcvtTokenCmp);
14390b57cec5SDimitry Andric }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric /// Returns true either if ToMBB is the next block after MBB or that all the
14420b57cec5SDimitry Andric /// intervening blocks are empty (given MBB can fall through to its next block).
canFallThroughTo(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB)14430b57cec5SDimitry Andric static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
14440b57cec5SDimitry Andric   MachineFunction::iterator PI = MBB.getIterator();
14450b57cec5SDimitry Andric   MachineFunction::iterator I = std::next(PI);
14460b57cec5SDimitry Andric   MachineFunction::iterator TI = ToMBB.getIterator();
14470b57cec5SDimitry Andric   MachineFunction::iterator E = MBB.getParent()->end();
14480b57cec5SDimitry Andric   while (I != TI) {
14490b57cec5SDimitry Andric     // Check isSuccessor to avoid case where the next block is empty, but
14500b57cec5SDimitry Andric     // it's not a successor.
14510b57cec5SDimitry Andric     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
14520b57cec5SDimitry Andric       return false;
14530b57cec5SDimitry Andric     PI = I++;
14540b57cec5SDimitry Andric   }
14550b57cec5SDimitry Andric   // Finally see if the last I is indeed a successor to PI.
14560b57cec5SDimitry Andric   return PI->isSuccessor(&*I);
14570b57cec5SDimitry Andric }
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
14600b57cec5SDimitry Andric /// can be if-converted. If predecessor is already enqueued, dequeue it!
InvalidatePreds(MachineBasicBlock & MBB)14610b57cec5SDimitry Andric void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
14620b57cec5SDimitry Andric   for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
14630b57cec5SDimitry Andric     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
14640b57cec5SDimitry Andric     if (PBBI.IsDone || PBBI.BB == &MBB)
14650b57cec5SDimitry Andric       continue;
14660b57cec5SDimitry Andric     PBBI.IsAnalyzed = false;
14670b57cec5SDimitry Andric     PBBI.IsEnqueued = false;
14680b57cec5SDimitry Andric   }
14690b57cec5SDimitry Andric }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric /// Inserts an unconditional branch from \p MBB to \p ToMBB.
InsertUncondBranch(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB,const TargetInstrInfo * TII)14720b57cec5SDimitry Andric static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
14730b57cec5SDimitry Andric                                const TargetInstrInfo *TII) {
14740b57cec5SDimitry Andric   DebugLoc dl;  // FIXME: this is nowhere
14750b57cec5SDimitry Andric   SmallVector<MachineOperand, 0> NoCond;
14760b57cec5SDimitry Andric   TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
14770b57cec5SDimitry Andric }
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
14800b57cec5SDimitry Andric /// values defined in MI which are also live/used by MI.
UpdatePredRedefs(MachineInstr & MI,LivePhysRegs & Redefs)14810b57cec5SDimitry Andric static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
14820b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric   // Before stepping forward past MI, remember which regs were live
14850b57cec5SDimitry Andric   // before MI. This is needed to set the Undef flag only when reg is
14860b57cec5SDimitry Andric   // dead.
14870b57cec5SDimitry Andric   SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
14880b57cec5SDimitry Andric   LiveBeforeMI.setUniverse(TRI->getNumRegs());
14890b57cec5SDimitry Andric   for (unsigned Reg : Redefs)
14900b57cec5SDimitry Andric     LiveBeforeMI.insert(Reg);
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
14930b57cec5SDimitry Andric   Redefs.stepForward(MI, Clobbers);
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   // Now add the implicit uses for each of the clobbered values.
14960b57cec5SDimitry Andric   for (auto Clobber : Clobbers) {
14970b57cec5SDimitry Andric     // FIXME: Const cast here is nasty, but better than making StepForward
14980b57cec5SDimitry Andric     // take a mutable instruction instead of const.
14990b57cec5SDimitry Andric     unsigned Reg = Clobber.first;
15000b57cec5SDimitry Andric     MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
15010b57cec5SDimitry Andric     MachineInstr *OpMI = Op.getParent();
15020b57cec5SDimitry Andric     MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
15030b57cec5SDimitry Andric     if (Op.isRegMask()) {
15040b57cec5SDimitry Andric       // First handle regmasks.  They clobber any entries in the mask which
15050b57cec5SDimitry Andric       // means that we need a def for those registers.
15060b57cec5SDimitry Andric       if (LiveBeforeMI.count(Reg))
15070b57cec5SDimitry Andric         MIB.addReg(Reg, RegState::Implicit);
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric       // We also need to add an implicit def of this register for the later
15100b57cec5SDimitry Andric       // use to read from.
15110b57cec5SDimitry Andric       // For the register allocator to have allocated a register clobbered
15120b57cec5SDimitry Andric       // by the call which is used later, it must be the case that
15130b57cec5SDimitry Andric       // the call doesn't return.
15140b57cec5SDimitry Andric       MIB.addReg(Reg, RegState::Implicit | RegState::Define);
15150b57cec5SDimitry Andric       continue;
15160b57cec5SDimitry Andric     }
15170b57cec5SDimitry Andric     if (LiveBeforeMI.count(Reg))
15180b57cec5SDimitry Andric       MIB.addReg(Reg, RegState::Implicit);
15190b57cec5SDimitry Andric     else {
15200b57cec5SDimitry Andric       bool HasLiveSubReg = false;
15210b57cec5SDimitry Andric       for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
15220b57cec5SDimitry Andric         if (!LiveBeforeMI.count(*S))
15230b57cec5SDimitry Andric           continue;
15240b57cec5SDimitry Andric         HasLiveSubReg = true;
15250b57cec5SDimitry Andric         break;
15260b57cec5SDimitry Andric       }
15270b57cec5SDimitry Andric       if (HasLiveSubReg)
15280b57cec5SDimitry Andric         MIB.addReg(Reg, RegState::Implicit);
15290b57cec5SDimitry Andric     }
15300b57cec5SDimitry Andric   }
15310b57cec5SDimitry Andric }
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric /// If convert a simple (split, no rejoin) sub-CFG.
IfConvertSimple(BBInfo & BBI,IfcvtKind Kind)15340b57cec5SDimitry Andric bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
15350b57cec5SDimitry Andric   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
15360b57cec5SDimitry Andric   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
15370b57cec5SDimitry Andric   BBInfo *CvtBBI = &TrueBBI;
15380b57cec5SDimitry Andric   BBInfo *NextBBI = &FalseBBI;
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
15410b57cec5SDimitry Andric   if (Kind == ICSimpleFalse)
15420b57cec5SDimitry Andric     std::swap(CvtBBI, NextBBI);
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
15450b57cec5SDimitry Andric   MachineBasicBlock &NextMBB = *NextBBI->BB;
15460b57cec5SDimitry Andric   if (CvtBBI->IsDone ||
15470b57cec5SDimitry Andric       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
15480b57cec5SDimitry Andric     // Something has changed. It's no longer safe to predicate this block.
15490b57cec5SDimitry Andric     BBI.IsAnalyzed = false;
15500b57cec5SDimitry Andric     CvtBBI->IsAnalyzed = false;
15510b57cec5SDimitry Andric     return false;
15520b57cec5SDimitry Andric   }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric   if (CvtMBB.hasAddressTaken())
15550b57cec5SDimitry Andric     // Conservatively abort if-conversion if BB's address is taken.
15560b57cec5SDimitry Andric     return false;
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   if (Kind == ICSimpleFalse)
15590b57cec5SDimitry Andric     if (TII->reverseBranchCondition(Cond))
15600b57cec5SDimitry Andric       llvm_unreachable("Unable to reverse branch condition!");
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   Redefs.init(*TRI);
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric   if (MRI->tracksLiveness()) {
15650b57cec5SDimitry Andric     // Initialize liveins to the first BB. These are potentially redefined by
15660b57cec5SDimitry Andric     // predicated instructions.
1567*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(CvtMBB);
1568*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(NextMBB);
15690b57cec5SDimitry Andric   }
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   // Remove the branches from the entry so we can add the contents of the true
15720b57cec5SDimitry Andric   // block to it.
15730b57cec5SDimitry Andric   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   if (CvtMBB.pred_size() > 1) {
15760b57cec5SDimitry Andric     // Copy instructions in the true block, predicate them, and add them to
15770b57cec5SDimitry Andric     // the entry block.
15780b57cec5SDimitry Andric     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric     // Keep the CFG updated.
15810b57cec5SDimitry Andric     BBI.BB->removeSuccessor(&CvtMBB, true);
15820b57cec5SDimitry Andric   } else {
15830b57cec5SDimitry Andric     // Predicate the instructions in the true block.
15840b57cec5SDimitry Andric     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric     // Merge converted block into entry block. The BB to Cvt edge is removed
15870b57cec5SDimitry Andric     // by MergeBlocks.
15880b57cec5SDimitry Andric     MergeBlocks(BBI, *CvtBBI);
15890b57cec5SDimitry Andric   }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   bool IterIfcvt = true;
15920b57cec5SDimitry Andric   if (!canFallThroughTo(*BBI.BB, NextMBB)) {
15930b57cec5SDimitry Andric     InsertUncondBranch(*BBI.BB, NextMBB, TII);
15940b57cec5SDimitry Andric     BBI.HasFallThrough = false;
15950b57cec5SDimitry Andric     // Now ifcvt'd block will look like this:
15960b57cec5SDimitry Andric     // BB:
15970b57cec5SDimitry Andric     // ...
15980b57cec5SDimitry Andric     // t, f = cmp
15990b57cec5SDimitry Andric     // if t op
16000b57cec5SDimitry Andric     // b BBf
16010b57cec5SDimitry Andric     //
16020b57cec5SDimitry Andric     // We cannot further ifcvt this block because the unconditional branch
16030b57cec5SDimitry Andric     // will have to be predicated on the new condition, that will not be
16040b57cec5SDimitry Andric     // available if cmp executes.
16050b57cec5SDimitry Andric     IterIfcvt = false;
16060b57cec5SDimitry Andric   }
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   // Update block info. BB can be iteratively if-converted.
16090b57cec5SDimitry Andric   if (!IterIfcvt)
16100b57cec5SDimitry Andric     BBI.IsDone = true;
16110b57cec5SDimitry Andric   InvalidatePreds(*BBI.BB);
16120b57cec5SDimitry Andric   CvtBBI->IsDone = true;
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric   // FIXME: Must maintain LiveIns.
16150b57cec5SDimitry Andric   return true;
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric /// If convert a triangle sub-CFG.
IfConvertTriangle(BBInfo & BBI,IfcvtKind Kind)16190b57cec5SDimitry Andric bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
16200b57cec5SDimitry Andric   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
16210b57cec5SDimitry Andric   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
16220b57cec5SDimitry Andric   BBInfo *CvtBBI = &TrueBBI;
16230b57cec5SDimitry Andric   BBInfo *NextBBI = &FalseBBI;
16240b57cec5SDimitry Andric   DebugLoc dl;  // FIXME: this is nowhere
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
16270b57cec5SDimitry Andric   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
16280b57cec5SDimitry Andric     std::swap(CvtBBI, NextBBI);
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
16310b57cec5SDimitry Andric   MachineBasicBlock &NextMBB = *NextBBI->BB;
16320b57cec5SDimitry Andric   if (CvtBBI->IsDone ||
16330b57cec5SDimitry Andric       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
16340b57cec5SDimitry Andric     // Something has changed. It's no longer safe to predicate this block.
16350b57cec5SDimitry Andric     BBI.IsAnalyzed = false;
16360b57cec5SDimitry Andric     CvtBBI->IsAnalyzed = false;
16370b57cec5SDimitry Andric     return false;
16380b57cec5SDimitry Andric   }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   if (CvtMBB.hasAddressTaken())
16410b57cec5SDimitry Andric     // Conservatively abort if-conversion if BB's address is taken.
16420b57cec5SDimitry Andric     return false;
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
16450b57cec5SDimitry Andric     if (TII->reverseBranchCondition(Cond))
16460b57cec5SDimitry Andric       llvm_unreachable("Unable to reverse branch condition!");
16470b57cec5SDimitry Andric 
16480b57cec5SDimitry Andric   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
16490b57cec5SDimitry Andric     if (reverseBranchCondition(*CvtBBI)) {
16500b57cec5SDimitry Andric       // BB has been changed, modify its predecessors (except for this
16510b57cec5SDimitry Andric       // one) so they don't get ifcvt'ed based on bad intel.
16520b57cec5SDimitry Andric       for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
16530b57cec5SDimitry Andric         if (PBB == BBI.BB)
16540b57cec5SDimitry Andric           continue;
16550b57cec5SDimitry Andric         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
16560b57cec5SDimitry Andric         if (PBBI.IsEnqueued) {
16570b57cec5SDimitry Andric           PBBI.IsAnalyzed = false;
16580b57cec5SDimitry Andric           PBBI.IsEnqueued = false;
16590b57cec5SDimitry Andric         }
16600b57cec5SDimitry Andric       }
16610b57cec5SDimitry Andric     }
16620b57cec5SDimitry Andric   }
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric   // Initialize liveins to the first BB. These are potentially redefined by
16650b57cec5SDimitry Andric   // predicated instructions.
16660b57cec5SDimitry Andric   Redefs.init(*TRI);
16670b57cec5SDimitry Andric   if (MRI->tracksLiveness()) {
1668*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(CvtMBB);
1669*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(NextMBB);
16700b57cec5SDimitry Andric   }
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
16730b57cec5SDimitry Andric   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric   if (HasEarlyExit) {
16760b57cec5SDimitry Andric     // Get probabilities before modifying CvtMBB and BBI.BB.
16770b57cec5SDimitry Andric     CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
16780b57cec5SDimitry Andric     CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
16790b57cec5SDimitry Andric     BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
16800b57cec5SDimitry Andric     BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
16810b57cec5SDimitry Andric   }
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   // Remove the branches from the entry so we can add the contents of the true
16840b57cec5SDimitry Andric   // block to it.
16850b57cec5SDimitry Andric   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric   if (CvtMBB.pred_size() > 1) {
16880b57cec5SDimitry Andric     // Copy instructions in the true block, predicate them, and add them to
16890b57cec5SDimitry Andric     // the entry block.
16900b57cec5SDimitry Andric     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
16910b57cec5SDimitry Andric   } else {
16920b57cec5SDimitry Andric     // Predicate the 'true' block after removing its branch.
16930b57cec5SDimitry Andric     CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
16940b57cec5SDimitry Andric     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric     // Now merge the entry of the triangle with the true block.
16970b57cec5SDimitry Andric     MergeBlocks(BBI, *CvtBBI, false);
16980b57cec5SDimitry Andric   }
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   // Keep the CFG updated.
17010b57cec5SDimitry Andric   BBI.BB->removeSuccessor(&CvtMBB, true);
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   // If 'true' block has a 'false' successor, add an exit branch to it.
17040b57cec5SDimitry Andric   if (HasEarlyExit) {
17050b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
17060b57cec5SDimitry Andric                                            CvtBBI->BrCond.end());
17070b57cec5SDimitry Andric     if (TII->reverseBranchCondition(RevCond))
17080b57cec5SDimitry Andric       llvm_unreachable("Unable to reverse branch condition!");
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
17110b57cec5SDimitry Andric     // NewNext = New_Prob(BBI.BB, NextMBB) =
17120b57cec5SDimitry Andric     //   Prob(BBI.BB, NextMBB) +
17130b57cec5SDimitry Andric     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
17140b57cec5SDimitry Andric     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
17150b57cec5SDimitry Andric     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
17160b57cec5SDimitry Andric     auto NewTrueBB = getNextBlock(*BBI.BB);
17170b57cec5SDimitry Andric     auto NewNext = BBNext + BBCvt * CvtNext;
17180b57cec5SDimitry Andric     auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
17190b57cec5SDimitry Andric     if (NewTrueBBIter != BBI.BB->succ_end())
17200b57cec5SDimitry Andric       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric     auto NewFalse = BBCvt * CvtFalse;
17230b57cec5SDimitry Andric     TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
17240b57cec5SDimitry Andric     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   // Merge in the 'false' block if the 'false' block has no other
17280b57cec5SDimitry Andric   // predecessors. Otherwise, add an unconditional branch to 'false'.
17290b57cec5SDimitry Andric   bool FalseBBDead = false;
17300b57cec5SDimitry Andric   bool IterIfcvt = true;
17310b57cec5SDimitry Andric   bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
17320b57cec5SDimitry Andric   if (!isFallThrough) {
17330b57cec5SDimitry Andric     // Only merge them if the true block does not fallthrough to the false
17340b57cec5SDimitry Andric     // block. By not merging them, we make it possible to iteratively
17350b57cec5SDimitry Andric     // ifcvt the blocks.
17360b57cec5SDimitry Andric     if (!HasEarlyExit &&
17370b57cec5SDimitry Andric         NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
17380b57cec5SDimitry Andric         !NextMBB.hasAddressTaken()) {
17390b57cec5SDimitry Andric       MergeBlocks(BBI, *NextBBI);
17400b57cec5SDimitry Andric       FalseBBDead = true;
17410b57cec5SDimitry Andric     } else {
17420b57cec5SDimitry Andric       InsertUncondBranch(*BBI.BB, NextMBB, TII);
17430b57cec5SDimitry Andric       BBI.HasFallThrough = false;
17440b57cec5SDimitry Andric     }
17450b57cec5SDimitry Andric     // Mixed predicated and unpredicated code. This cannot be iteratively
17460b57cec5SDimitry Andric     // predicated.
17470b57cec5SDimitry Andric     IterIfcvt = false;
17480b57cec5SDimitry Andric   }
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   // Update block info. BB can be iteratively if-converted.
17510b57cec5SDimitry Andric   if (!IterIfcvt)
17520b57cec5SDimitry Andric     BBI.IsDone = true;
17530b57cec5SDimitry Andric   InvalidatePreds(*BBI.BB);
17540b57cec5SDimitry Andric   CvtBBI->IsDone = true;
17550b57cec5SDimitry Andric   if (FalseBBDead)
17560b57cec5SDimitry Andric     NextBBI->IsDone = true;
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   // FIXME: Must maintain LiveIns.
17590b57cec5SDimitry Andric   return true;
17600b57cec5SDimitry Andric }
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric /// Common code shared between diamond conversions.
17630b57cec5SDimitry Andric /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
17640b57cec5SDimitry Andric /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
17650b57cec5SDimitry Andric ///               and FalseBBI
17660b57cec5SDimitry Andric /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
17670b57cec5SDimitry Andric ///               and \p FalseBBI
17680b57cec5SDimitry Andric /// \p RemoveBranch - Remove the common branch of the two blocks before
17690b57cec5SDimitry Andric ///                   predicating. Only false for unanalyzable fallthrough
17700b57cec5SDimitry Andric ///                   cases. The caller will replace the branch if necessary.
17710b57cec5SDimitry Andric /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
17720b57cec5SDimitry Andric ///                    unanalyzable fallthrough
IfConvertDiamondCommon(BBInfo & BBI,BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred,bool RemoveBranch,bool MergeAddEdges)17730b57cec5SDimitry Andric bool IfConverter::IfConvertDiamondCommon(
17740b57cec5SDimitry Andric     BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
17750b57cec5SDimitry Andric     unsigned NumDups1, unsigned NumDups2,
17760b57cec5SDimitry Andric     bool TClobbersPred, bool FClobbersPred,
17770b57cec5SDimitry Andric     bool RemoveBranch, bool MergeAddEdges) {
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric   if (TrueBBI.IsDone || FalseBBI.IsDone ||
17800b57cec5SDimitry Andric       TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
17810b57cec5SDimitry Andric     // Something has changed. It's no longer safe to predicate these blocks.
17820b57cec5SDimitry Andric     BBI.IsAnalyzed = false;
17830b57cec5SDimitry Andric     TrueBBI.IsAnalyzed = false;
17840b57cec5SDimitry Andric     FalseBBI.IsAnalyzed = false;
17850b57cec5SDimitry Andric     return false;
17860b57cec5SDimitry Andric   }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
17890b57cec5SDimitry Andric     // Conservatively abort if-conversion if either BB has its address taken.
17900b57cec5SDimitry Andric     return false;
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Put the predicated instructions from the 'true' block before the
17930b57cec5SDimitry Andric   // instructions from the 'false' block, unless the true block would clobber
17940b57cec5SDimitry Andric   // the predicate, in which case, do the opposite.
17950b57cec5SDimitry Andric   BBInfo *BBI1 = &TrueBBI;
17960b57cec5SDimitry Andric   BBInfo *BBI2 = &FalseBBI;
17970b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
17980b57cec5SDimitry Andric   if (TII->reverseBranchCondition(RevCond))
17990b57cec5SDimitry Andric     llvm_unreachable("Unable to reverse branch condition!");
18000b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
18010b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   // Figure out the more profitable ordering.
18040b57cec5SDimitry Andric   bool DoSwap = false;
18050b57cec5SDimitry Andric   if (TClobbersPred && !FClobbersPred)
18060b57cec5SDimitry Andric     DoSwap = true;
18070b57cec5SDimitry Andric   else if (!TClobbersPred && !FClobbersPred) {
18080b57cec5SDimitry Andric     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
18090b57cec5SDimitry Andric       DoSwap = true;
18100b57cec5SDimitry Andric   } else if (TClobbersPred && FClobbersPred)
18110b57cec5SDimitry Andric     llvm_unreachable("Predicate info cannot be clobbered by both sides.");
18120b57cec5SDimitry Andric   if (DoSwap) {
18130b57cec5SDimitry Andric     std::swap(BBI1, BBI2);
18140b57cec5SDimitry Andric     std::swap(Cond1, Cond2);
18150b57cec5SDimitry Andric   }
18160b57cec5SDimitry Andric 
18170b57cec5SDimitry Andric   // Remove the conditional branch from entry to the blocks.
18180b57cec5SDimitry Andric   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   MachineBasicBlock &MBB1 = *BBI1->BB;
18210b57cec5SDimitry Andric   MachineBasicBlock &MBB2 = *BBI2->BB;
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Initialize the Redefs:
18240b57cec5SDimitry Andric   // - BB2 live-in regs need implicit uses before being redefined by BB1
18250b57cec5SDimitry Andric   //   instructions.
18260b57cec5SDimitry Andric   // - BB1 live-out regs need implicit uses before being redefined by BB2
18270b57cec5SDimitry Andric   //   instructions. We start with BB1 live-ins so we have the live-out regs
18280b57cec5SDimitry Andric   //   after tracking the BB1 instructions.
18290b57cec5SDimitry Andric   Redefs.init(*TRI);
18300b57cec5SDimitry Andric   if (MRI->tracksLiveness()) {
1831*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(MBB1);
1832*5f7ddb14SDimitry Andric     Redefs.addLiveInsNoPristines(MBB2);
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Remove the duplicated instructions at the beginnings of both paths.
18360b57cec5SDimitry Andric   // Skip dbg_value instructions.
1837*5f7ddb14SDimitry Andric   MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr(false);
1838*5f7ddb14SDimitry Andric   MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr(false);
18390b57cec5SDimitry Andric   BBI1->NonPredSize -= NumDups1;
18400b57cec5SDimitry Andric   BBI2->NonPredSize -= NumDups1;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   // Skip past the dups on each side separately since there may be
18430b57cec5SDimitry Andric   // differing dbg_value entries. NumDups1 can include a "return"
18440b57cec5SDimitry Andric   // instruction, if it's not marked as "branch".
18450b57cec5SDimitry Andric   for (unsigned i = 0; i < NumDups1; ++DI1) {
18460b57cec5SDimitry Andric     if (DI1 == MBB1.end())
18470b57cec5SDimitry Andric       break;
18480b57cec5SDimitry Andric     if (!DI1->isDebugInstr())
18490b57cec5SDimitry Andric       ++i;
18500b57cec5SDimitry Andric   }
18510b57cec5SDimitry Andric   while (NumDups1 != 0) {
18528bcb0991SDimitry Andric     // Since this instruction is going to be deleted, update call
18538bcb0991SDimitry Andric     // site info state if the instruction is call instruction.
18545ffd83dbSDimitry Andric     if (DI2->shouldUpdateCallSiteInfo())
18558bcb0991SDimitry Andric       MBB2.getParent()->eraseCallSiteInfo(&*DI2);
18568bcb0991SDimitry Andric 
18570b57cec5SDimitry Andric     ++DI2;
18580b57cec5SDimitry Andric     if (DI2 == MBB2.end())
18590b57cec5SDimitry Andric       break;
18600b57cec5SDimitry Andric     if (!DI2->isDebugInstr())
18610b57cec5SDimitry Andric       --NumDups1;
18620b57cec5SDimitry Andric   }
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   if (MRI->tracksLiveness()) {
18650b57cec5SDimitry Andric     for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
18660b57cec5SDimitry Andric       SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
18670b57cec5SDimitry Andric       Redefs.stepForward(MI, Dummy);
18680b57cec5SDimitry Andric     }
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
18720b57cec5SDimitry Andric   MBB2.erase(MBB2.begin(), DI2);
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric   // The branches have been checked to match, so it is safe to remove the
18750b57cec5SDimitry Andric   // branch in BB1 and rely on the copy in BB2. The complication is that
18760b57cec5SDimitry Andric   // the blocks may end with a return instruction, which may or may not
18770b57cec5SDimitry Andric   // be marked as "branch". If it's not, then it could be included in
18780b57cec5SDimitry Andric   // "dups1", leaving the blocks potentially empty after moving the common
18790b57cec5SDimitry Andric   // duplicates.
18800b57cec5SDimitry Andric #ifndef NDEBUG
18810b57cec5SDimitry Andric   // Unanalyzable branches must match exactly. Check that now.
18820b57cec5SDimitry Andric   if (!BBI1->IsBrAnalyzable)
18830b57cec5SDimitry Andric     verifySameBranchInstructions(&MBB1, &MBB2);
18840b57cec5SDimitry Andric #endif
18850b57cec5SDimitry Andric   // Remove duplicated instructions from the tail of MBB1: any branch
18860b57cec5SDimitry Andric   // instructions, and the common instructions counted by NumDups2.
18870b57cec5SDimitry Andric   DI1 = MBB1.end();
18880b57cec5SDimitry Andric   while (DI1 != MBB1.begin()) {
18890b57cec5SDimitry Andric     MachineBasicBlock::iterator Prev = std::prev(DI1);
18900b57cec5SDimitry Andric     if (!Prev->isBranch() && !Prev->isDebugInstr())
18910b57cec5SDimitry Andric       break;
18920b57cec5SDimitry Andric     DI1 = Prev;
18930b57cec5SDimitry Andric   }
18940b57cec5SDimitry Andric   for (unsigned i = 0; i != NumDups2; ) {
18950b57cec5SDimitry Andric     // NumDups2 only counted non-dbg_value instructions, so this won't
18960b57cec5SDimitry Andric     // run off the head of the list.
18970b57cec5SDimitry Andric     assert(DI1 != MBB1.begin());
18988bcb0991SDimitry Andric 
18990b57cec5SDimitry Andric     --DI1;
19008bcb0991SDimitry Andric 
19018bcb0991SDimitry Andric     // Since this instruction is going to be deleted, update call
19028bcb0991SDimitry Andric     // site info state if the instruction is call instruction.
19035ffd83dbSDimitry Andric     if (DI1->shouldUpdateCallSiteInfo())
19048bcb0991SDimitry Andric       MBB1.getParent()->eraseCallSiteInfo(&*DI1);
19058bcb0991SDimitry Andric 
19060b57cec5SDimitry Andric     // skip dbg_value instructions
19070b57cec5SDimitry Andric     if (!DI1->isDebugInstr())
19080b57cec5SDimitry Andric       ++i;
19090b57cec5SDimitry Andric   }
19100b57cec5SDimitry Andric   MBB1.erase(DI1, MBB1.end());
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   DI2 = BBI2->BB->end();
19130b57cec5SDimitry Andric   // The branches have been checked to match. Skip over the branch in the false
19140b57cec5SDimitry Andric   // block so that we don't try to predicate it.
19150b57cec5SDimitry Andric   if (RemoveBranch)
19160b57cec5SDimitry Andric     BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
19170b57cec5SDimitry Andric   else {
19180b57cec5SDimitry Andric     // Make DI2 point to the end of the range where the common "tail"
19190b57cec5SDimitry Andric     // instructions could be found.
19200b57cec5SDimitry Andric     while (DI2 != MBB2.begin()) {
19210b57cec5SDimitry Andric       MachineBasicBlock::iterator Prev = std::prev(DI2);
19220b57cec5SDimitry Andric       if (!Prev->isBranch() && !Prev->isDebugInstr())
19230b57cec5SDimitry Andric         break;
19240b57cec5SDimitry Andric       DI2 = Prev;
19250b57cec5SDimitry Andric     }
19260b57cec5SDimitry Andric   }
19270b57cec5SDimitry Andric   while (NumDups2 != 0) {
19280b57cec5SDimitry Andric     // NumDups2 only counted non-dbg_value instructions, so this won't
19290b57cec5SDimitry Andric     // run off the head of the list.
19300b57cec5SDimitry Andric     assert(DI2 != MBB2.begin());
19310b57cec5SDimitry Andric     --DI2;
19320b57cec5SDimitry Andric     // skip dbg_value instructions
19330b57cec5SDimitry Andric     if (!DI2->isDebugInstr())
19340b57cec5SDimitry Andric       --NumDups2;
19350b57cec5SDimitry Andric   }
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   // Remember which registers would later be defined by the false block.
19380b57cec5SDimitry Andric   // This allows us not to predicate instructions in the true block that would
19390b57cec5SDimitry Andric   // later be re-defined. That is, rather than
19400b57cec5SDimitry Andric   //   subeq  r0, r1, #1
19410b57cec5SDimitry Andric   //   addne  r0, r1, #1
19420b57cec5SDimitry Andric   // generate:
19430b57cec5SDimitry Andric   //   sub    r0, r1, #1
19440b57cec5SDimitry Andric   //   addne  r0, r1, #1
19450b57cec5SDimitry Andric   SmallSet<MCPhysReg, 4> RedefsByFalse;
19460b57cec5SDimitry Andric   SmallSet<MCPhysReg, 4> ExtUses;
19470b57cec5SDimitry Andric   if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
19480b57cec5SDimitry Andric     for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
19490b57cec5SDimitry Andric       if (FI.isDebugInstr())
19500b57cec5SDimitry Andric         continue;
19510b57cec5SDimitry Andric       SmallVector<MCPhysReg, 4> Defs;
19520b57cec5SDimitry Andric       for (const MachineOperand &MO : FI.operands()) {
19530b57cec5SDimitry Andric         if (!MO.isReg())
19540b57cec5SDimitry Andric           continue;
19558bcb0991SDimitry Andric         Register Reg = MO.getReg();
19560b57cec5SDimitry Andric         if (!Reg)
19570b57cec5SDimitry Andric           continue;
19580b57cec5SDimitry Andric         if (MO.isDef()) {
19590b57cec5SDimitry Andric           Defs.push_back(Reg);
19600b57cec5SDimitry Andric         } else if (!RedefsByFalse.count(Reg)) {
19610b57cec5SDimitry Andric           // These are defined before ctrl flow reach the 'false' instructions.
19620b57cec5SDimitry Andric           // They cannot be modified by the 'true' instructions.
19630b57cec5SDimitry Andric           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
19640b57cec5SDimitry Andric                SubRegs.isValid(); ++SubRegs)
19650b57cec5SDimitry Andric             ExtUses.insert(*SubRegs);
19660b57cec5SDimitry Andric         }
19670b57cec5SDimitry Andric       }
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric       for (MCPhysReg Reg : Defs) {
19700b57cec5SDimitry Andric         if (!ExtUses.count(Reg)) {
19710b57cec5SDimitry Andric           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
19720b57cec5SDimitry Andric                SubRegs.isValid(); ++SubRegs)
19730b57cec5SDimitry Andric             RedefsByFalse.insert(*SubRegs);
19740b57cec5SDimitry Andric         }
19750b57cec5SDimitry Andric       }
19760b57cec5SDimitry Andric     }
19770b57cec5SDimitry Andric   }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric   // Predicate the 'true' block.
19800b57cec5SDimitry Andric   PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   // After predicating BBI1, if there is a predicated terminator in BBI1 and
19830b57cec5SDimitry Andric   // a non-predicated in BBI2, then we don't want to predicate the one from
19840b57cec5SDimitry Andric   // BBI2. The reason is that if we merged these blocks, we would end up with
19850b57cec5SDimitry Andric   // two predicated terminators in the same block.
19860b57cec5SDimitry Andric   // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
19870b57cec5SDimitry Andric   // predicate them either. They were checked to be identical, and so the
19880b57cec5SDimitry Andric   // same branch would happen regardless of which path was taken.
19890b57cec5SDimitry Andric   if (!MBB2.empty() && (DI2 == MBB2.end())) {
19900b57cec5SDimitry Andric     MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
19910b57cec5SDimitry Andric     MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
19920b57cec5SDimitry Andric     bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
19930b57cec5SDimitry Andric     bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
19940b57cec5SDimitry Andric     if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
19950b57cec5SDimitry Andric       --DI2;
19960b57cec5SDimitry Andric   }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   // Predicate the 'false' block.
19990b57cec5SDimitry Andric   PredicateBlock(*BBI2, DI2, *Cond2);
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric   // Merge the true block into the entry of the diamond.
20020b57cec5SDimitry Andric   MergeBlocks(BBI, *BBI1, MergeAddEdges);
20030b57cec5SDimitry Andric   MergeBlocks(BBI, *BBI2, MergeAddEdges);
20040b57cec5SDimitry Andric   return true;
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric /// If convert an almost-diamond sub-CFG where the true
20080b57cec5SDimitry Andric /// and false blocks share a common tail.
IfConvertForkedDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)20090b57cec5SDimitry Andric bool IfConverter::IfConvertForkedDiamond(
20100b57cec5SDimitry Andric     BBInfo &BBI, IfcvtKind Kind,
20110b57cec5SDimitry Andric     unsigned NumDups1, unsigned NumDups2,
20120b57cec5SDimitry Andric     bool TClobbersPred, bool FClobbersPred) {
20130b57cec5SDimitry Andric   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
20140b57cec5SDimitry Andric   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
20150b57cec5SDimitry Andric 
20160b57cec5SDimitry Andric   // Save the debug location for later.
20170b57cec5SDimitry Andric   DebugLoc dl;
20180b57cec5SDimitry Andric   MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
20190b57cec5SDimitry Andric   if (TIE != TrueBBI.BB->end())
20200b57cec5SDimitry Andric     dl = TIE->getDebugLoc();
20210b57cec5SDimitry Andric   // Removing branches from both blocks is safe, because we have already
20220b57cec5SDimitry Andric   // determined that both blocks have the same branch instructions. The branch
20230b57cec5SDimitry Andric   // will be added back at the end, unpredicated.
20240b57cec5SDimitry Andric   if (!IfConvertDiamondCommon(
20250b57cec5SDimitry Andric       BBI, TrueBBI, FalseBBI,
20260b57cec5SDimitry Andric       NumDups1, NumDups2,
20270b57cec5SDimitry Andric       TClobbersPred, FClobbersPred,
20280b57cec5SDimitry Andric       /* RemoveBranch */ true, /* MergeAddEdges */ true))
20290b57cec5SDimitry Andric     return false;
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   // Add back the branch.
20320b57cec5SDimitry Andric   // Debug location saved above when removing the branch from BBI2
20330b57cec5SDimitry Andric   TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
20340b57cec5SDimitry Andric                     TrueBBI.BrCond, dl);
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   // Update block info.
20370b57cec5SDimitry Andric   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
20380b57cec5SDimitry Andric   InvalidatePreds(*BBI.BB);
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric   // FIXME: Must maintain LiveIns.
20410b57cec5SDimitry Andric   return true;
20420b57cec5SDimitry Andric }
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric /// If convert a diamond sub-CFG.
IfConvertDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)20450b57cec5SDimitry Andric bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
20460b57cec5SDimitry Andric                                    unsigned NumDups1, unsigned NumDups2,
20470b57cec5SDimitry Andric                                    bool TClobbersPred, bool FClobbersPred) {
20480b57cec5SDimitry Andric   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
20490b57cec5SDimitry Andric   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
20500b57cec5SDimitry Andric   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric   // True block must fall through or end with an unanalyzable terminator.
20530b57cec5SDimitry Andric   if (!TailBB) {
20540b57cec5SDimitry Andric     if (blockAlwaysFallThrough(TrueBBI))
20550b57cec5SDimitry Andric       TailBB = FalseBBI.TrueBB;
20560b57cec5SDimitry Andric     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
20570b57cec5SDimitry Andric   }
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   if (!IfConvertDiamondCommon(
20600b57cec5SDimitry Andric       BBI, TrueBBI, FalseBBI,
20610b57cec5SDimitry Andric       NumDups1, NumDups2,
20620b57cec5SDimitry Andric       TClobbersPred, FClobbersPred,
20630b57cec5SDimitry Andric       /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
20640b57cec5SDimitry Andric       /* MergeAddEdges */ TailBB == nullptr))
20650b57cec5SDimitry Andric     return false;
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   // If the if-converted block falls through or unconditionally branches into
20680b57cec5SDimitry Andric   // the tail block, and the tail block does not have other predecessors, then
20690b57cec5SDimitry Andric   // fold the tail block in as well. Otherwise, unless it falls through to the
20700b57cec5SDimitry Andric   // tail, add a unconditional branch to it.
20710b57cec5SDimitry Andric   if (TailBB) {
20720b57cec5SDimitry Andric     // We need to remove the edges to the true and false blocks manually since
20730b57cec5SDimitry Andric     // we didn't let IfConvertDiamondCommon update the CFG.
20740b57cec5SDimitry Andric     BBI.BB->removeSuccessor(TrueBBI.BB);
20750b57cec5SDimitry Andric     BBI.BB->removeSuccessor(FalseBBI.BB, true);
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
20780b57cec5SDimitry Andric     bool CanMergeTail = !TailBBI.HasFallThrough &&
20790b57cec5SDimitry Andric       !TailBBI.BB->hasAddressTaken();
20800b57cec5SDimitry Andric     // The if-converted block can still have a predicated terminator
20810b57cec5SDimitry Andric     // (e.g. a predicated return). If that is the case, we cannot merge
20820b57cec5SDimitry Andric     // it with the tail block.
20830b57cec5SDimitry Andric     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
20840b57cec5SDimitry Andric     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
20850b57cec5SDimitry Andric       CanMergeTail = false;
20860b57cec5SDimitry Andric     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
20870b57cec5SDimitry Andric     // check if there are any other predecessors besides those.
20880b57cec5SDimitry Andric     unsigned NumPreds = TailBB->pred_size();
20890b57cec5SDimitry Andric     if (NumPreds > 1)
20900b57cec5SDimitry Andric       CanMergeTail = false;
20910b57cec5SDimitry Andric     else if (NumPreds == 1 && CanMergeTail) {
20920b57cec5SDimitry Andric       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
20930b57cec5SDimitry Andric       if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
20940b57cec5SDimitry Andric         CanMergeTail = false;
20950b57cec5SDimitry Andric     }
20960b57cec5SDimitry Andric     if (CanMergeTail) {
20970b57cec5SDimitry Andric       MergeBlocks(BBI, TailBBI);
20980b57cec5SDimitry Andric       TailBBI.IsDone = true;
20990b57cec5SDimitry Andric     } else {
21000b57cec5SDimitry Andric       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
21010b57cec5SDimitry Andric       InsertUncondBranch(*BBI.BB, *TailBB, TII);
21020b57cec5SDimitry Andric       BBI.HasFallThrough = false;
21030b57cec5SDimitry Andric     }
21040b57cec5SDimitry Andric   }
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric   // Update block info.
21070b57cec5SDimitry Andric   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
21080b57cec5SDimitry Andric   InvalidatePreds(*BBI.BB);
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // FIXME: Must maintain LiveIns.
21110b57cec5SDimitry Andric   return true;
21120b57cec5SDimitry Andric }
21130b57cec5SDimitry Andric 
MaySpeculate(const MachineInstr & MI,SmallSet<MCPhysReg,4> & LaterRedefs)21140b57cec5SDimitry Andric static bool MaySpeculate(const MachineInstr &MI,
21150b57cec5SDimitry Andric                          SmallSet<MCPhysReg, 4> &LaterRedefs) {
21160b57cec5SDimitry Andric   bool SawStore = true;
21170b57cec5SDimitry Andric   if (!MI.isSafeToMove(nullptr, SawStore))
21180b57cec5SDimitry Andric     return false;
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
21210b57cec5SDimitry Andric     if (!MO.isReg())
21220b57cec5SDimitry Andric       continue;
21238bcb0991SDimitry Andric     Register Reg = MO.getReg();
21240b57cec5SDimitry Andric     if (!Reg)
21250b57cec5SDimitry Andric       continue;
21260b57cec5SDimitry Andric     if (MO.isDef() && !LaterRedefs.count(Reg))
21270b57cec5SDimitry Andric       return false;
21280b57cec5SDimitry Andric   }
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   return true;
21310b57cec5SDimitry Andric }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric /// Predicate instructions from the start of the block to the specified end with
21340b57cec5SDimitry Andric /// the specified condition.
PredicateBlock(BBInfo & BBI,MachineBasicBlock::iterator E,SmallVectorImpl<MachineOperand> & Cond,SmallSet<MCPhysReg,4> * LaterRedefs)21350b57cec5SDimitry Andric void IfConverter::PredicateBlock(BBInfo &BBI,
21360b57cec5SDimitry Andric                                  MachineBasicBlock::iterator E,
21370b57cec5SDimitry Andric                                  SmallVectorImpl<MachineOperand> &Cond,
21380b57cec5SDimitry Andric                                  SmallSet<MCPhysReg, 4> *LaterRedefs) {
21390b57cec5SDimitry Andric   bool AnyUnpred = false;
21400b57cec5SDimitry Andric   bool MaySpec = LaterRedefs != nullptr;
21410b57cec5SDimitry Andric   for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
21420b57cec5SDimitry Andric     if (I.isDebugInstr() || TII->isPredicated(I))
21430b57cec5SDimitry Andric       continue;
21440b57cec5SDimitry Andric     // It may be possible not to predicate an instruction if it's the 'true'
21450b57cec5SDimitry Andric     // side of a diamond and the 'false' side may re-define the instruction's
21460b57cec5SDimitry Andric     // defs.
21470b57cec5SDimitry Andric     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
21480b57cec5SDimitry Andric       AnyUnpred = true;
21490b57cec5SDimitry Andric       continue;
21500b57cec5SDimitry Andric     }
21510b57cec5SDimitry Andric     // If any instruction is predicated, then every instruction after it must
21520b57cec5SDimitry Andric     // be predicated.
21530b57cec5SDimitry Andric     MaySpec = false;
21540b57cec5SDimitry Andric     if (!TII->PredicateInstruction(I, Cond)) {
21550b57cec5SDimitry Andric #ifndef NDEBUG
21560b57cec5SDimitry Andric       dbgs() << "Unable to predicate " << I << "!\n";
21570b57cec5SDimitry Andric #endif
21580b57cec5SDimitry Andric       llvm_unreachable(nullptr);
21590b57cec5SDimitry Andric     }
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric     // If the predicated instruction now redefines a register as the result of
21620b57cec5SDimitry Andric     // if-conversion, add an implicit kill.
21630b57cec5SDimitry Andric     UpdatePredRedefs(I, Redefs);
21640b57cec5SDimitry Andric   }
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   BBI.Predicate.append(Cond.begin(), Cond.end());
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric   BBI.IsAnalyzed = false;
21690b57cec5SDimitry Andric   BBI.NonPredSize = 0;
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   ++NumIfConvBBs;
21720b57cec5SDimitry Andric   if (AnyUnpred)
21730b57cec5SDimitry Andric     ++NumUnpred;
21740b57cec5SDimitry Andric }
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric /// Copy and predicate instructions from source BB to the destination block.
21770b57cec5SDimitry Andric /// Skip end of block branches if IgnoreBr is true.
CopyAndPredicateBlock(BBInfo & ToBBI,BBInfo & FromBBI,SmallVectorImpl<MachineOperand> & Cond,bool IgnoreBr)21780b57cec5SDimitry Andric void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
21790b57cec5SDimitry Andric                                         SmallVectorImpl<MachineOperand> &Cond,
21800b57cec5SDimitry Andric                                         bool IgnoreBr) {
21810b57cec5SDimitry Andric   MachineFunction &MF = *ToBBI.BB->getParent();
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   MachineBasicBlock &FromMBB = *FromBBI.BB;
21840b57cec5SDimitry Andric   for (MachineInstr &I : FromMBB) {
21850b57cec5SDimitry Andric     // Do not copy the end of the block branches.
21860b57cec5SDimitry Andric     if (IgnoreBr && I.isBranch())
21870b57cec5SDimitry Andric       break;
21880b57cec5SDimitry Andric 
21890b57cec5SDimitry Andric     MachineInstr *MI = MF.CloneMachineInstr(&I);
21908bcb0991SDimitry Andric     // Make a copy of the call site info.
21915ffd83dbSDimitry Andric     if (I.isCandidateForCallSiteEntry())
21928bcb0991SDimitry Andric       MF.copyCallSiteInfo(&I, MI);
21938bcb0991SDimitry Andric 
21940b57cec5SDimitry Andric     ToBBI.BB->insert(ToBBI.BB->end(), MI);
21950b57cec5SDimitry Andric     ToBBI.NonPredSize++;
21960b57cec5SDimitry Andric     unsigned ExtraPredCost = TII->getPredicationCost(I);
21970b57cec5SDimitry Andric     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
21980b57cec5SDimitry Andric     if (NumCycles > 1)
21990b57cec5SDimitry Andric       ToBBI.ExtraCost += NumCycles-1;
22000b57cec5SDimitry Andric     ToBBI.ExtraCost2 += ExtraPredCost;
22010b57cec5SDimitry Andric 
22020b57cec5SDimitry Andric     if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
22030b57cec5SDimitry Andric       if (!TII->PredicateInstruction(*MI, Cond)) {
22040b57cec5SDimitry Andric #ifndef NDEBUG
22050b57cec5SDimitry Andric         dbgs() << "Unable to predicate " << I << "!\n";
22060b57cec5SDimitry Andric #endif
22070b57cec5SDimitry Andric         llvm_unreachable(nullptr);
22080b57cec5SDimitry Andric       }
22090b57cec5SDimitry Andric     }
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric     // If the predicated instruction now redefines a register as the result of
22120b57cec5SDimitry Andric     // if-conversion, add an implicit kill.
22130b57cec5SDimitry Andric     UpdatePredRedefs(*MI, Redefs);
22140b57cec5SDimitry Andric   }
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric   if (!IgnoreBr) {
22170b57cec5SDimitry Andric     std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
22180b57cec5SDimitry Andric                                            FromMBB.succ_end());
22190b57cec5SDimitry Andric     MachineBasicBlock *NBB = getNextBlock(FromMBB);
22200b57cec5SDimitry Andric     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
22210b57cec5SDimitry Andric 
22220b57cec5SDimitry Andric     for (MachineBasicBlock *Succ : Succs) {
22230b57cec5SDimitry Andric       // Fallthrough edge can't be transferred.
22240b57cec5SDimitry Andric       if (Succ == FallThrough)
22250b57cec5SDimitry Andric         continue;
22260b57cec5SDimitry Andric       ToBBI.BB->addSuccessor(Succ);
22270b57cec5SDimitry Andric     }
22280b57cec5SDimitry Andric   }
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
22310b57cec5SDimitry Andric   ToBBI.Predicate.append(Cond.begin(), Cond.end());
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
22340b57cec5SDimitry Andric   ToBBI.IsAnalyzed = false;
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric   ++NumDupBBs;
22370b57cec5SDimitry Andric }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric /// Move all instructions from FromBB to the end of ToBB.  This will leave
22405ffd83dbSDimitry Andric /// FromBB as an empty block, so remove all of its successor edges and move it
22415ffd83dbSDimitry Andric /// to the end of the function.  If AddEdges is true, i.e., when FromBBI's
22425ffd83dbSDimitry Andric /// branch is being moved, add those successor edges to ToBBI and remove the old
22435ffd83dbSDimitry Andric /// edge from ToBBI to FromBBI.
MergeBlocks(BBInfo & ToBBI,BBInfo & FromBBI,bool AddEdges)22440b57cec5SDimitry Andric void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
22450b57cec5SDimitry Andric   MachineBasicBlock &FromMBB = *FromBBI.BB;
22460b57cec5SDimitry Andric   assert(!FromMBB.hasAddressTaken() &&
22470b57cec5SDimitry Andric          "Removing a BB whose address is taken!");
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   // In case FromMBB contains terminators (e.g. return instruction),
22500b57cec5SDimitry Andric   // first move the non-terminator instructions, then the terminators.
22510b57cec5SDimitry Andric   MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
22520b57cec5SDimitry Andric   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
22530b57cec5SDimitry Andric   ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   // If FromBB has non-predicated terminator we should copy it at the end.
22560b57cec5SDimitry Andric   if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
22570b57cec5SDimitry Andric     ToTI = ToBBI.BB->end();
22580b57cec5SDimitry Andric   ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
22610b57cec5SDimitry Andric   // unknown probabilities into known ones.
22620b57cec5SDimitry Andric   // FIXME: This usage is too tricky and in the future we would like to
22630b57cec5SDimitry Andric   // eliminate all unknown probabilities in MBB.
22640b57cec5SDimitry Andric   if (ToBBI.IsBrAnalyzable)
22650b57cec5SDimitry Andric     ToBBI.BB->normalizeSuccProbs();
22660b57cec5SDimitry Andric 
2267af732203SDimitry Andric   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
22680b57cec5SDimitry Andric   MachineBasicBlock *NBB = getNextBlock(FromMBB);
22690b57cec5SDimitry Andric   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
22700b57cec5SDimitry Andric   // The edge probability from ToBBI.BB to FromMBB, which is only needed when
22710b57cec5SDimitry Andric   // AddEdges is true and FromMBB is a successor of ToBBI.BB.
22720b57cec5SDimitry Andric   auto To2FromProb = BranchProbability::getZero();
22730b57cec5SDimitry Andric   if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
22740b57cec5SDimitry Andric     // Remove the old edge but remember the edge probability so we can calculate
22750b57cec5SDimitry Andric     // the correct weights on the new edges being added further down.
22760b57cec5SDimitry Andric     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
22770b57cec5SDimitry Andric     ToBBI.BB->removeSuccessor(&FromMBB);
22780b57cec5SDimitry Andric   }
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : FromSuccs) {
22810b57cec5SDimitry Andric     // Fallthrough edge can't be transferred.
22825ffd83dbSDimitry Andric     if (Succ == FallThrough) {
22835ffd83dbSDimitry Andric       FromMBB.removeSuccessor(Succ);
22840b57cec5SDimitry Andric       continue;
22855ffd83dbSDimitry Andric     }
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric     auto NewProb = BranchProbability::getZero();
22880b57cec5SDimitry Andric     if (AddEdges) {
22890b57cec5SDimitry Andric       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
22900b57cec5SDimitry Andric       // which is a portion of the edge probability from FromMBB to Succ. The
22910b57cec5SDimitry Andric       // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
22920b57cec5SDimitry Andric       // FromBBI is a successor of ToBBI.BB. See comment below for exception).
22930b57cec5SDimitry Andric       NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric       // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
22960b57cec5SDimitry Andric       // only happens when if-converting a diamond CFG and FromMBB is the
22970b57cec5SDimitry Andric       // tail BB.  In this case FromMBB post-dominates ToBBI.BB and hence we
22980b57cec5SDimitry Andric       // could just use the probabilities on FromMBB's out-edges when adding
22990b57cec5SDimitry Andric       // new successors.
23000b57cec5SDimitry Andric       if (!To2FromProb.isZero())
23010b57cec5SDimitry Andric         NewProb *= To2FromProb;
23020b57cec5SDimitry Andric     }
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric     FromMBB.removeSuccessor(Succ);
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric     if (AddEdges) {
23070b57cec5SDimitry Andric       // If the edge from ToBBI.BB to Succ already exists, update the
23080b57cec5SDimitry Andric       // probability of this edge by adding NewProb to it. An example is shown
23090b57cec5SDimitry Andric       // below, in which A is ToBBI.BB and B is FromMBB. In this case we
23100b57cec5SDimitry Andric       // don't have to set C as A's successor as it already is. We only need to
23110b57cec5SDimitry Andric       // update the edge probability on A->C. Note that B will not be
23120b57cec5SDimitry Andric       // immediately removed from A's successors. It is possible that B->D is
23130b57cec5SDimitry Andric       // not removed either if D is a fallthrough of B. Later the edge A->D
23140b57cec5SDimitry Andric       // (generated here) and B->D will be combined into one edge. To maintain
23150b57cec5SDimitry Andric       // correct edge probability of this combined edge, we need to set the edge
23160b57cec5SDimitry Andric       // probability of A->B to zero, which is already done above. The edge
23170b57cec5SDimitry Andric       // probability on A->D is calculated by scaling the original probability
23180b57cec5SDimitry Andric       // on A->B by the probability of B->D.
23190b57cec5SDimitry Andric       //
23200b57cec5SDimitry Andric       // Before ifcvt:      After ifcvt (assume B->D is kept):
23210b57cec5SDimitry Andric       //
23220b57cec5SDimitry Andric       //       A                A
23230b57cec5SDimitry Andric       //      /|               /|\
23240b57cec5SDimitry Andric       //     / B              / B|
23250b57cec5SDimitry Andric       //    | /|             |  ||
23260b57cec5SDimitry Andric       //    |/ |             |  |/
23270b57cec5SDimitry Andric       //    C  D             C  D
23280b57cec5SDimitry Andric       //
23290b57cec5SDimitry Andric       if (ToBBI.BB->isSuccessor(Succ))
23300b57cec5SDimitry Andric         ToBBI.BB->setSuccProbability(
23310b57cec5SDimitry Andric             find(ToBBI.BB->successors(), Succ),
23320b57cec5SDimitry Andric             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
23330b57cec5SDimitry Andric       else
23340b57cec5SDimitry Andric         ToBBI.BB->addSuccessor(Succ, NewProb);
23350b57cec5SDimitry Andric     }
23360b57cec5SDimitry Andric   }
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric   // Move the now empty FromMBB out of the way to the end of the function so
23390b57cec5SDimitry Andric   // it doesn't interfere with fallthrough checks done by canFallThroughTo().
23400b57cec5SDimitry Andric   MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
23410b57cec5SDimitry Andric   if (Last != &FromMBB)
23420b57cec5SDimitry Andric     FromMBB.moveAfter(Last);
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
23450b57cec5SDimitry Andric   // we've done above.
23460b57cec5SDimitry Andric   if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
23470b57cec5SDimitry Andric     ToBBI.BB->normalizeSuccProbs();
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
23500b57cec5SDimitry Andric   FromBBI.Predicate.clear();
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric   ToBBI.NonPredSize += FromBBI.NonPredSize;
23530b57cec5SDimitry Andric   ToBBI.ExtraCost += FromBBI.ExtraCost;
23540b57cec5SDimitry Andric   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
23550b57cec5SDimitry Andric   FromBBI.NonPredSize = 0;
23560b57cec5SDimitry Andric   FromBBI.ExtraCost = 0;
23570b57cec5SDimitry Andric   FromBBI.ExtraCost2 = 0;
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
23600b57cec5SDimitry Andric   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
23610b57cec5SDimitry Andric   ToBBI.IsAnalyzed = false;
23620b57cec5SDimitry Andric   FromBBI.IsAnalyzed = false;
23630b57cec5SDimitry Andric }
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric FunctionPass *
createIfConverter(std::function<bool (const MachineFunction &)> Ftor)23660b57cec5SDimitry Andric llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
23670b57cec5SDimitry Andric   return new IfConverter(std::move(Ftor));
23680b57cec5SDimitry Andric }
2369