1044eb2f6SDimitry Andric //===- IfConversion.cpp - Machine code if conversion pass -----------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
901095a5dSDimitry Andric // This file implements the machine instruction level if-conversion pass, which
1001095a5dSDimitry Andric // tries to convert conditional branches into predicated instructions.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten
144a16efa3SDimitry Andric #include "BranchFolding.h"
154a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
16b915e9e0SDimitry Andric #include "llvm/ADT/ScopeExit.h"
174a16efa3SDimitry Andric #include "llvm/ADT/SmallSet.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SparseSet.h"
204a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
21044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
22706b4fc4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
235ca98fd9SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
24145449b1SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
25044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
2667c32a98SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
2730815c53SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
28044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
29009b1c42SEd Schouten #include "llvm/CodeGen/MachineFunctionPass.h"
30044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
314a16efa3SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
32044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
3358b69754SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
34044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
35044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
36044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
37f8af5cf6SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
39044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
40706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
41044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
42044eb2f6SDimitry Andric #include "llvm/Pass.h"
43044eb2f6SDimitry Andric #include "llvm/Support/BranchProbability.h"
44009b1c42SEd Schouten #include "llvm/Support/CommandLine.h"
45009b1c42SEd Schouten #include "llvm/Support/Debug.h"
4659850d08SRoman Divacky #include "llvm/Support/ErrorHandling.h"
4759850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
48dd58ef01SDimitry Andric #include <algorithm>
49044eb2f6SDimitry Andric #include <cassert>
50044eb2f6SDimitry Andric #include <functional>
51044eb2f6SDimitry Andric #include <iterator>
52044eb2f6SDimitry Andric #include <memory>
5301095a5dSDimitry Andric #include <utility>
54044eb2f6SDimitry Andric #include <vector>
55f8af5cf6SDimitry Andric
56009b1c42SEd Schouten using namespace llvm;
57009b1c42SEd Schouten
58ab44ce3dSDimitry Andric #define DEBUG_TYPE "if-converter"
595ca98fd9SDimitry Andric
60009b1c42SEd Schouten // Hidden options for help debugging.
61009b1c42SEd Schouten static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
62009b1c42SEd Schouten static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
63009b1c42SEd Schouten static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
64009b1c42SEd Schouten static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
65009b1c42SEd Schouten cl::init(false), cl::Hidden);
66009b1c42SEd Schouten static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
67009b1c42SEd Schouten cl::init(false), cl::Hidden);
68009b1c42SEd Schouten static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
69009b1c42SEd Schouten cl::init(false), cl::Hidden);
70009b1c42SEd Schouten static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
71009b1c42SEd Schouten cl::init(false), cl::Hidden);
72009b1c42SEd Schouten static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
73009b1c42SEd Schouten cl::init(false), cl::Hidden);
74009b1c42SEd Schouten static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
75009b1c42SEd Schouten cl::init(false), cl::Hidden);
76b915e9e0SDimitry Andric static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
77b915e9e0SDimitry Andric cl::init(false), cl::Hidden);
7866e41e3cSRoman Divacky static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
7966e41e3cSRoman Divacky cl::init(true), cl::Hidden);
80009b1c42SEd Schouten
81009b1c42SEd Schouten STATISTIC(NumSimple, "Number of simple if-conversions performed");
82009b1c42SEd Schouten STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
83009b1c42SEd Schouten STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
84009b1c42SEd Schouten STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
85009b1c42SEd Schouten STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
86009b1c42SEd Schouten STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
87009b1c42SEd Schouten STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
88b915e9e0SDimitry Andric STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
89009b1c42SEd Schouten STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
90009b1c42SEd Schouten STATISTIC(NumDupBBs, "Number of duplicated blocks");
9163faed5bSDimitry Andric STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
92009b1c42SEd Schouten
93009b1c42SEd Schouten namespace {
94044eb2f6SDimitry Andric
9536bf506aSRoman Divacky class IfConverter : public MachineFunctionPass {
96009b1c42SEd Schouten enum IfcvtKind {
97009b1c42SEd Schouten ICNotClassfied, // BB data valid, but not classified.
98009b1c42SEd Schouten ICSimpleFalse, // Same as ICSimple, but on the false path.
99009b1c42SEd Schouten ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
100009b1c42SEd Schouten ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
101009b1c42SEd Schouten ICTriangleRev, // Same as ICTriangle, but true path rev condition.
102009b1c42SEd Schouten ICTriangleFalse, // Same as ICTriangle, but on the false path.
103009b1c42SEd Schouten ICTriangle, // BB is entry of a triangle sub-CFG.
104b915e9e0SDimitry Andric ICDiamond, // BB is entry of a diamond sub-CFG.
105b915e9e0SDimitry Andric ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
106b915e9e0SDimitry Andric // common tail that can be shared.
107009b1c42SEd Schouten };
108009b1c42SEd Schouten
109b915e9e0SDimitry Andric /// One per MachineBasicBlock, this is used to cache the result
110009b1c42SEd Schouten /// if-conversion feasibility analysis. This includes results from
11101095a5dSDimitry Andric /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
112009b1c42SEd Schouten /// classification, and common tail block of its successors (if it's a
113009b1c42SEd Schouten /// diamond shape), its size, whether it's predicable, and whether any
114009b1c42SEd Schouten /// instruction can clobber the 'would-be' predicate.
115009b1c42SEd Schouten ///
116009b1c42SEd Schouten /// IsDone - True if BB is not to be considered for ifcvt.
117009b1c42SEd Schouten /// IsBeingAnalyzed - True if BB is currently being analyzed.
118009b1c42SEd Schouten /// IsAnalyzed - True if BB has been analyzed (info is still valid).
119009b1c42SEd Schouten /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
12001095a5dSDimitry Andric /// IsBrAnalyzable - True if analyzeBranch() returns false.
121009b1c42SEd Schouten /// HasFallThrough - True if BB may fallthrough to the following BB.
122009b1c42SEd Schouten /// IsUnpredicable - True if BB is known to be unpredicable.
123009b1c42SEd Schouten /// ClobbersPred - True if BB could modify predicates (e.g. has
124009b1c42SEd Schouten /// cmp, call, etc.)
125009b1c42SEd Schouten /// NonPredSize - Number of non-predicated instructions.
126cf099d11SDimitry Andric /// ExtraCost - Extra cost for multi-cycle instructions.
127cf099d11SDimitry Andric /// ExtraCost2 - Some instructions are slower when predicated
128009b1c42SEd Schouten /// BB - Corresponding MachineBasicBlock.
12901095a5dSDimitry Andric /// TrueBB / FalseBB- See analyzeBranch().
130009b1c42SEd Schouten /// BrCond - Conditions for end of block conditional branches.
131009b1c42SEd Schouten /// Predicate - Predicate used in the BB.
132009b1c42SEd Schouten struct BBInfo {
133009b1c42SEd Schouten bool IsDone : 1;
134009b1c42SEd Schouten bool IsBeingAnalyzed : 1;
135009b1c42SEd Schouten bool IsAnalyzed : 1;
136009b1c42SEd Schouten bool IsEnqueued : 1;
137009b1c42SEd Schouten bool IsBrAnalyzable : 1;
138b915e9e0SDimitry Andric bool IsBrReversible : 1;
139009b1c42SEd Schouten bool HasFallThrough : 1;
140009b1c42SEd Schouten bool IsUnpredicable : 1;
141009b1c42SEd Schouten bool CannotBeCopied : 1;
142009b1c42SEd Schouten bool ClobbersPred : 1;
143044eb2f6SDimitry Andric unsigned NonPredSize = 0;
144044eb2f6SDimitry Andric unsigned ExtraCost = 0;
145044eb2f6SDimitry Andric unsigned ExtraCost2 = 0;
146044eb2f6SDimitry Andric MachineBasicBlock *BB = nullptr;
147044eb2f6SDimitry Andric MachineBasicBlock *TrueBB = nullptr;
148044eb2f6SDimitry Andric MachineBasicBlock *FalseBB = nullptr;
149009b1c42SEd Schouten SmallVector<MachineOperand, 4> BrCond;
150009b1c42SEd Schouten SmallVector<MachineOperand, 4> Predicate;
151044eb2f6SDimitry Andric
BBInfo__anonf5d77b7e0111::IfConverter::BBInfo152009b1c42SEd Schouten BBInfo() : IsDone(false), IsBeingAnalyzed(false),
153009b1c42SEd Schouten IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
154b915e9e0SDimitry Andric IsBrReversible(false), HasFallThrough(false),
155b915e9e0SDimitry Andric IsUnpredicable(false), CannotBeCopied(false),
156044eb2f6SDimitry Andric ClobbersPred(false) {}
157009b1c42SEd Schouten };
158009b1c42SEd Schouten
159b915e9e0SDimitry Andric /// Record information about pending if-conversions to attempt:
160009b1c42SEd Schouten /// BBI - Corresponding BBInfo.
161009b1c42SEd Schouten /// Kind - Type of block. See IfcvtKind.
162009b1c42SEd Schouten /// NeedSubsumption - True if the to-be-predicated BB has already been
163009b1c42SEd Schouten /// predicated.
164009b1c42SEd Schouten /// NumDups - Number of instructions that would be duplicated due
165009b1c42SEd Schouten /// to this if-conversion. (For diamonds, the number of
166009b1c42SEd Schouten /// identical instructions at the beginnings of both
167009b1c42SEd Schouten /// paths).
168009b1c42SEd Schouten /// NumDups2 - For diamonds, the number of identical instructions
169009b1c42SEd Schouten /// at the ends of both paths.
170009b1c42SEd Schouten struct IfcvtToken {
171009b1c42SEd Schouten BBInfo &BBI;
172009b1c42SEd Schouten IfcvtKind Kind;
173009b1c42SEd Schouten unsigned NumDups;
174009b1c42SEd Schouten unsigned NumDups2;
175b915e9e0SDimitry Andric bool NeedSubsumption : 1;
176b915e9e0SDimitry Andric bool TClobbersPred : 1;
177b915e9e0SDimitry Andric bool FClobbersPred : 1;
178044eb2f6SDimitry Andric
IfcvtToken__anonf5d77b7e0111::IfConverter::IfcvtToken179b915e9e0SDimitry Andric IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
180b915e9e0SDimitry Andric bool tc = false, bool fc = false)
181b915e9e0SDimitry Andric : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
182b915e9e0SDimitry Andric TClobbersPred(tc), FClobbersPred(fc) {}
183009b1c42SEd Schouten };
184009b1c42SEd Schouten
185b915e9e0SDimitry Andric /// Results of if-conversion feasibility analysis indexed by basic block
186b915e9e0SDimitry Andric /// number.
187009b1c42SEd Schouten std::vector<BBInfo> BBAnalysis;
188f8af5cf6SDimitry Andric TargetSchedModel SchedModel;
189009b1c42SEd Schouten
1907fa27ce4SDimitry Andric const TargetLoweringBase *TLI = nullptr;
1917fa27ce4SDimitry Andric const TargetInstrInfo *TII = nullptr;
1927fa27ce4SDimitry Andric const TargetRegisterInfo *TRI = nullptr;
1937fa27ce4SDimitry Andric const MachineBranchProbabilityInfo *MBPI = nullptr;
1947fa27ce4SDimitry Andric MachineRegisterInfo *MRI = nullptr;
19530815c53SDimitry Andric
1965ca98fd9SDimitry Andric LivePhysRegs Redefs;
197f8af5cf6SDimitry Andric
1987fa27ce4SDimitry Andric bool PreRegAlloc = true;
1997fa27ce4SDimitry Andric bool MadeChange = false;
200044eb2f6SDimitry Andric int FnNum = -1;
201b915e9e0SDimitry Andric std::function<bool(const MachineFunction &)> PredicateFtor;
20285d8b2bbSDimitry Andric
203009b1c42SEd Schouten public:
204009b1c42SEd Schouten static char ID;
205044eb2f6SDimitry Andric
IfConverter(std::function<bool (const MachineFunction &)> Ftor=nullptr)206b915e9e0SDimitry Andric IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
207044eb2f6SDimitry Andric : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
208cf099d11SDimitry Andric initializeIfConverterPass(*PassRegistry::getPassRegistry());
209cf099d11SDimitry Andric }
210cf099d11SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const2115ca98fd9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
212ac9a064cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
213ac9a064cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
214706b4fc4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>();
215cf099d11SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
216cf099d11SDimitry Andric }
217009b1c42SEd Schouten
2185ca98fd9SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override;
219009b1c42SEd Schouten
getRequiredProperties() const22001095a5dSDimitry Andric MachineFunctionProperties getRequiredProperties() const override {
22101095a5dSDimitry Andric return MachineFunctionProperties().set(
222b915e9e0SDimitry Andric MachineFunctionProperties::Property::NoVRegs);
22301095a5dSDimitry Andric }
22401095a5dSDimitry Andric
225009b1c42SEd Schouten private:
226b915e9e0SDimitry Andric bool reverseBranchCondition(BBInfo &BBI) const;
227cf099d11SDimitry Andric bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
228dd58ef01SDimitry Andric BranchProbability Prediction) const;
229009b1c42SEd Schouten bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
230cf099d11SDimitry Andric bool FalseBranch, unsigned &Dups,
231dd58ef01SDimitry Andric BranchProbability Prediction) const;
232b915e9e0SDimitry Andric bool CountDuplicatedInstructions(
233b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
234b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
235b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
236b915e9e0SDimitry Andric MachineBasicBlock &TBB, MachineBasicBlock &FBB,
237b915e9e0SDimitry Andric bool SkipUnconditionalBranches) const;
238009b1c42SEd Schouten bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
239b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
240b915e9e0SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
241b915e9e0SDimitry Andric bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
242b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
243b915e9e0SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
244b915e9e0SDimitry Andric void AnalyzeBranches(BBInfo &BBI);
245b915e9e0SDimitry Andric void ScanInstructions(BBInfo &BBI,
246b915e9e0SDimitry Andric MachineBasicBlock::iterator &Begin,
247b915e9e0SDimitry Andric MachineBasicBlock::iterator &End,
248b915e9e0SDimitry Andric bool BranchUnpredicable = false) const;
249b915e9e0SDimitry Andric bool RescanInstructions(
250b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
251b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
252b915e9e0SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI) const;
253b915e9e0SDimitry Andric void AnalyzeBlock(MachineBasicBlock &MBB,
25401095a5dSDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
255eb11fae6SDimitry Andric bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
256b915e9e0SDimitry Andric bool isTriangle = false, bool RevBranch = false,
257b915e9e0SDimitry Andric bool hasCommonTail = false);
25801095a5dSDimitry Andric void AnalyzeBlocks(MachineFunction &MF,
25901095a5dSDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
260b915e9e0SDimitry Andric void InvalidatePreds(MachineBasicBlock &MBB);
261009b1c42SEd Schouten bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
262009b1c42SEd Schouten bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
263b915e9e0SDimitry Andric bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
264b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
265b915e9e0SDimitry Andric bool TClobbersPred, bool FClobbersPred,
266b915e9e0SDimitry Andric bool RemoveBranch, bool MergeAddEdges);
267009b1c42SEd Schouten bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
268b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
269b915e9e0SDimitry Andric bool TClobbers, bool FClobbers);
270b915e9e0SDimitry Andric bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
271b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
272b915e9e0SDimitry Andric bool TClobbers, bool FClobbers);
273009b1c42SEd Schouten void PredicateBlock(BBInfo &BBI,
274009b1c42SEd Schouten MachineBasicBlock::iterator E,
27566e41e3cSRoman Divacky SmallVectorImpl<MachineOperand> &Cond,
276d8e91e46SDimitry Andric SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
277009b1c42SEd Schouten void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
278009b1c42SEd Schouten SmallVectorImpl<MachineOperand> &Cond,
279009b1c42SEd Schouten bool IgnoreBr = false);
28066e41e3cSRoman Divacky void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
281009b1c42SEd Schouten
MeetIfcvtSizeLimit(MachineBasicBlock & BB,unsigned Cycle,unsigned Extra,BranchProbability Prediction) const282cf099d11SDimitry Andric bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
283cf099d11SDimitry Andric unsigned Cycle, unsigned Extra,
284dd58ef01SDimitry Andric BranchProbability Prediction) const {
285cf099d11SDimitry Andric return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
286411bd29eSDimitry Andric Prediction);
28766e41e3cSRoman Divacky }
28866e41e3cSRoman Divacky
MeetIfcvtSizeLimit(BBInfo & TBBInfo,BBInfo & FBBInfo,MachineBasicBlock & CommBB,unsigned Dups,BranchProbability Prediction,bool Forked) const2891d5ae102SDimitry Andric bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
2901d5ae102SDimitry Andric MachineBasicBlock &CommBB, unsigned Dups,
2911d5ae102SDimitry Andric BranchProbability Prediction, bool Forked) const {
2921d5ae102SDimitry Andric const MachineFunction &MF = *TBBInfo.BB->getParent();
2931d5ae102SDimitry Andric if (MF.getFunction().hasMinSize()) {
2941d5ae102SDimitry Andric MachineBasicBlock::iterator TIB = TBBInfo.BB->begin();
2951d5ae102SDimitry Andric MachineBasicBlock::iterator FIB = FBBInfo.BB->begin();
2961d5ae102SDimitry Andric MachineBasicBlock::iterator TIE = TBBInfo.BB->end();
2971d5ae102SDimitry Andric MachineBasicBlock::iterator FIE = FBBInfo.BB->end();
2981d5ae102SDimitry Andric
299344a3780SDimitry Andric unsigned Dups1 = 0, Dups2 = 0;
3001d5ae102SDimitry Andric if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
3011d5ae102SDimitry Andric *TBBInfo.BB, *FBBInfo.BB,
3021d5ae102SDimitry Andric /*SkipUnconditionalBranches*/ true))
3031d5ae102SDimitry Andric llvm_unreachable("should already have been checked by ValidDiamond");
3041d5ae102SDimitry Andric
3051d5ae102SDimitry Andric unsigned BranchBytes = 0;
3061d5ae102SDimitry Andric unsigned CommonBytes = 0;
3071d5ae102SDimitry Andric
3081d5ae102SDimitry Andric // Count common instructions at the start of the true and false blocks.
3091d5ae102SDimitry Andric for (auto &I : make_range(TBBInfo.BB->begin(), TIB)) {
3101d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3111d5ae102SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3121d5ae102SDimitry Andric }
3131d5ae102SDimitry Andric for (auto &I : make_range(FBBInfo.BB->begin(), FIB)) {
3141d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3151d5ae102SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3161d5ae102SDimitry Andric }
3171d5ae102SDimitry Andric
3181d5ae102SDimitry Andric // Count instructions at the end of the true and false blocks, after
3191d5ae102SDimitry Andric // the ones we plan to predicate. Analyzable branches will be removed
3201d5ae102SDimitry Andric // (unless this is a forked diamond), and all other instructions are
3211d5ae102SDimitry Andric // common between the two blocks.
3221d5ae102SDimitry Andric for (auto &I : make_range(TIE, TBBInfo.BB->end())) {
3231d5ae102SDimitry Andric if (I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
3241d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3251d5ae102SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3261d5ae102SDimitry Andric } else {
3271d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3281d5ae102SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3291d5ae102SDimitry Andric }
3301d5ae102SDimitry Andric }
3311d5ae102SDimitry Andric for (auto &I : make_range(FIE, FBBInfo.BB->end())) {
3321d5ae102SDimitry Andric if (I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
3331d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3341d5ae102SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3351d5ae102SDimitry Andric } else {
3361d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3371d5ae102SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3381d5ae102SDimitry Andric }
3391d5ae102SDimitry Andric }
3401d5ae102SDimitry Andric for (auto &I : CommBB.terminators()) {
3411d5ae102SDimitry Andric if (I.isBranch()) {
3421d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3431d5ae102SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3441d5ae102SDimitry Andric }
3451d5ae102SDimitry Andric }
3461d5ae102SDimitry Andric
3471d5ae102SDimitry Andric // The common instructions in one branch will be eliminated, halving
3481d5ae102SDimitry Andric // their code size.
3491d5ae102SDimitry Andric CommonBytes /= 2;
3501d5ae102SDimitry Andric
3511d5ae102SDimitry Andric // Count the instructions which we need to predicate.
3521d5ae102SDimitry Andric unsigned NumPredicatedInstructions = 0;
3531d5ae102SDimitry Andric for (auto &I : make_range(TIB, TIE)) {
3541d5ae102SDimitry Andric if (!I.isDebugInstr()) {
3551d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Predicating: " << I);
3561d5ae102SDimitry Andric NumPredicatedInstructions++;
3571d5ae102SDimitry Andric }
3581d5ae102SDimitry Andric }
3591d5ae102SDimitry Andric for (auto &I : make_range(FIB, FIE)) {
3601d5ae102SDimitry Andric if (!I.isDebugInstr()) {
3611d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "Predicating: " << I);
3621d5ae102SDimitry Andric NumPredicatedInstructions++;
3631d5ae102SDimitry Andric }
3641d5ae102SDimitry Andric }
3651d5ae102SDimitry Andric
3661d5ae102SDimitry Andric // Even though we're optimising for size at the expense of performance,
3671d5ae102SDimitry Andric // avoid creating really long predicated blocks.
3681d5ae102SDimitry Andric if (NumPredicatedInstructions > 15)
3691d5ae102SDimitry Andric return false;
3701d5ae102SDimitry Andric
3711d5ae102SDimitry Andric // Some targets (e.g. Thumb2) need to insert extra instructions to
3721d5ae102SDimitry Andric // start predicated blocks.
3731d5ae102SDimitry Andric unsigned ExtraPredicateBytes = TII->extraSizeToPredicateInstructions(
3741d5ae102SDimitry Andric MF, NumPredicatedInstructions);
3751d5ae102SDimitry Andric
3761d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
3771d5ae102SDimitry Andric << ", CommonBytes=" << CommonBytes
3781d5ae102SDimitry Andric << ", NumPredicatedInstructions="
3791d5ae102SDimitry Andric << NumPredicatedInstructions
3801d5ae102SDimitry Andric << ", ExtraPredicateBytes=" << ExtraPredicateBytes
3811d5ae102SDimitry Andric << ")\n");
3821d5ae102SDimitry Andric return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
3831d5ae102SDimitry Andric } else {
3841d5ae102SDimitry Andric unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
3851d5ae102SDimitry Andric unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
3861d5ae102SDimitry Andric bool Res = TCycle > 0 && FCycle > 0 &&
3871d5ae102SDimitry Andric TII->isProfitableToIfCvt(
3881d5ae102SDimitry Andric *TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
3891d5ae102SDimitry Andric FCycle, FBBInfo.ExtraCost2, Prediction);
3901d5ae102SDimitry Andric LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle
3911d5ae102SDimitry Andric << ", FCycle=" << FCycle
3921d5ae102SDimitry Andric << ", TExtra=" << TBBInfo.ExtraCost2 << ", FExtra="
3931d5ae102SDimitry Andric << FBBInfo.ExtraCost2 << ") = " << Res << "\n");
3941d5ae102SDimitry Andric return Res;
3951d5ae102SDimitry Andric }
396009b1c42SEd Schouten }
397009b1c42SEd Schouten
398b915e9e0SDimitry Andric /// Returns true if Block ends without a terminator.
blockAlwaysFallThrough(BBInfo & BBI) const399009b1c42SEd Schouten bool blockAlwaysFallThrough(BBInfo &BBI) const {
4005ca98fd9SDimitry Andric return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
401009b1c42SEd Schouten }
402009b1c42SEd Schouten
403b915e9e0SDimitry Andric /// Used to sort if-conversion candidates.
IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> & C1,const std::unique_ptr<IfcvtToken> & C2)40401095a5dSDimitry Andric static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
40501095a5dSDimitry Andric const std::unique_ptr<IfcvtToken> &C2) {
406009b1c42SEd Schouten int Incr1 = (C1->Kind == ICDiamond)
407009b1c42SEd Schouten ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
408009b1c42SEd Schouten int Incr2 = (C2->Kind == ICDiamond)
409009b1c42SEd Schouten ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
410009b1c42SEd Schouten if (Incr1 > Incr2)
411009b1c42SEd Schouten return true;
412009b1c42SEd Schouten else if (Incr1 == Incr2) {
413009b1c42SEd Schouten // Favors subsumption.
4145a5ac124SDimitry Andric if (!C1->NeedSubsumption && C2->NeedSubsumption)
415009b1c42SEd Schouten return true;
416009b1c42SEd Schouten else if (C1->NeedSubsumption == C2->NeedSubsumption) {
417009b1c42SEd Schouten // Favors diamond over triangle, etc.
418009b1c42SEd Schouten if ((unsigned)C1->Kind < (unsigned)C2->Kind)
419009b1c42SEd Schouten return true;
420009b1c42SEd Schouten else if (C1->Kind == C2->Kind)
421009b1c42SEd Schouten return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
422009b1c42SEd Schouten }
423009b1c42SEd Schouten }
424009b1c42SEd Schouten return false;
425009b1c42SEd Schouten }
426009b1c42SEd Schouten };
427009b1c42SEd Schouten
428044eb2f6SDimitry Andric } // end anonymous namespace
429044eb2f6SDimitry Andric
430009b1c42SEd Schouten char IfConverter::ID = 0;
431009b1c42SEd Schouten
43263faed5bSDimitry Andric char &llvm::IfConverterID = IfConverter::ID;
43363faed5bSDimitry Andric
434ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)435ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
436706b4fc4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
437ab44ce3dSDimitry Andric INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
438009b1c42SEd Schouten
439009b1c42SEd Schouten bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
440044eb2f6SDimitry Andric if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
44185d8b2bbSDimitry Andric return false;
44285d8b2bbSDimitry Andric
4435a5ac124SDimitry Andric const TargetSubtargetInfo &ST = MF.getSubtarget();
4445a5ac124SDimitry Andric TLI = ST.getTargetLowering();
4455a5ac124SDimitry Andric TII = ST.getInstrInfo();
4465a5ac124SDimitry Andric TRI = ST.getRegisterInfo();
447ac9a064cSDimitry Andric MBFIWrapper MBFI(
448ac9a064cSDimitry Andric getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
449ac9a064cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
450706b4fc4SDimitry Andric ProfileSummaryInfo *PSI =
451706b4fc4SDimitry Andric &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
45258b69754SDimitry Andric MRI = &MF.getRegInfo();
453eb11fae6SDimitry Andric SchedModel.init(&ST);
454f8af5cf6SDimitry Andric
455009b1c42SEd Schouten if (!TII) return false;
456009b1c42SEd Schouten
45758b69754SDimitry Andric PreRegAlloc = MRI->isSSA();
45858b69754SDimitry Andric
45958b69754SDimitry Andric bool BFChange = false;
46058b69754SDimitry Andric if (!PreRegAlloc) {
46166e41e3cSRoman Divacky // Tail merge tend to expose more if-conversion opportunities.
462706b4fc4SDimitry Andric BranchFolder BF(true, false, MBFI, *MBPI, PSI);
463cfca06d7SDimitry Andric BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo());
46458b69754SDimitry Andric }
46566e41e3cSRoman Divacky
466eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
467522600a2SDimitry Andric << MF.getName() << "\'");
468009b1c42SEd Schouten
469009b1c42SEd Schouten if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
470eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " skipped\n");
471009b1c42SEd Schouten return false;
472009b1c42SEd Schouten }
473eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
474009b1c42SEd Schouten
475009b1c42SEd Schouten MF.RenumberBlocks();
476009b1c42SEd Schouten BBAnalysis.resize(MF.getNumBlockIDs());
477009b1c42SEd Schouten
47801095a5dSDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> Tokens;
479009b1c42SEd Schouten MadeChange = false;
480009b1c42SEd Schouten unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
481009b1c42SEd Schouten NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
482009b1c42SEd Schouten while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
483009b1c42SEd Schouten // Do an initial analysis for each basic block and find all the potential
484009b1c42SEd Schouten // candidates to perform if-conversion.
48566e41e3cSRoman Divacky bool Change = false;
48666e41e3cSRoman Divacky AnalyzeBlocks(MF, Tokens);
487009b1c42SEd Schouten while (!Tokens.empty()) {
48801095a5dSDimitry Andric std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
489009b1c42SEd Schouten Tokens.pop_back();
490009b1c42SEd Schouten BBInfo &BBI = Token->BBI;
491009b1c42SEd Schouten IfcvtKind Kind = Token->Kind;
492009b1c42SEd Schouten unsigned NumDups = Token->NumDups;
493009b1c42SEd Schouten unsigned NumDups2 = Token->NumDups2;
494009b1c42SEd Schouten
495009b1c42SEd Schouten // If the block has been evicted out of the queue or it has already been
496009b1c42SEd Schouten // marked dead (due to it being predicated), then skip it.
497009b1c42SEd Schouten if (BBI.IsDone)
498009b1c42SEd Schouten BBI.IsEnqueued = false;
499009b1c42SEd Schouten if (!BBI.IsEnqueued)
500009b1c42SEd Schouten continue;
501009b1c42SEd Schouten
502009b1c42SEd Schouten BBI.IsEnqueued = false;
503009b1c42SEd Schouten
504009b1c42SEd Schouten bool RetVal = false;
505009b1c42SEd Schouten switch (Kind) {
50663faed5bSDimitry Andric default: llvm_unreachable("Unexpected!");
507009b1c42SEd Schouten case ICSimple:
508009b1c42SEd Schouten case ICSimpleFalse: {
509009b1c42SEd Schouten bool isFalse = Kind == ICSimpleFalse;
510009b1c42SEd Schouten if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
511eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
512044eb2f6SDimitry Andric << (Kind == ICSimpleFalse ? " false" : "")
513044eb2f6SDimitry Andric << "): " << printMBBReference(*BBI.BB) << " ("
514044eb2f6SDimitry Andric << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
515044eb2f6SDimitry Andric : BBI.TrueBB->getNumber())
516044eb2f6SDimitry Andric << ") ");
517009b1c42SEd Schouten RetVal = IfConvertSimple(BBI, Kind);
518eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
519009b1c42SEd Schouten if (RetVal) {
52066e41e3cSRoman Divacky if (isFalse) ++NumSimpleFalse;
52166e41e3cSRoman Divacky else ++NumSimple;
522009b1c42SEd Schouten }
523009b1c42SEd Schouten break;
524009b1c42SEd Schouten }
525009b1c42SEd Schouten case ICTriangle:
526009b1c42SEd Schouten case ICTriangleRev:
527009b1c42SEd Schouten case ICTriangleFalse:
528009b1c42SEd Schouten case ICTriangleFRev: {
529009b1c42SEd Schouten bool isFalse = Kind == ICTriangleFalse;
530009b1c42SEd Schouten bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
531009b1c42SEd Schouten if (DisableTriangle && !isFalse && !isRev) break;
532009b1c42SEd Schouten if (DisableTriangleR && !isFalse && isRev) break;
533009b1c42SEd Schouten if (DisableTriangleF && isFalse && !isRev) break;
534eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
535009b1c42SEd Schouten if (isFalse)
536eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " false");
537009b1c42SEd Schouten if (isRev)
538eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " rev");
539eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
540044eb2f6SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
541044eb2f6SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
542009b1c42SEd Schouten RetVal = IfConvertTriangle(BBI, Kind);
543eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
544009b1c42SEd Schouten if (RetVal) {
545b1c73532SDimitry Andric if (isFalse)
546b1c73532SDimitry Andric ++NumTriangleFalse;
547b1c73532SDimitry Andric else if (isRev)
548b1c73532SDimitry Andric ++NumTriangleRev;
549b1c73532SDimitry Andric else
550b1c73532SDimitry Andric ++NumTriangle;
551009b1c42SEd Schouten }
552009b1c42SEd Schouten break;
553009b1c42SEd Schouten }
554044eb2f6SDimitry Andric case ICDiamond:
555009b1c42SEd Schouten if (DisableDiamond) break;
556eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
557044eb2f6SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
558044eb2f6SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
559b915e9e0SDimitry Andric RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
560b915e9e0SDimitry Andric Token->TClobbersPred,
561b915e9e0SDimitry Andric Token->FClobbersPred);
562eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
56366e41e3cSRoman Divacky if (RetVal) ++NumDiamonds;
564009b1c42SEd Schouten break;
565044eb2f6SDimitry Andric case ICForkedDiamond:
566b915e9e0SDimitry Andric if (DisableForkedDiamond) break;
567eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
568eb11fae6SDimitry Andric << printMBBReference(*BBI.BB)
569044eb2f6SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
570044eb2f6SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
571b915e9e0SDimitry Andric RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
572b915e9e0SDimitry Andric Token->TClobbersPred,
573b915e9e0SDimitry Andric Token->FClobbersPred);
574eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
575b915e9e0SDimitry Andric if (RetVal) ++NumForkedDiamonds;
576b915e9e0SDimitry Andric break;
577b915e9e0SDimitry Andric }
578044eb2f6SDimitry Andric
579044eb2f6SDimitry Andric if (RetVal && MRI->tracksLiveness())
580044eb2f6SDimitry Andric recomputeLivenessFlags(*BBI.BB);
581009b1c42SEd Schouten
582009b1c42SEd Schouten Change |= RetVal;
583009b1c42SEd Schouten
584009b1c42SEd Schouten NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
585009b1c42SEd Schouten NumTriangleFalse + NumTriangleFRev + NumDiamonds;
586009b1c42SEd Schouten if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
587009b1c42SEd Schouten break;
588009b1c42SEd Schouten }
589009b1c42SEd Schouten
590009b1c42SEd Schouten if (!Change)
591009b1c42SEd Schouten break;
592009b1c42SEd Schouten MadeChange |= Change;
593009b1c42SEd Schouten }
594009b1c42SEd Schouten
595009b1c42SEd Schouten Tokens.clear();
596009b1c42SEd Schouten BBAnalysis.clear();
597009b1c42SEd Schouten
59866e41e3cSRoman Divacky if (MadeChange && IfCvtBranchFold) {
599706b4fc4SDimitry Andric BranchFolder BF(false, false, MBFI, *MBPI, PSI);
600cfca06d7SDimitry Andric BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo());
60159850d08SRoman Divacky }
60259850d08SRoman Divacky
60366e41e3cSRoman Divacky MadeChange |= BFChange;
604009b1c42SEd Schouten return MadeChange;
605009b1c42SEd Schouten }
606009b1c42SEd Schouten
607b915e9e0SDimitry Andric /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
findFalseBlock(MachineBasicBlock * BB,MachineBasicBlock * TrueBB)608009b1c42SEd Schouten static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
609009b1c42SEd Schouten MachineBasicBlock *TrueBB) {
610b915e9e0SDimitry Andric for (MachineBasicBlock *SuccBB : BB->successors()) {
611009b1c42SEd Schouten if (SuccBB != TrueBB)
612009b1c42SEd Schouten return SuccBB;
613009b1c42SEd Schouten }
6145ca98fd9SDimitry Andric return nullptr;
615009b1c42SEd Schouten }
616009b1c42SEd Schouten
617b915e9e0SDimitry Andric /// Reverse the condition of the end of the block branch. Swap block's 'true'
618b915e9e0SDimitry Andric /// and 'false' successors.
reverseBranchCondition(BBInfo & BBI) const619b915e9e0SDimitry Andric bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
62066e41e3cSRoman Divacky DebugLoc dl; // FIXME: this is nowhere
621b915e9e0SDimitry Andric if (!TII->reverseBranchCondition(BBI.BrCond)) {
622b915e9e0SDimitry Andric TII->removeBranch(*BBI.BB);
623b915e9e0SDimitry Andric TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
624009b1c42SEd Schouten std::swap(BBI.TrueBB, BBI.FalseBB);
625009b1c42SEd Schouten return true;
626009b1c42SEd Schouten }
627009b1c42SEd Schouten return false;
628009b1c42SEd Schouten }
629009b1c42SEd Schouten
630b915e9e0SDimitry Andric /// Returns the next block in the function blocks ordering. If it is the end,
631b915e9e0SDimitry Andric /// returns NULL.
getNextBlock(MachineBasicBlock & MBB)632b915e9e0SDimitry Andric static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
633b915e9e0SDimitry Andric MachineFunction::iterator I = MBB.getIterator();
634b915e9e0SDimitry Andric MachineFunction::iterator E = MBB.getParent()->end();
635009b1c42SEd Schouten if (++I == E)
6365ca98fd9SDimitry Andric return nullptr;
637dd58ef01SDimitry Andric return &*I;
638009b1c42SEd Schouten }
639009b1c42SEd Schouten
640b915e9e0SDimitry Andric /// Returns true if the 'true' block (along with its predecessor) forms a valid
641b915e9e0SDimitry Andric /// simple shape for ifcvt. It also returns the number of instructions that the
642b915e9e0SDimitry Andric /// ifcvt would need to duplicate if performed in Dups.
ValidSimple(BBInfo & TrueBBI,unsigned & Dups,BranchProbability Prediction) const643cf099d11SDimitry Andric bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
644dd58ef01SDimitry Andric BranchProbability Prediction) const {
645009b1c42SEd Schouten Dups = 0;
646009b1c42SEd Schouten if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
647009b1c42SEd Schouten return false;
648009b1c42SEd Schouten
649009b1c42SEd Schouten if (TrueBBI.IsBrAnalyzable)
650009b1c42SEd Schouten return false;
651009b1c42SEd Schouten
652009b1c42SEd Schouten if (TrueBBI.BB->pred_size() > 1) {
653009b1c42SEd Schouten if (TrueBBI.CannotBeCopied ||
654cf099d11SDimitry Andric !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
655411bd29eSDimitry Andric Prediction))
656009b1c42SEd Schouten return false;
657009b1c42SEd Schouten Dups = TrueBBI.NonPredSize;
658009b1c42SEd Schouten }
659009b1c42SEd Schouten
660009b1c42SEd Schouten return true;
661009b1c42SEd Schouten }
662009b1c42SEd Schouten
663b915e9e0SDimitry Andric /// Returns true if the 'true' and 'false' blocks (along with their common
664b915e9e0SDimitry Andric /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
665b915e9e0SDimitry Andric /// true, it checks if 'true' block's false branch branches to the 'false' block
666b915e9e0SDimitry Andric /// rather than the other way around. It also returns the number of instructions
667b915e9e0SDimitry Andric /// that the ifcvt would need to duplicate if performed in 'Dups'.
ValidTriangle(BBInfo & TrueBBI,BBInfo & FalseBBI,bool FalseBranch,unsigned & Dups,BranchProbability Prediction) const668009b1c42SEd Schouten bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
669cf099d11SDimitry Andric bool FalseBranch, unsigned &Dups,
670dd58ef01SDimitry Andric BranchProbability Prediction) const {
671009b1c42SEd Schouten Dups = 0;
6721d5ae102SDimitry Andric if (TrueBBI.BB == FalseBBI.BB)
6731d5ae102SDimitry Andric return false;
6741d5ae102SDimitry Andric
675009b1c42SEd Schouten if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
676009b1c42SEd Schouten return false;
677009b1c42SEd Schouten
678009b1c42SEd Schouten if (TrueBBI.BB->pred_size() > 1) {
679009b1c42SEd Schouten if (TrueBBI.CannotBeCopied)
680009b1c42SEd Schouten return false;
681009b1c42SEd Schouten
682009b1c42SEd Schouten unsigned Size = TrueBBI.NonPredSize;
683009b1c42SEd Schouten if (TrueBBI.IsBrAnalyzable) {
684009b1c42SEd Schouten if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
685009b1c42SEd Schouten // Ends with an unconditional branch. It will be removed.
686009b1c42SEd Schouten --Size;
687009b1c42SEd Schouten else {
688009b1c42SEd Schouten MachineBasicBlock *FExit = FalseBranch
689009b1c42SEd Schouten ? TrueBBI.TrueBB : TrueBBI.FalseBB;
690009b1c42SEd Schouten if (FExit)
691009b1c42SEd Schouten // Require a conditional branch
692009b1c42SEd Schouten ++Size;
693009b1c42SEd Schouten }
694009b1c42SEd Schouten }
695411bd29eSDimitry Andric if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
696009b1c42SEd Schouten return false;
697009b1c42SEd Schouten Dups = Size;
698009b1c42SEd Schouten }
699009b1c42SEd Schouten
700009b1c42SEd Schouten MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
701009b1c42SEd Schouten if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
702dd58ef01SDimitry Andric MachineFunction::iterator I = TrueBBI.BB->getIterator();
703009b1c42SEd Schouten if (++I == TrueBBI.BB->getParent()->end())
704009b1c42SEd Schouten return false;
705dd58ef01SDimitry Andric TExit = &*I;
706009b1c42SEd Schouten }
707009b1c42SEd Schouten return TExit && TExit == FalseBBI.BB;
708009b1c42SEd Schouten }
709009b1c42SEd Schouten
710b915e9e0SDimitry Andric /// Count duplicated instructions and move the iterators to show where they
711b915e9e0SDimitry Andric /// are.
712b915e9e0SDimitry Andric /// @param TIB True Iterator Begin
713b915e9e0SDimitry Andric /// @param FIB False Iterator Begin
714b915e9e0SDimitry Andric /// These two iterators initially point to the first instruction of the two
715b915e9e0SDimitry Andric /// blocks, and finally point to the first non-shared instruction.
716b915e9e0SDimitry Andric /// @param TIE True Iterator End
717b915e9e0SDimitry Andric /// @param FIE False Iterator End
718b915e9e0SDimitry Andric /// These two iterators initially point to End() for the two blocks() and
719b915e9e0SDimitry Andric /// finally point to the first shared instruction in the tail.
720b915e9e0SDimitry Andric /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
721b915e9e0SDimitry Andric /// two blocks.
722b915e9e0SDimitry Andric /// @param Dups1 count of duplicated instructions at the beginning of the 2
723b915e9e0SDimitry Andric /// blocks.
724b915e9e0SDimitry Andric /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
725b915e9e0SDimitry Andric /// @param SkipUnconditionalBranches if true, Don't make sure that
726b915e9e0SDimitry Andric /// unconditional branches at the end of the blocks are the same. True is
727b915e9e0SDimitry Andric /// passed when the blocks are analyzable to allow for fallthrough to be
728b915e9e0SDimitry Andric /// handled.
729b915e9e0SDimitry Andric /// @return false if the shared portion prevents if conversion.
CountDuplicatedInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,unsigned & Dups1,unsigned & Dups2,MachineBasicBlock & TBB,MachineBasicBlock & FBB,bool SkipUnconditionalBranches) const730b915e9e0SDimitry Andric bool IfConverter::CountDuplicatedInstructions(
731b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIB,
732b915e9e0SDimitry Andric MachineBasicBlock::iterator &FIB,
733b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIE,
734b915e9e0SDimitry Andric MachineBasicBlock::iterator &FIE,
735b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
736b915e9e0SDimitry Andric MachineBasicBlock &TBB, MachineBasicBlock &FBB,
737b915e9e0SDimitry Andric bool SkipUnconditionalBranches) const {
738b915e9e0SDimitry Andric while (TIB != TIE && FIB != FIE) {
739b915e9e0SDimitry Andric // Skip dbg_value instructions. These do not count.
740344a3780SDimitry Andric TIB = skipDebugInstructionsForward(TIB, TIE, false);
741344a3780SDimitry Andric FIB = skipDebugInstructionsForward(FIB, FIE, false);
74271d5a254SDimitry Andric if (TIB == TIE || FIB == FIE)
743b915e9e0SDimitry Andric break;
744b915e9e0SDimitry Andric if (!TIB->isIdenticalTo(*FIB))
745b915e9e0SDimitry Andric break;
746b915e9e0SDimitry Andric // A pred-clobbering instruction in the shared portion prevents
747b915e9e0SDimitry Andric // if-conversion.
748b915e9e0SDimitry Andric std::vector<MachineOperand> PredDefs;
749b60736ecSDimitry Andric if (TII->ClobbersPredicate(*TIB, PredDefs, false))
750b915e9e0SDimitry Andric return false;
751b915e9e0SDimitry Andric // If we get all the way to the branch instructions, don't count them.
752b915e9e0SDimitry Andric if (!TIB->isBranch())
753b915e9e0SDimitry Andric ++Dups1;
754b915e9e0SDimitry Andric ++TIB;
755b915e9e0SDimitry Andric ++FIB;
756b915e9e0SDimitry Andric }
757b915e9e0SDimitry Andric
758b915e9e0SDimitry Andric // Check for already containing all of the block.
759b915e9e0SDimitry Andric if (TIB == TIE || FIB == FIE)
760b915e9e0SDimitry Andric return true;
761b915e9e0SDimitry Andric // Now, in preparation for counting duplicate instructions at the ends of the
76271d5a254SDimitry Andric // blocks, switch to reverse_iterators. Note that getReverse() returns an
76371d5a254SDimitry Andric // iterator that points to the same instruction, unlike std::reverse_iterator.
76471d5a254SDimitry Andric // We have to do our own shifting so that we get the same range.
76571d5a254SDimitry Andric MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
76671d5a254SDimitry Andric MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
76771d5a254SDimitry Andric const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
76871d5a254SDimitry Andric const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
769b915e9e0SDimitry Andric
770b915e9e0SDimitry Andric if (!TBB.succ_empty() || !FBB.succ_empty()) {
771b915e9e0SDimitry Andric if (SkipUnconditionalBranches) {
77271d5a254SDimitry Andric while (RTIE != RTIB && RTIE->isUnconditionalBranch())
77371d5a254SDimitry Andric ++RTIE;
77471d5a254SDimitry Andric while (RFIE != RFIB && RFIE->isUnconditionalBranch())
77571d5a254SDimitry Andric ++RFIE;
776b915e9e0SDimitry Andric }
777b915e9e0SDimitry Andric }
778b915e9e0SDimitry Andric
779b915e9e0SDimitry Andric // Count duplicate instructions at the ends of the blocks.
78071d5a254SDimitry Andric while (RTIE != RTIB && RFIE != RFIB) {
781b915e9e0SDimitry Andric // Skip dbg_value instructions. These do not count.
78271d5a254SDimitry Andric // Note that these are reverse iterators going forward.
783344a3780SDimitry Andric RTIE = skipDebugInstructionsForward(RTIE, RTIB, false);
784344a3780SDimitry Andric RFIE = skipDebugInstructionsForward(RFIE, RFIB, false);
78571d5a254SDimitry Andric if (RTIE == RTIB || RFIE == RFIB)
786b915e9e0SDimitry Andric break;
78771d5a254SDimitry Andric if (!RTIE->isIdenticalTo(*RFIE))
788b915e9e0SDimitry Andric break;
789b915e9e0SDimitry Andric // We have to verify that any branch instructions are the same, and then we
790b915e9e0SDimitry Andric // don't count them toward the # of duplicate instructions.
79171d5a254SDimitry Andric if (!RTIE->isBranch())
792b915e9e0SDimitry Andric ++Dups2;
79371d5a254SDimitry Andric ++RTIE;
79471d5a254SDimitry Andric ++RFIE;
795b915e9e0SDimitry Andric }
79671d5a254SDimitry Andric TIE = std::next(RTIE.getReverse());
79771d5a254SDimitry Andric FIE = std::next(RFIE.getReverse());
798b915e9e0SDimitry Andric return true;
799b915e9e0SDimitry Andric }
800b915e9e0SDimitry Andric
801b915e9e0SDimitry Andric /// RescanInstructions - Run ScanInstructions on a pair of blocks.
802b915e9e0SDimitry Andric /// @param TIB - True Iterator Begin, points to first non-shared instruction
803b915e9e0SDimitry Andric /// @param FIB - False Iterator Begin, points to first non-shared instruction
804b915e9e0SDimitry Andric /// @param TIE - True Iterator End, points past last non-shared instruction
805b915e9e0SDimitry Andric /// @param FIE - False Iterator End, points past last non-shared instruction
806b915e9e0SDimitry Andric /// @param TrueBBI - BBInfo to update for the true block.
807b915e9e0SDimitry Andric /// @param FalseBBI - BBInfo to update for the false block.
808b915e9e0SDimitry Andric /// @returns - false if either block cannot be predicated or if both blocks end
809b915e9e0SDimitry Andric /// with a predicate-clobbering instruction.
RescanInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,BBInfo & TrueBBI,BBInfo & FalseBBI) const810b915e9e0SDimitry Andric bool IfConverter::RescanInstructions(
811b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
812b915e9e0SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
813b915e9e0SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI) const {
814b915e9e0SDimitry Andric bool BranchUnpredicable = true;
815b915e9e0SDimitry Andric TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
816b915e9e0SDimitry Andric ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
817b915e9e0SDimitry Andric if (TrueBBI.IsUnpredicable)
818b915e9e0SDimitry Andric return false;
819b915e9e0SDimitry Andric ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
820b915e9e0SDimitry Andric if (FalseBBI.IsUnpredicable)
821b915e9e0SDimitry Andric return false;
822b915e9e0SDimitry Andric if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
823b915e9e0SDimitry Andric return false;
824b915e9e0SDimitry Andric return true;
825b915e9e0SDimitry Andric }
826b915e9e0SDimitry Andric
827b915e9e0SDimitry Andric #ifndef NDEBUG
verifySameBranchInstructions(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2)828b915e9e0SDimitry Andric static void verifySameBranchInstructions(
829b915e9e0SDimitry Andric MachineBasicBlock *MBB1,
830b915e9e0SDimitry Andric MachineBasicBlock *MBB2) {
83171d5a254SDimitry Andric const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
83271d5a254SDimitry Andric const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
83371d5a254SDimitry Andric MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
83471d5a254SDimitry Andric MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
83571d5a254SDimitry Andric while (E1 != B1 && E2 != B2) {
836344a3780SDimitry Andric skipDebugInstructionsForward(E1, B1, false);
837344a3780SDimitry Andric skipDebugInstructionsForward(E2, B2, false);
83871d5a254SDimitry Andric if (E1 == B1 && E2 == B2)
839b915e9e0SDimitry Andric break;
840b915e9e0SDimitry Andric
84171d5a254SDimitry Andric if (E1 == B1) {
842b915e9e0SDimitry Andric assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
843b915e9e0SDimitry Andric break;
844b915e9e0SDimitry Andric }
84571d5a254SDimitry Andric if (E2 == B2) {
846b915e9e0SDimitry Andric assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
847b915e9e0SDimitry Andric break;
848b915e9e0SDimitry Andric }
849b915e9e0SDimitry Andric
850b915e9e0SDimitry Andric if (E1->isBranch() || E2->isBranch())
851b915e9e0SDimitry Andric assert(E1->isIdenticalTo(*E2) &&
852b915e9e0SDimitry Andric "Branch mis-match, branch instructions don't match.");
853b915e9e0SDimitry Andric else
854b915e9e0SDimitry Andric break;
85571d5a254SDimitry Andric ++E1;
85671d5a254SDimitry Andric ++E2;
857b915e9e0SDimitry Andric }
858b915e9e0SDimitry Andric }
859b915e9e0SDimitry Andric #endif
860b915e9e0SDimitry Andric
861b915e9e0SDimitry Andric /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
862b915e9e0SDimitry Andric /// with their common predecessor) form a diamond if a common tail block is
863b915e9e0SDimitry Andric /// extracted.
864b915e9e0SDimitry Andric /// While not strictly a diamond, this pattern would form a diamond if
865b915e9e0SDimitry Andric /// tail-merging had merged the shared tails.
866b915e9e0SDimitry Andric /// EBB
867b915e9e0SDimitry Andric /// _/ \_
868b915e9e0SDimitry Andric /// | |
869b915e9e0SDimitry Andric /// TBB FBB
870b915e9e0SDimitry Andric /// / \ / \
871b915e9e0SDimitry Andric /// FalseBB TrueBB FalseBB
872b915e9e0SDimitry Andric /// Currently only handles analyzable branches.
873b915e9e0SDimitry Andric /// Specifically excludes actual diamonds to avoid overlap.
ValidForkedDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const874b915e9e0SDimitry Andric bool IfConverter::ValidForkedDiamond(
875b915e9e0SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI,
876b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
877b915e9e0SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
878b915e9e0SDimitry Andric Dups1 = Dups2 = 0;
879b915e9e0SDimitry Andric if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
880b915e9e0SDimitry Andric FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
881b915e9e0SDimitry Andric return false;
882b915e9e0SDimitry Andric
883b915e9e0SDimitry Andric if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
884b915e9e0SDimitry Andric return false;
885b915e9e0SDimitry Andric // Don't IfConvert blocks that can't be folded into their predecessor.
886b915e9e0SDimitry Andric if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
887b915e9e0SDimitry Andric return false;
888b915e9e0SDimitry Andric
889b915e9e0SDimitry Andric // This function is specifically looking for conditional tails, as
890b915e9e0SDimitry Andric // unconditional tails are already handled by the standard diamond case.
891b915e9e0SDimitry Andric if (TrueBBI.BrCond.size() == 0 ||
892b915e9e0SDimitry Andric FalseBBI.BrCond.size() == 0)
893b915e9e0SDimitry Andric return false;
894b915e9e0SDimitry Andric
895b915e9e0SDimitry Andric MachineBasicBlock *TT = TrueBBI.TrueBB;
896b915e9e0SDimitry Andric MachineBasicBlock *TF = TrueBBI.FalseBB;
897b915e9e0SDimitry Andric MachineBasicBlock *FT = FalseBBI.TrueBB;
898b915e9e0SDimitry Andric MachineBasicBlock *FF = FalseBBI.FalseBB;
899b915e9e0SDimitry Andric
900b915e9e0SDimitry Andric if (!TT)
901b915e9e0SDimitry Andric TT = getNextBlock(*TrueBBI.BB);
902b915e9e0SDimitry Andric if (!TF)
903b915e9e0SDimitry Andric TF = getNextBlock(*TrueBBI.BB);
904b915e9e0SDimitry Andric if (!FT)
905b915e9e0SDimitry Andric FT = getNextBlock(*FalseBBI.BB);
906b915e9e0SDimitry Andric if (!FF)
907b915e9e0SDimitry Andric FF = getNextBlock(*FalseBBI.BB);
908b915e9e0SDimitry Andric
909b915e9e0SDimitry Andric if (!TT || !TF)
910b915e9e0SDimitry Andric return false;
911b915e9e0SDimitry Andric
912b915e9e0SDimitry Andric // Check successors. If they don't match, bail.
913b915e9e0SDimitry Andric if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
914b915e9e0SDimitry Andric return false;
915b915e9e0SDimitry Andric
916b915e9e0SDimitry Andric bool FalseReversed = false;
917b915e9e0SDimitry Andric if (TF == FT && TT == FF) {
918b915e9e0SDimitry Andric // If the branches are opposing, but we can't reverse, don't do it.
919b915e9e0SDimitry Andric if (!FalseBBI.IsBrReversible)
920b915e9e0SDimitry Andric return false;
921b915e9e0SDimitry Andric FalseReversed = true;
922b915e9e0SDimitry Andric reverseBranchCondition(FalseBBI);
923b915e9e0SDimitry Andric }
924b915e9e0SDimitry Andric auto UnReverseOnExit = make_scope_exit([&]() {
925b915e9e0SDimitry Andric if (FalseReversed)
926b915e9e0SDimitry Andric reverseBranchCondition(FalseBBI);
927b915e9e0SDimitry Andric });
928b915e9e0SDimitry Andric
929b915e9e0SDimitry Andric // Count duplicate instructions at the beginning of the true and false blocks.
930b915e9e0SDimitry Andric MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
931b915e9e0SDimitry Andric MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
932b915e9e0SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
933b915e9e0SDimitry Andric MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
934b915e9e0SDimitry Andric if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
935b915e9e0SDimitry Andric *TrueBBI.BB, *FalseBBI.BB,
936b915e9e0SDimitry Andric /* SkipUnconditionalBranches */ true))
937b915e9e0SDimitry Andric return false;
938b915e9e0SDimitry Andric
939b915e9e0SDimitry Andric TrueBBICalc.BB = TrueBBI.BB;
940b915e9e0SDimitry Andric FalseBBICalc.BB = FalseBBI.BB;
9411d5ae102SDimitry Andric TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
9421d5ae102SDimitry Andric FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
943b915e9e0SDimitry Andric if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
944b915e9e0SDimitry Andric return false;
945b915e9e0SDimitry Andric
946b915e9e0SDimitry Andric // The size is used to decide whether to if-convert, and the shared portions
947b915e9e0SDimitry Andric // are subtracted off. Because of the subtraction, we just use the size that
948b915e9e0SDimitry Andric // was calculated by the original ScanInstructions, as it is correct.
949b915e9e0SDimitry Andric TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
950b915e9e0SDimitry Andric FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
951b915e9e0SDimitry Andric return true;
952b915e9e0SDimitry Andric }
953b915e9e0SDimitry Andric
954009b1c42SEd Schouten /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
955009b1c42SEd Schouten /// with their common predecessor) forms a valid diamond shape for ifcvt.
ValidDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const956b915e9e0SDimitry Andric bool IfConverter::ValidDiamond(
957b915e9e0SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI,
958b915e9e0SDimitry Andric unsigned &Dups1, unsigned &Dups2,
959b915e9e0SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
960009b1c42SEd Schouten Dups1 = Dups2 = 0;
961009b1c42SEd Schouten if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
962009b1c42SEd Schouten FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
963009b1c42SEd Schouten return false;
964009b1c42SEd Schouten
965cfca06d7SDimitry Andric // If the True and False BBs are equal we're dealing with a degenerate case
966cfca06d7SDimitry Andric // that we don't treat as a diamond.
967cfca06d7SDimitry Andric if (TrueBBI.BB == FalseBBI.BB)
968cfca06d7SDimitry Andric return false;
969cfca06d7SDimitry Andric
970009b1c42SEd Schouten MachineBasicBlock *TT = TrueBBI.TrueBB;
971009b1c42SEd Schouten MachineBasicBlock *FT = FalseBBI.TrueBB;
972009b1c42SEd Schouten
973009b1c42SEd Schouten if (!TT && blockAlwaysFallThrough(TrueBBI))
974b915e9e0SDimitry Andric TT = getNextBlock(*TrueBBI.BB);
975009b1c42SEd Schouten if (!FT && blockAlwaysFallThrough(FalseBBI))
976b915e9e0SDimitry Andric FT = getNextBlock(*FalseBBI.BB);
977009b1c42SEd Schouten if (TT != FT)
978009b1c42SEd Schouten return false;
9795ca98fd9SDimitry Andric if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
980009b1c42SEd Schouten return false;
981009b1c42SEd Schouten if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
982009b1c42SEd Schouten return false;
983009b1c42SEd Schouten
984009b1c42SEd Schouten // FIXME: Allow true block to have an early exit?
985b915e9e0SDimitry Andric if (TrueBBI.FalseBB || FalseBBI.FalseBB)
986009b1c42SEd Schouten return false;
987009b1c42SEd Schouten
988b915e9e0SDimitry Andric // Count duplicate instructions at the beginning and end of the true and
989b915e9e0SDimitry Andric // false blocks.
990b915e9e0SDimitry Andric // Skip unconditional branches only if we are considering an analyzable
991b915e9e0SDimitry Andric // diamond. Otherwise the branches must be the same.
992b915e9e0SDimitry Andric bool SkipUnconditionalBranches =
993b915e9e0SDimitry Andric TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
99466e41e3cSRoman Divacky MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
99566e41e3cSRoman Divacky MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
996cf099d11SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
997cf099d11SDimitry Andric MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
998b915e9e0SDimitry Andric if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
999b915e9e0SDimitry Andric *TrueBBI.BB, *FalseBBI.BB,
1000b915e9e0SDimitry Andric SkipUnconditionalBranches))
1001b915e9e0SDimitry Andric return false;
1002cf099d11SDimitry Andric
1003b915e9e0SDimitry Andric TrueBBICalc.BB = TrueBBI.BB;
1004b915e9e0SDimitry Andric FalseBBICalc.BB = FalseBBI.BB;
10051d5ae102SDimitry Andric TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
10061d5ae102SDimitry Andric FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
1007b915e9e0SDimitry Andric if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
1008b915e9e0SDimitry Andric return false;
1009b915e9e0SDimitry Andric // The size is used to decide whether to if-convert, and the shared portions
1010b915e9e0SDimitry Andric // are subtracted off. Because of the subtraction, we just use the size that
1011b915e9e0SDimitry Andric // was calculated by the original ScanInstructions, as it is correct.
1012b915e9e0SDimitry Andric TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
1013b915e9e0SDimitry Andric FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
1014009b1c42SEd Schouten return true;
1015009b1c42SEd Schouten }
1016009b1c42SEd Schouten
1017b915e9e0SDimitry Andric /// AnalyzeBranches - Look at the branches at the end of a block to determine if
1018b915e9e0SDimitry Andric /// the block is predicable.
AnalyzeBranches(BBInfo & BBI)1019b915e9e0SDimitry Andric void IfConverter::AnalyzeBranches(BBInfo &BBI) {
1020009b1c42SEd Schouten if (BBI.IsDone)
1021009b1c42SEd Schouten return;
1022009b1c42SEd Schouten
10235ca98fd9SDimitry Andric BBI.TrueBB = BBI.FalseBB = nullptr;
1024009b1c42SEd Schouten BBI.BrCond.clear();
1025009b1c42SEd Schouten BBI.IsBrAnalyzable =
102601095a5dSDimitry Andric !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
10271d5ae102SDimitry Andric if (!BBI.IsBrAnalyzable) {
10281d5ae102SDimitry Andric BBI.TrueBB = nullptr;
10291d5ae102SDimitry Andric BBI.FalseBB = nullptr;
10301d5ae102SDimitry Andric BBI.BrCond.clear();
10311d5ae102SDimitry Andric }
10321d5ae102SDimitry Andric
1033b915e9e0SDimitry Andric SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1034b915e9e0SDimitry Andric BBI.IsBrReversible = (RevCond.size() == 0) ||
1035b915e9e0SDimitry Andric !TII->reverseBranchCondition(RevCond);
10365ca98fd9SDimitry Andric BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
1037009b1c42SEd Schouten
1038009b1c42SEd Schouten if (BBI.BrCond.size()) {
1039009b1c42SEd Schouten // No false branch. This BB must end with a conditional branch and a
1040009b1c42SEd Schouten // fallthrough.
1041009b1c42SEd Schouten if (!BBI.FalseBB)
1042009b1c42SEd Schouten BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
1043b2f21fb0SEd Schouten if (!BBI.FalseBB) {
1044b2f21fb0SEd Schouten // Malformed bcc? True and false blocks are the same?
1045b2f21fb0SEd Schouten BBI.IsUnpredicable = true;
1046b915e9e0SDimitry Andric }
1047b2f21fb0SEd Schouten }
1048009b1c42SEd Schouten }
1049009b1c42SEd Schouten
1050b915e9e0SDimitry Andric /// ScanInstructions - Scan all the instructions in the block to determine if
1051b915e9e0SDimitry Andric /// the block is predicable. In most cases, that means all the instructions
1052b915e9e0SDimitry Andric /// in the block are isPredicable(). Also checks if the block contains any
1053b915e9e0SDimitry Andric /// instruction which can clobber a predicate (e.g. condition code register).
1054b915e9e0SDimitry Andric /// If so, the block is not predicable unless it's the last instruction.
ScanInstructions(BBInfo & BBI,MachineBasicBlock::iterator & Begin,MachineBasicBlock::iterator & End,bool BranchUnpredicable) const1055b915e9e0SDimitry Andric void IfConverter::ScanInstructions(BBInfo &BBI,
1056b915e9e0SDimitry Andric MachineBasicBlock::iterator &Begin,
1057b915e9e0SDimitry Andric MachineBasicBlock::iterator &End,
1058b915e9e0SDimitry Andric bool BranchUnpredicable) const {
1059b915e9e0SDimitry Andric if (BBI.IsDone || BBI.IsUnpredicable)
1060b915e9e0SDimitry Andric return;
1061b915e9e0SDimitry Andric
1062b915e9e0SDimitry Andric bool AlreadyPredicated = !BBI.Predicate.empty();
1063b915e9e0SDimitry Andric
1064009b1c42SEd Schouten BBI.NonPredSize = 0;
1065cf099d11SDimitry Andric BBI.ExtraCost = 0;
1066cf099d11SDimitry Andric BBI.ExtraCost2 = 0;
1067009b1c42SEd Schouten BBI.ClobbersPred = false;
1068b915e9e0SDimitry Andric for (MachineInstr &MI : make_range(Begin, End)) {
1069eb11fae6SDimitry Andric if (MI.isDebugInstr())
107066e41e3cSRoman Divacky continue;
107166e41e3cSRoman Divacky
107201095a5dSDimitry Andric // It's unsafe to duplicate convergent instructions in this context, so set
107301095a5dSDimitry Andric // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
107401095a5dSDimitry Andric // following CFG, which is subject to our "simple" transformation.
107501095a5dSDimitry Andric //
107601095a5dSDimitry Andric // BB0 // if (c1) goto BB1; else goto BB2;
107701095a5dSDimitry Andric // / \
107801095a5dSDimitry Andric // BB1 |
107901095a5dSDimitry Andric // | BB2 // if (c2) goto TBB; else goto FBB;
108001095a5dSDimitry Andric // | / |
108101095a5dSDimitry Andric // | / |
108201095a5dSDimitry Andric // TBB |
108301095a5dSDimitry Andric // | |
108401095a5dSDimitry Andric // | FBB
108501095a5dSDimitry Andric // |
108601095a5dSDimitry Andric // exit
108701095a5dSDimitry Andric //
108801095a5dSDimitry Andric // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
108901095a5dSDimitry Andric // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
109001095a5dSDimitry Andric // TBB contains a convergent instruction. This is safe iff doing so does
109101095a5dSDimitry Andric // not add a control-flow dependency to the convergent instruction -- i.e.,
109201095a5dSDimitry Andric // it's safe iff the set of control flows that leads us to the convergent
109301095a5dSDimitry Andric // instruction does not get smaller after the transformation.
109401095a5dSDimitry Andric //
109501095a5dSDimitry Andric // Originally we executed TBB if c1 || c2. After the transformation, there
109601095a5dSDimitry Andric // are two copies of TBB's instructions. We get to the first if c1, and we
109701095a5dSDimitry Andric // get to the second if !c1 && c2.
109801095a5dSDimitry Andric //
109901095a5dSDimitry Andric // There are clearly fewer ways to satisfy the condition "c1" than
110001095a5dSDimitry Andric // "c1 || c2". Since we've shrunk the set of control flows which lead to
110101095a5dSDimitry Andric // our convergent instruction, the transformation is unsafe.
110201095a5dSDimitry Andric if (MI.isNotDuplicable() || MI.isConvergent())
1103009b1c42SEd Schouten BBI.CannotBeCopied = true;
1104009b1c42SEd Schouten
110501095a5dSDimitry Andric bool isPredicated = TII->isPredicated(MI);
110601095a5dSDimitry Andric bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
1107009b1c42SEd Schouten
1108b915e9e0SDimitry Andric if (BranchUnpredicable && MI.isBranch()) {
1109b915e9e0SDimitry Andric BBI.IsUnpredicable = true;
1110b915e9e0SDimitry Andric return;
1111b915e9e0SDimitry Andric }
1112b915e9e0SDimitry Andric
1113f8af5cf6SDimitry Andric // A conditional branch is not predicable, but it may be eliminated.
1114f8af5cf6SDimitry Andric if (isCondBr)
1115f8af5cf6SDimitry Andric continue;
1116f8af5cf6SDimitry Andric
1117cf099d11SDimitry Andric if (!isPredicated) {
1118009b1c42SEd Schouten BBI.NonPredSize++;
111901095a5dSDimitry Andric unsigned ExtraPredCost = TII->getPredicationCost(MI);
112001095a5dSDimitry Andric unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1121cf099d11SDimitry Andric if (NumCycles > 1)
1122cf099d11SDimitry Andric BBI.ExtraCost += NumCycles-1;
1123cf099d11SDimitry Andric BBI.ExtraCost2 += ExtraPredCost;
1124cf099d11SDimitry Andric } else if (!AlreadyPredicated) {
1125009b1c42SEd Schouten // FIXME: This instruction is already predicated before the
1126009b1c42SEd Schouten // if-conversion pass. It's probably something like a conditional move.
1127009b1c42SEd Schouten // Mark this block unpredicable for now.
1128009b1c42SEd Schouten BBI.IsUnpredicable = true;
1129009b1c42SEd Schouten return;
1130009b1c42SEd Schouten }
1131009b1c42SEd Schouten
1132009b1c42SEd Schouten if (BBI.ClobbersPred && !isPredicated) {
1133009b1c42SEd Schouten // Predicate modification instruction should end the block (except for
1134009b1c42SEd Schouten // already predicated instructions and end of block branches).
1135009b1c42SEd Schouten // Predicate may have been modified, the subsequent (currently)
1136009b1c42SEd Schouten // unpredicated instructions cannot be correctly predicated.
1137009b1c42SEd Schouten BBI.IsUnpredicable = true;
1138009b1c42SEd Schouten return;
1139009b1c42SEd Schouten }
1140009b1c42SEd Schouten
1141009b1c42SEd Schouten // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1142009b1c42SEd Schouten // still potentially predicable.
1143009b1c42SEd Schouten std::vector<MachineOperand> PredDefs;
1144b60736ecSDimitry Andric if (TII->ClobbersPredicate(MI, PredDefs, true))
1145009b1c42SEd Schouten BBI.ClobbersPred = true;
1146009b1c42SEd Schouten
114701095a5dSDimitry Andric if (!TII->isPredicable(MI)) {
1148009b1c42SEd Schouten BBI.IsUnpredicable = true;
1149009b1c42SEd Schouten return;
1150009b1c42SEd Schouten }
1151009b1c42SEd Schouten }
1152009b1c42SEd Schouten }
1153009b1c42SEd Schouten
1154b915e9e0SDimitry Andric /// Determine if the block is a suitable candidate to be predicated by the
1155b915e9e0SDimitry Andric /// specified predicate.
1156b915e9e0SDimitry Andric /// @param BBI BBInfo for the block to check
1157b915e9e0SDimitry Andric /// @param Pred Predicate array for the branch that leads to BBI
1158b915e9e0SDimitry Andric /// @param isTriangle true if the Analysis is for a triangle
1159b915e9e0SDimitry Andric /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1160b915e9e0SDimitry Andric /// case
1161b915e9e0SDimitry Andric /// @param hasCommonTail true if BBI shares a tail with a sibling block that
1162b915e9e0SDimitry Andric /// contains any instruction that would make the block unpredicable.
FeasibilityAnalysis(BBInfo & BBI,SmallVectorImpl<MachineOperand> & Pred,bool isTriangle,bool RevBranch,bool hasCommonTail)1163009b1c42SEd Schouten bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1164009b1c42SEd Schouten SmallVectorImpl<MachineOperand> &Pred,
1165b915e9e0SDimitry Andric bool isTriangle, bool RevBranch,
1166b915e9e0SDimitry Andric bool hasCommonTail) {
1167009b1c42SEd Schouten // If the block is dead or unpredicable, then it cannot be predicated.
1168b915e9e0SDimitry Andric // Two blocks may share a common unpredicable tail, but this doesn't prevent
1169b915e9e0SDimitry Andric // them from being if-converted. The non-shared portion is assumed to have
1170b915e9e0SDimitry Andric // been checked
1171b915e9e0SDimitry Andric if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1172009b1c42SEd Schouten return false;
1173009b1c42SEd Schouten
11745a5ac124SDimitry Andric // If it is already predicated but we couldn't analyze its terminator, the
11755a5ac124SDimitry Andric // latter might fallthrough, but we can't determine where to.
11765a5ac124SDimitry Andric // Conservatively avoid if-converting again.
11775a5ac124SDimitry Andric if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
11785a5ac124SDimitry Andric return false;
11795a5ac124SDimitry Andric
1180f8af5cf6SDimitry Andric // If it is already predicated, check if the new predicate subsumes
1181f8af5cf6SDimitry Andric // its predicate.
1182f8af5cf6SDimitry Andric if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1183009b1c42SEd Schouten return false;
1184009b1c42SEd Schouten
1185b915e9e0SDimitry Andric if (!hasCommonTail && BBI.BrCond.size()) {
1186009b1c42SEd Schouten if (!isTriangle)
1187009b1c42SEd Schouten return false;
1188009b1c42SEd Schouten
1189009b1c42SEd Schouten // Test predicate subsumption.
1190009b1c42SEd Schouten SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1191009b1c42SEd Schouten SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1192009b1c42SEd Schouten if (RevBranch) {
1193b915e9e0SDimitry Andric if (TII->reverseBranchCondition(Cond))
1194009b1c42SEd Schouten return false;
1195009b1c42SEd Schouten }
1196b915e9e0SDimitry Andric if (TII->reverseBranchCondition(RevPred) ||
1197009b1c42SEd Schouten !TII->SubsumesPredicate(Cond, RevPred))
1198009b1c42SEd Schouten return false;
1199009b1c42SEd Schouten }
1200009b1c42SEd Schouten
1201009b1c42SEd Schouten return true;
1202009b1c42SEd Schouten }
1203009b1c42SEd Schouten
1204b915e9e0SDimitry Andric /// Analyze the structure of the sub-CFG starting from the specified block.
1205b915e9e0SDimitry Andric /// Record its successors and whether it looks like an if-conversion candidate.
AnalyzeBlock(MachineBasicBlock & MBB,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)120601095a5dSDimitry Andric void IfConverter::AnalyzeBlock(
1207b915e9e0SDimitry Andric MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
12081a82d4c0SDimitry Andric struct BBState {
1209ecbca9f5SDimitry Andric BBState(MachineBasicBlock &MBB) : MBB(&MBB) {}
12101a82d4c0SDimitry Andric MachineBasicBlock *MBB;
12111a82d4c0SDimitry Andric
12121a82d4c0SDimitry Andric /// This flag is true if MBB's successors have been analyzed.
1213ecbca9f5SDimitry Andric bool SuccsAnalyzed = false;
12141a82d4c0SDimitry Andric };
12151a82d4c0SDimitry Andric
12161a82d4c0SDimitry Andric // Push MBB to the stack.
12171a82d4c0SDimitry Andric SmallVector<BBState, 16> BBStack(1, MBB);
12181a82d4c0SDimitry Andric
12191a82d4c0SDimitry Andric while (!BBStack.empty()) {
12201a82d4c0SDimitry Andric BBState &State = BBStack.back();
12211a82d4c0SDimitry Andric MachineBasicBlock *BB = State.MBB;
1222009b1c42SEd Schouten BBInfo &BBI = BBAnalysis[BB->getNumber()];
1223009b1c42SEd Schouten
12241a82d4c0SDimitry Andric if (!State.SuccsAnalyzed) {
12251a82d4c0SDimitry Andric if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
12261a82d4c0SDimitry Andric BBStack.pop_back();
12271a82d4c0SDimitry Andric continue;
12281a82d4c0SDimitry Andric }
1229009b1c42SEd Schouten
1230009b1c42SEd Schouten BBI.BB = BB;
1231009b1c42SEd Schouten BBI.IsBeingAnalyzed = true;
1232009b1c42SEd Schouten
1233b915e9e0SDimitry Andric AnalyzeBranches(BBI);
1234b915e9e0SDimitry Andric MachineBasicBlock::iterator Begin = BBI.BB->begin();
1235b915e9e0SDimitry Andric MachineBasicBlock::iterator End = BBI.BB->end();
1236b915e9e0SDimitry Andric ScanInstructions(BBI, Begin, End);
1237009b1c42SEd Schouten
12381a82d4c0SDimitry Andric // Unanalyzable or ends with fallthrough or unconditional branch, or if is
12391a82d4c0SDimitry Andric // not considered for ifcvt anymore.
1240411bd29eSDimitry Andric if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1241009b1c42SEd Schouten BBI.IsBeingAnalyzed = false;
1242009b1c42SEd Schouten BBI.IsAnalyzed = true;
12431a82d4c0SDimitry Andric BBStack.pop_back();
12441a82d4c0SDimitry Andric continue;
1245009b1c42SEd Schouten }
1246009b1c42SEd Schouten
1247009b1c42SEd Schouten // Do not ifcvt if either path is a back edge to the entry block.
1248009b1c42SEd Schouten if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1249009b1c42SEd Schouten BBI.IsBeingAnalyzed = false;
1250009b1c42SEd Schouten BBI.IsAnalyzed = true;
12511a82d4c0SDimitry Andric BBStack.pop_back();
12521a82d4c0SDimitry Andric continue;
1253009b1c42SEd Schouten }
1254009b1c42SEd Schouten
1255b2f21fb0SEd Schouten // Do not ifcvt if true and false fallthrough blocks are the same.
1256b2f21fb0SEd Schouten if (!BBI.FalseBB) {
1257b2f21fb0SEd Schouten BBI.IsBeingAnalyzed = false;
1258b2f21fb0SEd Schouten BBI.IsAnalyzed = true;
12591a82d4c0SDimitry Andric BBStack.pop_back();
12601a82d4c0SDimitry Andric continue;
1261b2f21fb0SEd Schouten }
1262b2f21fb0SEd Schouten
12631a82d4c0SDimitry Andric // Push the False and True blocks to the stack.
12641a82d4c0SDimitry Andric State.SuccsAnalyzed = true;
1265b915e9e0SDimitry Andric BBStack.push_back(*BBI.FalseBB);
1266b915e9e0SDimitry Andric BBStack.push_back(*BBI.TrueBB);
12671a82d4c0SDimitry Andric continue;
12681a82d4c0SDimitry Andric }
12691a82d4c0SDimitry Andric
12701a82d4c0SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
12711a82d4c0SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1272009b1c42SEd Schouten
1273009b1c42SEd Schouten if (TrueBBI.IsDone && FalseBBI.IsDone) {
1274009b1c42SEd Schouten BBI.IsBeingAnalyzed = false;
1275009b1c42SEd Schouten BBI.IsAnalyzed = true;
12761a82d4c0SDimitry Andric BBStack.pop_back();
12771a82d4c0SDimitry Andric continue;
1278009b1c42SEd Schouten }
1279009b1c42SEd Schouten
12801a82d4c0SDimitry Andric SmallVector<MachineOperand, 4>
12811a82d4c0SDimitry Andric RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1282b915e9e0SDimitry Andric bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1283009b1c42SEd Schouten
1284009b1c42SEd Schouten unsigned Dups = 0;
1285009b1c42SEd Schouten unsigned Dups2 = 0;
128658b69754SDimitry Andric bool TNeedSub = !TrueBBI.Predicate.empty();
128758b69754SDimitry Andric bool FNeedSub = !FalseBBI.Predicate.empty();
1288009b1c42SEd Schouten bool Enqueued = false;
1289cf099d11SDimitry Andric
129030815c53SDimitry Andric BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1291cf099d11SDimitry Andric
1292b915e9e0SDimitry Andric if (CanRevCond) {
1293b915e9e0SDimitry Andric BBInfo TrueBBICalc, FalseBBICalc;
12941d5ae102SDimitry Andric auto feasibleDiamond = [&](bool Forked) {
12951d5ae102SDimitry Andric bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
12961d5ae102SDimitry Andric Dups + Dups2, Prediction, Forked);
1297b915e9e0SDimitry Andric bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1298b915e9e0SDimitry Andric /* IsTriangle */ false, /* RevCond */ false,
1299b915e9e0SDimitry Andric /* hasCommonTail */ true);
1300b915e9e0SDimitry Andric bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1301b915e9e0SDimitry Andric /* IsTriangle */ false, /* RevCond */ false,
1302b915e9e0SDimitry Andric /* hasCommonTail */ true);
1303b915e9e0SDimitry Andric return MeetsSize && TrueFeasible && FalseFeasible;
1304b915e9e0SDimitry Andric };
1305b915e9e0SDimitry Andric
1306b915e9e0SDimitry Andric if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1307b915e9e0SDimitry Andric TrueBBICalc, FalseBBICalc)) {
13081d5ae102SDimitry Andric if (feasibleDiamond(false)) {
1309009b1c42SEd Schouten // Diamond:
1310009b1c42SEd Schouten // EBB
1311009b1c42SEd Schouten // / \_
1312009b1c42SEd Schouten // | |
1313009b1c42SEd Schouten // TBB FBB
1314009b1c42SEd Schouten // \ /
1315009b1c42SEd Schouten // TailBB
1316009b1c42SEd Schouten // Note TailBB can be empty.
13171d5ae102SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(
1318b915e9e0SDimitry Andric BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1319b915e9e0SDimitry Andric (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1320009b1c42SEd Schouten Enqueued = true;
1321009b1c42SEd Schouten }
1322b915e9e0SDimitry Andric } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1323b915e9e0SDimitry Andric TrueBBICalc, FalseBBICalc)) {
13241d5ae102SDimitry Andric if (feasibleDiamond(true)) {
1325b915e9e0SDimitry Andric // ForkedDiamond:
1326b915e9e0SDimitry Andric // if TBB and FBB have a common tail that includes their conditional
1327b915e9e0SDimitry Andric // branch instructions, then we can If Convert this pattern.
1328b915e9e0SDimitry Andric // EBB
1329b915e9e0SDimitry Andric // _/ \_
1330b915e9e0SDimitry Andric // | |
1331b915e9e0SDimitry Andric // TBB FBB
1332b915e9e0SDimitry Andric // / \ / \
1333b915e9e0SDimitry Andric // FalseBB TrueBB FalseBB
1334b915e9e0SDimitry Andric //
13351d5ae102SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(
1336b915e9e0SDimitry Andric BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1337b915e9e0SDimitry Andric (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1338b915e9e0SDimitry Andric Enqueued = true;
1339b915e9e0SDimitry Andric }
1340b915e9e0SDimitry Andric }
1341b915e9e0SDimitry Andric }
1342009b1c42SEd Schouten
1343411bd29eSDimitry Andric if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1344cf099d11SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1345411bd29eSDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
1346009b1c42SEd Schouten FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1347009b1c42SEd Schouten // Triangle:
1348009b1c42SEd Schouten // EBB
1349009b1c42SEd Schouten // | \_
1350009b1c42SEd Schouten // | |
1351009b1c42SEd Schouten // | TBB
1352009b1c42SEd Schouten // | /
1353009b1c42SEd Schouten // FBB
135401095a5dSDimitry Andric Tokens.push_back(
13551d5ae102SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1356009b1c42SEd Schouten Enqueued = true;
1357009b1c42SEd Schouten }
1358009b1c42SEd Schouten
1359411bd29eSDimitry Andric if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1360cf099d11SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1361411bd29eSDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
1362009b1c42SEd Schouten FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
136301095a5dSDimitry Andric Tokens.push_back(
13641d5ae102SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1365009b1c42SEd Schouten Enqueued = true;
1366009b1c42SEd Schouten }
1367009b1c42SEd Schouten
1368411bd29eSDimitry Andric if (ValidSimple(TrueBBI, Dups, Prediction) &&
1369cf099d11SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1370411bd29eSDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
1371009b1c42SEd Schouten FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1372009b1c42SEd Schouten // Simple (split, no rejoin):
1373009b1c42SEd Schouten // EBB
1374009b1c42SEd Schouten // | \_
1375009b1c42SEd Schouten // | |
1376009b1c42SEd Schouten // | TBB---> exit
1377009b1c42SEd Schouten // |
1378009b1c42SEd Schouten // FBB
137901095a5dSDimitry Andric Tokens.push_back(
13801d5ae102SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1381009b1c42SEd Schouten Enqueued = true;
1382009b1c42SEd Schouten }
1383009b1c42SEd Schouten
1384009b1c42SEd Schouten if (CanRevCond) {
1385009b1c42SEd Schouten // Try the other path...
1386cf099d11SDimitry Andric if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1387411bd29eSDimitry Andric Prediction.getCompl()) &&
1388cf099d11SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
1389cf099d11SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1390411bd29eSDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1391009b1c42SEd Schouten FeasibilityAnalysis(FalseBBI, RevCond, true)) {
13921d5ae102SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
139301095a5dSDimitry Andric FNeedSub, Dups));
1394009b1c42SEd Schouten Enqueued = true;
1395009b1c42SEd Schouten }
1396009b1c42SEd Schouten
1397cf099d11SDimitry Andric if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1398411bd29eSDimitry Andric Prediction.getCompl()) &&
1399cf099d11SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
1400cf099d11SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1401411bd29eSDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1402009b1c42SEd Schouten FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
140301095a5dSDimitry Andric Tokens.push_back(
14041d5ae102SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1405009b1c42SEd Schouten Enqueued = true;
1406009b1c42SEd Schouten }
1407009b1c42SEd Schouten
1408411bd29eSDimitry Andric if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1409cf099d11SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
1410cf099d11SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1411411bd29eSDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1412009b1c42SEd Schouten FeasibilityAnalysis(FalseBBI, RevCond)) {
141301095a5dSDimitry Andric Tokens.push_back(
14141d5ae102SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1415009b1c42SEd Schouten Enqueued = true;
1416009b1c42SEd Schouten }
1417009b1c42SEd Schouten }
1418009b1c42SEd Schouten
1419009b1c42SEd Schouten BBI.IsEnqueued = Enqueued;
1420009b1c42SEd Schouten BBI.IsBeingAnalyzed = false;
1421009b1c42SEd Schouten BBI.IsAnalyzed = true;
14221a82d4c0SDimitry Andric BBStack.pop_back();
14231a82d4c0SDimitry Andric }
1424009b1c42SEd Schouten }
1425009b1c42SEd Schouten
1426b915e9e0SDimitry Andric /// Analyze all blocks and find entries for all if-conversion candidates.
AnalyzeBlocks(MachineFunction & MF,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)142701095a5dSDimitry Andric void IfConverter::AnalyzeBlocks(
142801095a5dSDimitry Andric MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1429b915e9e0SDimitry Andric for (MachineBasicBlock &MBB : MF)
1430b915e9e0SDimitry Andric AnalyzeBlock(MBB, Tokens);
1431009b1c42SEd Schouten
1432009b1c42SEd Schouten // Sort to favor more complex ifcvt scheme.
1433e6d15924SDimitry Andric llvm::stable_sort(Tokens, IfcvtTokenCmp);
1434009b1c42SEd Schouten }
1435009b1c42SEd Schouten
1436b915e9e0SDimitry Andric /// Returns true either if ToMBB is the next block after MBB or that all the
1437b915e9e0SDimitry Andric /// intervening blocks are empty (given MBB can fall through to its next block).
canFallThroughTo(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB)1438b915e9e0SDimitry Andric static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1439b915e9e0SDimitry Andric MachineFunction::iterator PI = MBB.getIterator();
14405ca98fd9SDimitry Andric MachineFunction::iterator I = std::next(PI);
1441b915e9e0SDimitry Andric MachineFunction::iterator TI = ToMBB.getIterator();
1442b915e9e0SDimitry Andric MachineFunction::iterator E = MBB.getParent()->end();
144366e41e3cSRoman Divacky while (I != TI) {
144466e41e3cSRoman Divacky // Check isSuccessor to avoid case where the next block is empty, but
144566e41e3cSRoman Divacky // it's not a successor.
1446dd58ef01SDimitry Andric if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1447009b1c42SEd Schouten return false;
144866e41e3cSRoman Divacky PI = I++;
144966e41e3cSRoman Divacky }
14506b3f41edSDimitry Andric // Finally see if the last I is indeed a successor to PI.
14516b3f41edSDimitry Andric return PI->isSuccessor(&*I);
1452009b1c42SEd Schouten }
1453009b1c42SEd Schouten
1454b915e9e0SDimitry Andric /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1455b915e9e0SDimitry Andric /// can be if-converted. If predecessor is already enqueued, dequeue it!
InvalidatePreds(MachineBasicBlock & MBB)1456b915e9e0SDimitry Andric void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1457b915e9e0SDimitry Andric for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
145867c32a98SDimitry Andric BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1459b915e9e0SDimitry Andric if (PBBI.IsDone || PBBI.BB == &MBB)
1460009b1c42SEd Schouten continue;
1461009b1c42SEd Schouten PBBI.IsAnalyzed = false;
1462009b1c42SEd Schouten PBBI.IsEnqueued = false;
1463009b1c42SEd Schouten }
1464009b1c42SEd Schouten }
1465009b1c42SEd Schouten
1466b915e9e0SDimitry Andric /// Inserts an unconditional branch from \p MBB to \p ToMBB.
InsertUncondBranch(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB,const TargetInstrInfo * TII)1467b915e9e0SDimitry Andric static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
1468009b1c42SEd Schouten const TargetInstrInfo *TII) {
146966e41e3cSRoman Divacky DebugLoc dl; // FIXME: this is nowhere
1470009b1c42SEd Schouten SmallVector<MachineOperand, 0> NoCond;
1471b915e9e0SDimitry Andric TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1472009b1c42SEd Schouten }
1473009b1c42SEd Schouten
1474f8af5cf6SDimitry Andric /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1475b915e9e0SDimitry Andric /// values defined in MI which are also live/used by MI.
UpdatePredRedefs(MachineInstr & MI,LivePhysRegs & Redefs)147601095a5dSDimitry Andric static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1477044eb2f6SDimitry Andric const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
1478b915e9e0SDimitry Andric
1479b915e9e0SDimitry Andric // Before stepping forward past MI, remember which regs were live
1480b915e9e0SDimitry Andric // before MI. This is needed to set the Undef flag only when reg is
1481b915e9e0SDimitry Andric // dead.
1482d8e91e46SDimitry Andric SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
1483b915e9e0SDimitry Andric LiveBeforeMI.setUniverse(TRI->getNumRegs());
1484b915e9e0SDimitry Andric for (unsigned Reg : Redefs)
1485b915e9e0SDimitry Andric LiveBeforeMI.insert(Reg);
1486b915e9e0SDimitry Andric
1487d8e91e46SDimitry Andric SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
148801095a5dSDimitry Andric Redefs.stepForward(MI, Clobbers);
148966e41e3cSRoman Divacky
14905a5ac124SDimitry Andric // Now add the implicit uses for each of the clobbered values.
1491b915e9e0SDimitry Andric for (auto Clobber : Clobbers) {
14925a5ac124SDimitry Andric // FIXME: Const cast here is nasty, but better than making StepForward
14935a5ac124SDimitry Andric // take a mutable instruction instead of const.
1494b915e9e0SDimitry Andric unsigned Reg = Clobber.first;
1495b915e9e0SDimitry Andric MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
14965a5ac124SDimitry Andric MachineInstr *OpMI = Op.getParent();
1497044eb2f6SDimitry Andric MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
14985a5ac124SDimitry Andric if (Op.isRegMask()) {
14995a5ac124SDimitry Andric // First handle regmasks. They clobber any entries in the mask which
15005a5ac124SDimitry Andric // means that we need a def for those registers.
1501b915e9e0SDimitry Andric if (LiveBeforeMI.count(Reg))
1502b915e9e0SDimitry Andric MIB.addReg(Reg, RegState::Implicit);
15035a5ac124SDimitry Andric
15045a5ac124SDimitry Andric // We also need to add an implicit def of this register for the later
15055a5ac124SDimitry Andric // use to read from.
15065a5ac124SDimitry Andric // For the register allocator to have allocated a register clobbered
15075a5ac124SDimitry Andric // by the call which is used later, it must be the case that
15085a5ac124SDimitry Andric // the call doesn't return.
1509b915e9e0SDimitry Andric MIB.addReg(Reg, RegState::Implicit | RegState::Define);
15105a5ac124SDimitry Andric continue;
15115a5ac124SDimitry Andric }
15127fa27ce4SDimitry Andric if (any_of(TRI->subregs_inclusive(Reg),
15137fa27ce4SDimitry Andric [&](MCPhysReg S) { return LiveBeforeMI.count(S); }))
1514b915e9e0SDimitry Andric MIB.addReg(Reg, RegState::Implicit);
151566e41e3cSRoman Divacky }
151666e41e3cSRoman Divacky }
151766e41e3cSRoman Divacky
1518b915e9e0SDimitry Andric /// If convert a simple (split, no rejoin) sub-CFG.
IfConvertSimple(BBInfo & BBI,IfcvtKind Kind)1519009b1c42SEd Schouten bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1520009b1c42SEd Schouten BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1521009b1c42SEd Schouten BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1522009b1c42SEd Schouten BBInfo *CvtBBI = &TrueBBI;
1523009b1c42SEd Schouten BBInfo *NextBBI = &FalseBBI;
1524009b1c42SEd Schouten
1525009b1c42SEd Schouten SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1526009b1c42SEd Schouten if (Kind == ICSimpleFalse)
1527009b1c42SEd Schouten std::swap(CvtBBI, NextBBI);
1528009b1c42SEd Schouten
1529b915e9e0SDimitry Andric MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1530b915e9e0SDimitry Andric MachineBasicBlock &NextMBB = *NextBBI->BB;
1531009b1c42SEd Schouten if (CvtBBI->IsDone ||
1532b915e9e0SDimitry Andric (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1533009b1c42SEd Schouten // Something has changed. It's no longer safe to predicate this block.
1534009b1c42SEd Schouten BBI.IsAnalyzed = false;
1535009b1c42SEd Schouten CvtBBI->IsAnalyzed = false;
1536009b1c42SEd Schouten return false;
1537009b1c42SEd Schouten }
1538009b1c42SEd Schouten
1539b915e9e0SDimitry Andric if (CvtMBB.hasAddressTaken())
154059d6cff9SDimitry Andric // Conservatively abort if-conversion if BB's address is taken.
154159d6cff9SDimitry Andric return false;
154259d6cff9SDimitry Andric
1543009b1c42SEd Schouten if (Kind == ICSimpleFalse)
1544b915e9e0SDimitry Andric if (TII->reverseBranchCondition(Cond))
154563faed5bSDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
1546009b1c42SEd Schouten
15477e7b6700SDimitry Andric Redefs.init(*TRI);
15487e7b6700SDimitry Andric
15497e7b6700SDimitry Andric if (MRI->tracksLiveness()) {
1550d8e91e46SDimitry Andric // Initialize liveins to the first BB. These are potentially redefined by
155166e41e3cSRoman Divacky // predicated instructions.
1552344a3780SDimitry Andric Redefs.addLiveInsNoPristines(CvtMBB);
1553344a3780SDimitry Andric Redefs.addLiveInsNoPristines(NextMBB);
15547e7b6700SDimitry Andric }
155566e41e3cSRoman Divacky
155608bbd35aSDimitry Andric // Remove the branches from the entry so we can add the contents of the true
155708bbd35aSDimitry Andric // block to it.
1558b915e9e0SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
155908bbd35aSDimitry Andric
156008bbd35aSDimitry Andric if (CvtMBB.pred_size() > 1) {
1561009b1c42SEd Schouten // Copy instructions in the true block, predicate them, and add them to
1562009b1c42SEd Schouten // the entry block.
1563f8af5cf6SDimitry Andric CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
156459d6cff9SDimitry Andric
1565044eb2f6SDimitry Andric // Keep the CFG updated.
1566b915e9e0SDimitry Andric BBI.BB->removeSuccessor(&CvtMBB, true);
1567009b1c42SEd Schouten } else {
156808bbd35aSDimitry Andric // Predicate the instructions in the true block.
1569b915e9e0SDimitry Andric PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1570009b1c42SEd Schouten
1571044eb2f6SDimitry Andric // Merge converted block into entry block. The BB to Cvt edge is removed
1572044eb2f6SDimitry Andric // by MergeBlocks.
1573009b1c42SEd Schouten MergeBlocks(BBI, *CvtBBI);
1574009b1c42SEd Schouten }
1575009b1c42SEd Schouten
1576009b1c42SEd Schouten bool IterIfcvt = true;
1577b915e9e0SDimitry Andric if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1578b915e9e0SDimitry Andric InsertUncondBranch(*BBI.BB, NextMBB, TII);
1579009b1c42SEd Schouten BBI.HasFallThrough = false;
1580009b1c42SEd Schouten // Now ifcvt'd block will look like this:
1581009b1c42SEd Schouten // BB:
1582009b1c42SEd Schouten // ...
1583009b1c42SEd Schouten // t, f = cmp
1584009b1c42SEd Schouten // if t op
1585009b1c42SEd Schouten // b BBf
1586009b1c42SEd Schouten //
1587009b1c42SEd Schouten // We cannot further ifcvt this block because the unconditional branch
1588009b1c42SEd Schouten // will have to be predicated on the new condition, that will not be
1589009b1c42SEd Schouten // available if cmp executes.
1590009b1c42SEd Schouten IterIfcvt = false;
1591009b1c42SEd Schouten }
1592009b1c42SEd Schouten
1593009b1c42SEd Schouten // Update block info. BB can be iteratively if-converted.
1594009b1c42SEd Schouten if (!IterIfcvt)
1595009b1c42SEd Schouten BBI.IsDone = true;
1596b915e9e0SDimitry Andric InvalidatePreds(*BBI.BB);
1597009b1c42SEd Schouten CvtBBI->IsDone = true;
1598009b1c42SEd Schouten
1599009b1c42SEd Schouten // FIXME: Must maintain LiveIns.
1600009b1c42SEd Schouten return true;
1601009b1c42SEd Schouten }
1602009b1c42SEd Schouten
1603b915e9e0SDimitry Andric /// If convert a triangle sub-CFG.
IfConvertTriangle(BBInfo & BBI,IfcvtKind Kind)1604009b1c42SEd Schouten bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1605009b1c42SEd Schouten BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1606009b1c42SEd Schouten BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1607009b1c42SEd Schouten BBInfo *CvtBBI = &TrueBBI;
1608009b1c42SEd Schouten BBInfo *NextBBI = &FalseBBI;
160966e41e3cSRoman Divacky DebugLoc dl; // FIXME: this is nowhere
1610009b1c42SEd Schouten
1611009b1c42SEd Schouten SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1612009b1c42SEd Schouten if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1613009b1c42SEd Schouten std::swap(CvtBBI, NextBBI);
1614009b1c42SEd Schouten
1615b915e9e0SDimitry Andric MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1616b915e9e0SDimitry Andric MachineBasicBlock &NextMBB = *NextBBI->BB;
1617009b1c42SEd Schouten if (CvtBBI->IsDone ||
1618b915e9e0SDimitry Andric (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1619009b1c42SEd Schouten // Something has changed. It's no longer safe to predicate this block.
1620009b1c42SEd Schouten BBI.IsAnalyzed = false;
1621009b1c42SEd Schouten CvtBBI->IsAnalyzed = false;
1622009b1c42SEd Schouten return false;
1623009b1c42SEd Schouten }
1624009b1c42SEd Schouten
1625b915e9e0SDimitry Andric if (CvtMBB.hasAddressTaken())
162659d6cff9SDimitry Andric // Conservatively abort if-conversion if BB's address is taken.
162759d6cff9SDimitry Andric return false;
162859d6cff9SDimitry Andric
1629009b1c42SEd Schouten if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1630b915e9e0SDimitry Andric if (TII->reverseBranchCondition(Cond))
163163faed5bSDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
1632009b1c42SEd Schouten
1633009b1c42SEd Schouten if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1634b915e9e0SDimitry Andric if (reverseBranchCondition(*CvtBBI)) {
1635009b1c42SEd Schouten // BB has been changed, modify its predecessors (except for this
1636009b1c42SEd Schouten // one) so they don't get ifcvt'ed based on bad intel.
1637b915e9e0SDimitry Andric for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1638009b1c42SEd Schouten if (PBB == BBI.BB)
1639009b1c42SEd Schouten continue;
1640009b1c42SEd Schouten BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1641009b1c42SEd Schouten if (PBBI.IsEnqueued) {
1642009b1c42SEd Schouten PBBI.IsAnalyzed = false;
1643009b1c42SEd Schouten PBBI.IsEnqueued = false;
1644009b1c42SEd Schouten }
1645009b1c42SEd Schouten }
1646009b1c42SEd Schouten }
1647009b1c42SEd Schouten }
1648009b1c42SEd Schouten
164966e41e3cSRoman Divacky // Initialize liveins to the first BB. These are potentially redefined by
165066e41e3cSRoman Divacky // predicated instructions.
1651b915e9e0SDimitry Andric Redefs.init(*TRI);
16527e7b6700SDimitry Andric if (MRI->tracksLiveness()) {
1653344a3780SDimitry Andric Redefs.addLiveInsNoPristines(CvtMBB);
1654344a3780SDimitry Andric Redefs.addLiveInsNoPristines(NextMBB);
16557e7b6700SDimitry Andric }
1656f8af5cf6SDimitry Andric
16575ca98fd9SDimitry Andric bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1658dd58ef01SDimitry Andric BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
165967c32a98SDimitry Andric
16605ca98fd9SDimitry Andric if (HasEarlyExit) {
1661b915e9e0SDimitry Andric // Get probabilities before modifying CvtMBB and BBI.BB.
1662b915e9e0SDimitry Andric CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1663b915e9e0SDimitry Andric CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1664b915e9e0SDimitry Andric BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1665b915e9e0SDimitry Andric BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
16665ca98fd9SDimitry Andric }
166767c32a98SDimitry Andric
166808bbd35aSDimitry Andric // Remove the branches from the entry so we can add the contents of the true
166908bbd35aSDimitry Andric // block to it.
1670b915e9e0SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
167108bbd35aSDimitry Andric
167208bbd35aSDimitry Andric if (CvtMBB.pred_size() > 1) {
1673009b1c42SEd Schouten // Copy instructions in the true block, predicate them, and add them to
1674009b1c42SEd Schouten // the entry block.
1675f8af5cf6SDimitry Andric CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1676009b1c42SEd Schouten } else {
1677009b1c42SEd Schouten // Predicate the 'true' block after removing its branch.
1678b915e9e0SDimitry Andric CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1679b915e9e0SDimitry Andric PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1680009b1c42SEd Schouten
16816b3f41edSDimitry Andric // Now merge the entry of the triangle with the true block.
168266e41e3cSRoman Divacky MergeBlocks(BBI, *CvtBBI, false);
1683009b1c42SEd Schouten }
1684009b1c42SEd Schouten
1685044eb2f6SDimitry Andric // Keep the CFG updated.
1686044eb2f6SDimitry Andric BBI.BB->removeSuccessor(&CvtMBB, true);
1687044eb2f6SDimitry Andric
1688009b1c42SEd Schouten // If 'true' block has a 'false' successor, add an exit branch to it.
1689009b1c42SEd Schouten if (HasEarlyExit) {
1690009b1c42SEd Schouten SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1691009b1c42SEd Schouten CvtBBI->BrCond.end());
1692b915e9e0SDimitry Andric if (TII->reverseBranchCondition(RevCond))
169363faed5bSDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
16945ca98fd9SDimitry Andric
1695dd58ef01SDimitry Andric // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1696b915e9e0SDimitry Andric // NewNext = New_Prob(BBI.BB, NextMBB) =
1697b915e9e0SDimitry Andric // Prob(BBI.BB, NextMBB) +
1698b915e9e0SDimitry Andric // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1699dd58ef01SDimitry Andric // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1700b915e9e0SDimitry Andric // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1701b915e9e0SDimitry Andric auto NewTrueBB = getNextBlock(*BBI.BB);
1702dd58ef01SDimitry Andric auto NewNext = BBNext + BBCvt * CvtNext;
1703b915e9e0SDimitry Andric auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1704dd58ef01SDimitry Andric if (NewTrueBBIter != BBI.BB->succ_end())
1705dd58ef01SDimitry Andric BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1706dd58ef01SDimitry Andric
1707dd58ef01SDimitry Andric auto NewFalse = BBCvt * CvtFalse;
1708b915e9e0SDimitry Andric TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1709dd58ef01SDimitry Andric BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1710009b1c42SEd Schouten }
1711009b1c42SEd Schouten
1712009b1c42SEd Schouten // Merge in the 'false' block if the 'false' block has no other
1713009b1c42SEd Schouten // predecessors. Otherwise, add an unconditional branch to 'false'.
1714009b1c42SEd Schouten bool FalseBBDead = false;
1715009b1c42SEd Schouten bool IterIfcvt = true;
1716b915e9e0SDimitry Andric bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1717009b1c42SEd Schouten if (!isFallThrough) {
1718009b1c42SEd Schouten // Only merge them if the true block does not fallthrough to the false
1719009b1c42SEd Schouten // block. By not merging them, we make it possible to iteratively
1720009b1c42SEd Schouten // ifcvt the blocks.
1721009b1c42SEd Schouten if (!HasEarlyExit &&
1722ab44ce3dSDimitry Andric NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1723b915e9e0SDimitry Andric !NextMBB.hasAddressTaken()) {
1724009b1c42SEd Schouten MergeBlocks(BBI, *NextBBI);
1725009b1c42SEd Schouten FalseBBDead = true;
1726009b1c42SEd Schouten } else {
1727b915e9e0SDimitry Andric InsertUncondBranch(*BBI.BB, NextMBB, TII);
1728009b1c42SEd Schouten BBI.HasFallThrough = false;
1729009b1c42SEd Schouten }
1730009b1c42SEd Schouten // Mixed predicated and unpredicated code. This cannot be iteratively
1731009b1c42SEd Schouten // predicated.
1732009b1c42SEd Schouten IterIfcvt = false;
1733009b1c42SEd Schouten }
1734009b1c42SEd Schouten
1735009b1c42SEd Schouten // Update block info. BB can be iteratively if-converted.
1736009b1c42SEd Schouten if (!IterIfcvt)
1737009b1c42SEd Schouten BBI.IsDone = true;
1738b915e9e0SDimitry Andric InvalidatePreds(*BBI.BB);
1739009b1c42SEd Schouten CvtBBI->IsDone = true;
1740009b1c42SEd Schouten if (FalseBBDead)
1741009b1c42SEd Schouten NextBBI->IsDone = true;
1742009b1c42SEd Schouten
1743009b1c42SEd Schouten // FIXME: Must maintain LiveIns.
1744009b1c42SEd Schouten return true;
1745009b1c42SEd Schouten }
1746009b1c42SEd Schouten
1747b915e9e0SDimitry Andric /// Common code shared between diamond conversions.
1748b915e9e0SDimitry Andric /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1749b915e9e0SDimitry Andric /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1750b915e9e0SDimitry Andric /// and FalseBBI
1751b915e9e0SDimitry Andric /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1752b915e9e0SDimitry Andric /// and \p FalseBBI
1753b915e9e0SDimitry Andric /// \p RemoveBranch - Remove the common branch of the two blocks before
1754b915e9e0SDimitry Andric /// predicating. Only false for unanalyzable fallthrough
1755b915e9e0SDimitry Andric /// cases. The caller will replace the branch if necessary.
1756b915e9e0SDimitry Andric /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1757b915e9e0SDimitry Andric /// unanalyzable fallthrough
IfConvertDiamondCommon(BBInfo & BBI,BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred,bool RemoveBranch,bool MergeAddEdges)1758b915e9e0SDimitry Andric bool IfConverter::IfConvertDiamondCommon(
1759b915e9e0SDimitry Andric BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1760b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
1761b915e9e0SDimitry Andric bool TClobbersPred, bool FClobbersPred,
1762b915e9e0SDimitry Andric bool RemoveBranch, bool MergeAddEdges) {
1763009b1c42SEd Schouten
1764009b1c42SEd Schouten if (TrueBBI.IsDone || FalseBBI.IsDone ||
1765b915e9e0SDimitry Andric TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1766009b1c42SEd Schouten // Something has changed. It's no longer safe to predicate these blocks.
1767009b1c42SEd Schouten BBI.IsAnalyzed = false;
1768009b1c42SEd Schouten TrueBBI.IsAnalyzed = false;
1769009b1c42SEd Schouten FalseBBI.IsAnalyzed = false;
1770009b1c42SEd Schouten return false;
1771009b1c42SEd Schouten }
1772009b1c42SEd Schouten
177359d6cff9SDimitry Andric if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
177459d6cff9SDimitry Andric // Conservatively abort if-conversion if either BB has its address taken.
177559d6cff9SDimitry Andric return false;
177659d6cff9SDimitry Andric
177766e41e3cSRoman Divacky // Put the predicated instructions from the 'true' block before the
177866e41e3cSRoman Divacky // instructions from the 'false' block, unless the true block would clobber
177966e41e3cSRoman Divacky // the predicate, in which case, do the opposite.
1780009b1c42SEd Schouten BBInfo *BBI1 = &TrueBBI;
1781009b1c42SEd Schouten BBInfo *BBI2 = &FalseBBI;
1782009b1c42SEd Schouten SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1783b915e9e0SDimitry Andric if (TII->reverseBranchCondition(RevCond))
178463faed5bSDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
1785009b1c42SEd Schouten SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1786009b1c42SEd Schouten SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1787009b1c42SEd Schouten
1788009b1c42SEd Schouten // Figure out the more profitable ordering.
1789009b1c42SEd Schouten bool DoSwap = false;
1790b915e9e0SDimitry Andric if (TClobbersPred && !FClobbersPred)
1791009b1c42SEd Schouten DoSwap = true;
1792b915e9e0SDimitry Andric else if (!TClobbersPred && !FClobbersPred) {
1793009b1c42SEd Schouten if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1794009b1c42SEd Schouten DoSwap = true;
1795b915e9e0SDimitry Andric } else if (TClobbersPred && FClobbersPred)
1796b915e9e0SDimitry Andric llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1797009b1c42SEd Schouten if (DoSwap) {
1798009b1c42SEd Schouten std::swap(BBI1, BBI2);
1799009b1c42SEd Schouten std::swap(Cond1, Cond2);
1800009b1c42SEd Schouten }
1801009b1c42SEd Schouten
1802009b1c42SEd Schouten // Remove the conditional branch from entry to the blocks.
1803b915e9e0SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1804009b1c42SEd Schouten
1805b915e9e0SDimitry Andric MachineBasicBlock &MBB1 = *BBI1->BB;
1806b915e9e0SDimitry Andric MachineBasicBlock &MBB2 = *BBI2->BB;
1807b915e9e0SDimitry Andric
1808b915e9e0SDimitry Andric // Initialize the Redefs:
1809b915e9e0SDimitry Andric // - BB2 live-in regs need implicit uses before being redefined by BB1
1810b915e9e0SDimitry Andric // instructions.
1811b915e9e0SDimitry Andric // - BB1 live-out regs need implicit uses before being redefined by BB2
1812b915e9e0SDimitry Andric // instructions. We start with BB1 live-ins so we have the live-out regs
1813b915e9e0SDimitry Andric // after tracking the BB1 instructions.
1814b915e9e0SDimitry Andric Redefs.init(*TRI);
18157e7b6700SDimitry Andric if (MRI->tracksLiveness()) {
1816344a3780SDimitry Andric Redefs.addLiveInsNoPristines(MBB1);
1817344a3780SDimitry Andric Redefs.addLiveInsNoPristines(MBB2);
18187e7b6700SDimitry Andric }
181966e41e3cSRoman Divacky
1820009b1c42SEd Schouten // Remove the duplicated instructions at the beginnings of both paths.
1821eb11fae6SDimitry Andric // Skip dbg_value instructions.
1822344a3780SDimitry Andric MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr(false);
1823344a3780SDimitry Andric MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr(false);
1824009b1c42SEd Schouten BBI1->NonPredSize -= NumDups1;
1825009b1c42SEd Schouten BBI2->NonPredSize -= NumDups1;
182666e41e3cSRoman Divacky
182766e41e3cSRoman Divacky // Skip past the dups on each side separately since there may be
1828eb11fae6SDimitry Andric // differing dbg_value entries. NumDups1 can include a "return"
1829eb11fae6SDimitry Andric // instruction, if it's not marked as "branch".
183066e41e3cSRoman Divacky for (unsigned i = 0; i < NumDups1; ++DI1) {
1831eb11fae6SDimitry Andric if (DI1 == MBB1.end())
1832eb11fae6SDimitry Andric break;
1833eb11fae6SDimitry Andric if (!DI1->isDebugInstr())
183466e41e3cSRoman Divacky ++i;
183566e41e3cSRoman Divacky }
1836009b1c42SEd Schouten while (NumDups1 != 0) {
18371d5ae102SDimitry Andric // Since this instruction is going to be deleted, update call
18381d5ae102SDimitry Andric // site info state if the instruction is call instruction.
1839cfca06d7SDimitry Andric if (DI2->shouldUpdateCallSiteInfo())
18401d5ae102SDimitry Andric MBB2.getParent()->eraseCallSiteInfo(&*DI2);
18411d5ae102SDimitry Andric
1842009b1c42SEd Schouten ++DI2;
1843eb11fae6SDimitry Andric if (DI2 == MBB2.end())
1844eb11fae6SDimitry Andric break;
1845eb11fae6SDimitry Andric if (!DI2->isDebugInstr())
1846009b1c42SEd Schouten --NumDups1;
1847009b1c42SEd Schouten }
184866e41e3cSRoman Divacky
18497e7b6700SDimitry Andric if (MRI->tracksLiveness()) {
1850b915e9e0SDimitry Andric for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1851d8e91e46SDimitry Andric SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
18527e7b6700SDimitry Andric Redefs.stepForward(MI, Dummy);
18537e7b6700SDimitry Andric }
1854f8af5cf6SDimitry Andric }
1855eb11fae6SDimitry Andric
1856b915e9e0SDimitry Andric BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1857b915e9e0SDimitry Andric MBB2.erase(MBB2.begin(), DI2);
1858009b1c42SEd Schouten
1859eb11fae6SDimitry Andric // The branches have been checked to match, so it is safe to remove the
1860eb11fae6SDimitry Andric // branch in BB1 and rely on the copy in BB2. The complication is that
1861eb11fae6SDimitry Andric // the blocks may end with a return instruction, which may or may not
1862eb11fae6SDimitry Andric // be marked as "branch". If it's not, then it could be included in
1863eb11fae6SDimitry Andric // "dups1", leaving the blocks potentially empty after moving the common
1864eb11fae6SDimitry Andric // duplicates.
1865b915e9e0SDimitry Andric #ifndef NDEBUG
1866b915e9e0SDimitry Andric // Unanalyzable branches must match exactly. Check that now.
1867b915e9e0SDimitry Andric if (!BBI1->IsBrAnalyzable)
1868b915e9e0SDimitry Andric verifySameBranchInstructions(&MBB1, &MBB2);
1869b915e9e0SDimitry Andric #endif
18701d5ae102SDimitry Andric // Remove duplicated instructions from the tail of MBB1: any branch
18711d5ae102SDimitry Andric // instructions, and the common instructions counted by NumDups2.
1872b915e9e0SDimitry Andric DI1 = MBB1.end();
18731d5ae102SDimitry Andric while (DI1 != MBB1.begin()) {
18741d5ae102SDimitry Andric MachineBasicBlock::iterator Prev = std::prev(DI1);
18751d5ae102SDimitry Andric if (!Prev->isBranch() && !Prev->isDebugInstr())
18761d5ae102SDimitry Andric break;
18771d5ae102SDimitry Andric DI1 = Prev;
18781d5ae102SDimitry Andric }
187966e41e3cSRoman Divacky for (unsigned i = 0; i != NumDups2; ) {
188066e41e3cSRoman Divacky // NumDups2 only counted non-dbg_value instructions, so this won't
188166e41e3cSRoman Divacky // run off the head of the list.
1882b915e9e0SDimitry Andric assert(DI1 != MBB1.begin());
18831d5ae102SDimitry Andric
1884009b1c42SEd Schouten --DI1;
18851d5ae102SDimitry Andric
18861d5ae102SDimitry Andric // Since this instruction is going to be deleted, update call
18871d5ae102SDimitry Andric // site info state if the instruction is call instruction.
1888cfca06d7SDimitry Andric if (DI1->shouldUpdateCallSiteInfo())
18891d5ae102SDimitry Andric MBB1.getParent()->eraseCallSiteInfo(&*DI1);
18901d5ae102SDimitry Andric
189166e41e3cSRoman Divacky // skip dbg_value instructions
1892eb11fae6SDimitry Andric if (!DI1->isDebugInstr())
189366e41e3cSRoman Divacky ++i;
189466e41e3cSRoman Divacky }
1895b915e9e0SDimitry Andric MBB1.erase(DI1, MBB1.end());
1896009b1c42SEd Schouten
1897009b1c42SEd Schouten DI2 = BBI2->BB->end();
1898b915e9e0SDimitry Andric // The branches have been checked to match. Skip over the branch in the false
1899b915e9e0SDimitry Andric // block so that we don't try to predicate it.
1900b915e9e0SDimitry Andric if (RemoveBranch)
1901b915e9e0SDimitry Andric BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1902b915e9e0SDimitry Andric else {
1903eb11fae6SDimitry Andric // Make DI2 point to the end of the range where the common "tail"
1904eb11fae6SDimitry Andric // instructions could be found.
1905eb11fae6SDimitry Andric while (DI2 != MBB2.begin()) {
1906eb11fae6SDimitry Andric MachineBasicBlock::iterator Prev = std::prev(DI2);
1907eb11fae6SDimitry Andric if (!Prev->isBranch() && !Prev->isDebugInstr())
1908eb11fae6SDimitry Andric break;
1909eb11fae6SDimitry Andric DI2 = Prev;
1910eb11fae6SDimitry Andric }
1911b915e9e0SDimitry Andric }
1912009b1c42SEd Schouten while (NumDups2 != 0) {
191366e41e3cSRoman Divacky // NumDups2 only counted non-dbg_value instructions, so this won't
191466e41e3cSRoman Divacky // run off the head of the list.
1915b915e9e0SDimitry Andric assert(DI2 != MBB2.begin());
1916009b1c42SEd Schouten --DI2;
191766e41e3cSRoman Divacky // skip dbg_value instructions
1918eb11fae6SDimitry Andric if (!DI2->isDebugInstr())
1919009b1c42SEd Schouten --NumDups2;
1920009b1c42SEd Schouten }
192163faed5bSDimitry Andric
192263faed5bSDimitry Andric // Remember which registers would later be defined by the false block.
192363faed5bSDimitry Andric // This allows us not to predicate instructions in the true block that would
192463faed5bSDimitry Andric // later be re-defined. That is, rather than
192563faed5bSDimitry Andric // subeq r0, r1, #1
192663faed5bSDimitry Andric // addne r0, r1, #1
192763faed5bSDimitry Andric // generate:
192863faed5bSDimitry Andric // sub r0, r1, #1
192963faed5bSDimitry Andric // addne r0, r1, #1
1930d8e91e46SDimitry Andric SmallSet<MCPhysReg, 4> RedefsByFalse;
1931d8e91e46SDimitry Andric SmallSet<MCPhysReg, 4> ExtUses;
1932b915e9e0SDimitry Andric if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1933b915e9e0SDimitry Andric for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1934eb11fae6SDimitry Andric if (FI.isDebugInstr())
193563faed5bSDimitry Andric continue;
1936d8e91e46SDimitry Andric SmallVector<MCPhysReg, 4> Defs;
1937b915e9e0SDimitry Andric for (const MachineOperand &MO : FI.operands()) {
193863faed5bSDimitry Andric if (!MO.isReg())
193963faed5bSDimitry Andric continue;
19401d5ae102SDimitry Andric Register Reg = MO.getReg();
194163faed5bSDimitry Andric if (!Reg)
194263faed5bSDimitry Andric continue;
194363faed5bSDimitry Andric if (MO.isDef()) {
194463faed5bSDimitry Andric Defs.push_back(Reg);
194563faed5bSDimitry Andric } else if (!RedefsByFalse.count(Reg)) {
194663faed5bSDimitry Andric // These are defined before ctrl flow reach the 'false' instructions.
194763faed5bSDimitry Andric // They cannot be modified by the 'true' instructions.
19487fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
19497fa27ce4SDimitry Andric ExtUses.insert(SubReg);
195063faed5bSDimitry Andric }
195163faed5bSDimitry Andric }
195263faed5bSDimitry Andric
1953d8e91e46SDimitry Andric for (MCPhysReg Reg : Defs) {
195463faed5bSDimitry Andric if (!ExtUses.count(Reg)) {
19557fa27ce4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
19567fa27ce4SDimitry Andric RedefsByFalse.insert(SubReg);
195763faed5bSDimitry Andric }
195863faed5bSDimitry Andric }
195963faed5bSDimitry Andric }
196063faed5bSDimitry Andric }
196163faed5bSDimitry Andric
196263faed5bSDimitry Andric // Predicate the 'true' block.
1963b915e9e0SDimitry Andric PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
196463faed5bSDimitry Andric
196501095a5dSDimitry Andric // After predicating BBI1, if there is a predicated terminator in BBI1 and
196601095a5dSDimitry Andric // a non-predicated in BBI2, then we don't want to predicate the one from
196701095a5dSDimitry Andric // BBI2. The reason is that if we merged these blocks, we would end up with
196801095a5dSDimitry Andric // two predicated terminators in the same block.
1969eb11fae6SDimitry Andric // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1970eb11fae6SDimitry Andric // predicate them either. They were checked to be identical, and so the
1971eb11fae6SDimitry Andric // same branch would happen regardless of which path was taken.
1972b915e9e0SDimitry Andric if (!MBB2.empty() && (DI2 == MBB2.end())) {
1973b915e9e0SDimitry Andric MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1974b915e9e0SDimitry Andric MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1975eb11fae6SDimitry Andric bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
1976eb11fae6SDimitry Andric bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
1977eb11fae6SDimitry Andric if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
197801095a5dSDimitry Andric --DI2;
197901095a5dSDimitry Andric }
198001095a5dSDimitry Andric
198163faed5bSDimitry Andric // Predicate the 'false' block.
1982f8af5cf6SDimitry Andric PredicateBlock(*BBI2, DI2, *Cond2);
1983009b1c42SEd Schouten
1984009b1c42SEd Schouten // Merge the true block into the entry of the diamond.
1985b915e9e0SDimitry Andric MergeBlocks(BBI, *BBI1, MergeAddEdges);
1986b915e9e0SDimitry Andric MergeBlocks(BBI, *BBI2, MergeAddEdges);
1987b915e9e0SDimitry Andric return true;
1988b915e9e0SDimitry Andric }
1989b915e9e0SDimitry Andric
1990b915e9e0SDimitry Andric /// If convert an almost-diamond sub-CFG where the true
1991b915e9e0SDimitry Andric /// and false blocks share a common tail.
IfConvertForkedDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)1992b915e9e0SDimitry Andric bool IfConverter::IfConvertForkedDiamond(
1993b915e9e0SDimitry Andric BBInfo &BBI, IfcvtKind Kind,
1994b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
1995b915e9e0SDimitry Andric bool TClobbersPred, bool FClobbersPred) {
1996b915e9e0SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1997b915e9e0SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1998b915e9e0SDimitry Andric
1999b915e9e0SDimitry Andric // Save the debug location for later.
2000b915e9e0SDimitry Andric DebugLoc dl;
2001b915e9e0SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
2002b915e9e0SDimitry Andric if (TIE != TrueBBI.BB->end())
2003b915e9e0SDimitry Andric dl = TIE->getDebugLoc();
2004b915e9e0SDimitry Andric // Removing branches from both blocks is safe, because we have already
2005b915e9e0SDimitry Andric // determined that both blocks have the same branch instructions. The branch
2006b915e9e0SDimitry Andric // will be added back at the end, unpredicated.
2007b915e9e0SDimitry Andric if (!IfConvertDiamondCommon(
2008b915e9e0SDimitry Andric BBI, TrueBBI, FalseBBI,
2009b915e9e0SDimitry Andric NumDups1, NumDups2,
2010b915e9e0SDimitry Andric TClobbersPred, FClobbersPred,
2011b915e9e0SDimitry Andric /* RemoveBranch */ true, /* MergeAddEdges */ true))
2012b915e9e0SDimitry Andric return false;
2013b915e9e0SDimitry Andric
2014b915e9e0SDimitry Andric // Add back the branch.
2015b915e9e0SDimitry Andric // Debug location saved above when removing the branch from BBI2
2016b915e9e0SDimitry Andric TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
2017b915e9e0SDimitry Andric TrueBBI.BrCond, dl);
2018b915e9e0SDimitry Andric
2019b915e9e0SDimitry Andric // Update block info.
2020b915e9e0SDimitry Andric BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
2021b915e9e0SDimitry Andric InvalidatePreds(*BBI.BB);
2022b915e9e0SDimitry Andric
2023b915e9e0SDimitry Andric // FIXME: Must maintain LiveIns.
2024b915e9e0SDimitry Andric return true;
2025b915e9e0SDimitry Andric }
2026b915e9e0SDimitry Andric
2027b915e9e0SDimitry Andric /// If convert a diamond sub-CFG.
IfConvertDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)2028b915e9e0SDimitry Andric bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
2029b915e9e0SDimitry Andric unsigned NumDups1, unsigned NumDups2,
2030b915e9e0SDimitry Andric bool TClobbersPred, bool FClobbersPred) {
2031b915e9e0SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
2032b915e9e0SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
2033b915e9e0SDimitry Andric MachineBasicBlock *TailBB = TrueBBI.TrueBB;
2034b915e9e0SDimitry Andric
2035b915e9e0SDimitry Andric // True block must fall through or end with an unanalyzable terminator.
2036b915e9e0SDimitry Andric if (!TailBB) {
2037b915e9e0SDimitry Andric if (blockAlwaysFallThrough(TrueBBI))
2038b915e9e0SDimitry Andric TailBB = FalseBBI.TrueBB;
2039b915e9e0SDimitry Andric assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
2040b915e9e0SDimitry Andric }
2041b915e9e0SDimitry Andric
2042b915e9e0SDimitry Andric if (!IfConvertDiamondCommon(
2043b915e9e0SDimitry Andric BBI, TrueBBI, FalseBBI,
2044b915e9e0SDimitry Andric NumDups1, NumDups2,
2045b915e9e0SDimitry Andric TClobbersPred, FClobbersPred,
2046b915e9e0SDimitry Andric /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
2047b915e9e0SDimitry Andric /* MergeAddEdges */ TailBB == nullptr))
2048b915e9e0SDimitry Andric return false;
2049009b1c42SEd Schouten
2050009b1c42SEd Schouten // If the if-converted block falls through or unconditionally branches into
2051009b1c42SEd Schouten // the tail block, and the tail block does not have other predecessors, then
2052009b1c42SEd Schouten // fold the tail block in as well. Otherwise, unless it falls through to the
2053009b1c42SEd Schouten // tail, add a unconditional branch to it.
2054009b1c42SEd Schouten if (TailBB) {
2055044eb2f6SDimitry Andric // We need to remove the edges to the true and false blocks manually since
2056044eb2f6SDimitry Andric // we didn't let IfConvertDiamondCommon update the CFG.
2057044eb2f6SDimitry Andric BBI.BB->removeSuccessor(TrueBBI.BB);
2058044eb2f6SDimitry Andric BBI.BB->removeSuccessor(FalseBBI.BB, true);
2059044eb2f6SDimitry Andric
206063faed5bSDimitry Andric BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
206159d6cff9SDimitry Andric bool CanMergeTail = !TailBBI.HasFallThrough &&
206259d6cff9SDimitry Andric !TailBBI.BB->hasAddressTaken();
206301095a5dSDimitry Andric // The if-converted block can still have a predicated terminator
206401095a5dSDimitry Andric // (e.g. a predicated return). If that is the case, we cannot merge
206501095a5dSDimitry Andric // it with the tail block.
206601095a5dSDimitry Andric MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
206701095a5dSDimitry Andric if (TI != BBI.BB->end() && TII->isPredicated(*TI))
206801095a5dSDimitry Andric CanMergeTail = false;
206966e41e3cSRoman Divacky // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
207066e41e3cSRoman Divacky // check if there are any other predecessors besides those.
207166e41e3cSRoman Divacky unsigned NumPreds = TailBB->pred_size();
207266e41e3cSRoman Divacky if (NumPreds > 1)
207366e41e3cSRoman Divacky CanMergeTail = false;
207466e41e3cSRoman Divacky else if (NumPreds == 1 && CanMergeTail) {
207566e41e3cSRoman Divacky MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
2076b915e9e0SDimitry Andric if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
207766e41e3cSRoman Divacky CanMergeTail = false;
207866e41e3cSRoman Divacky }
207966e41e3cSRoman Divacky if (CanMergeTail) {
2080009b1c42SEd Schouten MergeBlocks(BBI, TailBBI);
2081009b1c42SEd Schouten TailBBI.IsDone = true;
2082009b1c42SEd Schouten } else {
2083dd58ef01SDimitry Andric BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
2084b915e9e0SDimitry Andric InsertUncondBranch(*BBI.BB, *TailBB, TII);
2085009b1c42SEd Schouten BBI.HasFallThrough = false;
2086009b1c42SEd Schouten }
2087009b1c42SEd Schouten }
2088009b1c42SEd Schouten
2089009b1c42SEd Schouten // Update block info.
2090009b1c42SEd Schouten BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
2091b915e9e0SDimitry Andric InvalidatePreds(*BBI.BB);
2092009b1c42SEd Schouten
2093009b1c42SEd Schouten // FIXME: Must maintain LiveIns.
2094009b1c42SEd Schouten return true;
2095009b1c42SEd Schouten }
2096009b1c42SEd Schouten
MaySpeculate(const MachineInstr & MI,SmallSet<MCPhysReg,4> & LaterRedefs)209701095a5dSDimitry Andric static bool MaySpeculate(const MachineInstr &MI,
2098d8e91e46SDimitry Andric SmallSet<MCPhysReg, 4> &LaterRedefs) {
209963faed5bSDimitry Andric bool SawStore = true;
210001095a5dSDimitry Andric if (!MI.isSafeToMove(nullptr, SawStore))
210163faed5bSDimitry Andric return false;
210263faed5bSDimitry Andric
2103b915e9e0SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
210463faed5bSDimitry Andric if (!MO.isReg())
210563faed5bSDimitry Andric continue;
21061d5ae102SDimitry Andric Register Reg = MO.getReg();
210763faed5bSDimitry Andric if (!Reg)
210863faed5bSDimitry Andric continue;
210963faed5bSDimitry Andric if (MO.isDef() && !LaterRedefs.count(Reg))
211063faed5bSDimitry Andric return false;
211163faed5bSDimitry Andric }
211263faed5bSDimitry Andric
211363faed5bSDimitry Andric return true;
211463faed5bSDimitry Andric }
211563faed5bSDimitry Andric
2116b915e9e0SDimitry Andric /// Predicate instructions from the start of the block to the specified end with
2117b915e9e0SDimitry Andric /// the specified condition.
PredicateBlock(BBInfo & BBI,MachineBasicBlock::iterator E,SmallVectorImpl<MachineOperand> & Cond,SmallSet<MCPhysReg,4> * LaterRedefs)2118009b1c42SEd Schouten void IfConverter::PredicateBlock(BBInfo &BBI,
2119009b1c42SEd Schouten MachineBasicBlock::iterator E,
212066e41e3cSRoman Divacky SmallVectorImpl<MachineOperand> &Cond,
2121d8e91e46SDimitry Andric SmallSet<MCPhysReg, 4> *LaterRedefs) {
212263faed5bSDimitry Andric bool AnyUnpred = false;
21235ca98fd9SDimitry Andric bool MaySpec = LaterRedefs != nullptr;
2124b915e9e0SDimitry Andric for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2125eb11fae6SDimitry Andric if (I.isDebugInstr() || TII->isPredicated(I))
2126009b1c42SEd Schouten continue;
212763faed5bSDimitry Andric // It may be possible not to predicate an instruction if it's the 'true'
212863faed5bSDimitry Andric // side of a diamond and the 'false' side may re-define the instruction's
212963faed5bSDimitry Andric // defs.
21305a5ac124SDimitry Andric if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
213163faed5bSDimitry Andric AnyUnpred = true;
213263faed5bSDimitry Andric continue;
213363faed5bSDimitry Andric }
213463faed5bSDimitry Andric // If any instruction is predicated, then every instruction after it must
213563faed5bSDimitry Andric // be predicated.
213663faed5bSDimitry Andric MaySpec = false;
2137009b1c42SEd Schouten if (!TII->PredicateInstruction(I, Cond)) {
213859850d08SRoman Divacky #ifndef NDEBUG
213901095a5dSDimitry Andric dbgs() << "Unable to predicate " << I << "!\n";
214059850d08SRoman Divacky #endif
21415ca98fd9SDimitry Andric llvm_unreachable(nullptr);
2142009b1c42SEd Schouten }
214366e41e3cSRoman Divacky
214466e41e3cSRoman Divacky // If the predicated instruction now redefines a register as the result of
214566e41e3cSRoman Divacky // if-conversion, add an implicit kill.
21465ca98fd9SDimitry Andric UpdatePredRedefs(I, Redefs);
2147009b1c42SEd Schouten }
2148009b1c42SEd Schouten
21495a5ac124SDimitry Andric BBI.Predicate.append(Cond.begin(), Cond.end());
2150009b1c42SEd Schouten
2151009b1c42SEd Schouten BBI.IsAnalyzed = false;
2152009b1c42SEd Schouten BBI.NonPredSize = 0;
2153009b1c42SEd Schouten
215466e41e3cSRoman Divacky ++NumIfConvBBs;
215563faed5bSDimitry Andric if (AnyUnpred)
215663faed5bSDimitry Andric ++NumUnpred;
2157009b1c42SEd Schouten }
2158009b1c42SEd Schouten
2159b915e9e0SDimitry Andric /// Copy and predicate instructions from source BB to the destination block.
2160b915e9e0SDimitry Andric /// Skip end of block branches if IgnoreBr is true.
CopyAndPredicateBlock(BBInfo & ToBBI,BBInfo & FromBBI,SmallVectorImpl<MachineOperand> & Cond,bool IgnoreBr)2161009b1c42SEd Schouten void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2162009b1c42SEd Schouten SmallVectorImpl<MachineOperand> &Cond,
2163009b1c42SEd Schouten bool IgnoreBr) {
2164009b1c42SEd Schouten MachineFunction &MF = *ToBBI.BB->getParent();
2165009b1c42SEd Schouten
2166b915e9e0SDimitry Andric MachineBasicBlock &FromMBB = *FromBBI.BB;
2167b915e9e0SDimitry Andric for (MachineInstr &I : FromMBB) {
2168009b1c42SEd Schouten // Do not copy the end of the block branches.
216901095a5dSDimitry Andric if (IgnoreBr && I.isBranch())
2170009b1c42SEd Schouten break;
2171009b1c42SEd Schouten
217201095a5dSDimitry Andric MachineInstr *MI = MF.CloneMachineInstr(&I);
21731d5ae102SDimitry Andric // Make a copy of the call site info.
2174cfca06d7SDimitry Andric if (I.isCandidateForCallSiteEntry())
21751d5ae102SDimitry Andric MF.copyCallSiteInfo(&I, MI);
21761d5ae102SDimitry Andric
2177009b1c42SEd Schouten ToBBI.BB->insert(ToBBI.BB->end(), MI);
2178009b1c42SEd Schouten ToBBI.NonPredSize++;
217901095a5dSDimitry Andric unsigned ExtraPredCost = TII->getPredicationCost(I);
218001095a5dSDimitry Andric unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2181cf099d11SDimitry Andric if (NumCycles > 1)
2182cf099d11SDimitry Andric ToBBI.ExtraCost += NumCycles-1;
2183cf099d11SDimitry Andric ToBBI.ExtraCost2 += ExtraPredCost;
2184009b1c42SEd Schouten
2185eb11fae6SDimitry Andric if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
218601095a5dSDimitry Andric if (!TII->PredicateInstruction(*MI, Cond)) {
218759850d08SRoman Divacky #ifndef NDEBUG
218801095a5dSDimitry Andric dbgs() << "Unable to predicate " << I << "!\n";
218959850d08SRoman Divacky #endif
21905ca98fd9SDimitry Andric llvm_unreachable(nullptr);
2191009b1c42SEd Schouten }
2192009b1c42SEd Schouten }
2193009b1c42SEd Schouten
219466e41e3cSRoman Divacky // If the predicated instruction now redefines a register as the result of
219566e41e3cSRoman Divacky // if-conversion, add an implicit kill.
219601095a5dSDimitry Andric UpdatePredRedefs(*MI, Redefs);
219766e41e3cSRoman Divacky }
219866e41e3cSRoman Divacky
219966e41e3cSRoman Divacky if (!IgnoreBr) {
2200b915e9e0SDimitry Andric std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2201b915e9e0SDimitry Andric FromMBB.succ_end());
2202b915e9e0SDimitry Andric MachineBasicBlock *NBB = getNextBlock(FromMBB);
22035ca98fd9SDimitry Andric MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2204009b1c42SEd Schouten
2205b915e9e0SDimitry Andric for (MachineBasicBlock *Succ : Succs) {
2206009b1c42SEd Schouten // Fallthrough edge can't be transferred.
2207009b1c42SEd Schouten if (Succ == FallThrough)
2208009b1c42SEd Schouten continue;
2209009b1c42SEd Schouten ToBBI.BB->addSuccessor(Succ);
2210009b1c42SEd Schouten }
221166e41e3cSRoman Divacky }
2212009b1c42SEd Schouten
22135a5ac124SDimitry Andric ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
22145a5ac124SDimitry Andric ToBBI.Predicate.append(Cond.begin(), Cond.end());
2215009b1c42SEd Schouten
2216009b1c42SEd Schouten ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2217009b1c42SEd Schouten ToBBI.IsAnalyzed = false;
2218009b1c42SEd Schouten
221966e41e3cSRoman Divacky ++NumDupBBs;
2220009b1c42SEd Schouten }
2221009b1c42SEd Schouten
2222b915e9e0SDimitry Andric /// Move all instructions from FromBB to the end of ToBB. This will leave
2223cfca06d7SDimitry Andric /// FromBB as an empty block, so remove all of its successor edges and move it
2224cfca06d7SDimitry Andric /// to the end of the function. If AddEdges is true, i.e., when FromBBI's
2225cfca06d7SDimitry Andric /// branch is being moved, add those successor edges to ToBBI and remove the old
2226cfca06d7SDimitry Andric /// edge from ToBBI to FromBBI.
MergeBlocks(BBInfo & ToBBI,BBInfo & FromBBI,bool AddEdges)222766e41e3cSRoman Divacky void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2228b915e9e0SDimitry Andric MachineBasicBlock &FromMBB = *FromBBI.BB;
2229b915e9e0SDimitry Andric assert(!FromMBB.hasAddressTaken() &&
223059d6cff9SDimitry Andric "Removing a BB whose address is taken!");
223159d6cff9SDimitry Andric
22327fa27ce4SDimitry Andric // If we're about to splice an INLINEASM_BR from FromBBI, we need to update
22337fa27ce4SDimitry Andric // ToBBI's successor list accordingly.
22347fa27ce4SDimitry Andric if (FromMBB.mayHaveInlineAsmBr())
22357fa27ce4SDimitry Andric for (MachineInstr &MI : FromMBB)
22367fa27ce4SDimitry Andric if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
22377fa27ce4SDimitry Andric for (MachineOperand &MO : MI.operands())
22387fa27ce4SDimitry Andric if (MO.isMBB() && !ToBBI.BB->isSuccessor(MO.getMBB()))
22397fa27ce4SDimitry Andric ToBBI.BB->addSuccessor(MO.getMBB(), BranchProbability::getZero());
22407fa27ce4SDimitry Andric
2241b915e9e0SDimitry Andric // In case FromMBB contains terminators (e.g. return instruction),
224201095a5dSDimitry Andric // first move the non-terminator instructions, then the terminators.
2243b915e9e0SDimitry Andric MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
224401095a5dSDimitry Andric MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2245b915e9e0SDimitry Andric ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
224601095a5dSDimitry Andric
224701095a5dSDimitry Andric // If FromBB has non-predicated terminator we should copy it at the end.
2248b915e9e0SDimitry Andric if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
224901095a5dSDimitry Andric ToTI = ToBBI.BB->end();
2250b915e9e0SDimitry Andric ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2251009b1c42SEd Schouten
2252dd58ef01SDimitry Andric // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2253dd58ef01SDimitry Andric // unknown probabilities into known ones.
2254dd58ef01SDimitry Andric // FIXME: This usage is too tricky and in the future we would like to
2255dd58ef01SDimitry Andric // eliminate all unknown probabilities in MBB.
225671d5a254SDimitry Andric if (ToBBI.IsBrAnalyzable)
2257dd58ef01SDimitry Andric ToBBI.BB->normalizeSuccProbs();
2258dd58ef01SDimitry Andric
2259b60736ecSDimitry Andric SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
2260b915e9e0SDimitry Andric MachineBasicBlock *NBB = getNextBlock(FromMBB);
22615ca98fd9SDimitry Andric MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2262b915e9e0SDimitry Andric // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2263b915e9e0SDimitry Andric // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2264dd58ef01SDimitry Andric auto To2FromProb = BranchProbability::getZero();
2265b915e9e0SDimitry Andric if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2266044eb2f6SDimitry Andric // Remove the old edge but remember the edge probability so we can calculate
2267044eb2f6SDimitry Andric // the correct weights on the new edges being added further down.
2268b915e9e0SDimitry Andric To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2269044eb2f6SDimitry Andric ToBBI.BB->removeSuccessor(&FromMBB);
2270dd58ef01SDimitry Andric }
2271009b1c42SEd Schouten
2272b915e9e0SDimitry Andric for (MachineBasicBlock *Succ : FromSuccs) {
2273009b1c42SEd Schouten // Fallthrough edge can't be transferred.
2274cfca06d7SDimitry Andric if (Succ == FallThrough) {
2275cfca06d7SDimitry Andric FromMBB.removeSuccessor(Succ);
2276009b1c42SEd Schouten continue;
2277cfca06d7SDimitry Andric }
2278dd58ef01SDimitry Andric
2279dd58ef01SDimitry Andric auto NewProb = BranchProbability::getZero();
2280dd58ef01SDimitry Andric if (AddEdges) {
2281dd58ef01SDimitry Andric // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2282b915e9e0SDimitry Andric // which is a portion of the edge probability from FromMBB to Succ. The
2283b915e9e0SDimitry Andric // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2284d8e91e46SDimitry Andric // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2285b915e9e0SDimitry Andric NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2286dd58ef01SDimitry Andric
2287b915e9e0SDimitry Andric // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2288b915e9e0SDimitry Andric // only happens when if-converting a diamond CFG and FromMBB is the
2289b915e9e0SDimitry Andric // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2290b915e9e0SDimitry Andric // could just use the probabilities on FromMBB's out-edges when adding
2291dd58ef01SDimitry Andric // new successors.
2292dd58ef01SDimitry Andric if (!To2FromProb.isZero())
2293dd58ef01SDimitry Andric NewProb *= To2FromProb;
2294dd58ef01SDimitry Andric }
2295dd58ef01SDimitry Andric
2296b915e9e0SDimitry Andric FromMBB.removeSuccessor(Succ);
2297dd58ef01SDimitry Andric
2298dd58ef01SDimitry Andric if (AddEdges) {
2299dd58ef01SDimitry Andric // If the edge from ToBBI.BB to Succ already exists, update the
2300dd58ef01SDimitry Andric // probability of this edge by adding NewProb to it. An example is shown
2301b915e9e0SDimitry Andric // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2302dd58ef01SDimitry Andric // don't have to set C as A's successor as it already is. We only need to
2303dd58ef01SDimitry Andric // update the edge probability on A->C. Note that B will not be
2304dd58ef01SDimitry Andric // immediately removed from A's successors. It is possible that B->D is
2305dd58ef01SDimitry Andric // not removed either if D is a fallthrough of B. Later the edge A->D
2306dd58ef01SDimitry Andric // (generated here) and B->D will be combined into one edge. To maintain
2307dd58ef01SDimitry Andric // correct edge probability of this combined edge, we need to set the edge
2308dd58ef01SDimitry Andric // probability of A->B to zero, which is already done above. The edge
2309dd58ef01SDimitry Andric // probability on A->D is calculated by scaling the original probability
2310dd58ef01SDimitry Andric // on A->B by the probability of B->D.
2311dd58ef01SDimitry Andric //
2312dd58ef01SDimitry Andric // Before ifcvt: After ifcvt (assume B->D is kept):
2313dd58ef01SDimitry Andric //
2314dd58ef01SDimitry Andric // A A
2315dd58ef01SDimitry Andric // /| /|\
2316dd58ef01SDimitry Andric // / B / B|
2317dd58ef01SDimitry Andric // | /| | ||
2318dd58ef01SDimitry Andric // |/ | | |/
2319dd58ef01SDimitry Andric // C D C D
2320dd58ef01SDimitry Andric //
2321dd58ef01SDimitry Andric if (ToBBI.BB->isSuccessor(Succ))
2322dd58ef01SDimitry Andric ToBBI.BB->setSuccProbability(
2323b915e9e0SDimitry Andric find(ToBBI.BB->successors(), Succ),
2324dd58ef01SDimitry Andric MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2325dd58ef01SDimitry Andric else
2326dd58ef01SDimitry Andric ToBBI.BB->addSuccessor(Succ, NewProb);
2327dd58ef01SDimitry Andric }
2328009b1c42SEd Schouten }
2329009b1c42SEd Schouten
2330044eb2f6SDimitry Andric // Move the now empty FromMBB out of the way to the end of the function so
2331044eb2f6SDimitry Andric // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2332044eb2f6SDimitry Andric MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2333044eb2f6SDimitry Andric if (Last != &FromMBB)
2334044eb2f6SDimitry Andric FromMBB.moveAfter(Last);
2335009b1c42SEd Schouten
2336dd58ef01SDimitry Andric // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2337dd58ef01SDimitry Andric // we've done above.
233871d5a254SDimitry Andric if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2339dd58ef01SDimitry Andric ToBBI.BB->normalizeSuccProbs();
2340dd58ef01SDimitry Andric
23415a5ac124SDimitry Andric ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2342009b1c42SEd Schouten FromBBI.Predicate.clear();
2343009b1c42SEd Schouten
2344009b1c42SEd Schouten ToBBI.NonPredSize += FromBBI.NonPredSize;
2345cf099d11SDimitry Andric ToBBI.ExtraCost += FromBBI.ExtraCost;
2346cf099d11SDimitry Andric ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2347009b1c42SEd Schouten FromBBI.NonPredSize = 0;
2348cf099d11SDimitry Andric FromBBI.ExtraCost = 0;
2349cf099d11SDimitry Andric FromBBI.ExtraCost2 = 0;
2350009b1c42SEd Schouten
2351009b1c42SEd Schouten ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2352009b1c42SEd Schouten ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2353009b1c42SEd Schouten ToBBI.IsAnalyzed = false;
2354009b1c42SEd Schouten FromBBI.IsAnalyzed = false;
2355009b1c42SEd Schouten }
235685d8b2bbSDimitry Andric
235785d8b2bbSDimitry Andric FunctionPass *
createIfConverter(std::function<bool (const MachineFunction &)> Ftor)2358b915e9e0SDimitry Andric llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
235901095a5dSDimitry Andric return new IfConverter(std::move(Ftor));
236085d8b2bbSDimitry Andric }
2361