xref: /aosp_15_r20/external/llvm/lib/CodeGen/IfConversion.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the machine instruction level if-conversion pass, which
11*9880d681SAndroid Build Coastguard Worker // tries to convert conditional branches into predicated instructions.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/Passes.h"
16*9880d681SAndroid Build Coastguard Worker #include "BranchFolding.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/LivePhysRegs.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineFunctionPass.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineInstrBuilder.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineModuleInfo.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/MachineRegisterInfo.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/TargetSchedule.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ErrorHandling.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetInstrInfo.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetLowering.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetRegisterInfo.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetSubtargetInfo.h"
36*9880d681SAndroid Build Coastguard Worker #include <algorithm>
37*9880d681SAndroid Build Coastguard Worker #include <utility>
38*9880d681SAndroid Build Coastguard Worker 
39*9880d681SAndroid Build Coastguard Worker using namespace llvm;
40*9880d681SAndroid Build Coastguard Worker 
41*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "ifcvt"
42*9880d681SAndroid Build Coastguard Worker 
43*9880d681SAndroid Build Coastguard Worker // Hidden options for help debugging.
44*9880d681SAndroid Build Coastguard Worker static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
45*9880d681SAndroid Build Coastguard Worker static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
46*9880d681SAndroid Build Coastguard Worker static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
47*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
48*9880d681SAndroid Build Coastguard Worker                                    cl::init(false), cl::Hidden);
49*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
50*9880d681SAndroid Build Coastguard Worker                                     cl::init(false), cl::Hidden);
51*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
52*9880d681SAndroid Build Coastguard Worker                                      cl::init(false), cl::Hidden);
53*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
54*9880d681SAndroid Build Coastguard Worker                                       cl::init(false), cl::Hidden);
55*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
56*9880d681SAndroid Build Coastguard Worker                                       cl::init(false), cl::Hidden);
57*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
58*9880d681SAndroid Build Coastguard Worker                                        cl::init(false), cl::Hidden);
59*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
60*9880d681SAndroid Build Coastguard Worker                                     cl::init(false), cl::Hidden);
61*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
62*9880d681SAndroid Build Coastguard Worker                                      cl::init(true), cl::Hidden);
63*9880d681SAndroid Build Coastguard Worker 
64*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSimple,       "Number of simple if-conversions performed");
65*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
66*9880d681SAndroid Build Coastguard Worker STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
67*9880d681SAndroid Build Coastguard Worker STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
68*9880d681SAndroid Build Coastguard Worker STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
69*9880d681SAndroid Build Coastguard Worker STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
70*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
71*9880d681SAndroid Build Coastguard Worker STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
72*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDupBBs,       "Number of duplicated blocks");
73*9880d681SAndroid Build Coastguard Worker STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker namespace {
76*9880d681SAndroid Build Coastguard Worker   class IfConverter : public MachineFunctionPass {
77*9880d681SAndroid Build Coastguard Worker     enum IfcvtKind {
78*9880d681SAndroid Build Coastguard Worker       ICNotClassfied,  // BB data valid, but not classified.
79*9880d681SAndroid Build Coastguard Worker       ICSimpleFalse,   // Same as ICSimple, but on the false path.
80*9880d681SAndroid Build Coastguard Worker       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
81*9880d681SAndroid Build Coastguard Worker       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
82*9880d681SAndroid Build Coastguard Worker       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
83*9880d681SAndroid Build Coastguard Worker       ICTriangleFalse, // Same as ICTriangle, but on the false path.
84*9880d681SAndroid Build Coastguard Worker       ICTriangle,      // BB is entry of a triangle sub-CFG.
85*9880d681SAndroid Build Coastguard Worker       ICDiamond        // BB is entry of a diamond sub-CFG.
86*9880d681SAndroid Build Coastguard Worker     };
87*9880d681SAndroid Build Coastguard Worker 
88*9880d681SAndroid Build Coastguard Worker     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
89*9880d681SAndroid Build Coastguard Worker     /// if-conversion feasibility analysis. This includes results from
90*9880d681SAndroid Build Coastguard Worker     /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
91*9880d681SAndroid Build Coastguard Worker     /// classification, and common tail block of its successors (if it's a
92*9880d681SAndroid Build Coastguard Worker     /// diamond shape), its size, whether it's predicable, and whether any
93*9880d681SAndroid Build Coastguard Worker     /// instruction can clobber the 'would-be' predicate.
94*9880d681SAndroid Build Coastguard Worker     ///
95*9880d681SAndroid Build Coastguard Worker     /// IsDone          - True if BB is not to be considered for ifcvt.
96*9880d681SAndroid Build Coastguard Worker     /// IsBeingAnalyzed - True if BB is currently being analyzed.
97*9880d681SAndroid Build Coastguard Worker     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
98*9880d681SAndroid Build Coastguard Worker     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
99*9880d681SAndroid Build Coastguard Worker     /// IsBrAnalyzable  - True if analyzeBranch() returns false.
100*9880d681SAndroid Build Coastguard Worker     /// HasFallThrough  - True if BB may fallthrough to the following BB.
101*9880d681SAndroid Build Coastguard Worker     /// IsUnpredicable  - True if BB is known to be unpredicable.
102*9880d681SAndroid Build Coastguard Worker     /// ClobbersPred    - True if BB could modify predicates (e.g. has
103*9880d681SAndroid Build Coastguard Worker     ///                   cmp, call, etc.)
104*9880d681SAndroid Build Coastguard Worker     /// NonPredSize     - Number of non-predicated instructions.
105*9880d681SAndroid Build Coastguard Worker     /// ExtraCost       - Extra cost for multi-cycle instructions.
106*9880d681SAndroid Build Coastguard Worker     /// ExtraCost2      - Some instructions are slower when predicated
107*9880d681SAndroid Build Coastguard Worker     /// BB              - Corresponding MachineBasicBlock.
108*9880d681SAndroid Build Coastguard Worker     /// TrueBB / FalseBB- See analyzeBranch().
109*9880d681SAndroid Build Coastguard Worker     /// BrCond          - Conditions for end of block conditional branches.
110*9880d681SAndroid Build Coastguard Worker     /// Predicate       - Predicate used in the BB.
111*9880d681SAndroid Build Coastguard Worker     struct BBInfo {
112*9880d681SAndroid Build Coastguard Worker       bool IsDone          : 1;
113*9880d681SAndroid Build Coastguard Worker       bool IsBeingAnalyzed : 1;
114*9880d681SAndroid Build Coastguard Worker       bool IsAnalyzed      : 1;
115*9880d681SAndroid Build Coastguard Worker       bool IsEnqueued      : 1;
116*9880d681SAndroid Build Coastguard Worker       bool IsBrAnalyzable  : 1;
117*9880d681SAndroid Build Coastguard Worker       bool HasFallThrough  : 1;
118*9880d681SAndroid Build Coastguard Worker       bool IsUnpredicable  : 1;
119*9880d681SAndroid Build Coastguard Worker       bool CannotBeCopied  : 1;
120*9880d681SAndroid Build Coastguard Worker       bool ClobbersPred    : 1;
121*9880d681SAndroid Build Coastguard Worker       unsigned NonPredSize;
122*9880d681SAndroid Build Coastguard Worker       unsigned ExtraCost;
123*9880d681SAndroid Build Coastguard Worker       unsigned ExtraCost2;
124*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock *BB;
125*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock *TrueBB;
126*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock *FalseBB;
127*9880d681SAndroid Build Coastguard Worker       SmallVector<MachineOperand, 4> BrCond;
128*9880d681SAndroid Build Coastguard Worker       SmallVector<MachineOperand, 4> Predicate;
BBInfo__anon94f999010111::IfConverter::BBInfo129*9880d681SAndroid Build Coastguard Worker       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
130*9880d681SAndroid Build Coastguard Worker                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
131*9880d681SAndroid Build Coastguard Worker                  HasFallThrough(false), IsUnpredicable(false),
132*9880d681SAndroid Build Coastguard Worker                  CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
133*9880d681SAndroid Build Coastguard Worker                  ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
134*9880d681SAndroid Build Coastguard Worker                  FalseBB(nullptr) {}
135*9880d681SAndroid Build Coastguard Worker     };
136*9880d681SAndroid Build Coastguard Worker 
137*9880d681SAndroid Build Coastguard Worker     /// IfcvtToken - Record information about pending if-conversions to attempt:
138*9880d681SAndroid Build Coastguard Worker     /// BBI             - Corresponding BBInfo.
139*9880d681SAndroid Build Coastguard Worker     /// Kind            - Type of block. See IfcvtKind.
140*9880d681SAndroid Build Coastguard Worker     /// NeedSubsumption - True if the to-be-predicated BB has already been
141*9880d681SAndroid Build Coastguard Worker     ///                   predicated.
142*9880d681SAndroid Build Coastguard Worker     /// NumDups      - Number of instructions that would be duplicated due
143*9880d681SAndroid Build Coastguard Worker     ///                   to this if-conversion. (For diamonds, the number of
144*9880d681SAndroid Build Coastguard Worker     ///                   identical instructions at the beginnings of both
145*9880d681SAndroid Build Coastguard Worker     ///                   paths).
146*9880d681SAndroid Build Coastguard Worker     /// NumDups2     - For diamonds, the number of identical instructions
147*9880d681SAndroid Build Coastguard Worker     ///                   at the ends of both paths.
148*9880d681SAndroid Build Coastguard Worker     struct IfcvtToken {
149*9880d681SAndroid Build Coastguard Worker       BBInfo &BBI;
150*9880d681SAndroid Build Coastguard Worker       IfcvtKind Kind;
151*9880d681SAndroid Build Coastguard Worker       bool NeedSubsumption;
152*9880d681SAndroid Build Coastguard Worker       unsigned NumDups;
153*9880d681SAndroid Build Coastguard Worker       unsigned NumDups2;
IfcvtToken__anon94f999010111::IfConverter::IfcvtToken154*9880d681SAndroid Build Coastguard Worker       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
155*9880d681SAndroid Build Coastguard Worker         : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
156*9880d681SAndroid Build Coastguard Worker     };
157*9880d681SAndroid Build Coastguard Worker 
158*9880d681SAndroid Build Coastguard Worker     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
159*9880d681SAndroid Build Coastguard Worker     /// basic block number.
160*9880d681SAndroid Build Coastguard Worker     std::vector<BBInfo> BBAnalysis;
161*9880d681SAndroid Build Coastguard Worker     TargetSchedModel SchedModel;
162*9880d681SAndroid Build Coastguard Worker 
163*9880d681SAndroid Build Coastguard Worker     const TargetLoweringBase *TLI;
164*9880d681SAndroid Build Coastguard Worker     const TargetInstrInfo *TII;
165*9880d681SAndroid Build Coastguard Worker     const TargetRegisterInfo *TRI;
166*9880d681SAndroid Build Coastguard Worker     const MachineBranchProbabilityInfo *MBPI;
167*9880d681SAndroid Build Coastguard Worker     MachineRegisterInfo *MRI;
168*9880d681SAndroid Build Coastguard Worker 
169*9880d681SAndroid Build Coastguard Worker     LivePhysRegs Redefs;
170*9880d681SAndroid Build Coastguard Worker     LivePhysRegs DontKill;
171*9880d681SAndroid Build Coastguard Worker 
172*9880d681SAndroid Build Coastguard Worker     bool PreRegAlloc;
173*9880d681SAndroid Build Coastguard Worker     bool MadeChange;
174*9880d681SAndroid Build Coastguard Worker     int FnNum;
175*9880d681SAndroid Build Coastguard Worker     std::function<bool(const Function &)> PredicateFtor;
176*9880d681SAndroid Build Coastguard Worker 
177*9880d681SAndroid Build Coastguard Worker   public:
178*9880d681SAndroid Build Coastguard Worker     static char ID;
IfConverter(std::function<bool (const Function &)> Ftor=nullptr)179*9880d681SAndroid Build Coastguard Worker     IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
180*9880d681SAndroid Build Coastguard Worker         : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
181*9880d681SAndroid Build Coastguard Worker       initializeIfConverterPass(*PassRegistry::getPassRegistry());
182*9880d681SAndroid Build Coastguard Worker     }
183*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const184*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
185*9880d681SAndroid Build Coastguard Worker       AU.addRequired<MachineBlockFrequencyInfo>();
186*9880d681SAndroid Build Coastguard Worker       AU.addRequired<MachineBranchProbabilityInfo>();
187*9880d681SAndroid Build Coastguard Worker       MachineFunctionPass::getAnalysisUsage(AU);
188*9880d681SAndroid Build Coastguard Worker     }
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker     bool runOnMachineFunction(MachineFunction &MF) override;
191*9880d681SAndroid Build Coastguard Worker 
getRequiredProperties() const192*9880d681SAndroid Build Coastguard Worker     MachineFunctionProperties getRequiredProperties() const override {
193*9880d681SAndroid Build Coastguard Worker       return MachineFunctionProperties().set(
194*9880d681SAndroid Build Coastguard Worker           MachineFunctionProperties::Property::AllVRegsAllocated);
195*9880d681SAndroid Build Coastguard Worker     }
196*9880d681SAndroid Build Coastguard Worker 
197*9880d681SAndroid Build Coastguard Worker   private:
198*9880d681SAndroid Build Coastguard Worker     bool ReverseBranchCondition(BBInfo &BBI);
199*9880d681SAndroid Build Coastguard Worker     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
200*9880d681SAndroid Build Coastguard Worker                      BranchProbability Prediction) const;
201*9880d681SAndroid Build Coastguard Worker     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
202*9880d681SAndroid Build Coastguard Worker                        bool FalseBranch, unsigned &Dups,
203*9880d681SAndroid Build Coastguard Worker                        BranchProbability Prediction) const;
204*9880d681SAndroid Build Coastguard Worker     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
205*9880d681SAndroid Build Coastguard Worker                       unsigned &Dups1, unsigned &Dups2) const;
206*9880d681SAndroid Build Coastguard Worker     void ScanInstructions(BBInfo &BBI);
207*9880d681SAndroid Build Coastguard Worker     void AnalyzeBlock(MachineBasicBlock *MBB,
208*9880d681SAndroid Build Coastguard Worker                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
209*9880d681SAndroid Build Coastguard Worker     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
210*9880d681SAndroid Build Coastguard Worker                              bool isTriangle = false, bool RevBranch = false);
211*9880d681SAndroid Build Coastguard Worker     void AnalyzeBlocks(MachineFunction &MF,
212*9880d681SAndroid Build Coastguard Worker                        std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
213*9880d681SAndroid Build Coastguard Worker     void InvalidatePreds(MachineBasicBlock *BB);
214*9880d681SAndroid Build Coastguard Worker     void RemoveExtraEdges(BBInfo &BBI);
215*9880d681SAndroid Build Coastguard Worker     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
216*9880d681SAndroid Build Coastguard Worker     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
217*9880d681SAndroid Build Coastguard Worker     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
218*9880d681SAndroid Build Coastguard Worker                           unsigned NumDups1, unsigned NumDups2);
219*9880d681SAndroid Build Coastguard Worker     void PredicateBlock(BBInfo &BBI,
220*9880d681SAndroid Build Coastguard Worker                         MachineBasicBlock::iterator E,
221*9880d681SAndroid Build Coastguard Worker                         SmallVectorImpl<MachineOperand> &Cond,
222*9880d681SAndroid Build Coastguard Worker                         SmallSet<unsigned, 4> *LaterRedefs = nullptr);
223*9880d681SAndroid Build Coastguard Worker     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
224*9880d681SAndroid Build Coastguard Worker                                SmallVectorImpl<MachineOperand> &Cond,
225*9880d681SAndroid Build Coastguard Worker                                bool IgnoreBr = false);
226*9880d681SAndroid Build Coastguard Worker     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
227*9880d681SAndroid Build Coastguard Worker 
MeetIfcvtSizeLimit(MachineBasicBlock & BB,unsigned Cycle,unsigned Extra,BranchProbability Prediction) const228*9880d681SAndroid Build Coastguard Worker     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
229*9880d681SAndroid Build Coastguard Worker                             unsigned Cycle, unsigned Extra,
230*9880d681SAndroid Build Coastguard Worker                             BranchProbability Prediction) const {
231*9880d681SAndroid Build Coastguard Worker       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
232*9880d681SAndroid Build Coastguard Worker                                                    Prediction);
233*9880d681SAndroid Build Coastguard Worker     }
234*9880d681SAndroid Build Coastguard Worker 
MeetIfcvtSizeLimit(MachineBasicBlock & TBB,unsigned TCycle,unsigned TExtra,MachineBasicBlock & FBB,unsigned FCycle,unsigned FExtra,BranchProbability Prediction) const235*9880d681SAndroid Build Coastguard Worker     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
236*9880d681SAndroid Build Coastguard Worker                             unsigned TCycle, unsigned TExtra,
237*9880d681SAndroid Build Coastguard Worker                             MachineBasicBlock &FBB,
238*9880d681SAndroid Build Coastguard Worker                             unsigned FCycle, unsigned FExtra,
239*9880d681SAndroid Build Coastguard Worker                             BranchProbability Prediction) const {
240*9880d681SAndroid Build Coastguard Worker       return TCycle > 0 && FCycle > 0 &&
241*9880d681SAndroid Build Coastguard Worker         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
242*9880d681SAndroid Build Coastguard Worker                                  Prediction);
243*9880d681SAndroid Build Coastguard Worker     }
244*9880d681SAndroid Build Coastguard Worker 
245*9880d681SAndroid Build Coastguard Worker     // blockAlwaysFallThrough - Block ends without a terminator.
blockAlwaysFallThrough(BBInfo & BBI) const246*9880d681SAndroid Build Coastguard Worker     bool blockAlwaysFallThrough(BBInfo &BBI) const {
247*9880d681SAndroid Build Coastguard Worker       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
248*9880d681SAndroid Build Coastguard Worker     }
249*9880d681SAndroid Build Coastguard Worker 
250*9880d681SAndroid Build Coastguard Worker     // IfcvtTokenCmp - Used to sort if-conversion candidates.
IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> & C1,const std::unique_ptr<IfcvtToken> & C2)251*9880d681SAndroid Build Coastguard Worker     static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
252*9880d681SAndroid Build Coastguard Worker                               const std::unique_ptr<IfcvtToken> &C2) {
253*9880d681SAndroid Build Coastguard Worker       int Incr1 = (C1->Kind == ICDiamond)
254*9880d681SAndroid Build Coastguard Worker         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
255*9880d681SAndroid Build Coastguard Worker       int Incr2 = (C2->Kind == ICDiamond)
256*9880d681SAndroid Build Coastguard Worker         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
257*9880d681SAndroid Build Coastguard Worker       if (Incr1 > Incr2)
258*9880d681SAndroid Build Coastguard Worker         return true;
259*9880d681SAndroid Build Coastguard Worker       else if (Incr1 == Incr2) {
260*9880d681SAndroid Build Coastguard Worker         // Favors subsumption.
261*9880d681SAndroid Build Coastguard Worker         if (!C1->NeedSubsumption && C2->NeedSubsumption)
262*9880d681SAndroid Build Coastguard Worker           return true;
263*9880d681SAndroid Build Coastguard Worker         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
264*9880d681SAndroid Build Coastguard Worker           // Favors diamond over triangle, etc.
265*9880d681SAndroid Build Coastguard Worker           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
266*9880d681SAndroid Build Coastguard Worker             return true;
267*9880d681SAndroid Build Coastguard Worker           else if (C1->Kind == C2->Kind)
268*9880d681SAndroid Build Coastguard Worker             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
269*9880d681SAndroid Build Coastguard Worker         }
270*9880d681SAndroid Build Coastguard Worker       }
271*9880d681SAndroid Build Coastguard Worker       return false;
272*9880d681SAndroid Build Coastguard Worker     }
273*9880d681SAndroid Build Coastguard Worker   };
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker   char IfConverter::ID = 0;
276*9880d681SAndroid Build Coastguard Worker }
277*9880d681SAndroid Build Coastguard Worker 
278*9880d681SAndroid Build Coastguard Worker char &llvm::IfConverterID = IfConverter::ID;
279*9880d681SAndroid Build Coastguard Worker 
280*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)281*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
282*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
283*9880d681SAndroid Build Coastguard Worker 
284*9880d681SAndroid Build Coastguard Worker bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
285*9880d681SAndroid Build Coastguard Worker   if (skipFunction(*MF.getFunction()) ||
286*9880d681SAndroid Build Coastguard Worker       (PredicateFtor && !PredicateFtor(*MF.getFunction())))
287*9880d681SAndroid Build Coastguard Worker     return false;
288*9880d681SAndroid Build Coastguard Worker 
289*9880d681SAndroid Build Coastguard Worker   const TargetSubtargetInfo &ST = MF.getSubtarget();
290*9880d681SAndroid Build Coastguard Worker   TLI = ST.getTargetLowering();
291*9880d681SAndroid Build Coastguard Worker   TII = ST.getInstrInfo();
292*9880d681SAndroid Build Coastguard Worker   TRI = ST.getRegisterInfo();
293*9880d681SAndroid Build Coastguard Worker   BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
294*9880d681SAndroid Build Coastguard Worker   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
295*9880d681SAndroid Build Coastguard Worker   MRI = &MF.getRegInfo();
296*9880d681SAndroid Build Coastguard Worker   SchedModel.init(ST.getSchedModel(), &ST, TII);
297*9880d681SAndroid Build Coastguard Worker 
298*9880d681SAndroid Build Coastguard Worker   if (!TII) return false;
299*9880d681SAndroid Build Coastguard Worker 
300*9880d681SAndroid Build Coastguard Worker   PreRegAlloc = MRI->isSSA();
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker   bool BFChange = false;
303*9880d681SAndroid Build Coastguard Worker   if (!PreRegAlloc) {
304*9880d681SAndroid Build Coastguard Worker     // Tail merge tend to expose more if-conversion opportunities.
305*9880d681SAndroid Build Coastguard Worker     BranchFolder BF(true, false, MBFI, *MBPI);
306*9880d681SAndroid Build Coastguard Worker     BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
307*9880d681SAndroid Build Coastguard Worker                                    getAnalysisIfAvailable<MachineModuleInfo>());
308*9880d681SAndroid Build Coastguard Worker   }
309*9880d681SAndroid Build Coastguard Worker 
310*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
311*9880d681SAndroid Build Coastguard Worker                << MF.getName() << "\'");
312*9880d681SAndroid Build Coastguard Worker 
313*9880d681SAndroid Build Coastguard Worker   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
314*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << " skipped\n");
315*9880d681SAndroid Build Coastguard Worker     return false;
316*9880d681SAndroid Build Coastguard Worker   }
317*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\n");
318*9880d681SAndroid Build Coastguard Worker 
319*9880d681SAndroid Build Coastguard Worker   MF.RenumberBlocks();
320*9880d681SAndroid Build Coastguard Worker   BBAnalysis.resize(MF.getNumBlockIDs());
321*9880d681SAndroid Build Coastguard Worker 
322*9880d681SAndroid Build Coastguard Worker   std::vector<std::unique_ptr<IfcvtToken>> Tokens;
323*9880d681SAndroid Build Coastguard Worker   MadeChange = false;
324*9880d681SAndroid Build Coastguard Worker   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
325*9880d681SAndroid Build Coastguard Worker     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
326*9880d681SAndroid Build Coastguard Worker   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
327*9880d681SAndroid Build Coastguard Worker     // Do an initial analysis for each basic block and find all the potential
328*9880d681SAndroid Build Coastguard Worker     // candidates to perform if-conversion.
329*9880d681SAndroid Build Coastguard Worker     bool Change = false;
330*9880d681SAndroid Build Coastguard Worker     AnalyzeBlocks(MF, Tokens);
331*9880d681SAndroid Build Coastguard Worker     while (!Tokens.empty()) {
332*9880d681SAndroid Build Coastguard Worker       std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
333*9880d681SAndroid Build Coastguard Worker       Tokens.pop_back();
334*9880d681SAndroid Build Coastguard Worker       BBInfo &BBI = Token->BBI;
335*9880d681SAndroid Build Coastguard Worker       IfcvtKind Kind = Token->Kind;
336*9880d681SAndroid Build Coastguard Worker       unsigned NumDups = Token->NumDups;
337*9880d681SAndroid Build Coastguard Worker       unsigned NumDups2 = Token->NumDups2;
338*9880d681SAndroid Build Coastguard Worker 
339*9880d681SAndroid Build Coastguard Worker       // If the block has been evicted out of the queue or it has already been
340*9880d681SAndroid Build Coastguard Worker       // marked dead (due to it being predicated), then skip it.
341*9880d681SAndroid Build Coastguard Worker       if (BBI.IsDone)
342*9880d681SAndroid Build Coastguard Worker         BBI.IsEnqueued = false;
343*9880d681SAndroid Build Coastguard Worker       if (!BBI.IsEnqueued)
344*9880d681SAndroid Build Coastguard Worker         continue;
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker       BBI.IsEnqueued = false;
347*9880d681SAndroid Build Coastguard Worker 
348*9880d681SAndroid Build Coastguard Worker       bool RetVal = false;
349*9880d681SAndroid Build Coastguard Worker       switch (Kind) {
350*9880d681SAndroid Build Coastguard Worker       default: llvm_unreachable("Unexpected!");
351*9880d681SAndroid Build Coastguard Worker       case ICSimple:
352*9880d681SAndroid Build Coastguard Worker       case ICSimpleFalse: {
353*9880d681SAndroid Build Coastguard Worker         bool isFalse = Kind == ICSimpleFalse;
354*9880d681SAndroid Build Coastguard Worker         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
355*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
356*9880d681SAndroid Build Coastguard Worker                                             " false" : "")
357*9880d681SAndroid Build Coastguard Worker                      << "): BB#" << BBI.BB->getNumber() << " ("
358*9880d681SAndroid Build Coastguard Worker                      << ((Kind == ICSimpleFalse)
359*9880d681SAndroid Build Coastguard Worker                          ? BBI.FalseBB->getNumber()
360*9880d681SAndroid Build Coastguard Worker                          : BBI.TrueBB->getNumber()) << ") ");
361*9880d681SAndroid Build Coastguard Worker         RetVal = IfConvertSimple(BBI, Kind);
362*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
363*9880d681SAndroid Build Coastguard Worker         if (RetVal) {
364*9880d681SAndroid Build Coastguard Worker           if (isFalse) ++NumSimpleFalse;
365*9880d681SAndroid Build Coastguard Worker           else         ++NumSimple;
366*9880d681SAndroid Build Coastguard Worker         }
367*9880d681SAndroid Build Coastguard Worker        break;
368*9880d681SAndroid Build Coastguard Worker       }
369*9880d681SAndroid Build Coastguard Worker       case ICTriangle:
370*9880d681SAndroid Build Coastguard Worker       case ICTriangleRev:
371*9880d681SAndroid Build Coastguard Worker       case ICTriangleFalse:
372*9880d681SAndroid Build Coastguard Worker       case ICTriangleFRev: {
373*9880d681SAndroid Build Coastguard Worker         bool isFalse = Kind == ICTriangleFalse;
374*9880d681SAndroid Build Coastguard Worker         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
375*9880d681SAndroid Build Coastguard Worker         if (DisableTriangle && !isFalse && !isRev) break;
376*9880d681SAndroid Build Coastguard Worker         if (DisableTriangleR && !isFalse && isRev) break;
377*9880d681SAndroid Build Coastguard Worker         if (DisableTriangleF && isFalse && !isRev) break;
378*9880d681SAndroid Build Coastguard Worker         if (DisableTriangleFR && isFalse && isRev) break;
379*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "Ifcvt (Triangle");
380*9880d681SAndroid Build Coastguard Worker         if (isFalse)
381*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << " false");
382*9880d681SAndroid Build Coastguard Worker         if (isRev)
383*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << " rev");
384*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
385*9880d681SAndroid Build Coastguard Worker                      << BBI.TrueBB->getNumber() << ",F:"
386*9880d681SAndroid Build Coastguard Worker                      << BBI.FalseBB->getNumber() << ") ");
387*9880d681SAndroid Build Coastguard Worker         RetVal = IfConvertTriangle(BBI, Kind);
388*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
389*9880d681SAndroid Build Coastguard Worker         if (RetVal) {
390*9880d681SAndroid Build Coastguard Worker           if (isFalse) {
391*9880d681SAndroid Build Coastguard Worker             if (isRev) ++NumTriangleFRev;
392*9880d681SAndroid Build Coastguard Worker             else       ++NumTriangleFalse;
393*9880d681SAndroid Build Coastguard Worker           } else {
394*9880d681SAndroid Build Coastguard Worker             if (isRev) ++NumTriangleRev;
395*9880d681SAndroid Build Coastguard Worker             else       ++NumTriangle;
396*9880d681SAndroid Build Coastguard Worker           }
397*9880d681SAndroid Build Coastguard Worker         }
398*9880d681SAndroid Build Coastguard Worker         break;
399*9880d681SAndroid Build Coastguard Worker       }
400*9880d681SAndroid Build Coastguard Worker       case ICDiamond: {
401*9880d681SAndroid Build Coastguard Worker         if (DisableDiamond) break;
402*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
403*9880d681SAndroid Build Coastguard Worker                      << BBI.TrueBB->getNumber() << ",F:"
404*9880d681SAndroid Build Coastguard Worker                      << BBI.FalseBB->getNumber() << ") ");
405*9880d681SAndroid Build Coastguard Worker         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
406*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
407*9880d681SAndroid Build Coastguard Worker         if (RetVal) ++NumDiamonds;
408*9880d681SAndroid Build Coastguard Worker         break;
409*9880d681SAndroid Build Coastguard Worker       }
410*9880d681SAndroid Build Coastguard Worker       }
411*9880d681SAndroid Build Coastguard Worker 
412*9880d681SAndroid Build Coastguard Worker       Change |= RetVal;
413*9880d681SAndroid Build Coastguard Worker 
414*9880d681SAndroid Build Coastguard Worker       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
415*9880d681SAndroid Build Coastguard Worker         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
416*9880d681SAndroid Build Coastguard Worker       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
417*9880d681SAndroid Build Coastguard Worker         break;
418*9880d681SAndroid Build Coastguard Worker     }
419*9880d681SAndroid Build Coastguard Worker 
420*9880d681SAndroid Build Coastguard Worker     if (!Change)
421*9880d681SAndroid Build Coastguard Worker       break;
422*9880d681SAndroid Build Coastguard Worker     MadeChange |= Change;
423*9880d681SAndroid Build Coastguard Worker   }
424*9880d681SAndroid Build Coastguard Worker 
425*9880d681SAndroid Build Coastguard Worker   Tokens.clear();
426*9880d681SAndroid Build Coastguard Worker   BBAnalysis.clear();
427*9880d681SAndroid Build Coastguard Worker 
428*9880d681SAndroid Build Coastguard Worker   if (MadeChange && IfCvtBranchFold) {
429*9880d681SAndroid Build Coastguard Worker     BranchFolder BF(false, false, MBFI, *MBPI);
430*9880d681SAndroid Build Coastguard Worker     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
431*9880d681SAndroid Build Coastguard Worker                         getAnalysisIfAvailable<MachineModuleInfo>());
432*9880d681SAndroid Build Coastguard Worker   }
433*9880d681SAndroid Build Coastguard Worker 
434*9880d681SAndroid Build Coastguard Worker   MadeChange |= BFChange;
435*9880d681SAndroid Build Coastguard Worker   return MadeChange;
436*9880d681SAndroid Build Coastguard Worker }
437*9880d681SAndroid Build Coastguard Worker 
438*9880d681SAndroid Build Coastguard Worker /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
439*9880d681SAndroid Build Coastguard Worker /// its 'true' successor.
findFalseBlock(MachineBasicBlock * BB,MachineBasicBlock * TrueBB)440*9880d681SAndroid Build Coastguard Worker static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
441*9880d681SAndroid Build Coastguard Worker                                          MachineBasicBlock *TrueBB) {
442*9880d681SAndroid Build Coastguard Worker   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
443*9880d681SAndroid Build Coastguard Worker          E = BB->succ_end(); SI != E; ++SI) {
444*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *SuccBB = *SI;
445*9880d681SAndroid Build Coastguard Worker     if (SuccBB != TrueBB)
446*9880d681SAndroid Build Coastguard Worker       return SuccBB;
447*9880d681SAndroid Build Coastguard Worker   }
448*9880d681SAndroid Build Coastguard Worker   return nullptr;
449*9880d681SAndroid Build Coastguard Worker }
450*9880d681SAndroid Build Coastguard Worker 
451*9880d681SAndroid Build Coastguard Worker /// ReverseBranchCondition - Reverse the condition of the end of the block
452*9880d681SAndroid Build Coastguard Worker /// branch. Swap block's 'true' and 'false' successors.
ReverseBranchCondition(BBInfo & BBI)453*9880d681SAndroid Build Coastguard Worker bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
454*9880d681SAndroid Build Coastguard Worker   DebugLoc dl;  // FIXME: this is nowhere
455*9880d681SAndroid Build Coastguard Worker   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
456*9880d681SAndroid Build Coastguard Worker     TII->RemoveBranch(*BBI.BB);
457*9880d681SAndroid Build Coastguard Worker     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
458*9880d681SAndroid Build Coastguard Worker     std::swap(BBI.TrueBB, BBI.FalseBB);
459*9880d681SAndroid Build Coastguard Worker     return true;
460*9880d681SAndroid Build Coastguard Worker   }
461*9880d681SAndroid Build Coastguard Worker   return false;
462*9880d681SAndroid Build Coastguard Worker }
463*9880d681SAndroid Build Coastguard Worker 
464*9880d681SAndroid Build Coastguard Worker /// getNextBlock - Returns the next block in the function blocks ordering. If
465*9880d681SAndroid Build Coastguard Worker /// it is the end, returns NULL.
getNextBlock(MachineBasicBlock * BB)466*9880d681SAndroid Build Coastguard Worker static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
467*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator I = BB->getIterator();
468*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator E = BB->getParent()->end();
469*9880d681SAndroid Build Coastguard Worker   if (++I == E)
470*9880d681SAndroid Build Coastguard Worker     return nullptr;
471*9880d681SAndroid Build Coastguard Worker   return &*I;
472*9880d681SAndroid Build Coastguard Worker }
473*9880d681SAndroid Build Coastguard Worker 
474*9880d681SAndroid Build Coastguard Worker /// ValidSimple - Returns true if the 'true' block (along with its
475*9880d681SAndroid Build Coastguard Worker /// predecessor) forms a valid simple shape for ifcvt. It also returns the
476*9880d681SAndroid Build Coastguard Worker /// number of instructions that the ifcvt would need to duplicate if performed
477*9880d681SAndroid Build Coastguard Worker /// in Dups.
ValidSimple(BBInfo & TrueBBI,unsigned & Dups,BranchProbability Prediction) const478*9880d681SAndroid Build Coastguard Worker bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
479*9880d681SAndroid Build Coastguard Worker                               BranchProbability Prediction) const {
480*9880d681SAndroid Build Coastguard Worker   Dups = 0;
481*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
482*9880d681SAndroid Build Coastguard Worker     return false;
483*9880d681SAndroid Build Coastguard Worker 
484*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.IsBrAnalyzable)
485*9880d681SAndroid Build Coastguard Worker     return false;
486*9880d681SAndroid Build Coastguard Worker 
487*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.BB->pred_size() > 1) {
488*9880d681SAndroid Build Coastguard Worker     if (TrueBBI.CannotBeCopied ||
489*9880d681SAndroid Build Coastguard Worker         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
490*9880d681SAndroid Build Coastguard Worker                                         Prediction))
491*9880d681SAndroid Build Coastguard Worker       return false;
492*9880d681SAndroid Build Coastguard Worker     Dups = TrueBBI.NonPredSize;
493*9880d681SAndroid Build Coastguard Worker   }
494*9880d681SAndroid Build Coastguard Worker 
495*9880d681SAndroid Build Coastguard Worker   return true;
496*9880d681SAndroid Build Coastguard Worker }
497*9880d681SAndroid Build Coastguard Worker 
498*9880d681SAndroid Build Coastguard Worker /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
499*9880d681SAndroid Build Coastguard Worker /// with their common predecessor) forms a valid triangle shape for ifcvt.
500*9880d681SAndroid Build Coastguard Worker /// If 'FalseBranch' is true, it checks if 'true' block's false branch
501*9880d681SAndroid Build Coastguard Worker /// branches to the 'false' block rather than the other way around. It also
502*9880d681SAndroid Build Coastguard Worker /// returns the number of instructions that the ifcvt would need to duplicate
503*9880d681SAndroid Build Coastguard Worker /// if performed in 'Dups'.
ValidTriangle(BBInfo & TrueBBI,BBInfo & FalseBBI,bool FalseBranch,unsigned & Dups,BranchProbability Prediction) const504*9880d681SAndroid Build Coastguard Worker bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
505*9880d681SAndroid Build Coastguard Worker                                 bool FalseBranch, unsigned &Dups,
506*9880d681SAndroid Build Coastguard Worker                                 BranchProbability Prediction) const {
507*9880d681SAndroid Build Coastguard Worker   Dups = 0;
508*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
509*9880d681SAndroid Build Coastguard Worker     return false;
510*9880d681SAndroid Build Coastguard Worker 
511*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.BB->pred_size() > 1) {
512*9880d681SAndroid Build Coastguard Worker     if (TrueBBI.CannotBeCopied)
513*9880d681SAndroid Build Coastguard Worker       return false;
514*9880d681SAndroid Build Coastguard Worker 
515*9880d681SAndroid Build Coastguard Worker     unsigned Size = TrueBBI.NonPredSize;
516*9880d681SAndroid Build Coastguard Worker     if (TrueBBI.IsBrAnalyzable) {
517*9880d681SAndroid Build Coastguard Worker       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
518*9880d681SAndroid Build Coastguard Worker         // Ends with an unconditional branch. It will be removed.
519*9880d681SAndroid Build Coastguard Worker         --Size;
520*9880d681SAndroid Build Coastguard Worker       else {
521*9880d681SAndroid Build Coastguard Worker         MachineBasicBlock *FExit = FalseBranch
522*9880d681SAndroid Build Coastguard Worker           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
523*9880d681SAndroid Build Coastguard Worker         if (FExit)
524*9880d681SAndroid Build Coastguard Worker           // Require a conditional branch
525*9880d681SAndroid Build Coastguard Worker           ++Size;
526*9880d681SAndroid Build Coastguard Worker       }
527*9880d681SAndroid Build Coastguard Worker     }
528*9880d681SAndroid Build Coastguard Worker     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
529*9880d681SAndroid Build Coastguard Worker       return false;
530*9880d681SAndroid Build Coastguard Worker     Dups = Size;
531*9880d681SAndroid Build Coastguard Worker   }
532*9880d681SAndroid Build Coastguard Worker 
533*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
534*9880d681SAndroid Build Coastguard Worker   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
535*9880d681SAndroid Build Coastguard Worker     MachineFunction::iterator I = TrueBBI.BB->getIterator();
536*9880d681SAndroid Build Coastguard Worker     if (++I == TrueBBI.BB->getParent()->end())
537*9880d681SAndroid Build Coastguard Worker       return false;
538*9880d681SAndroid Build Coastguard Worker     TExit = &*I;
539*9880d681SAndroid Build Coastguard Worker   }
540*9880d681SAndroid Build Coastguard Worker   return TExit && TExit == FalseBBI.BB;
541*9880d681SAndroid Build Coastguard Worker }
542*9880d681SAndroid Build Coastguard Worker 
543*9880d681SAndroid Build Coastguard Worker /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
544*9880d681SAndroid Build Coastguard Worker /// with their common predecessor) forms a valid diamond shape for ifcvt.
ValidDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2) const545*9880d681SAndroid Build Coastguard Worker bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
546*9880d681SAndroid Build Coastguard Worker                                unsigned &Dups1, unsigned &Dups2) const {
547*9880d681SAndroid Build Coastguard Worker   Dups1 = Dups2 = 0;
548*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
549*9880d681SAndroid Build Coastguard Worker       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
550*9880d681SAndroid Build Coastguard Worker     return false;
551*9880d681SAndroid Build Coastguard Worker 
552*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *TT = TrueBBI.TrueBB;
553*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *FT = FalseBBI.TrueBB;
554*9880d681SAndroid Build Coastguard Worker 
555*9880d681SAndroid Build Coastguard Worker   if (!TT && blockAlwaysFallThrough(TrueBBI))
556*9880d681SAndroid Build Coastguard Worker     TT = getNextBlock(TrueBBI.BB);
557*9880d681SAndroid Build Coastguard Worker   if (!FT && blockAlwaysFallThrough(FalseBBI))
558*9880d681SAndroid Build Coastguard Worker     FT = getNextBlock(FalseBBI.BB);
559*9880d681SAndroid Build Coastguard Worker   if (TT != FT)
560*9880d681SAndroid Build Coastguard Worker     return false;
561*9880d681SAndroid Build Coastguard Worker   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
562*9880d681SAndroid Build Coastguard Worker     return false;
563*9880d681SAndroid Build Coastguard Worker   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
564*9880d681SAndroid Build Coastguard Worker     return false;
565*9880d681SAndroid Build Coastguard Worker 
566*9880d681SAndroid Build Coastguard Worker   // FIXME: Allow true block to have an early exit?
567*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
568*9880d681SAndroid Build Coastguard Worker       (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
569*9880d681SAndroid Build Coastguard Worker     return false;
570*9880d681SAndroid Build Coastguard Worker 
571*9880d681SAndroid Build Coastguard Worker   // Count duplicate instructions at the beginning of the true and false blocks.
572*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
573*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
574*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
575*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
576*9880d681SAndroid Build Coastguard Worker   while (TIB != TIE && FIB != FIE) {
577*9880d681SAndroid Build Coastguard Worker     // Skip dbg_value instructions. These do not count.
578*9880d681SAndroid Build Coastguard Worker     if (TIB->isDebugValue()) {
579*9880d681SAndroid Build Coastguard Worker       while (TIB != TIE && TIB->isDebugValue())
580*9880d681SAndroid Build Coastguard Worker         ++TIB;
581*9880d681SAndroid Build Coastguard Worker       if (TIB == TIE)
582*9880d681SAndroid Build Coastguard Worker         break;
583*9880d681SAndroid Build Coastguard Worker     }
584*9880d681SAndroid Build Coastguard Worker     if (FIB->isDebugValue()) {
585*9880d681SAndroid Build Coastguard Worker       while (FIB != FIE && FIB->isDebugValue())
586*9880d681SAndroid Build Coastguard Worker         ++FIB;
587*9880d681SAndroid Build Coastguard Worker       if (FIB == FIE)
588*9880d681SAndroid Build Coastguard Worker         break;
589*9880d681SAndroid Build Coastguard Worker     }
590*9880d681SAndroid Build Coastguard Worker     if (!TIB->isIdenticalTo(*FIB))
591*9880d681SAndroid Build Coastguard Worker       break;
592*9880d681SAndroid Build Coastguard Worker     ++Dups1;
593*9880d681SAndroid Build Coastguard Worker     ++TIB;
594*9880d681SAndroid Build Coastguard Worker     ++FIB;
595*9880d681SAndroid Build Coastguard Worker   }
596*9880d681SAndroid Build Coastguard Worker 
597*9880d681SAndroid Build Coastguard Worker   // Now, in preparation for counting duplicate instructions at the ends of the
598*9880d681SAndroid Build Coastguard Worker   // blocks, move the end iterators up past any branch instructions.
599*9880d681SAndroid Build Coastguard Worker   // If both blocks are returning don't skip the branches, since they will
600*9880d681SAndroid Build Coastguard Worker   // likely be both identical return instructions. In such cases the return
601*9880d681SAndroid Build Coastguard Worker   // can be left unpredicated.
602*9880d681SAndroid Build Coastguard Worker   // Check for already containing all of the block.
603*9880d681SAndroid Build Coastguard Worker   if (TIB == TIE || FIB == FIE)
604*9880d681SAndroid Build Coastguard Worker     return true;
605*9880d681SAndroid Build Coastguard Worker   --TIE;
606*9880d681SAndroid Build Coastguard Worker   --FIE;
607*9880d681SAndroid Build Coastguard Worker   if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
608*9880d681SAndroid Build Coastguard Worker     while (TIE != TIB && TIE->isBranch())
609*9880d681SAndroid Build Coastguard Worker       --TIE;
610*9880d681SAndroid Build Coastguard Worker     while (FIE != FIB && FIE->isBranch())
611*9880d681SAndroid Build Coastguard Worker       --FIE;
612*9880d681SAndroid Build Coastguard Worker   }
613*9880d681SAndroid Build Coastguard Worker 
614*9880d681SAndroid Build Coastguard Worker   // If Dups1 includes all of a block, then don't count duplicate
615*9880d681SAndroid Build Coastguard Worker   // instructions at the end of the blocks.
616*9880d681SAndroid Build Coastguard Worker   if (TIB == TIE || FIB == FIE)
617*9880d681SAndroid Build Coastguard Worker     return true;
618*9880d681SAndroid Build Coastguard Worker 
619*9880d681SAndroid Build Coastguard Worker   // Count duplicate instructions at the ends of the blocks.
620*9880d681SAndroid Build Coastguard Worker   while (TIE != TIB && FIE != FIB) {
621*9880d681SAndroid Build Coastguard Worker     // Skip dbg_value instructions. These do not count.
622*9880d681SAndroid Build Coastguard Worker     if (TIE->isDebugValue()) {
623*9880d681SAndroid Build Coastguard Worker       while (TIE != TIB && TIE->isDebugValue())
624*9880d681SAndroid Build Coastguard Worker         --TIE;
625*9880d681SAndroid Build Coastguard Worker       if (TIE == TIB)
626*9880d681SAndroid Build Coastguard Worker         break;
627*9880d681SAndroid Build Coastguard Worker     }
628*9880d681SAndroid Build Coastguard Worker     if (FIE->isDebugValue()) {
629*9880d681SAndroid Build Coastguard Worker       while (FIE != FIB && FIE->isDebugValue())
630*9880d681SAndroid Build Coastguard Worker         --FIE;
631*9880d681SAndroid Build Coastguard Worker       if (FIE == FIB)
632*9880d681SAndroid Build Coastguard Worker         break;
633*9880d681SAndroid Build Coastguard Worker     }
634*9880d681SAndroid Build Coastguard Worker     if (!TIE->isIdenticalTo(*FIE))
635*9880d681SAndroid Build Coastguard Worker       break;
636*9880d681SAndroid Build Coastguard Worker     ++Dups2;
637*9880d681SAndroid Build Coastguard Worker     --TIE;
638*9880d681SAndroid Build Coastguard Worker     --FIE;
639*9880d681SAndroid Build Coastguard Worker   }
640*9880d681SAndroid Build Coastguard Worker 
641*9880d681SAndroid Build Coastguard Worker   return true;
642*9880d681SAndroid Build Coastguard Worker }
643*9880d681SAndroid Build Coastguard Worker 
644*9880d681SAndroid Build Coastguard Worker /// ScanInstructions - Scan all the instructions in the block to determine if
645*9880d681SAndroid Build Coastguard Worker /// the block is predicable. In most cases, that means all the instructions
646*9880d681SAndroid Build Coastguard Worker /// in the block are isPredicable(). Also checks if the block contains any
647*9880d681SAndroid Build Coastguard Worker /// instruction which can clobber a predicate (e.g. condition code register).
648*9880d681SAndroid Build Coastguard Worker /// If so, the block is not predicable unless it's the last instruction.
ScanInstructions(BBInfo & BBI)649*9880d681SAndroid Build Coastguard Worker void IfConverter::ScanInstructions(BBInfo &BBI) {
650*9880d681SAndroid Build Coastguard Worker   if (BBI.IsDone)
651*9880d681SAndroid Build Coastguard Worker     return;
652*9880d681SAndroid Build Coastguard Worker 
653*9880d681SAndroid Build Coastguard Worker   bool AlreadyPredicated = !BBI.Predicate.empty();
654*9880d681SAndroid Build Coastguard Worker   // First analyze the end of BB branches.
655*9880d681SAndroid Build Coastguard Worker   BBI.TrueBB = BBI.FalseBB = nullptr;
656*9880d681SAndroid Build Coastguard Worker   BBI.BrCond.clear();
657*9880d681SAndroid Build Coastguard Worker   BBI.IsBrAnalyzable =
658*9880d681SAndroid Build Coastguard Worker       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
659*9880d681SAndroid Build Coastguard Worker   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
660*9880d681SAndroid Build Coastguard Worker 
661*9880d681SAndroid Build Coastguard Worker   if (BBI.BrCond.size()) {
662*9880d681SAndroid Build Coastguard Worker     // No false branch. This BB must end with a conditional branch and a
663*9880d681SAndroid Build Coastguard Worker     // fallthrough.
664*9880d681SAndroid Build Coastguard Worker     if (!BBI.FalseBB)
665*9880d681SAndroid Build Coastguard Worker       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
666*9880d681SAndroid Build Coastguard Worker     if (!BBI.FalseBB) {
667*9880d681SAndroid Build Coastguard Worker       // Malformed bcc? True and false blocks are the same?
668*9880d681SAndroid Build Coastguard Worker       BBI.IsUnpredicable = true;
669*9880d681SAndroid Build Coastguard Worker       return;
670*9880d681SAndroid Build Coastguard Worker     }
671*9880d681SAndroid Build Coastguard Worker   }
672*9880d681SAndroid Build Coastguard Worker 
673*9880d681SAndroid Build Coastguard Worker   // Then scan all the instructions.
674*9880d681SAndroid Build Coastguard Worker   BBI.NonPredSize = 0;
675*9880d681SAndroid Build Coastguard Worker   BBI.ExtraCost = 0;
676*9880d681SAndroid Build Coastguard Worker   BBI.ExtraCost2 = 0;
677*9880d681SAndroid Build Coastguard Worker   BBI.ClobbersPred = false;
678*9880d681SAndroid Build Coastguard Worker   for (auto &MI : *BBI.BB) {
679*9880d681SAndroid Build Coastguard Worker     if (MI.isDebugValue())
680*9880d681SAndroid Build Coastguard Worker       continue;
681*9880d681SAndroid Build Coastguard Worker 
682*9880d681SAndroid Build Coastguard Worker     // It's unsafe to duplicate convergent instructions in this context, so set
683*9880d681SAndroid Build Coastguard Worker     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
684*9880d681SAndroid Build Coastguard Worker     // following CFG, which is subject to our "simple" transformation.
685*9880d681SAndroid Build Coastguard Worker     //
686*9880d681SAndroid Build Coastguard Worker     //    BB0     // if (c1) goto BB1; else goto BB2;
687*9880d681SAndroid Build Coastguard Worker     //   /   \
688*9880d681SAndroid Build Coastguard Worker     //  BB1   |
689*9880d681SAndroid Build Coastguard Worker     //   |   BB2  // if (c2) goto TBB; else goto FBB;
690*9880d681SAndroid Build Coastguard Worker     //   |   / |
691*9880d681SAndroid Build Coastguard Worker     //   |  /  |
692*9880d681SAndroid Build Coastguard Worker     //   TBB   |
693*9880d681SAndroid Build Coastguard Worker     //    |    |
694*9880d681SAndroid Build Coastguard Worker     //    |   FBB
695*9880d681SAndroid Build Coastguard Worker     //    |
696*9880d681SAndroid Build Coastguard Worker     //    exit
697*9880d681SAndroid Build Coastguard Worker     //
698*9880d681SAndroid Build Coastguard Worker     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
699*9880d681SAndroid Build Coastguard Worker     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
700*9880d681SAndroid Build Coastguard Worker     // TBB contains a convergent instruction.  This is safe iff doing so does
701*9880d681SAndroid Build Coastguard Worker     // not add a control-flow dependency to the convergent instruction -- i.e.,
702*9880d681SAndroid Build Coastguard Worker     // it's safe iff the set of control flows that leads us to the convergent
703*9880d681SAndroid Build Coastguard Worker     // instruction does not get smaller after the transformation.
704*9880d681SAndroid Build Coastguard Worker     //
705*9880d681SAndroid Build Coastguard Worker     // Originally we executed TBB if c1 || c2.  After the transformation, there
706*9880d681SAndroid Build Coastguard Worker     // are two copies of TBB's instructions.  We get to the first if c1, and we
707*9880d681SAndroid Build Coastguard Worker     // get to the second if !c1 && c2.
708*9880d681SAndroid Build Coastguard Worker     //
709*9880d681SAndroid Build Coastguard Worker     // There are clearly fewer ways to satisfy the condition "c1" than
710*9880d681SAndroid Build Coastguard Worker     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
711*9880d681SAndroid Build Coastguard Worker     // our convergent instruction, the transformation is unsafe.
712*9880d681SAndroid Build Coastguard Worker     if (MI.isNotDuplicable() || MI.isConvergent())
713*9880d681SAndroid Build Coastguard Worker       BBI.CannotBeCopied = true;
714*9880d681SAndroid Build Coastguard Worker 
715*9880d681SAndroid Build Coastguard Worker     bool isPredicated = TII->isPredicated(MI);
716*9880d681SAndroid Build Coastguard Worker     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
717*9880d681SAndroid Build Coastguard Worker 
718*9880d681SAndroid Build Coastguard Worker     // A conditional branch is not predicable, but it may be eliminated.
719*9880d681SAndroid Build Coastguard Worker     if (isCondBr)
720*9880d681SAndroid Build Coastguard Worker       continue;
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker     if (!isPredicated) {
723*9880d681SAndroid Build Coastguard Worker       BBI.NonPredSize++;
724*9880d681SAndroid Build Coastguard Worker       unsigned ExtraPredCost = TII->getPredicationCost(MI);
725*9880d681SAndroid Build Coastguard Worker       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
726*9880d681SAndroid Build Coastguard Worker       if (NumCycles > 1)
727*9880d681SAndroid Build Coastguard Worker         BBI.ExtraCost += NumCycles-1;
728*9880d681SAndroid Build Coastguard Worker       BBI.ExtraCost2 += ExtraPredCost;
729*9880d681SAndroid Build Coastguard Worker     } else if (!AlreadyPredicated) {
730*9880d681SAndroid Build Coastguard Worker       // FIXME: This instruction is already predicated before the
731*9880d681SAndroid Build Coastguard Worker       // if-conversion pass. It's probably something like a conditional move.
732*9880d681SAndroid Build Coastguard Worker       // Mark this block unpredicable for now.
733*9880d681SAndroid Build Coastguard Worker       BBI.IsUnpredicable = true;
734*9880d681SAndroid Build Coastguard Worker       return;
735*9880d681SAndroid Build Coastguard Worker     }
736*9880d681SAndroid Build Coastguard Worker 
737*9880d681SAndroid Build Coastguard Worker     if (BBI.ClobbersPred && !isPredicated) {
738*9880d681SAndroid Build Coastguard Worker       // Predicate modification instruction should end the block (except for
739*9880d681SAndroid Build Coastguard Worker       // already predicated instructions and end of block branches).
740*9880d681SAndroid Build Coastguard Worker       // Predicate may have been modified, the subsequent (currently)
741*9880d681SAndroid Build Coastguard Worker       // unpredicated instructions cannot be correctly predicated.
742*9880d681SAndroid Build Coastguard Worker       BBI.IsUnpredicable = true;
743*9880d681SAndroid Build Coastguard Worker       return;
744*9880d681SAndroid Build Coastguard Worker     }
745*9880d681SAndroid Build Coastguard Worker 
746*9880d681SAndroid Build Coastguard Worker     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
747*9880d681SAndroid Build Coastguard Worker     // still potentially predicable.
748*9880d681SAndroid Build Coastguard Worker     std::vector<MachineOperand> PredDefs;
749*9880d681SAndroid Build Coastguard Worker     if (TII->DefinesPredicate(MI, PredDefs))
750*9880d681SAndroid Build Coastguard Worker       BBI.ClobbersPred = true;
751*9880d681SAndroid Build Coastguard Worker 
752*9880d681SAndroid Build Coastguard Worker     if (!TII->isPredicable(MI)) {
753*9880d681SAndroid Build Coastguard Worker       BBI.IsUnpredicable = true;
754*9880d681SAndroid Build Coastguard Worker       return;
755*9880d681SAndroid Build Coastguard Worker     }
756*9880d681SAndroid Build Coastguard Worker   }
757*9880d681SAndroid Build Coastguard Worker }
758*9880d681SAndroid Build Coastguard Worker 
759*9880d681SAndroid Build Coastguard Worker /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
760*9880d681SAndroid Build Coastguard Worker /// predicated by the specified predicate.
FeasibilityAnalysis(BBInfo & BBI,SmallVectorImpl<MachineOperand> & Pred,bool isTriangle,bool RevBranch)761*9880d681SAndroid Build Coastguard Worker bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
762*9880d681SAndroid Build Coastguard Worker                                       SmallVectorImpl<MachineOperand> &Pred,
763*9880d681SAndroid Build Coastguard Worker                                       bool isTriangle, bool RevBranch) {
764*9880d681SAndroid Build Coastguard Worker   // If the block is dead or unpredicable, then it cannot be predicated.
765*9880d681SAndroid Build Coastguard Worker   if (BBI.IsDone || BBI.IsUnpredicable)
766*9880d681SAndroid Build Coastguard Worker     return false;
767*9880d681SAndroid Build Coastguard Worker 
768*9880d681SAndroid Build Coastguard Worker   // If it is already predicated but we couldn't analyze its terminator, the
769*9880d681SAndroid Build Coastguard Worker   // latter might fallthrough, but we can't determine where to.
770*9880d681SAndroid Build Coastguard Worker   // Conservatively avoid if-converting again.
771*9880d681SAndroid Build Coastguard Worker   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
772*9880d681SAndroid Build Coastguard Worker     return false;
773*9880d681SAndroid Build Coastguard Worker 
774*9880d681SAndroid Build Coastguard Worker   // If it is already predicated, check if the new predicate subsumes
775*9880d681SAndroid Build Coastguard Worker   // its predicate.
776*9880d681SAndroid Build Coastguard Worker   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
777*9880d681SAndroid Build Coastguard Worker     return false;
778*9880d681SAndroid Build Coastguard Worker 
779*9880d681SAndroid Build Coastguard Worker   if (BBI.BrCond.size()) {
780*9880d681SAndroid Build Coastguard Worker     if (!isTriangle)
781*9880d681SAndroid Build Coastguard Worker       return false;
782*9880d681SAndroid Build Coastguard Worker 
783*9880d681SAndroid Build Coastguard Worker     // Test predicate subsumption.
784*9880d681SAndroid Build Coastguard Worker     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
785*9880d681SAndroid Build Coastguard Worker     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
786*9880d681SAndroid Build Coastguard Worker     if (RevBranch) {
787*9880d681SAndroid Build Coastguard Worker       if (TII->ReverseBranchCondition(Cond))
788*9880d681SAndroid Build Coastguard Worker         return false;
789*9880d681SAndroid Build Coastguard Worker     }
790*9880d681SAndroid Build Coastguard Worker     if (TII->ReverseBranchCondition(RevPred) ||
791*9880d681SAndroid Build Coastguard Worker         !TII->SubsumesPredicate(Cond, RevPred))
792*9880d681SAndroid Build Coastguard Worker       return false;
793*9880d681SAndroid Build Coastguard Worker   }
794*9880d681SAndroid Build Coastguard Worker 
795*9880d681SAndroid Build Coastguard Worker   return true;
796*9880d681SAndroid Build Coastguard Worker }
797*9880d681SAndroid Build Coastguard Worker 
798*9880d681SAndroid Build Coastguard Worker /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
799*9880d681SAndroid Build Coastguard Worker /// the specified block. Record its successors and whether it looks like an
800*9880d681SAndroid Build Coastguard Worker /// if-conversion candidate.
AnalyzeBlock(MachineBasicBlock * MBB,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)801*9880d681SAndroid Build Coastguard Worker void IfConverter::AnalyzeBlock(
802*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
803*9880d681SAndroid Build Coastguard Worker   struct BBState {
804*9880d681SAndroid Build Coastguard Worker     BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
805*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *MBB;
806*9880d681SAndroid Build Coastguard Worker 
807*9880d681SAndroid Build Coastguard Worker     /// This flag is true if MBB's successors have been analyzed.
808*9880d681SAndroid Build Coastguard Worker     bool SuccsAnalyzed;
809*9880d681SAndroid Build Coastguard Worker   };
810*9880d681SAndroid Build Coastguard Worker 
811*9880d681SAndroid Build Coastguard Worker   // Push MBB to the stack.
812*9880d681SAndroid Build Coastguard Worker   SmallVector<BBState, 16> BBStack(1, MBB);
813*9880d681SAndroid Build Coastguard Worker 
814*9880d681SAndroid Build Coastguard Worker   while (!BBStack.empty()) {
815*9880d681SAndroid Build Coastguard Worker     BBState &State = BBStack.back();
816*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *BB = State.MBB;
817*9880d681SAndroid Build Coastguard Worker     BBInfo &BBI = BBAnalysis[BB->getNumber()];
818*9880d681SAndroid Build Coastguard Worker 
819*9880d681SAndroid Build Coastguard Worker     if (!State.SuccsAnalyzed) {
820*9880d681SAndroid Build Coastguard Worker       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
821*9880d681SAndroid Build Coastguard Worker         BBStack.pop_back();
822*9880d681SAndroid Build Coastguard Worker         continue;
823*9880d681SAndroid Build Coastguard Worker       }
824*9880d681SAndroid Build Coastguard Worker 
825*9880d681SAndroid Build Coastguard Worker       BBI.BB = BB;
826*9880d681SAndroid Build Coastguard Worker       BBI.IsBeingAnalyzed = true;
827*9880d681SAndroid Build Coastguard Worker 
828*9880d681SAndroid Build Coastguard Worker       ScanInstructions(BBI);
829*9880d681SAndroid Build Coastguard Worker 
830*9880d681SAndroid Build Coastguard Worker       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
831*9880d681SAndroid Build Coastguard Worker       // not considered for ifcvt anymore.
832*9880d681SAndroid Build Coastguard Worker       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
833*9880d681SAndroid Build Coastguard Worker         BBI.IsBeingAnalyzed = false;
834*9880d681SAndroid Build Coastguard Worker         BBI.IsAnalyzed = true;
835*9880d681SAndroid Build Coastguard Worker         BBStack.pop_back();
836*9880d681SAndroid Build Coastguard Worker         continue;
837*9880d681SAndroid Build Coastguard Worker       }
838*9880d681SAndroid Build Coastguard Worker 
839*9880d681SAndroid Build Coastguard Worker       // Do not ifcvt if either path is a back edge to the entry block.
840*9880d681SAndroid Build Coastguard Worker       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
841*9880d681SAndroid Build Coastguard Worker         BBI.IsBeingAnalyzed = false;
842*9880d681SAndroid Build Coastguard Worker         BBI.IsAnalyzed = true;
843*9880d681SAndroid Build Coastguard Worker         BBStack.pop_back();
844*9880d681SAndroid Build Coastguard Worker         continue;
845*9880d681SAndroid Build Coastguard Worker       }
846*9880d681SAndroid Build Coastguard Worker 
847*9880d681SAndroid Build Coastguard Worker       // Do not ifcvt if true and false fallthrough blocks are the same.
848*9880d681SAndroid Build Coastguard Worker       if (!BBI.FalseBB) {
849*9880d681SAndroid Build Coastguard Worker         BBI.IsBeingAnalyzed = false;
850*9880d681SAndroid Build Coastguard Worker         BBI.IsAnalyzed = true;
851*9880d681SAndroid Build Coastguard Worker         BBStack.pop_back();
852*9880d681SAndroid Build Coastguard Worker         continue;
853*9880d681SAndroid Build Coastguard Worker       }
854*9880d681SAndroid Build Coastguard Worker 
855*9880d681SAndroid Build Coastguard Worker       // Push the False and True blocks to the stack.
856*9880d681SAndroid Build Coastguard Worker       State.SuccsAnalyzed = true;
857*9880d681SAndroid Build Coastguard Worker       BBStack.push_back(BBI.FalseBB);
858*9880d681SAndroid Build Coastguard Worker       BBStack.push_back(BBI.TrueBB);
859*9880d681SAndroid Build Coastguard Worker       continue;
860*9880d681SAndroid Build Coastguard Worker     }
861*9880d681SAndroid Build Coastguard Worker 
862*9880d681SAndroid Build Coastguard Worker     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
863*9880d681SAndroid Build Coastguard Worker     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
864*9880d681SAndroid Build Coastguard Worker 
865*9880d681SAndroid Build Coastguard Worker     if (TrueBBI.IsDone && FalseBBI.IsDone) {
866*9880d681SAndroid Build Coastguard Worker       BBI.IsBeingAnalyzed = false;
867*9880d681SAndroid Build Coastguard Worker       BBI.IsAnalyzed = true;
868*9880d681SAndroid Build Coastguard Worker       BBStack.pop_back();
869*9880d681SAndroid Build Coastguard Worker       continue;
870*9880d681SAndroid Build Coastguard Worker     }
871*9880d681SAndroid Build Coastguard Worker 
872*9880d681SAndroid Build Coastguard Worker     SmallVector<MachineOperand, 4>
873*9880d681SAndroid Build Coastguard Worker         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
874*9880d681SAndroid Build Coastguard Worker     bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
875*9880d681SAndroid Build Coastguard Worker 
876*9880d681SAndroid Build Coastguard Worker     unsigned Dups = 0;
877*9880d681SAndroid Build Coastguard Worker     unsigned Dups2 = 0;
878*9880d681SAndroid Build Coastguard Worker     bool TNeedSub = !TrueBBI.Predicate.empty();
879*9880d681SAndroid Build Coastguard Worker     bool FNeedSub = !FalseBBI.Predicate.empty();
880*9880d681SAndroid Build Coastguard Worker     bool Enqueued = false;
881*9880d681SAndroid Build Coastguard Worker 
882*9880d681SAndroid Build Coastguard Worker     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
883*9880d681SAndroid Build Coastguard Worker 
884*9880d681SAndroid Build Coastguard Worker     if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
885*9880d681SAndroid Build Coastguard Worker         MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
886*9880d681SAndroid Build Coastguard Worker                                          TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
887*9880d681SAndroid Build Coastguard Worker                            *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
888*9880d681SAndroid Build Coastguard Worker                                         FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
889*9880d681SAndroid Build Coastguard Worker                          Prediction) &&
890*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
891*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(FalseBBI, RevCond)) {
892*9880d681SAndroid Build Coastguard Worker       // Diamond:
893*9880d681SAndroid Build Coastguard Worker       //   EBB
894*9880d681SAndroid Build Coastguard Worker       //   / \_
895*9880d681SAndroid Build Coastguard Worker       //  |   |
896*9880d681SAndroid Build Coastguard Worker       // TBB FBB
897*9880d681SAndroid Build Coastguard Worker       //   \ /
898*9880d681SAndroid Build Coastguard Worker       //  TailBB
899*9880d681SAndroid Build Coastguard Worker       // Note TailBB can be empty.
900*9880d681SAndroid Build Coastguard Worker       Tokens.push_back(llvm::make_unique<IfcvtToken>(
901*9880d681SAndroid Build Coastguard Worker           BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
902*9880d681SAndroid Build Coastguard Worker       Enqueued = true;
903*9880d681SAndroid Build Coastguard Worker     }
904*9880d681SAndroid Build Coastguard Worker 
905*9880d681SAndroid Build Coastguard Worker     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
906*9880d681SAndroid Build Coastguard Worker         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
907*9880d681SAndroid Build Coastguard Worker                            TrueBBI.ExtraCost2, Prediction) &&
908*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
909*9880d681SAndroid Build Coastguard Worker       // Triangle:
910*9880d681SAndroid Build Coastguard Worker       //   EBB
911*9880d681SAndroid Build Coastguard Worker       //   | \_
912*9880d681SAndroid Build Coastguard Worker       //   |  |
913*9880d681SAndroid Build Coastguard Worker       //   | TBB
914*9880d681SAndroid Build Coastguard Worker       //   |  /
915*9880d681SAndroid Build Coastguard Worker       //   FBB
916*9880d681SAndroid Build Coastguard Worker       Tokens.push_back(
917*9880d681SAndroid Build Coastguard Worker           llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
918*9880d681SAndroid Build Coastguard Worker       Enqueued = true;
919*9880d681SAndroid Build Coastguard Worker     }
920*9880d681SAndroid Build Coastguard Worker 
921*9880d681SAndroid Build Coastguard Worker     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
922*9880d681SAndroid Build Coastguard Worker         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
923*9880d681SAndroid Build Coastguard Worker                            TrueBBI.ExtraCost2, Prediction) &&
924*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
925*9880d681SAndroid Build Coastguard Worker       Tokens.push_back(
926*9880d681SAndroid Build Coastguard Worker           llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
927*9880d681SAndroid Build Coastguard Worker       Enqueued = true;
928*9880d681SAndroid Build Coastguard Worker     }
929*9880d681SAndroid Build Coastguard Worker 
930*9880d681SAndroid Build Coastguard Worker     if (ValidSimple(TrueBBI, Dups, Prediction) &&
931*9880d681SAndroid Build Coastguard Worker         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
932*9880d681SAndroid Build Coastguard Worker                            TrueBBI.ExtraCost2, Prediction) &&
933*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
934*9880d681SAndroid Build Coastguard Worker       // Simple (split, no rejoin):
935*9880d681SAndroid Build Coastguard Worker       //   EBB
936*9880d681SAndroid Build Coastguard Worker       //   | \_
937*9880d681SAndroid Build Coastguard Worker       //   |  |
938*9880d681SAndroid Build Coastguard Worker       //   | TBB---> exit
939*9880d681SAndroid Build Coastguard Worker       //   |
940*9880d681SAndroid Build Coastguard Worker       //   FBB
941*9880d681SAndroid Build Coastguard Worker       Tokens.push_back(
942*9880d681SAndroid Build Coastguard Worker           llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
943*9880d681SAndroid Build Coastguard Worker       Enqueued = true;
944*9880d681SAndroid Build Coastguard Worker     }
945*9880d681SAndroid Build Coastguard Worker 
946*9880d681SAndroid Build Coastguard Worker     if (CanRevCond) {
947*9880d681SAndroid Build Coastguard Worker       // Try the other path...
948*9880d681SAndroid Build Coastguard Worker       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
949*9880d681SAndroid Build Coastguard Worker                         Prediction.getCompl()) &&
950*9880d681SAndroid Build Coastguard Worker           MeetIfcvtSizeLimit(*FalseBBI.BB,
951*9880d681SAndroid Build Coastguard Worker                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
952*9880d681SAndroid Build Coastguard Worker                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
953*9880d681SAndroid Build Coastguard Worker           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
954*9880d681SAndroid Build Coastguard Worker         Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
955*9880d681SAndroid Build Coastguard Worker                                                        FNeedSub, Dups));
956*9880d681SAndroid Build Coastguard Worker         Enqueued = true;
957*9880d681SAndroid Build Coastguard Worker       }
958*9880d681SAndroid Build Coastguard Worker 
959*9880d681SAndroid Build Coastguard Worker       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
960*9880d681SAndroid Build Coastguard Worker                         Prediction.getCompl()) &&
961*9880d681SAndroid Build Coastguard Worker           MeetIfcvtSizeLimit(*FalseBBI.BB,
962*9880d681SAndroid Build Coastguard Worker                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
963*9880d681SAndroid Build Coastguard Worker                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
964*9880d681SAndroid Build Coastguard Worker         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
965*9880d681SAndroid Build Coastguard Worker         Tokens.push_back(
966*9880d681SAndroid Build Coastguard Worker             llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
967*9880d681SAndroid Build Coastguard Worker         Enqueued = true;
968*9880d681SAndroid Build Coastguard Worker       }
969*9880d681SAndroid Build Coastguard Worker 
970*9880d681SAndroid Build Coastguard Worker       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
971*9880d681SAndroid Build Coastguard Worker           MeetIfcvtSizeLimit(*FalseBBI.BB,
972*9880d681SAndroid Build Coastguard Worker                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
973*9880d681SAndroid Build Coastguard Worker                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
974*9880d681SAndroid Build Coastguard Worker           FeasibilityAnalysis(FalseBBI, RevCond)) {
975*9880d681SAndroid Build Coastguard Worker         Tokens.push_back(
976*9880d681SAndroid Build Coastguard Worker             llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
977*9880d681SAndroid Build Coastguard Worker         Enqueued = true;
978*9880d681SAndroid Build Coastguard Worker       }
979*9880d681SAndroid Build Coastguard Worker     }
980*9880d681SAndroid Build Coastguard Worker 
981*9880d681SAndroid Build Coastguard Worker     BBI.IsEnqueued = Enqueued;
982*9880d681SAndroid Build Coastguard Worker     BBI.IsBeingAnalyzed = false;
983*9880d681SAndroid Build Coastguard Worker     BBI.IsAnalyzed = true;
984*9880d681SAndroid Build Coastguard Worker     BBStack.pop_back();
985*9880d681SAndroid Build Coastguard Worker   }
986*9880d681SAndroid Build Coastguard Worker }
987*9880d681SAndroid Build Coastguard Worker 
988*9880d681SAndroid Build Coastguard Worker /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
989*9880d681SAndroid Build Coastguard Worker /// candidates.
AnalyzeBlocks(MachineFunction & MF,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)990*9880d681SAndroid Build Coastguard Worker void IfConverter::AnalyzeBlocks(
991*9880d681SAndroid Build Coastguard Worker     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
992*9880d681SAndroid Build Coastguard Worker   for (auto &BB : MF)
993*9880d681SAndroid Build Coastguard Worker     AnalyzeBlock(&BB, Tokens);
994*9880d681SAndroid Build Coastguard Worker 
995*9880d681SAndroid Build Coastguard Worker   // Sort to favor more complex ifcvt scheme.
996*9880d681SAndroid Build Coastguard Worker   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
997*9880d681SAndroid Build Coastguard Worker }
998*9880d681SAndroid Build Coastguard Worker 
999*9880d681SAndroid Build Coastguard Worker /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1000*9880d681SAndroid Build Coastguard Worker /// that all the intervening blocks are empty (given BB can fall through to its
1001*9880d681SAndroid Build Coastguard Worker /// next block).
canFallThroughTo(MachineBasicBlock * BB,MachineBasicBlock * ToBB)1002*9880d681SAndroid Build Coastguard Worker static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
1003*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator PI = BB->getIterator();
1004*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator I = std::next(PI);
1005*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator TI = ToBB->getIterator();
1006*9880d681SAndroid Build Coastguard Worker   MachineFunction::iterator E = BB->getParent()->end();
1007*9880d681SAndroid Build Coastguard Worker   while (I != TI) {
1008*9880d681SAndroid Build Coastguard Worker     // Check isSuccessor to avoid case where the next block is empty, but
1009*9880d681SAndroid Build Coastguard Worker     // it's not a successor.
1010*9880d681SAndroid Build Coastguard Worker     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1011*9880d681SAndroid Build Coastguard Worker       return false;
1012*9880d681SAndroid Build Coastguard Worker     PI = I++;
1013*9880d681SAndroid Build Coastguard Worker   }
1014*9880d681SAndroid Build Coastguard Worker   return true;
1015*9880d681SAndroid Build Coastguard Worker }
1016*9880d681SAndroid Build Coastguard Worker 
1017*9880d681SAndroid Build Coastguard Worker /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1018*9880d681SAndroid Build Coastguard Worker /// to determine if it can be if-converted. If predecessor is already enqueued,
1019*9880d681SAndroid Build Coastguard Worker /// dequeue it!
InvalidatePreds(MachineBasicBlock * BB)1020*9880d681SAndroid Build Coastguard Worker void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
1021*9880d681SAndroid Build Coastguard Worker   for (const auto &Predecessor : BB->predecessors()) {
1022*9880d681SAndroid Build Coastguard Worker     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1023*9880d681SAndroid Build Coastguard Worker     if (PBBI.IsDone || PBBI.BB == BB)
1024*9880d681SAndroid Build Coastguard Worker       continue;
1025*9880d681SAndroid Build Coastguard Worker     PBBI.IsAnalyzed = false;
1026*9880d681SAndroid Build Coastguard Worker     PBBI.IsEnqueued = false;
1027*9880d681SAndroid Build Coastguard Worker   }
1028*9880d681SAndroid Build Coastguard Worker }
1029*9880d681SAndroid Build Coastguard Worker 
1030*9880d681SAndroid Build Coastguard Worker /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1031*9880d681SAndroid Build Coastguard Worker ///
InsertUncondBranch(MachineBasicBlock * BB,MachineBasicBlock * ToBB,const TargetInstrInfo * TII)1032*9880d681SAndroid Build Coastguard Worker static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1033*9880d681SAndroid Build Coastguard Worker                                const TargetInstrInfo *TII) {
1034*9880d681SAndroid Build Coastguard Worker   DebugLoc dl;  // FIXME: this is nowhere
1035*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 0> NoCond;
1036*9880d681SAndroid Build Coastguard Worker   TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
1037*9880d681SAndroid Build Coastguard Worker }
1038*9880d681SAndroid Build Coastguard Worker 
1039*9880d681SAndroid Build Coastguard Worker /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1040*9880d681SAndroid Build Coastguard Worker /// successors.
RemoveExtraEdges(BBInfo & BBI)1041*9880d681SAndroid Build Coastguard Worker void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
1042*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1043*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> Cond;
1044*9880d681SAndroid Build Coastguard Worker   if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
1045*9880d681SAndroid Build Coastguard Worker     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
1046*9880d681SAndroid Build Coastguard Worker }
1047*9880d681SAndroid Build Coastguard Worker 
1048*9880d681SAndroid Build Coastguard Worker /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1049*9880d681SAndroid Build Coastguard Worker /// values defined in MI which are not live/used by MI.
UpdatePredRedefs(MachineInstr & MI,LivePhysRegs & Redefs)1050*9880d681SAndroid Build Coastguard Worker static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1051*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1052*9880d681SAndroid Build Coastguard Worker   Redefs.stepForward(MI, Clobbers);
1053*9880d681SAndroid Build Coastguard Worker 
1054*9880d681SAndroid Build Coastguard Worker   // Now add the implicit uses for each of the clobbered values.
1055*9880d681SAndroid Build Coastguard Worker   for (auto Reg : Clobbers) {
1056*9880d681SAndroid Build Coastguard Worker     // FIXME: Const cast here is nasty, but better than making StepForward
1057*9880d681SAndroid Build Coastguard Worker     // take a mutable instruction instead of const.
1058*9880d681SAndroid Build Coastguard Worker     MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1059*9880d681SAndroid Build Coastguard Worker     MachineInstr *OpMI = Op.getParent();
1060*9880d681SAndroid Build Coastguard Worker     MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1061*9880d681SAndroid Build Coastguard Worker     if (Op.isRegMask()) {
1062*9880d681SAndroid Build Coastguard Worker       // First handle regmasks.  They clobber any entries in the mask which
1063*9880d681SAndroid Build Coastguard Worker       // means that we need a def for those registers.
1064*9880d681SAndroid Build Coastguard Worker       MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1065*9880d681SAndroid Build Coastguard Worker 
1066*9880d681SAndroid Build Coastguard Worker       // We also need to add an implicit def of this register for the later
1067*9880d681SAndroid Build Coastguard Worker       // use to read from.
1068*9880d681SAndroid Build Coastguard Worker       // For the register allocator to have allocated a register clobbered
1069*9880d681SAndroid Build Coastguard Worker       // by the call which is used later, it must be the case that
1070*9880d681SAndroid Build Coastguard Worker       // the call doesn't return.
1071*9880d681SAndroid Build Coastguard Worker       MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1072*9880d681SAndroid Build Coastguard Worker       continue;
1073*9880d681SAndroid Build Coastguard Worker     }
1074*9880d681SAndroid Build Coastguard Worker     assert(Op.isReg() && "Register operand required");
1075*9880d681SAndroid Build Coastguard Worker     if (Op.isDead()) {
1076*9880d681SAndroid Build Coastguard Worker       // If we found a dead def, but it needs to be live, then remove the dead
1077*9880d681SAndroid Build Coastguard Worker       // flag.
1078*9880d681SAndroid Build Coastguard Worker       if (Redefs.contains(Op.getReg()))
1079*9880d681SAndroid Build Coastguard Worker         Op.setIsDead(false);
1080*9880d681SAndroid Build Coastguard Worker     }
1081*9880d681SAndroid Build Coastguard Worker     MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1082*9880d681SAndroid Build Coastguard Worker   }
1083*9880d681SAndroid Build Coastguard Worker }
1084*9880d681SAndroid Build Coastguard Worker 
1085*9880d681SAndroid Build Coastguard Worker /**
1086*9880d681SAndroid Build Coastguard Worker  * Remove kill flags from operands with a registers in the @p DontKill set.
1087*9880d681SAndroid Build Coastguard Worker  */
RemoveKills(MachineInstr & MI,const LivePhysRegs & DontKill)1088*9880d681SAndroid Build Coastguard Worker static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
1089*9880d681SAndroid Build Coastguard Worker   for (MIBundleOperands O(MI); O.isValid(); ++O) {
1090*9880d681SAndroid Build Coastguard Worker     if (!O->isReg() || !O->isKill())
1091*9880d681SAndroid Build Coastguard Worker       continue;
1092*9880d681SAndroid Build Coastguard Worker     if (DontKill.contains(O->getReg()))
1093*9880d681SAndroid Build Coastguard Worker       O->setIsKill(false);
1094*9880d681SAndroid Build Coastguard Worker   }
1095*9880d681SAndroid Build Coastguard Worker }
1096*9880d681SAndroid Build Coastguard Worker 
1097*9880d681SAndroid Build Coastguard Worker /**
1098*9880d681SAndroid Build Coastguard Worker  * Walks a range of machine instructions and removes kill flags for registers
1099*9880d681SAndroid Build Coastguard Worker  * in the @p DontKill set.
1100*9880d681SAndroid Build Coastguard Worker  */
RemoveKills(MachineBasicBlock::iterator I,MachineBasicBlock::iterator E,const LivePhysRegs & DontKill,const MCRegisterInfo & MCRI)1101*9880d681SAndroid Build Coastguard Worker static void RemoveKills(MachineBasicBlock::iterator I,
1102*9880d681SAndroid Build Coastguard Worker                         MachineBasicBlock::iterator E,
1103*9880d681SAndroid Build Coastguard Worker                         const LivePhysRegs &DontKill,
1104*9880d681SAndroid Build Coastguard Worker                         const MCRegisterInfo &MCRI) {
1105*9880d681SAndroid Build Coastguard Worker   for ( ; I != E; ++I)
1106*9880d681SAndroid Build Coastguard Worker     RemoveKills(*I, DontKill);
1107*9880d681SAndroid Build Coastguard Worker }
1108*9880d681SAndroid Build Coastguard Worker 
1109*9880d681SAndroid Build Coastguard Worker /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1110*9880d681SAndroid Build Coastguard Worker ///
IfConvertSimple(BBInfo & BBI,IfcvtKind Kind)1111*9880d681SAndroid Build Coastguard Worker bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1112*9880d681SAndroid Build Coastguard Worker   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1113*9880d681SAndroid Build Coastguard Worker   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1114*9880d681SAndroid Build Coastguard Worker   BBInfo *CvtBBI = &TrueBBI;
1115*9880d681SAndroid Build Coastguard Worker   BBInfo *NextBBI = &FalseBBI;
1116*9880d681SAndroid Build Coastguard Worker 
1117*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1118*9880d681SAndroid Build Coastguard Worker   if (Kind == ICSimpleFalse)
1119*9880d681SAndroid Build Coastguard Worker     std::swap(CvtBBI, NextBBI);
1120*9880d681SAndroid Build Coastguard Worker 
1121*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->IsDone ||
1122*9880d681SAndroid Build Coastguard Worker       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1123*9880d681SAndroid Build Coastguard Worker     // Something has changed. It's no longer safe to predicate this block.
1124*9880d681SAndroid Build Coastguard Worker     BBI.IsAnalyzed = false;
1125*9880d681SAndroid Build Coastguard Worker     CvtBBI->IsAnalyzed = false;
1126*9880d681SAndroid Build Coastguard Worker     return false;
1127*9880d681SAndroid Build Coastguard Worker   }
1128*9880d681SAndroid Build Coastguard Worker 
1129*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->BB->hasAddressTaken())
1130*9880d681SAndroid Build Coastguard Worker     // Conservatively abort if-conversion if BB's address is taken.
1131*9880d681SAndroid Build Coastguard Worker     return false;
1132*9880d681SAndroid Build Coastguard Worker 
1133*9880d681SAndroid Build Coastguard Worker   if (Kind == ICSimpleFalse)
1134*9880d681SAndroid Build Coastguard Worker     if (TII->ReverseBranchCondition(Cond))
1135*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Unable to reverse branch condition!");
1136*9880d681SAndroid Build Coastguard Worker 
1137*9880d681SAndroid Build Coastguard Worker   // Initialize liveins to the first BB. These are potentiall redefined by
1138*9880d681SAndroid Build Coastguard Worker   // predicated instructions.
1139*9880d681SAndroid Build Coastguard Worker   Redefs.init(TRI);
1140*9880d681SAndroid Build Coastguard Worker   Redefs.addLiveIns(*CvtBBI->BB);
1141*9880d681SAndroid Build Coastguard Worker   Redefs.addLiveIns(*NextBBI->BB);
1142*9880d681SAndroid Build Coastguard Worker 
1143*9880d681SAndroid Build Coastguard Worker   // Compute a set of registers which must not be killed by instructions in
1144*9880d681SAndroid Build Coastguard Worker   // BB1: This is everything live-in to BB2.
1145*9880d681SAndroid Build Coastguard Worker   DontKill.init(TRI);
1146*9880d681SAndroid Build Coastguard Worker   DontKill.addLiveIns(*NextBBI->BB);
1147*9880d681SAndroid Build Coastguard Worker 
1148*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->BB->pred_size() > 1) {
1149*9880d681SAndroid Build Coastguard Worker     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1150*9880d681SAndroid Build Coastguard Worker     // Copy instructions in the true block, predicate them, and add them to
1151*9880d681SAndroid Build Coastguard Worker     // the entry block.
1152*9880d681SAndroid Build Coastguard Worker     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1153*9880d681SAndroid Build Coastguard Worker 
1154*9880d681SAndroid Build Coastguard Worker     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1155*9880d681SAndroid Build Coastguard Worker     // explicitly remove CvtBBI as a successor.
1156*9880d681SAndroid Build Coastguard Worker     BBI.BB->removeSuccessor(CvtBBI->BB, true);
1157*9880d681SAndroid Build Coastguard Worker   } else {
1158*9880d681SAndroid Build Coastguard Worker     RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
1159*9880d681SAndroid Build Coastguard Worker     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1160*9880d681SAndroid Build Coastguard Worker 
1161*9880d681SAndroid Build Coastguard Worker     // Merge converted block into entry block.
1162*9880d681SAndroid Build Coastguard Worker     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1163*9880d681SAndroid Build Coastguard Worker     MergeBlocks(BBI, *CvtBBI);
1164*9880d681SAndroid Build Coastguard Worker   }
1165*9880d681SAndroid Build Coastguard Worker 
1166*9880d681SAndroid Build Coastguard Worker   bool IterIfcvt = true;
1167*9880d681SAndroid Build Coastguard Worker   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1168*9880d681SAndroid Build Coastguard Worker     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1169*9880d681SAndroid Build Coastguard Worker     BBI.HasFallThrough = false;
1170*9880d681SAndroid Build Coastguard Worker     // Now ifcvt'd block will look like this:
1171*9880d681SAndroid Build Coastguard Worker     // BB:
1172*9880d681SAndroid Build Coastguard Worker     // ...
1173*9880d681SAndroid Build Coastguard Worker     // t, f = cmp
1174*9880d681SAndroid Build Coastguard Worker     // if t op
1175*9880d681SAndroid Build Coastguard Worker     // b BBf
1176*9880d681SAndroid Build Coastguard Worker     //
1177*9880d681SAndroid Build Coastguard Worker     // We cannot further ifcvt this block because the unconditional branch
1178*9880d681SAndroid Build Coastguard Worker     // will have to be predicated on the new condition, that will not be
1179*9880d681SAndroid Build Coastguard Worker     // available if cmp executes.
1180*9880d681SAndroid Build Coastguard Worker     IterIfcvt = false;
1181*9880d681SAndroid Build Coastguard Worker   }
1182*9880d681SAndroid Build Coastguard Worker 
1183*9880d681SAndroid Build Coastguard Worker   RemoveExtraEdges(BBI);
1184*9880d681SAndroid Build Coastguard Worker 
1185*9880d681SAndroid Build Coastguard Worker   // Update block info. BB can be iteratively if-converted.
1186*9880d681SAndroid Build Coastguard Worker   if (!IterIfcvt)
1187*9880d681SAndroid Build Coastguard Worker     BBI.IsDone = true;
1188*9880d681SAndroid Build Coastguard Worker   InvalidatePreds(BBI.BB);
1189*9880d681SAndroid Build Coastguard Worker   CvtBBI->IsDone = true;
1190*9880d681SAndroid Build Coastguard Worker 
1191*9880d681SAndroid Build Coastguard Worker   // FIXME: Must maintain LiveIns.
1192*9880d681SAndroid Build Coastguard Worker   return true;
1193*9880d681SAndroid Build Coastguard Worker }
1194*9880d681SAndroid Build Coastguard Worker 
1195*9880d681SAndroid Build Coastguard Worker /// IfConvertTriangle - If convert a triangle sub-CFG.
1196*9880d681SAndroid Build Coastguard Worker ///
IfConvertTriangle(BBInfo & BBI,IfcvtKind Kind)1197*9880d681SAndroid Build Coastguard Worker bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1198*9880d681SAndroid Build Coastguard Worker   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1199*9880d681SAndroid Build Coastguard Worker   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1200*9880d681SAndroid Build Coastguard Worker   BBInfo *CvtBBI = &TrueBBI;
1201*9880d681SAndroid Build Coastguard Worker   BBInfo *NextBBI = &FalseBBI;
1202*9880d681SAndroid Build Coastguard Worker   DebugLoc dl;  // FIXME: this is nowhere
1203*9880d681SAndroid Build Coastguard Worker 
1204*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1205*9880d681SAndroid Build Coastguard Worker   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1206*9880d681SAndroid Build Coastguard Worker     std::swap(CvtBBI, NextBBI);
1207*9880d681SAndroid Build Coastguard Worker 
1208*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->IsDone ||
1209*9880d681SAndroid Build Coastguard Worker       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1210*9880d681SAndroid Build Coastguard Worker     // Something has changed. It's no longer safe to predicate this block.
1211*9880d681SAndroid Build Coastguard Worker     BBI.IsAnalyzed = false;
1212*9880d681SAndroid Build Coastguard Worker     CvtBBI->IsAnalyzed = false;
1213*9880d681SAndroid Build Coastguard Worker     return false;
1214*9880d681SAndroid Build Coastguard Worker   }
1215*9880d681SAndroid Build Coastguard Worker 
1216*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->BB->hasAddressTaken())
1217*9880d681SAndroid Build Coastguard Worker     // Conservatively abort if-conversion if BB's address is taken.
1218*9880d681SAndroid Build Coastguard Worker     return false;
1219*9880d681SAndroid Build Coastguard Worker 
1220*9880d681SAndroid Build Coastguard Worker   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1221*9880d681SAndroid Build Coastguard Worker     if (TII->ReverseBranchCondition(Cond))
1222*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Unable to reverse branch condition!");
1223*9880d681SAndroid Build Coastguard Worker 
1224*9880d681SAndroid Build Coastguard Worker   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1225*9880d681SAndroid Build Coastguard Worker     if (ReverseBranchCondition(*CvtBBI)) {
1226*9880d681SAndroid Build Coastguard Worker       // BB has been changed, modify its predecessors (except for this
1227*9880d681SAndroid Build Coastguard Worker       // one) so they don't get ifcvt'ed based on bad intel.
1228*9880d681SAndroid Build Coastguard Worker       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1229*9880d681SAndroid Build Coastguard Worker              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1230*9880d681SAndroid Build Coastguard Worker         MachineBasicBlock *PBB = *PI;
1231*9880d681SAndroid Build Coastguard Worker         if (PBB == BBI.BB)
1232*9880d681SAndroid Build Coastguard Worker           continue;
1233*9880d681SAndroid Build Coastguard Worker         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1234*9880d681SAndroid Build Coastguard Worker         if (PBBI.IsEnqueued) {
1235*9880d681SAndroid Build Coastguard Worker           PBBI.IsAnalyzed = false;
1236*9880d681SAndroid Build Coastguard Worker           PBBI.IsEnqueued = false;
1237*9880d681SAndroid Build Coastguard Worker         }
1238*9880d681SAndroid Build Coastguard Worker       }
1239*9880d681SAndroid Build Coastguard Worker     }
1240*9880d681SAndroid Build Coastguard Worker   }
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker   // Initialize liveins to the first BB. These are potentially redefined by
1243*9880d681SAndroid Build Coastguard Worker   // predicated instructions.
1244*9880d681SAndroid Build Coastguard Worker   Redefs.init(TRI);
1245*9880d681SAndroid Build Coastguard Worker   Redefs.addLiveIns(*CvtBBI->BB);
1246*9880d681SAndroid Build Coastguard Worker   Redefs.addLiveIns(*NextBBI->BB);
1247*9880d681SAndroid Build Coastguard Worker 
1248*9880d681SAndroid Build Coastguard Worker   DontKill.clear();
1249*9880d681SAndroid Build Coastguard Worker 
1250*9880d681SAndroid Build Coastguard Worker   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1251*9880d681SAndroid Build Coastguard Worker   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1252*9880d681SAndroid Build Coastguard Worker 
1253*9880d681SAndroid Build Coastguard Worker   if (HasEarlyExit) {
1254*9880d681SAndroid Build Coastguard Worker     // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1255*9880d681SAndroid Build Coastguard Worker     CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1256*9880d681SAndroid Build Coastguard Worker     CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1257*9880d681SAndroid Build Coastguard Worker     BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1258*9880d681SAndroid Build Coastguard Worker     BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
1259*9880d681SAndroid Build Coastguard Worker   }
1260*9880d681SAndroid Build Coastguard Worker 
1261*9880d681SAndroid Build Coastguard Worker   if (CvtBBI->BB->pred_size() > 1) {
1262*9880d681SAndroid Build Coastguard Worker     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1263*9880d681SAndroid Build Coastguard Worker     // Copy instructions in the true block, predicate them, and add them to
1264*9880d681SAndroid Build Coastguard Worker     // the entry block.
1265*9880d681SAndroid Build Coastguard Worker     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1266*9880d681SAndroid Build Coastguard Worker 
1267*9880d681SAndroid Build Coastguard Worker     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1268*9880d681SAndroid Build Coastguard Worker     // explicitly remove CvtBBI as a successor.
1269*9880d681SAndroid Build Coastguard Worker     BBI.BB->removeSuccessor(CvtBBI->BB, true);
1270*9880d681SAndroid Build Coastguard Worker   } else {
1271*9880d681SAndroid Build Coastguard Worker     // Predicate the 'true' block after removing its branch.
1272*9880d681SAndroid Build Coastguard Worker     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1273*9880d681SAndroid Build Coastguard Worker     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1274*9880d681SAndroid Build Coastguard Worker 
1275*9880d681SAndroid Build Coastguard Worker     // Now merge the entry of the triangle with the true block.
1276*9880d681SAndroid Build Coastguard Worker     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1277*9880d681SAndroid Build Coastguard Worker     MergeBlocks(BBI, *CvtBBI, false);
1278*9880d681SAndroid Build Coastguard Worker   }
1279*9880d681SAndroid Build Coastguard Worker 
1280*9880d681SAndroid Build Coastguard Worker   // If 'true' block has a 'false' successor, add an exit branch to it.
1281*9880d681SAndroid Build Coastguard Worker   if (HasEarlyExit) {
1282*9880d681SAndroid Build Coastguard Worker     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1283*9880d681SAndroid Build Coastguard Worker                                            CvtBBI->BrCond.end());
1284*9880d681SAndroid Build Coastguard Worker     if (TII->ReverseBranchCondition(RevCond))
1285*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Unable to reverse branch condition!");
1286*9880d681SAndroid Build Coastguard Worker 
1287*9880d681SAndroid Build Coastguard Worker     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1288*9880d681SAndroid Build Coastguard Worker     // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1289*9880d681SAndroid Build Coastguard Worker     //   Prob(BBI.BB, NextBBI->BB) +
1290*9880d681SAndroid Build Coastguard Worker     //   Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1291*9880d681SAndroid Build Coastguard Worker     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1292*9880d681SAndroid Build Coastguard Worker     //   Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1293*9880d681SAndroid Build Coastguard Worker     auto NewTrueBB = getNextBlock(BBI.BB);
1294*9880d681SAndroid Build Coastguard Worker     auto NewNext = BBNext + BBCvt * CvtNext;
1295*9880d681SAndroid Build Coastguard Worker     auto NewTrueBBIter =
1296*9880d681SAndroid Build Coastguard Worker         std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
1297*9880d681SAndroid Build Coastguard Worker     if (NewTrueBBIter != BBI.BB->succ_end())
1298*9880d681SAndroid Build Coastguard Worker       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1299*9880d681SAndroid Build Coastguard Worker 
1300*9880d681SAndroid Build Coastguard Worker     auto NewFalse = BBCvt * CvtFalse;
1301*9880d681SAndroid Build Coastguard Worker     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1302*9880d681SAndroid Build Coastguard Worker     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1303*9880d681SAndroid Build Coastguard Worker   }
1304*9880d681SAndroid Build Coastguard Worker 
1305*9880d681SAndroid Build Coastguard Worker   // Merge in the 'false' block if the 'false' block has no other
1306*9880d681SAndroid Build Coastguard Worker   // predecessors. Otherwise, add an unconditional branch to 'false'.
1307*9880d681SAndroid Build Coastguard Worker   bool FalseBBDead = false;
1308*9880d681SAndroid Build Coastguard Worker   bool IterIfcvt = true;
1309*9880d681SAndroid Build Coastguard Worker   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1310*9880d681SAndroid Build Coastguard Worker   if (!isFallThrough) {
1311*9880d681SAndroid Build Coastguard Worker     // Only merge them if the true block does not fallthrough to the false
1312*9880d681SAndroid Build Coastguard Worker     // block. By not merging them, we make it possible to iteratively
1313*9880d681SAndroid Build Coastguard Worker     // ifcvt the blocks.
1314*9880d681SAndroid Build Coastguard Worker     if (!HasEarlyExit &&
1315*9880d681SAndroid Build Coastguard Worker         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1316*9880d681SAndroid Build Coastguard Worker         !NextBBI->BB->hasAddressTaken()) {
1317*9880d681SAndroid Build Coastguard Worker       MergeBlocks(BBI, *NextBBI);
1318*9880d681SAndroid Build Coastguard Worker       FalseBBDead = true;
1319*9880d681SAndroid Build Coastguard Worker     } else {
1320*9880d681SAndroid Build Coastguard Worker       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1321*9880d681SAndroid Build Coastguard Worker       BBI.HasFallThrough = false;
1322*9880d681SAndroid Build Coastguard Worker     }
1323*9880d681SAndroid Build Coastguard Worker     // Mixed predicated and unpredicated code. This cannot be iteratively
1324*9880d681SAndroid Build Coastguard Worker     // predicated.
1325*9880d681SAndroid Build Coastguard Worker     IterIfcvt = false;
1326*9880d681SAndroid Build Coastguard Worker   }
1327*9880d681SAndroid Build Coastguard Worker 
1328*9880d681SAndroid Build Coastguard Worker   RemoveExtraEdges(BBI);
1329*9880d681SAndroid Build Coastguard Worker 
1330*9880d681SAndroid Build Coastguard Worker   // Update block info. BB can be iteratively if-converted.
1331*9880d681SAndroid Build Coastguard Worker   if (!IterIfcvt)
1332*9880d681SAndroid Build Coastguard Worker     BBI.IsDone = true;
1333*9880d681SAndroid Build Coastguard Worker   InvalidatePreds(BBI.BB);
1334*9880d681SAndroid Build Coastguard Worker   CvtBBI->IsDone = true;
1335*9880d681SAndroid Build Coastguard Worker   if (FalseBBDead)
1336*9880d681SAndroid Build Coastguard Worker     NextBBI->IsDone = true;
1337*9880d681SAndroid Build Coastguard Worker 
1338*9880d681SAndroid Build Coastguard Worker   // FIXME: Must maintain LiveIns.
1339*9880d681SAndroid Build Coastguard Worker   return true;
1340*9880d681SAndroid Build Coastguard Worker }
1341*9880d681SAndroid Build Coastguard Worker 
1342*9880d681SAndroid Build Coastguard Worker /// IfConvertDiamond - If convert a diamond sub-CFG.
1343*9880d681SAndroid Build Coastguard Worker ///
IfConvertDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2)1344*9880d681SAndroid Build Coastguard Worker bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1345*9880d681SAndroid Build Coastguard Worker                                    unsigned NumDups1, unsigned NumDups2) {
1346*9880d681SAndroid Build Coastguard Worker   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1347*9880d681SAndroid Build Coastguard Worker   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1348*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1349*9880d681SAndroid Build Coastguard Worker   // True block must fall through or end with an unanalyzable terminator.
1350*9880d681SAndroid Build Coastguard Worker   if (!TailBB) {
1351*9880d681SAndroid Build Coastguard Worker     if (blockAlwaysFallThrough(TrueBBI))
1352*9880d681SAndroid Build Coastguard Worker       TailBB = FalseBBI.TrueBB;
1353*9880d681SAndroid Build Coastguard Worker     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1354*9880d681SAndroid Build Coastguard Worker   }
1355*9880d681SAndroid Build Coastguard Worker 
1356*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1357*9880d681SAndroid Build Coastguard Worker       TrueBBI.BB->pred_size() > 1 ||
1358*9880d681SAndroid Build Coastguard Worker       FalseBBI.BB->pred_size() > 1) {
1359*9880d681SAndroid Build Coastguard Worker     // Something has changed. It's no longer safe to predicate these blocks.
1360*9880d681SAndroid Build Coastguard Worker     BBI.IsAnalyzed = false;
1361*9880d681SAndroid Build Coastguard Worker     TrueBBI.IsAnalyzed = false;
1362*9880d681SAndroid Build Coastguard Worker     FalseBBI.IsAnalyzed = false;
1363*9880d681SAndroid Build Coastguard Worker     return false;
1364*9880d681SAndroid Build Coastguard Worker   }
1365*9880d681SAndroid Build Coastguard Worker 
1366*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1367*9880d681SAndroid Build Coastguard Worker     // Conservatively abort if-conversion if either BB has its address taken.
1368*9880d681SAndroid Build Coastguard Worker     return false;
1369*9880d681SAndroid Build Coastguard Worker 
1370*9880d681SAndroid Build Coastguard Worker   // Put the predicated instructions from the 'true' block before the
1371*9880d681SAndroid Build Coastguard Worker   // instructions from the 'false' block, unless the true block would clobber
1372*9880d681SAndroid Build Coastguard Worker   // the predicate, in which case, do the opposite.
1373*9880d681SAndroid Build Coastguard Worker   BBInfo *BBI1 = &TrueBBI;
1374*9880d681SAndroid Build Coastguard Worker   BBInfo *BBI2 = &FalseBBI;
1375*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1376*9880d681SAndroid Build Coastguard Worker   if (TII->ReverseBranchCondition(RevCond))
1377*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unable to reverse branch condition!");
1378*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1379*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1380*9880d681SAndroid Build Coastguard Worker 
1381*9880d681SAndroid Build Coastguard Worker   // Figure out the more profitable ordering.
1382*9880d681SAndroid Build Coastguard Worker   bool DoSwap = false;
1383*9880d681SAndroid Build Coastguard Worker   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1384*9880d681SAndroid Build Coastguard Worker     DoSwap = true;
1385*9880d681SAndroid Build Coastguard Worker   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1386*9880d681SAndroid Build Coastguard Worker     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1387*9880d681SAndroid Build Coastguard Worker       DoSwap = true;
1388*9880d681SAndroid Build Coastguard Worker   }
1389*9880d681SAndroid Build Coastguard Worker   if (DoSwap) {
1390*9880d681SAndroid Build Coastguard Worker     std::swap(BBI1, BBI2);
1391*9880d681SAndroid Build Coastguard Worker     std::swap(Cond1, Cond2);
1392*9880d681SAndroid Build Coastguard Worker   }
1393*9880d681SAndroid Build Coastguard Worker 
1394*9880d681SAndroid Build Coastguard Worker   // Remove the conditional branch from entry to the blocks.
1395*9880d681SAndroid Build Coastguard Worker   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1396*9880d681SAndroid Build Coastguard Worker 
1397*9880d681SAndroid Build Coastguard Worker   // Initialize liveins to the first BB. These are potentially redefined by
1398*9880d681SAndroid Build Coastguard Worker   // predicated instructions.
1399*9880d681SAndroid Build Coastguard Worker   Redefs.init(TRI);
1400*9880d681SAndroid Build Coastguard Worker   Redefs.addLiveIns(*BBI1->BB);
1401*9880d681SAndroid Build Coastguard Worker 
1402*9880d681SAndroid Build Coastguard Worker   // Remove the duplicated instructions at the beginnings of both paths.
1403*9880d681SAndroid Build Coastguard Worker   // Skip dbg_value instructions
1404*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1405*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
1406*9880d681SAndroid Build Coastguard Worker   BBI1->NonPredSize -= NumDups1;
1407*9880d681SAndroid Build Coastguard Worker   BBI2->NonPredSize -= NumDups1;
1408*9880d681SAndroid Build Coastguard Worker 
1409*9880d681SAndroid Build Coastguard Worker   // Skip past the dups on each side separately since there may be
1410*9880d681SAndroid Build Coastguard Worker   // differing dbg_value entries.
1411*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i < NumDups1; ++DI1) {
1412*9880d681SAndroid Build Coastguard Worker     if (!DI1->isDebugValue())
1413*9880d681SAndroid Build Coastguard Worker       ++i;
1414*9880d681SAndroid Build Coastguard Worker   }
1415*9880d681SAndroid Build Coastguard Worker   while (NumDups1 != 0) {
1416*9880d681SAndroid Build Coastguard Worker     ++DI2;
1417*9880d681SAndroid Build Coastguard Worker     if (!DI2->isDebugValue())
1418*9880d681SAndroid Build Coastguard Worker       --NumDups1;
1419*9880d681SAndroid Build Coastguard Worker   }
1420*9880d681SAndroid Build Coastguard Worker 
1421*9880d681SAndroid Build Coastguard Worker   // Compute a set of registers which must not be killed by instructions in BB1:
1422*9880d681SAndroid Build Coastguard Worker   // This is everything used+live in BB2 after the duplicated instructions. We
1423*9880d681SAndroid Build Coastguard Worker   // can compute this set by simulating liveness backwards from the end of BB2.
1424*9880d681SAndroid Build Coastguard Worker   DontKill.init(TRI);
1425*9880d681SAndroid Build Coastguard Worker   for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1426*9880d681SAndroid Build Coastguard Worker        E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
1427*9880d681SAndroid Build Coastguard Worker     DontKill.stepBackward(*I);
1428*9880d681SAndroid Build Coastguard Worker   }
1429*9880d681SAndroid Build Coastguard Worker 
1430*9880d681SAndroid Build Coastguard Worker   for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1431*9880d681SAndroid Build Coastguard Worker        ++I) {
1432*9880d681SAndroid Build Coastguard Worker     SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1433*9880d681SAndroid Build Coastguard Worker     Redefs.stepForward(*I, IgnoredClobbers);
1434*9880d681SAndroid Build Coastguard Worker   }
1435*9880d681SAndroid Build Coastguard Worker   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1436*9880d681SAndroid Build Coastguard Worker   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1437*9880d681SAndroid Build Coastguard Worker 
1438*9880d681SAndroid Build Coastguard Worker   // Remove branch from the 'true' block, unless it was not analyzable.
1439*9880d681SAndroid Build Coastguard Worker   // Non-analyzable branches need to be preserved, since in such cases,
1440*9880d681SAndroid Build Coastguard Worker   // the CFG structure is not an actual diamond (the join block may not
1441*9880d681SAndroid Build Coastguard Worker   // be present).
1442*9880d681SAndroid Build Coastguard Worker   if (BBI1->IsBrAnalyzable)
1443*9880d681SAndroid Build Coastguard Worker     BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1444*9880d681SAndroid Build Coastguard Worker   // Remove duplicated instructions.
1445*9880d681SAndroid Build Coastguard Worker   DI1 = BBI1->BB->end();
1446*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0; i != NumDups2; ) {
1447*9880d681SAndroid Build Coastguard Worker     // NumDups2 only counted non-dbg_value instructions, so this won't
1448*9880d681SAndroid Build Coastguard Worker     // run off the head of the list.
1449*9880d681SAndroid Build Coastguard Worker     assert (DI1 != BBI1->BB->begin());
1450*9880d681SAndroid Build Coastguard Worker     --DI1;
1451*9880d681SAndroid Build Coastguard Worker     // skip dbg_value instructions
1452*9880d681SAndroid Build Coastguard Worker     if (!DI1->isDebugValue())
1453*9880d681SAndroid Build Coastguard Worker       ++i;
1454*9880d681SAndroid Build Coastguard Worker   }
1455*9880d681SAndroid Build Coastguard Worker   BBI1->BB->erase(DI1, BBI1->BB->end());
1456*9880d681SAndroid Build Coastguard Worker 
1457*9880d681SAndroid Build Coastguard Worker   // Kill flags in the true block for registers living into the false block
1458*9880d681SAndroid Build Coastguard Worker   // must be removed.
1459*9880d681SAndroid Build Coastguard Worker   RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1460*9880d681SAndroid Build Coastguard Worker 
1461*9880d681SAndroid Build Coastguard Worker   // Remove 'false' block branch (unless it was not analyzable), and find
1462*9880d681SAndroid Build Coastguard Worker   // the last instruction to predicate.
1463*9880d681SAndroid Build Coastguard Worker   if (BBI2->IsBrAnalyzable)
1464*9880d681SAndroid Build Coastguard Worker     BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1465*9880d681SAndroid Build Coastguard Worker   DI2 = BBI2->BB->end();
1466*9880d681SAndroid Build Coastguard Worker   while (NumDups2 != 0) {
1467*9880d681SAndroid Build Coastguard Worker     // NumDups2 only counted non-dbg_value instructions, so this won't
1468*9880d681SAndroid Build Coastguard Worker     // run off the head of the list.
1469*9880d681SAndroid Build Coastguard Worker     assert (DI2 != BBI2->BB->begin());
1470*9880d681SAndroid Build Coastguard Worker     --DI2;
1471*9880d681SAndroid Build Coastguard Worker     // skip dbg_value instructions
1472*9880d681SAndroid Build Coastguard Worker     if (!DI2->isDebugValue())
1473*9880d681SAndroid Build Coastguard Worker       --NumDups2;
1474*9880d681SAndroid Build Coastguard Worker   }
1475*9880d681SAndroid Build Coastguard Worker 
1476*9880d681SAndroid Build Coastguard Worker   // Remember which registers would later be defined by the false block.
1477*9880d681SAndroid Build Coastguard Worker   // This allows us not to predicate instructions in the true block that would
1478*9880d681SAndroid Build Coastguard Worker   // later be re-defined. That is, rather than
1479*9880d681SAndroid Build Coastguard Worker   //   subeq  r0, r1, #1
1480*9880d681SAndroid Build Coastguard Worker   //   addne  r0, r1, #1
1481*9880d681SAndroid Build Coastguard Worker   // generate:
1482*9880d681SAndroid Build Coastguard Worker   //   sub    r0, r1, #1
1483*9880d681SAndroid Build Coastguard Worker   //   addne  r0, r1, #1
1484*9880d681SAndroid Build Coastguard Worker   SmallSet<unsigned, 4> RedefsByFalse;
1485*9880d681SAndroid Build Coastguard Worker   SmallSet<unsigned, 4> ExtUses;
1486*9880d681SAndroid Build Coastguard Worker   if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1487*9880d681SAndroid Build Coastguard Worker     for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1488*9880d681SAndroid Build Coastguard Worker       if (FI->isDebugValue())
1489*9880d681SAndroid Build Coastguard Worker         continue;
1490*9880d681SAndroid Build Coastguard Worker       SmallVector<unsigned, 4> Defs;
1491*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1492*9880d681SAndroid Build Coastguard Worker         const MachineOperand &MO = FI->getOperand(i);
1493*9880d681SAndroid Build Coastguard Worker         if (!MO.isReg())
1494*9880d681SAndroid Build Coastguard Worker           continue;
1495*9880d681SAndroid Build Coastguard Worker         unsigned Reg = MO.getReg();
1496*9880d681SAndroid Build Coastguard Worker         if (!Reg)
1497*9880d681SAndroid Build Coastguard Worker           continue;
1498*9880d681SAndroid Build Coastguard Worker         if (MO.isDef()) {
1499*9880d681SAndroid Build Coastguard Worker           Defs.push_back(Reg);
1500*9880d681SAndroid Build Coastguard Worker         } else if (!RedefsByFalse.count(Reg)) {
1501*9880d681SAndroid Build Coastguard Worker           // These are defined before ctrl flow reach the 'false' instructions.
1502*9880d681SAndroid Build Coastguard Worker           // They cannot be modified by the 'true' instructions.
1503*9880d681SAndroid Build Coastguard Worker           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1504*9880d681SAndroid Build Coastguard Worker                SubRegs.isValid(); ++SubRegs)
1505*9880d681SAndroid Build Coastguard Worker             ExtUses.insert(*SubRegs);
1506*9880d681SAndroid Build Coastguard Worker         }
1507*9880d681SAndroid Build Coastguard Worker       }
1508*9880d681SAndroid Build Coastguard Worker 
1509*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1510*9880d681SAndroid Build Coastguard Worker         unsigned Reg = Defs[i];
1511*9880d681SAndroid Build Coastguard Worker         if (!ExtUses.count(Reg)) {
1512*9880d681SAndroid Build Coastguard Worker           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1513*9880d681SAndroid Build Coastguard Worker                SubRegs.isValid(); ++SubRegs)
1514*9880d681SAndroid Build Coastguard Worker             RedefsByFalse.insert(*SubRegs);
1515*9880d681SAndroid Build Coastguard Worker         }
1516*9880d681SAndroid Build Coastguard Worker       }
1517*9880d681SAndroid Build Coastguard Worker     }
1518*9880d681SAndroid Build Coastguard Worker   }
1519*9880d681SAndroid Build Coastguard Worker 
1520*9880d681SAndroid Build Coastguard Worker   // Predicate the 'true' block.
1521*9880d681SAndroid Build Coastguard Worker   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
1522*9880d681SAndroid Build Coastguard Worker 
1523*9880d681SAndroid Build Coastguard Worker   // After predicating BBI1, if there is a predicated terminator in BBI1 and
1524*9880d681SAndroid Build Coastguard Worker   // a non-predicated in BBI2, then we don't want to predicate the one from
1525*9880d681SAndroid Build Coastguard Worker   // BBI2. The reason is that if we merged these blocks, we would end up with
1526*9880d681SAndroid Build Coastguard Worker   // two predicated terminators in the same block.
1527*9880d681SAndroid Build Coastguard Worker   if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1528*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1529*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
1530*9880d681SAndroid Build Coastguard Worker     if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1531*9880d681SAndroid Build Coastguard Worker         BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
1532*9880d681SAndroid Build Coastguard Worker       --DI2;
1533*9880d681SAndroid Build Coastguard Worker   }
1534*9880d681SAndroid Build Coastguard Worker 
1535*9880d681SAndroid Build Coastguard Worker   // Predicate the 'false' block.
1536*9880d681SAndroid Build Coastguard Worker   PredicateBlock(*BBI2, DI2, *Cond2);
1537*9880d681SAndroid Build Coastguard Worker 
1538*9880d681SAndroid Build Coastguard Worker   // Merge the true block into the entry of the diamond.
1539*9880d681SAndroid Build Coastguard Worker   MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1540*9880d681SAndroid Build Coastguard Worker   MergeBlocks(BBI, *BBI2, TailBB == nullptr);
1541*9880d681SAndroid Build Coastguard Worker 
1542*9880d681SAndroid Build Coastguard Worker   // If the if-converted block falls through or unconditionally branches into
1543*9880d681SAndroid Build Coastguard Worker   // the tail block, and the tail block does not have other predecessors, then
1544*9880d681SAndroid Build Coastguard Worker   // fold the tail block in as well. Otherwise, unless it falls through to the
1545*9880d681SAndroid Build Coastguard Worker   // tail, add a unconditional branch to it.
1546*9880d681SAndroid Build Coastguard Worker   if (TailBB) {
1547*9880d681SAndroid Build Coastguard Worker     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1548*9880d681SAndroid Build Coastguard Worker     bool CanMergeTail = !TailBBI.HasFallThrough &&
1549*9880d681SAndroid Build Coastguard Worker       !TailBBI.BB->hasAddressTaken();
1550*9880d681SAndroid Build Coastguard Worker     // The if-converted block can still have a predicated terminator
1551*9880d681SAndroid Build Coastguard Worker     // (e.g. a predicated return). If that is the case, we cannot merge
1552*9880d681SAndroid Build Coastguard Worker     // it with the tail block.
1553*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1554*9880d681SAndroid Build Coastguard Worker     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1555*9880d681SAndroid Build Coastguard Worker       CanMergeTail = false;
1556*9880d681SAndroid Build Coastguard Worker     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1557*9880d681SAndroid Build Coastguard Worker     // check if there are any other predecessors besides those.
1558*9880d681SAndroid Build Coastguard Worker     unsigned NumPreds = TailBB->pred_size();
1559*9880d681SAndroid Build Coastguard Worker     if (NumPreds > 1)
1560*9880d681SAndroid Build Coastguard Worker       CanMergeTail = false;
1561*9880d681SAndroid Build Coastguard Worker     else if (NumPreds == 1 && CanMergeTail) {
1562*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1563*9880d681SAndroid Build Coastguard Worker       if (*PI != BBI1->BB && *PI != BBI2->BB)
1564*9880d681SAndroid Build Coastguard Worker         CanMergeTail = false;
1565*9880d681SAndroid Build Coastguard Worker     }
1566*9880d681SAndroid Build Coastguard Worker     if (CanMergeTail) {
1567*9880d681SAndroid Build Coastguard Worker       MergeBlocks(BBI, TailBBI);
1568*9880d681SAndroid Build Coastguard Worker       TailBBI.IsDone = true;
1569*9880d681SAndroid Build Coastguard Worker     } else {
1570*9880d681SAndroid Build Coastguard Worker       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1571*9880d681SAndroid Build Coastguard Worker       InsertUncondBranch(BBI.BB, TailBB, TII);
1572*9880d681SAndroid Build Coastguard Worker       BBI.HasFallThrough = false;
1573*9880d681SAndroid Build Coastguard Worker     }
1574*9880d681SAndroid Build Coastguard Worker   }
1575*9880d681SAndroid Build Coastguard Worker 
1576*9880d681SAndroid Build Coastguard Worker   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1577*9880d681SAndroid Build Coastguard Worker   // which can happen here if TailBB is unanalyzable and is merged, so
1578*9880d681SAndroid Build Coastguard Worker   // explicitly remove BBI1 and BBI2 as successors.
1579*9880d681SAndroid Build Coastguard Worker   BBI.BB->removeSuccessor(BBI1->BB);
1580*9880d681SAndroid Build Coastguard Worker   BBI.BB->removeSuccessor(BBI2->BB, true);
1581*9880d681SAndroid Build Coastguard Worker   RemoveExtraEdges(BBI);
1582*9880d681SAndroid Build Coastguard Worker 
1583*9880d681SAndroid Build Coastguard Worker   // Update block info.
1584*9880d681SAndroid Build Coastguard Worker   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1585*9880d681SAndroid Build Coastguard Worker   InvalidatePreds(BBI.BB);
1586*9880d681SAndroid Build Coastguard Worker 
1587*9880d681SAndroid Build Coastguard Worker   // FIXME: Must maintain LiveIns.
1588*9880d681SAndroid Build Coastguard Worker   return true;
1589*9880d681SAndroid Build Coastguard Worker }
1590*9880d681SAndroid Build Coastguard Worker 
MaySpeculate(const MachineInstr & MI,SmallSet<unsigned,4> & LaterRedefs)1591*9880d681SAndroid Build Coastguard Worker static bool MaySpeculate(const MachineInstr &MI,
1592*9880d681SAndroid Build Coastguard Worker                          SmallSet<unsigned, 4> &LaterRedefs) {
1593*9880d681SAndroid Build Coastguard Worker   bool SawStore = true;
1594*9880d681SAndroid Build Coastguard Worker   if (!MI.isSafeToMove(nullptr, SawStore))
1595*9880d681SAndroid Build Coastguard Worker     return false;
1596*9880d681SAndroid Build Coastguard Worker 
1597*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1598*9880d681SAndroid Build Coastguard Worker     const MachineOperand &MO = MI.getOperand(i);
1599*9880d681SAndroid Build Coastguard Worker     if (!MO.isReg())
1600*9880d681SAndroid Build Coastguard Worker       continue;
1601*9880d681SAndroid Build Coastguard Worker     unsigned Reg = MO.getReg();
1602*9880d681SAndroid Build Coastguard Worker     if (!Reg)
1603*9880d681SAndroid Build Coastguard Worker       continue;
1604*9880d681SAndroid Build Coastguard Worker     if (MO.isDef() && !LaterRedefs.count(Reg))
1605*9880d681SAndroid Build Coastguard Worker       return false;
1606*9880d681SAndroid Build Coastguard Worker   }
1607*9880d681SAndroid Build Coastguard Worker 
1608*9880d681SAndroid Build Coastguard Worker   return true;
1609*9880d681SAndroid Build Coastguard Worker }
1610*9880d681SAndroid Build Coastguard Worker 
1611*9880d681SAndroid Build Coastguard Worker /// PredicateBlock - Predicate instructions from the start of the block to the
1612*9880d681SAndroid Build Coastguard Worker /// specified end with the specified condition.
PredicateBlock(BBInfo & BBI,MachineBasicBlock::iterator E,SmallVectorImpl<MachineOperand> & Cond,SmallSet<unsigned,4> * LaterRedefs)1613*9880d681SAndroid Build Coastguard Worker void IfConverter::PredicateBlock(BBInfo &BBI,
1614*9880d681SAndroid Build Coastguard Worker                                  MachineBasicBlock::iterator E,
1615*9880d681SAndroid Build Coastguard Worker                                  SmallVectorImpl<MachineOperand> &Cond,
1616*9880d681SAndroid Build Coastguard Worker                                  SmallSet<unsigned, 4> *LaterRedefs) {
1617*9880d681SAndroid Build Coastguard Worker   bool AnyUnpred = false;
1618*9880d681SAndroid Build Coastguard Worker   bool MaySpec = LaterRedefs != nullptr;
1619*9880d681SAndroid Build Coastguard Worker   for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1620*9880d681SAndroid Build Coastguard Worker     if (I.isDebugValue() || TII->isPredicated(I))
1621*9880d681SAndroid Build Coastguard Worker       continue;
1622*9880d681SAndroid Build Coastguard Worker     // It may be possible not to predicate an instruction if it's the 'true'
1623*9880d681SAndroid Build Coastguard Worker     // side of a diamond and the 'false' side may re-define the instruction's
1624*9880d681SAndroid Build Coastguard Worker     // defs.
1625*9880d681SAndroid Build Coastguard Worker     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
1626*9880d681SAndroid Build Coastguard Worker       AnyUnpred = true;
1627*9880d681SAndroid Build Coastguard Worker       continue;
1628*9880d681SAndroid Build Coastguard Worker     }
1629*9880d681SAndroid Build Coastguard Worker     // If any instruction is predicated, then every instruction after it must
1630*9880d681SAndroid Build Coastguard Worker     // be predicated.
1631*9880d681SAndroid Build Coastguard Worker     MaySpec = false;
1632*9880d681SAndroid Build Coastguard Worker     if (!TII->PredicateInstruction(I, Cond)) {
1633*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
1634*9880d681SAndroid Build Coastguard Worker       dbgs() << "Unable to predicate " << I << "!\n";
1635*9880d681SAndroid Build Coastguard Worker #endif
1636*9880d681SAndroid Build Coastguard Worker       llvm_unreachable(nullptr);
1637*9880d681SAndroid Build Coastguard Worker     }
1638*9880d681SAndroid Build Coastguard Worker 
1639*9880d681SAndroid Build Coastguard Worker     // If the predicated instruction now redefines a register as the result of
1640*9880d681SAndroid Build Coastguard Worker     // if-conversion, add an implicit kill.
1641*9880d681SAndroid Build Coastguard Worker     UpdatePredRedefs(I, Redefs);
1642*9880d681SAndroid Build Coastguard Worker   }
1643*9880d681SAndroid Build Coastguard Worker 
1644*9880d681SAndroid Build Coastguard Worker   BBI.Predicate.append(Cond.begin(), Cond.end());
1645*9880d681SAndroid Build Coastguard Worker 
1646*9880d681SAndroid Build Coastguard Worker   BBI.IsAnalyzed = false;
1647*9880d681SAndroid Build Coastguard Worker   BBI.NonPredSize = 0;
1648*9880d681SAndroid Build Coastguard Worker 
1649*9880d681SAndroid Build Coastguard Worker   ++NumIfConvBBs;
1650*9880d681SAndroid Build Coastguard Worker   if (AnyUnpred)
1651*9880d681SAndroid Build Coastguard Worker     ++NumUnpred;
1652*9880d681SAndroid Build Coastguard Worker }
1653*9880d681SAndroid Build Coastguard Worker 
1654*9880d681SAndroid Build Coastguard Worker /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1655*9880d681SAndroid Build Coastguard Worker /// the destination block. Skip end of block branches if IgnoreBr is true.
CopyAndPredicateBlock(BBInfo & ToBBI,BBInfo & FromBBI,SmallVectorImpl<MachineOperand> & Cond,bool IgnoreBr)1656*9880d681SAndroid Build Coastguard Worker void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1657*9880d681SAndroid Build Coastguard Worker                                         SmallVectorImpl<MachineOperand> &Cond,
1658*9880d681SAndroid Build Coastguard Worker                                         bool IgnoreBr) {
1659*9880d681SAndroid Build Coastguard Worker   MachineFunction &MF = *ToBBI.BB->getParent();
1660*9880d681SAndroid Build Coastguard Worker 
1661*9880d681SAndroid Build Coastguard Worker   for (auto &I : *FromBBI.BB) {
1662*9880d681SAndroid Build Coastguard Worker     // Do not copy the end of the block branches.
1663*9880d681SAndroid Build Coastguard Worker     if (IgnoreBr && I.isBranch())
1664*9880d681SAndroid Build Coastguard Worker       break;
1665*9880d681SAndroid Build Coastguard Worker 
1666*9880d681SAndroid Build Coastguard Worker     MachineInstr *MI = MF.CloneMachineInstr(&I);
1667*9880d681SAndroid Build Coastguard Worker     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1668*9880d681SAndroid Build Coastguard Worker     ToBBI.NonPredSize++;
1669*9880d681SAndroid Build Coastguard Worker     unsigned ExtraPredCost = TII->getPredicationCost(I);
1670*9880d681SAndroid Build Coastguard Worker     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1671*9880d681SAndroid Build Coastguard Worker     if (NumCycles > 1)
1672*9880d681SAndroid Build Coastguard Worker       ToBBI.ExtraCost += NumCycles-1;
1673*9880d681SAndroid Build Coastguard Worker     ToBBI.ExtraCost2 += ExtraPredCost;
1674*9880d681SAndroid Build Coastguard Worker 
1675*9880d681SAndroid Build Coastguard Worker     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1676*9880d681SAndroid Build Coastguard Worker       if (!TII->PredicateInstruction(*MI, Cond)) {
1677*9880d681SAndroid Build Coastguard Worker #ifndef NDEBUG
1678*9880d681SAndroid Build Coastguard Worker         dbgs() << "Unable to predicate " << I << "!\n";
1679*9880d681SAndroid Build Coastguard Worker #endif
1680*9880d681SAndroid Build Coastguard Worker         llvm_unreachable(nullptr);
1681*9880d681SAndroid Build Coastguard Worker       }
1682*9880d681SAndroid Build Coastguard Worker     }
1683*9880d681SAndroid Build Coastguard Worker 
1684*9880d681SAndroid Build Coastguard Worker     // If the predicated instruction now redefines a register as the result of
1685*9880d681SAndroid Build Coastguard Worker     // if-conversion, add an implicit kill.
1686*9880d681SAndroid Build Coastguard Worker     UpdatePredRedefs(*MI, Redefs);
1687*9880d681SAndroid Build Coastguard Worker 
1688*9880d681SAndroid Build Coastguard Worker     // Some kill flags may not be correct anymore.
1689*9880d681SAndroid Build Coastguard Worker     if (!DontKill.empty())
1690*9880d681SAndroid Build Coastguard Worker       RemoveKills(*MI, DontKill);
1691*9880d681SAndroid Build Coastguard Worker   }
1692*9880d681SAndroid Build Coastguard Worker 
1693*9880d681SAndroid Build Coastguard Worker   if (!IgnoreBr) {
1694*9880d681SAndroid Build Coastguard Worker     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1695*9880d681SAndroid Build Coastguard Worker                                            FromBBI.BB->succ_end());
1696*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1697*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1698*9880d681SAndroid Build Coastguard Worker 
1699*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1700*9880d681SAndroid Build Coastguard Worker       MachineBasicBlock *Succ = Succs[i];
1701*9880d681SAndroid Build Coastguard Worker       // Fallthrough edge can't be transferred.
1702*9880d681SAndroid Build Coastguard Worker       if (Succ == FallThrough)
1703*9880d681SAndroid Build Coastguard Worker         continue;
1704*9880d681SAndroid Build Coastguard Worker       ToBBI.BB->addSuccessor(Succ);
1705*9880d681SAndroid Build Coastguard Worker     }
1706*9880d681SAndroid Build Coastguard Worker   }
1707*9880d681SAndroid Build Coastguard Worker 
1708*9880d681SAndroid Build Coastguard Worker   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1709*9880d681SAndroid Build Coastguard Worker   ToBBI.Predicate.append(Cond.begin(), Cond.end());
1710*9880d681SAndroid Build Coastguard Worker 
1711*9880d681SAndroid Build Coastguard Worker   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1712*9880d681SAndroid Build Coastguard Worker   ToBBI.IsAnalyzed = false;
1713*9880d681SAndroid Build Coastguard Worker 
1714*9880d681SAndroid Build Coastguard Worker   ++NumDupBBs;
1715*9880d681SAndroid Build Coastguard Worker }
1716*9880d681SAndroid Build Coastguard Worker 
1717*9880d681SAndroid Build Coastguard Worker /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1718*9880d681SAndroid Build Coastguard Worker /// This will leave FromBB as an empty block, so remove all of its
1719*9880d681SAndroid Build Coastguard Worker /// successor edges except for the fall-through edge.  If AddEdges is true,
1720*9880d681SAndroid Build Coastguard Worker /// i.e., when FromBBI's branch is being moved, add those successor edges to
1721*9880d681SAndroid Build Coastguard Worker /// ToBBI.
MergeBlocks(BBInfo & ToBBI,BBInfo & FromBBI,bool AddEdges)1722*9880d681SAndroid Build Coastguard Worker void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1723*9880d681SAndroid Build Coastguard Worker   assert(!FromBBI.BB->hasAddressTaken() &&
1724*9880d681SAndroid Build Coastguard Worker          "Removing a BB whose address is taken!");
1725*9880d681SAndroid Build Coastguard Worker 
1726*9880d681SAndroid Build Coastguard Worker   // In case FromBBI.BB contains terminators (e.g. return instruction),
1727*9880d681SAndroid Build Coastguard Worker   // first move the non-terminator instructions, then the terminators.
1728*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1729*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1730*9880d681SAndroid Build Coastguard Worker   ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1731*9880d681SAndroid Build Coastguard Worker 
1732*9880d681SAndroid Build Coastguard Worker   // If FromBB has non-predicated terminator we should copy it at the end.
1733*9880d681SAndroid Build Coastguard Worker   if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
1734*9880d681SAndroid Build Coastguard Worker     ToTI = ToBBI.BB->end();
1735*9880d681SAndroid Build Coastguard Worker   ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
1736*9880d681SAndroid Build Coastguard Worker 
1737*9880d681SAndroid Build Coastguard Worker   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1738*9880d681SAndroid Build Coastguard Worker   // unknown probabilities into known ones.
1739*9880d681SAndroid Build Coastguard Worker   // FIXME: This usage is too tricky and in the future we would like to
1740*9880d681SAndroid Build Coastguard Worker   // eliminate all unknown probabilities in MBB.
1741*9880d681SAndroid Build Coastguard Worker   ToBBI.BB->normalizeSuccProbs();
1742*9880d681SAndroid Build Coastguard Worker 
1743*9880d681SAndroid Build Coastguard Worker   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1744*9880d681SAndroid Build Coastguard Worker                                                 FromBBI.BB->succ_end());
1745*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1746*9880d681SAndroid Build Coastguard Worker   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1747*9880d681SAndroid Build Coastguard Worker   // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
1748*9880d681SAndroid Build Coastguard Worker   // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
1749*9880d681SAndroid Build Coastguard Worker   auto To2FromProb = BranchProbability::getZero();
1750*9880d681SAndroid Build Coastguard Worker   if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
1751*9880d681SAndroid Build Coastguard Worker     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1752*9880d681SAndroid Build Coastguard Worker     // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1753*9880d681SAndroid Build Coastguard Worker     // edge probability being merged to other edges when this edge is removed
1754*9880d681SAndroid Build Coastguard Worker     // later.
1755*9880d681SAndroid Build Coastguard Worker     ToBBI.BB->setSuccProbability(
1756*9880d681SAndroid Build Coastguard Worker         std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1757*9880d681SAndroid Build Coastguard Worker         BranchProbability::getZero());
1758*9880d681SAndroid Build Coastguard Worker   }
1759*9880d681SAndroid Build Coastguard Worker 
1760*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1761*9880d681SAndroid Build Coastguard Worker     MachineBasicBlock *Succ = FromSuccs[i];
1762*9880d681SAndroid Build Coastguard Worker     // Fallthrough edge can't be transferred.
1763*9880d681SAndroid Build Coastguard Worker     if (Succ == FallThrough)
1764*9880d681SAndroid Build Coastguard Worker       continue;
1765*9880d681SAndroid Build Coastguard Worker 
1766*9880d681SAndroid Build Coastguard Worker     auto NewProb = BranchProbability::getZero();
1767*9880d681SAndroid Build Coastguard Worker     if (AddEdges) {
1768*9880d681SAndroid Build Coastguard Worker       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1769*9880d681SAndroid Build Coastguard Worker       // which is a portion of the edge probability from FromBBI.BB to Succ. The
1770*9880d681SAndroid Build Coastguard Worker       // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1771*9880d681SAndroid Build Coastguard Worker       // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1772*9880d681SAndroid Build Coastguard Worker       NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
1773*9880d681SAndroid Build Coastguard Worker 
1774*9880d681SAndroid Build Coastguard Worker       // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
1775*9880d681SAndroid Build Coastguard Worker       // only happens when if-converting a diamond CFG and FromBBI.BB is the
1776*9880d681SAndroid Build Coastguard Worker       // tail BB.  In this case FromBBI.BB post-dominates ToBBI.BB and hence we
1777*9880d681SAndroid Build Coastguard Worker       // could just use the probabilities on FromBBI.BB's out-edges when adding
1778*9880d681SAndroid Build Coastguard Worker       // new successors.
1779*9880d681SAndroid Build Coastguard Worker       if (!To2FromProb.isZero())
1780*9880d681SAndroid Build Coastguard Worker         NewProb *= To2FromProb;
1781*9880d681SAndroid Build Coastguard Worker     }
1782*9880d681SAndroid Build Coastguard Worker 
1783*9880d681SAndroid Build Coastguard Worker     FromBBI.BB->removeSuccessor(Succ);
1784*9880d681SAndroid Build Coastguard Worker 
1785*9880d681SAndroid Build Coastguard Worker     if (AddEdges) {
1786*9880d681SAndroid Build Coastguard Worker       // If the edge from ToBBI.BB to Succ already exists, update the
1787*9880d681SAndroid Build Coastguard Worker       // probability of this edge by adding NewProb to it. An example is shown
1788*9880d681SAndroid Build Coastguard Worker       // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1789*9880d681SAndroid Build Coastguard Worker       // don't have to set C as A's successor as it already is. We only need to
1790*9880d681SAndroid Build Coastguard Worker       // update the edge probability on A->C. Note that B will not be
1791*9880d681SAndroid Build Coastguard Worker       // immediately removed from A's successors. It is possible that B->D is
1792*9880d681SAndroid Build Coastguard Worker       // not removed either if D is a fallthrough of B. Later the edge A->D
1793*9880d681SAndroid Build Coastguard Worker       // (generated here) and B->D will be combined into one edge. To maintain
1794*9880d681SAndroid Build Coastguard Worker       // correct edge probability of this combined edge, we need to set the edge
1795*9880d681SAndroid Build Coastguard Worker       // probability of A->B to zero, which is already done above. The edge
1796*9880d681SAndroid Build Coastguard Worker       // probability on A->D is calculated by scaling the original probability
1797*9880d681SAndroid Build Coastguard Worker       // on A->B by the probability of B->D.
1798*9880d681SAndroid Build Coastguard Worker       //
1799*9880d681SAndroid Build Coastguard Worker       // Before ifcvt:      After ifcvt (assume B->D is kept):
1800*9880d681SAndroid Build Coastguard Worker       //
1801*9880d681SAndroid Build Coastguard Worker       //       A                A
1802*9880d681SAndroid Build Coastguard Worker       //      /|               /|\
1803*9880d681SAndroid Build Coastguard Worker       //     / B              / B|
1804*9880d681SAndroid Build Coastguard Worker       //    | /|             |  ||
1805*9880d681SAndroid Build Coastguard Worker       //    |/ |             |  |/
1806*9880d681SAndroid Build Coastguard Worker       //    C  D             C  D
1807*9880d681SAndroid Build Coastguard Worker       //
1808*9880d681SAndroid Build Coastguard Worker       if (ToBBI.BB->isSuccessor(Succ))
1809*9880d681SAndroid Build Coastguard Worker         ToBBI.BB->setSuccProbability(
1810*9880d681SAndroid Build Coastguard Worker             std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
1811*9880d681SAndroid Build Coastguard Worker             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
1812*9880d681SAndroid Build Coastguard Worker       else
1813*9880d681SAndroid Build Coastguard Worker         ToBBI.BB->addSuccessor(Succ, NewProb);
1814*9880d681SAndroid Build Coastguard Worker     }
1815*9880d681SAndroid Build Coastguard Worker   }
1816*9880d681SAndroid Build Coastguard Worker 
1817*9880d681SAndroid Build Coastguard Worker   // Now FromBBI always falls through to the next block!
1818*9880d681SAndroid Build Coastguard Worker   if (NBB && !FromBBI.BB->isSuccessor(NBB))
1819*9880d681SAndroid Build Coastguard Worker     FromBBI.BB->addSuccessor(NBB);
1820*9880d681SAndroid Build Coastguard Worker 
1821*9880d681SAndroid Build Coastguard Worker   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1822*9880d681SAndroid Build Coastguard Worker   // we've done above.
1823*9880d681SAndroid Build Coastguard Worker   ToBBI.BB->normalizeSuccProbs();
1824*9880d681SAndroid Build Coastguard Worker 
1825*9880d681SAndroid Build Coastguard Worker   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1826*9880d681SAndroid Build Coastguard Worker   FromBBI.Predicate.clear();
1827*9880d681SAndroid Build Coastguard Worker 
1828*9880d681SAndroid Build Coastguard Worker   ToBBI.NonPredSize += FromBBI.NonPredSize;
1829*9880d681SAndroid Build Coastguard Worker   ToBBI.ExtraCost += FromBBI.ExtraCost;
1830*9880d681SAndroid Build Coastguard Worker   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1831*9880d681SAndroid Build Coastguard Worker   FromBBI.NonPredSize = 0;
1832*9880d681SAndroid Build Coastguard Worker   FromBBI.ExtraCost = 0;
1833*9880d681SAndroid Build Coastguard Worker   FromBBI.ExtraCost2 = 0;
1834*9880d681SAndroid Build Coastguard Worker 
1835*9880d681SAndroid Build Coastguard Worker   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1836*9880d681SAndroid Build Coastguard Worker   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1837*9880d681SAndroid Build Coastguard Worker   ToBBI.IsAnalyzed = false;
1838*9880d681SAndroid Build Coastguard Worker   FromBBI.IsAnalyzed = false;
1839*9880d681SAndroid Build Coastguard Worker }
1840*9880d681SAndroid Build Coastguard Worker 
1841*9880d681SAndroid Build Coastguard Worker FunctionPass *
createIfConverter(std::function<bool (const Function &)> Ftor)1842*9880d681SAndroid Build Coastguard Worker llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1843*9880d681SAndroid Build Coastguard Worker   return new IfConverter(std::move(Ftor));
1844*9880d681SAndroid Build Coastguard Worker }
1845