1f8a63a15SJakob Stoklund Olesen //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2f8a63a15SJakob Stoklund Olesen //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f8a63a15SJakob Stoklund Olesen //
7f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
8f8a63a15SJakob Stoklund Olesen //
9f8a63a15SJakob Stoklund Olesen // Early if-conversion is for out-of-order CPUs that don't have a lot of
10f8a63a15SJakob Stoklund Olesen // predicable instructions. The goal is to eliminate conditional branches that
11f8a63a15SJakob Stoklund Olesen // may mispredict.
12f8a63a15SJakob Stoklund Olesen //
13f8a63a15SJakob Stoklund Olesen // Instructions from both sides of the branch are executed specutatively, and a
14f8a63a15SJakob Stoklund Olesen // cmov instruction selects the result.
15f8a63a15SJakob Stoklund Olesen //
16f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
17f8a63a15SJakob Stoklund Olesen
18f8a63a15SJakob Stoklund Olesen #include "llvm/ADT/BitVector.h"
1902638392SJakob Stoklund Olesen #include "llvm/ADT/PostOrderIterator.h"
20f8a63a15SJakob Stoklund Olesen #include "llvm/ADT/SmallPtrSet.h"
21f8a63a15SJakob Stoklund Olesen #include "llvm/ADT/SparseSet.h"
22d0af1d96SJakob Stoklund Olesen #include "llvm/ADT/Statistic.h"
23989f1c72Sserge-sans-paille #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24f8a63a15SJakob Stoklund Olesen #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
2502638392SJakob Stoklund Olesen #include "llvm/CodeGen/MachineDominators.h"
26f8a63a15SJakob Stoklund Olesen #include "llvm/CodeGen/MachineFunction.h"
27f8a63a15SJakob Stoklund Olesen #include "llvm/CodeGen/MachineFunctionPass.h"
28be699bf3SThomas Raoux #include "llvm/CodeGen/MachineInstr.h"
29bc90a4eaSJakob Stoklund Olesen #include "llvm/CodeGen/MachineLoopInfo.h"
30b15f2bd3SJon Roelofs #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31f8a63a15SJakob Stoklund Olesen #include "llvm/CodeGen/MachineRegisterInfo.h"
32965665bbSJakob Stoklund Olesen #include "llvm/CodeGen/MachineTraceMetrics.h"
333f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
34b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
35b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
3605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
37f8a63a15SJakob Stoklund Olesen #include "llvm/Support/CommandLine.h"
38f8a63a15SJakob Stoklund Olesen #include "llvm/Support/Debug.h"
39f8a63a15SJakob Stoklund Olesen #include "llvm/Support/raw_ostream.h"
40f8a63a15SJakob Stoklund Olesen
41f8a63a15SJakob Stoklund Olesen using namespace llvm;
42f8a63a15SJakob Stoklund Olesen
431b9dde08SChandler Carruth #define DEBUG_TYPE "early-ifcvt"
441b9dde08SChandler Carruth
45f8a63a15SJakob Stoklund Olesen // Absolute maximum number of instructions allowed per speculated block.
46f8a63a15SJakob Stoklund Olesen // This bypasses all other heuristics, so it should be set fairly high.
47f8a63a15SJakob Stoklund Olesen static cl::opt<unsigned>
48f8a63a15SJakob Stoklund Olesen BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
49f8a63a15SJakob Stoklund Olesen cl::desc("Maximum number of instructions per speculated block."));
50f8a63a15SJakob Stoklund Olesen
51f8a63a15SJakob Stoklund Olesen // Stress testing mode - disable heuristics.
52f8a63a15SJakob Stoklund Olesen static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
53f8a63a15SJakob Stoklund Olesen cl::desc("Turn all knobs to 11"));
54f8a63a15SJakob Stoklund Olesen
55d0af1d96SJakob Stoklund Olesen STATISTIC(NumDiamondsSeen, "Number of diamonds");
56d0af1d96SJakob Stoklund Olesen STATISTIC(NumDiamondsConv, "Number of diamonds converted");
57d0af1d96SJakob Stoklund Olesen STATISTIC(NumTrianglesSeen, "Number of triangles");
58d0af1d96SJakob Stoklund Olesen STATISTIC(NumTrianglesConv, "Number of triangles converted");
59d0af1d96SJakob Stoklund Olesen
60f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
61f8a63a15SJakob Stoklund Olesen // SSAIfConv
62f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
63f8a63a15SJakob Stoklund Olesen //
64f8a63a15SJakob Stoklund Olesen // The SSAIfConv class performs if-conversion on SSA form machine code after
6511d08b2eSMatt Beaumont-Gay // determining if it is possible. The class contains no heuristics; external
66f8a63a15SJakob Stoklund Olesen // code should be used to determine when if-conversion is a good idea.
67f8a63a15SJakob Stoklund Olesen //
6811d08b2eSMatt Beaumont-Gay // SSAIfConv can convert both triangles and diamonds:
69f8a63a15SJakob Stoklund Olesen //
70f8a63a15SJakob Stoklund Olesen // Triangle: Head Diamond: Head
7111d08b2eSMatt Beaumont-Gay // | \ / \_
7211d08b2eSMatt Beaumont-Gay // | \ / |
73f8a63a15SJakob Stoklund Olesen // | [TF]BB FBB TBB
74f8a63a15SJakob Stoklund Olesen // | / \ /
75f8a63a15SJakob Stoklund Olesen // | / \ /
76f8a63a15SJakob Stoklund Olesen // Tail Tail
77f8a63a15SJakob Stoklund Olesen //
78f8a63a15SJakob Stoklund Olesen // Instructions in the conditional blocks TBB and/or FBB are spliced into the
7911d08b2eSMatt Beaumont-Gay // Head block, and phis in the Tail block are converted to select instructions.
80f8a63a15SJakob Stoklund Olesen //
81f8a63a15SJakob Stoklund Olesen namespace {
82f8a63a15SJakob Stoklund Olesen class SSAIfConv {
83f8a63a15SJakob Stoklund Olesen const TargetInstrInfo *TII;
84f8a63a15SJakob Stoklund Olesen const TargetRegisterInfo *TRI;
85f8a63a15SJakob Stoklund Olesen MachineRegisterInfo *MRI;
86f8a63a15SJakob Stoklund Olesen
8702638392SJakob Stoklund Olesen public:
88f8a63a15SJakob Stoklund Olesen /// The block containing the conditional branch.
89f8a63a15SJakob Stoklund Olesen MachineBasicBlock *Head;
90f8a63a15SJakob Stoklund Olesen
91f8a63a15SJakob Stoklund Olesen /// The block containing phis after the if-then-else.
92f8a63a15SJakob Stoklund Olesen MachineBasicBlock *Tail;
93f8a63a15SJakob Stoklund Olesen
94020041d9SKrzysztof Parzyszek /// The 'true' conditional block as determined by analyzeBranch.
95f8a63a15SJakob Stoklund Olesen MachineBasicBlock *TBB;
96f8a63a15SJakob Stoklund Olesen
97020041d9SKrzysztof Parzyszek /// The 'false' conditional block as determined by analyzeBranch.
98f8a63a15SJakob Stoklund Olesen MachineBasicBlock *FBB;
99f8a63a15SJakob Stoklund Olesen
100f8a63a15SJakob Stoklund Olesen /// isTriangle - When there is no 'else' block, either TBB or FBB will be
101f8a63a15SJakob Stoklund Olesen /// equal to Tail.
isTriangle() const102f8a63a15SJakob Stoklund Olesen bool isTriangle() const { return TBB == Tail || FBB == Tail; }
103f8a63a15SJakob Stoklund Olesen
1040a99062cSJakob Stoklund Olesen /// Returns the Tail predecessor for the True side.
getTPred() const1050a99062cSJakob Stoklund Olesen MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
1060a99062cSJakob Stoklund Olesen
1070a99062cSJakob Stoklund Olesen /// Returns the Tail predecessor for the False side.
getFPred() const1080a99062cSJakob Stoklund Olesen MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
1090a99062cSJakob Stoklund Olesen
110f8a63a15SJakob Stoklund Olesen /// Information about each phi in the Tail block.
111f8a63a15SJakob Stoklund Olesen struct PHIInfo {
112f8a63a15SJakob Stoklund Olesen MachineInstr *PHI;
1132bea207dSKazu Hirata unsigned TReg = 0, FReg = 0;
114f8a63a15SJakob Stoklund Olesen // Latencies from Cond+Branch, TReg, and FReg to DstReg.
1152bea207dSKazu Hirata int CondCycles = 0, TCycles = 0, FCycles = 0;
116f8a63a15SJakob Stoklund Olesen
PHIInfo__anon1f7aa2560111::SSAIfConv::PHIInfo1172bea207dSKazu Hirata PHIInfo(MachineInstr *phi) : PHI(phi) {}
118f8a63a15SJakob Stoklund Olesen };
119f8a63a15SJakob Stoklund Olesen
120f8a63a15SJakob Stoklund Olesen SmallVector<PHIInfo, 8> PHIs;
121f8a63a15SJakob Stoklund Olesen
12202638392SJakob Stoklund Olesen private:
123020041d9SKrzysztof Parzyszek /// The branch condition determined by analyzeBranch.
12402638392SJakob Stoklund Olesen SmallVector<MachineOperand, 4> Cond;
12502638392SJakob Stoklund Olesen
126f8a63a15SJakob Stoklund Olesen /// Instructions in Head that define values used by the conditional blocks.
127f8a63a15SJakob Stoklund Olesen /// The hoisted instructions must be inserted after these instructions.
128f8a63a15SJakob Stoklund Olesen SmallPtrSet<MachineInstr*, 8> InsertAfter;
129f8a63a15SJakob Stoklund Olesen
130f8a63a15SJakob Stoklund Olesen /// Register units clobbered by the conditional blocks.
131f8a63a15SJakob Stoklund Olesen BitVector ClobberedRegUnits;
132f8a63a15SJakob Stoklund Olesen
133f8a63a15SJakob Stoklund Olesen // Scratch pad for findInsertionPoint.
134f8a63a15SJakob Stoklund Olesen SparseSet<unsigned> LiveRegUnits;
135f8a63a15SJakob Stoklund Olesen
136f8a63a15SJakob Stoklund Olesen /// Insertion point in Head for speculatively executed instructions form TBB
137f8a63a15SJakob Stoklund Olesen /// and FBB.
138f8a63a15SJakob Stoklund Olesen MachineBasicBlock::iterator InsertionPoint;
139f8a63a15SJakob Stoklund Olesen
140f8a63a15SJakob Stoklund Olesen /// Return true if all non-terminator instructions in MBB can be safely
141f8a63a15SJakob Stoklund Olesen /// speculated.
142f8a63a15SJakob Stoklund Olesen bool canSpeculateInstrs(MachineBasicBlock *MBB);
143f8a63a15SJakob Stoklund Olesen
144be699bf3SThomas Raoux /// Return true if all non-terminator instructions in MBB can be safely
145be699bf3SThomas Raoux /// predicated.
146be699bf3SThomas Raoux bool canPredicateInstrs(MachineBasicBlock *MBB);
147be699bf3SThomas Raoux
148be699bf3SThomas Raoux /// Scan through instruction dependencies and update InsertAfter array.
149be699bf3SThomas Raoux /// Return false if any dependency is incompatible with if conversion.
150be699bf3SThomas Raoux bool InstrDependenciesAllowIfConv(MachineInstr *I);
151be699bf3SThomas Raoux
152be699bf3SThomas Raoux /// Predicate all instructions of the basic block with current condition
153be699bf3SThomas Raoux /// except for terminators. Reverse the condition if ReversePredicate is set.
154be699bf3SThomas Raoux void PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate);
155be699bf3SThomas Raoux
156f8a63a15SJakob Stoklund Olesen /// Find a valid insertion point in Head.
157f8a63a15SJakob Stoklund Olesen bool findInsertionPoint();
158f8a63a15SJakob Stoklund Olesen
15983a927d8SJakob Stoklund Olesen /// Replace PHI instructions in Tail with selects.
16083a927d8SJakob Stoklund Olesen void replacePHIInstrs();
16183a927d8SJakob Stoklund Olesen
16283a927d8SJakob Stoklund Olesen /// Insert selects and rewrite PHI operands to use them.
16383a927d8SJakob Stoklund Olesen void rewritePHIOperands();
16483a927d8SJakob Stoklund Olesen
165f8a63a15SJakob Stoklund Olesen public:
166f8a63a15SJakob Stoklund Olesen /// runOnMachineFunction - Initialize per-function data structures.
runOnMachineFunction(MachineFunction & MF)167f8a63a15SJakob Stoklund Olesen void runOnMachineFunction(MachineFunction &MF) {
168fc6de428SEric Christopher TII = MF.getSubtarget().getInstrInfo();
169fc6de428SEric Christopher TRI = MF.getSubtarget().getRegisterInfo();
170f8a63a15SJakob Stoklund Olesen MRI = &MF.getRegInfo();
171f8a63a15SJakob Stoklund Olesen LiveRegUnits.clear();
172f8a63a15SJakob Stoklund Olesen LiveRegUnits.setUniverse(TRI->getNumRegUnits());
173f8a63a15SJakob Stoklund Olesen ClobberedRegUnits.clear();
174f8a63a15SJakob Stoklund Olesen ClobberedRegUnits.resize(TRI->getNumRegUnits());
175f8a63a15SJakob Stoklund Olesen }
176f8a63a15SJakob Stoklund Olesen
177f8a63a15SJakob Stoklund Olesen /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
178f8a63a15SJakob Stoklund Olesen /// initialize the internal state, and return true.
179be699bf3SThomas Raoux /// If predicate is set try to predicate the block otherwise try to
180be699bf3SThomas Raoux /// speculatively execute it.
181be699bf3SThomas Raoux bool canConvertIf(MachineBasicBlock *MBB, bool Predicate = false);
182f8a63a15SJakob Stoklund Olesen
183f8a63a15SJakob Stoklund Olesen /// convertIf - If-convert the last block passed to canConvertIf(), assuming
18402638392SJakob Stoklund Olesen /// it is possible. Add any erased blocks to RemovedBlocks.
185be699bf3SThomas Raoux void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
186be699bf3SThomas Raoux bool Predicate = false);
187f8a63a15SJakob Stoklund Olesen };
188f8a63a15SJakob Stoklund Olesen } // end anonymous namespace
189f8a63a15SJakob Stoklund Olesen
190f8a63a15SJakob Stoklund Olesen
191f8a63a15SJakob Stoklund Olesen /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
192f8a63a15SJakob Stoklund Olesen /// be speculated. The terminators are not considered.
193f8a63a15SJakob Stoklund Olesen ///
194f8a63a15SJakob Stoklund Olesen /// If instructions use any values that are defined in the head basic block,
195f8a63a15SJakob Stoklund Olesen /// the defining instructions are added to InsertAfter.
196f8a63a15SJakob Stoklund Olesen ///
197f8a63a15SJakob Stoklund Olesen /// Any clobbered regunits are added to ClobberedRegUnits.
198f8a63a15SJakob Stoklund Olesen ///
canSpeculateInstrs(MachineBasicBlock * MBB)199f8a63a15SJakob Stoklund Olesen bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
200f8a63a15SJakob Stoklund Olesen // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
201f8a63a15SJakob Stoklund Olesen // get right.
202f8a63a15SJakob Stoklund Olesen if (!MBB->livein_empty()) {
203d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
204f8a63a15SJakob Stoklund Olesen return false;
205f8a63a15SJakob Stoklund Olesen }
206f8a63a15SJakob Stoklund Olesen
207f8a63a15SJakob Stoklund Olesen unsigned InstrCount = 0;
2083f1bb93cSJakob Stoklund Olesen
2093f1bb93cSJakob Stoklund Olesen // Check all instructions, except the terminators. It is assumed that
2103f1bb93cSJakob Stoklund Olesen // terminators never have side effects or define any used register values.
2111457e783SKazu Hirata for (MachineInstr &MI :
2121457e783SKazu Hirata llvm::make_range(MBB->begin(), MBB->getFirstTerminator())) {
2131457e783SKazu Hirata if (MI.isDebugInstr())
214f8a63a15SJakob Stoklund Olesen continue;
215f8a63a15SJakob Stoklund Olesen
216f8a63a15SJakob Stoklund Olesen if (++InstrCount > BlockInstrLimit && !Stress) {
217d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
218f8a63a15SJakob Stoklund Olesen << BlockInstrLimit << " instructions.\n");
219f8a63a15SJakob Stoklund Olesen return false;
220f8a63a15SJakob Stoklund Olesen }
221f8a63a15SJakob Stoklund Olesen
222f8a63a15SJakob Stoklund Olesen // There shouldn't normally be any phis in a single-predecessor block.
2231457e783SKazu Hirata if (MI.isPHI()) {
2241457e783SKazu Hirata LLVM_DEBUG(dbgs() << "Can't hoist: " << MI);
225f8a63a15SJakob Stoklund Olesen return false;
226f8a63a15SJakob Stoklund Olesen }
227f8a63a15SJakob Stoklund Olesen
228f8a63a15SJakob Stoklund Olesen // Don't speculate loads. Note that it may be possible and desirable to
229f8a63a15SJakob Stoklund Olesen // speculate GOT or constant pool loads that are guaranteed not to trap,
230f8a63a15SJakob Stoklund Olesen // but we don't support that for now.
2311457e783SKazu Hirata if (MI.mayLoad()) {
2321457e783SKazu Hirata LLVM_DEBUG(dbgs() << "Won't speculate load: " << MI);
233f8a63a15SJakob Stoklund Olesen return false;
234f8a63a15SJakob Stoklund Olesen }
235f8a63a15SJakob Stoklund Olesen
236f8a63a15SJakob Stoklund Olesen // We never speculate stores, so an AA pointer isn't necessary.
237f8a63a15SJakob Stoklund Olesen bool DontMoveAcrossStore = true;
2381457e783SKazu Hirata if (!MI.isSafeToMove(nullptr, DontMoveAcrossStore)) {
2391457e783SKazu Hirata LLVM_DEBUG(dbgs() << "Can't speculate: " << MI);
240f8a63a15SJakob Stoklund Olesen return false;
241f8a63a15SJakob Stoklund Olesen }
242f8a63a15SJakob Stoklund Olesen
243f8a63a15SJakob Stoklund Olesen // Check for any dependencies on Head instructions.
2441457e783SKazu Hirata if (!InstrDependenciesAllowIfConv(&MI))
245be699bf3SThomas Raoux return false;
246be699bf3SThomas Raoux }
247be699bf3SThomas Raoux return true;
248be699bf3SThomas Raoux }
249be699bf3SThomas Raoux
250be699bf3SThomas Raoux /// Check that there is no dependencies preventing if conversion.
251be699bf3SThomas Raoux ///
252be699bf3SThomas Raoux /// If instruction uses any values that are defined in the head basic block,
253be699bf3SThomas Raoux /// the defining instructions are added to InsertAfter.
InstrDependenciesAllowIfConv(MachineInstr * I)254be699bf3SThomas Raoux bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *I) {
25527a6cfd8SMatthias Braun for (const MachineOperand &MO : I->operands()) {
256e41e146cSMatthias Braun if (MO.isRegMask()) {
257d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
258f8a63a15SJakob Stoklund Olesen return false;
259f8a63a15SJakob Stoklund Olesen }
260e41e146cSMatthias Braun if (!MO.isReg())
261f8a63a15SJakob Stoklund Olesen continue;
2620c476111SDaniel Sanders Register Reg = MO.getReg();
263f8a63a15SJakob Stoklund Olesen
264f8a63a15SJakob Stoklund Olesen // Remember clobbered regunits.
2652bea69bfSDaniel Sanders if (MO.isDef() && Register::isPhysicalRegister(Reg))
266d85b845cSMircea Trofin for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
267d85b845cSMircea Trofin ++Units)
268f8a63a15SJakob Stoklund Olesen ClobberedRegUnits.set(*Units);
269f8a63a15SJakob Stoklund Olesen
2702bea69bfSDaniel Sanders if (!MO.readsReg() || !Register::isVirtualRegister(Reg))
271f8a63a15SJakob Stoklund Olesen continue;
272f8a63a15SJakob Stoklund Olesen MachineInstr *DefMI = MRI->getVRegDef(Reg);
273f8a63a15SJakob Stoklund Olesen if (!DefMI || DefMI->getParent() != Head)
274f8a63a15SJakob Stoklund Olesen continue;
27570573dcdSDavid Blaikie if (InsertAfter.insert(DefMI).second)
276be699bf3SThomas Raoux LLVM_DEBUG(dbgs() << printMBBReference(*I->getParent()) << " depends on "
277d34e60caSNicola Zaghen << *DefMI);
278f8a63a15SJakob Stoklund Olesen if (DefMI->isTerminator()) {
279d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
280f8a63a15SJakob Stoklund Olesen return false;
281f8a63a15SJakob Stoklund Olesen }
282f8a63a15SJakob Stoklund Olesen }
283be699bf3SThomas Raoux return true;
284be699bf3SThomas Raoux }
285be699bf3SThomas Raoux
286be699bf3SThomas Raoux /// canPredicateInstrs - Returns true if all the instructions in MBB can safely
287be699bf3SThomas Raoux /// be predicates. The terminators are not considered.
288be699bf3SThomas Raoux ///
289be699bf3SThomas Raoux /// If instructions use any values that are defined in the head basic block,
290be699bf3SThomas Raoux /// the defining instructions are added to InsertAfter.
291be699bf3SThomas Raoux ///
292be699bf3SThomas Raoux /// Any clobbered regunits are added to ClobberedRegUnits.
293be699bf3SThomas Raoux ///
canPredicateInstrs(MachineBasicBlock * MBB)294be699bf3SThomas Raoux bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *MBB) {
295be699bf3SThomas Raoux // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
296be699bf3SThomas Raoux // get right.
297be699bf3SThomas Raoux if (!MBB->livein_empty()) {
298be699bf3SThomas Raoux LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
299be699bf3SThomas Raoux return false;
300be699bf3SThomas Raoux }
301be699bf3SThomas Raoux
302be699bf3SThomas Raoux unsigned InstrCount = 0;
303be699bf3SThomas Raoux
304be699bf3SThomas Raoux // Check all instructions, except the terminators. It is assumed that
305be699bf3SThomas Raoux // terminators never have side effects or define any used register values.
306be699bf3SThomas Raoux for (MachineBasicBlock::iterator I = MBB->begin(),
307be699bf3SThomas Raoux E = MBB->getFirstTerminator();
308be699bf3SThomas Raoux I != E; ++I) {
309be699bf3SThomas Raoux if (I->isDebugInstr())
310be699bf3SThomas Raoux continue;
311be699bf3SThomas Raoux
312be699bf3SThomas Raoux if (++InstrCount > BlockInstrLimit && !Stress) {
313be699bf3SThomas Raoux LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
314be699bf3SThomas Raoux << BlockInstrLimit << " instructions.\n");
315be699bf3SThomas Raoux return false;
316be699bf3SThomas Raoux }
317be699bf3SThomas Raoux
318be699bf3SThomas Raoux // There shouldn't normally be any phis in a single-predecessor block.
319be699bf3SThomas Raoux if (I->isPHI()) {
320be699bf3SThomas Raoux LLVM_DEBUG(dbgs() << "Can't predicate: " << *I);
321be699bf3SThomas Raoux return false;
322be699bf3SThomas Raoux }
323be699bf3SThomas Raoux
324be699bf3SThomas Raoux // Check that instruction is predicable and that it is not already
325be699bf3SThomas Raoux // predicated.
326be699bf3SThomas Raoux if (!TII->isPredicable(*I) || TII->isPredicated(*I)) {
327be699bf3SThomas Raoux return false;
328be699bf3SThomas Raoux }
329be699bf3SThomas Raoux
330be699bf3SThomas Raoux // Check for any dependencies on Head instructions.
331be699bf3SThomas Raoux if (!InstrDependenciesAllowIfConv(&(*I)))
332be699bf3SThomas Raoux return false;
333f8a63a15SJakob Stoklund Olesen }
334f8a63a15SJakob Stoklund Olesen return true;
335f8a63a15SJakob Stoklund Olesen }
336f8a63a15SJakob Stoklund Olesen
337be699bf3SThomas Raoux // Apply predicate to all instructions in the machine block.
PredicateBlock(MachineBasicBlock * MBB,bool ReversePredicate)338be699bf3SThomas Raoux void SSAIfConv::PredicateBlock(MachineBasicBlock *MBB, bool ReversePredicate) {
339be699bf3SThomas Raoux auto Condition = Cond;
340be699bf3SThomas Raoux if (ReversePredicate)
341be699bf3SThomas Raoux TII->reverseBranchCondition(Condition);
342be699bf3SThomas Raoux // Terminators don't need to be predicated as they will be removed.
343be699bf3SThomas Raoux for (MachineBasicBlock::iterator I = MBB->begin(),
344be699bf3SThomas Raoux E = MBB->getFirstTerminator();
345be699bf3SThomas Raoux I != E; ++I) {
346be699bf3SThomas Raoux if (I->isDebugInstr())
347be699bf3SThomas Raoux continue;
348be699bf3SThomas Raoux TII->PredicateInstruction(*I, Condition);
349be699bf3SThomas Raoux }
350be699bf3SThomas Raoux }
351f8a63a15SJakob Stoklund Olesen
352f8a63a15SJakob Stoklund Olesen /// Find an insertion point in Head for the speculated instructions. The
353f8a63a15SJakob Stoklund Olesen /// insertion point must be:
354f8a63a15SJakob Stoklund Olesen ///
355f8a63a15SJakob Stoklund Olesen /// 1. Before any terminators.
356f8a63a15SJakob Stoklund Olesen /// 2. After any instructions in InsertAfter.
357f8a63a15SJakob Stoklund Olesen /// 3. Not have any clobbered regunits live.
358f8a63a15SJakob Stoklund Olesen ///
359f8a63a15SJakob Stoklund Olesen /// This function sets InsertionPoint and returns true when successful, it
360f8a63a15SJakob Stoklund Olesen /// returns false if no valid insertion point could be found.
361f8a63a15SJakob Stoklund Olesen ///
findInsertionPoint()362f8a63a15SJakob Stoklund Olesen bool SSAIfConv::findInsertionPoint() {
363f8a63a15SJakob Stoklund Olesen // Keep track of live regunits before the current position.
364f8a63a15SJakob Stoklund Olesen // Only track RegUnits that are also in ClobberedRegUnits.
365f8a63a15SJakob Stoklund Olesen LiveRegUnits.clear();
366d85b845cSMircea Trofin SmallVector<MCRegister, 8> Reads;
367f8a63a15SJakob Stoklund Olesen MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
368f8a63a15SJakob Stoklund Olesen MachineBasicBlock::iterator I = Head->end();
369f8a63a15SJakob Stoklund Olesen MachineBasicBlock::iterator B = Head->begin();
370f8a63a15SJakob Stoklund Olesen while (I != B) {
371f8a63a15SJakob Stoklund Olesen --I;
372f8a63a15SJakob Stoklund Olesen // Some of the conditional code depends in I.
373395bd9cdSDuncan P. N. Exon Smith if (InsertAfter.count(&*I)) {
374d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
375f8a63a15SJakob Stoklund Olesen return false;
376f8a63a15SJakob Stoklund Olesen }
377f8a63a15SJakob Stoklund Olesen
378f8a63a15SJakob Stoklund Olesen // Update live regunits.
379e41e146cSMatthias Braun for (const MachineOperand &MO : I->operands()) {
380f8a63a15SJakob Stoklund Olesen // We're ignoring regmask operands. That is conservatively correct.
381e41e146cSMatthias Braun if (!MO.isReg())
382f8a63a15SJakob Stoklund Olesen continue;
3830c476111SDaniel Sanders Register Reg = MO.getReg();
3842bea69bfSDaniel Sanders if (!Register::isPhysicalRegister(Reg))
385f8a63a15SJakob Stoklund Olesen continue;
386f8a63a15SJakob Stoklund Olesen // I clobbers Reg, so it isn't live before I.
387e41e146cSMatthias Braun if (MO.isDef())
388d85b845cSMircea Trofin for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
389d85b845cSMircea Trofin ++Units)
390f8a63a15SJakob Stoklund Olesen LiveRegUnits.erase(*Units);
391f8a63a15SJakob Stoklund Olesen // Unless I reads Reg.
392e41e146cSMatthias Braun if (MO.readsReg())
393d85b845cSMircea Trofin Reads.push_back(Reg.asMCReg());
394f8a63a15SJakob Stoklund Olesen }
395f8a63a15SJakob Stoklund Olesen // Anything read by I is live before I.
396f8a63a15SJakob Stoklund Olesen while (!Reads.empty())
397f8a63a15SJakob Stoklund Olesen for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
398f8a63a15SJakob Stoklund Olesen ++Units)
399f8a63a15SJakob Stoklund Olesen if (ClobberedRegUnits.test(*Units))
400f8a63a15SJakob Stoklund Olesen LiveRegUnits.insert(*Units);
401f8a63a15SJakob Stoklund Olesen
402f8a63a15SJakob Stoklund Olesen // We can't insert before a terminator.
403f8a63a15SJakob Stoklund Olesen if (I != FirstTerm && I->isTerminator())
404f8a63a15SJakob Stoklund Olesen continue;
405f8a63a15SJakob Stoklund Olesen
406f8a63a15SJakob Stoklund Olesen // Some of the clobbered registers are live before I, not a valid insertion
407f8a63a15SJakob Stoklund Olesen // point.
408f8a63a15SJakob Stoklund Olesen if (!LiveRegUnits.empty()) {
409d34e60caSNicola Zaghen LLVM_DEBUG({
410f8a63a15SJakob Stoklund Olesen dbgs() << "Would clobber";
411d5adba10SKazu Hirata for (unsigned LRU : LiveRegUnits)
412d5adba10SKazu Hirata dbgs() << ' ' << printRegUnit(LRU, TRI);
413f8a63a15SJakob Stoklund Olesen dbgs() << " live before " << *I;
414f8a63a15SJakob Stoklund Olesen });
415f8a63a15SJakob Stoklund Olesen continue;
416f8a63a15SJakob Stoklund Olesen }
417f8a63a15SJakob Stoklund Olesen
418f8a63a15SJakob Stoklund Olesen // This is a valid insertion point.
419f8a63a15SJakob Stoklund Olesen InsertionPoint = I;
420d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Can insert before " << *I);
421f8a63a15SJakob Stoklund Olesen return true;
422f8a63a15SJakob Stoklund Olesen }
423d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
424f8a63a15SJakob Stoklund Olesen return false;
425f8a63a15SJakob Stoklund Olesen }
426f8a63a15SJakob Stoklund Olesen
427f8a63a15SJakob Stoklund Olesen
428f8a63a15SJakob Stoklund Olesen
429f8a63a15SJakob Stoklund Olesen /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
430f8a63a15SJakob Stoklund Olesen /// a potential candidate for if-conversion. Fill out the internal state.
431f8a63a15SJakob Stoklund Olesen ///
canConvertIf(MachineBasicBlock * MBB,bool Predicate)432be699bf3SThomas Raoux bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB, bool Predicate) {
433f8a63a15SJakob Stoklund Olesen Head = MBB;
434c0196b1bSCraig Topper TBB = FBB = Tail = nullptr;
435f8a63a15SJakob Stoklund Olesen
436f8a63a15SJakob Stoklund Olesen if (Head->succ_size() != 2)
437f8a63a15SJakob Stoklund Olesen return false;
438f8a63a15SJakob Stoklund Olesen MachineBasicBlock *Succ0 = Head->succ_begin()[0];
439f8a63a15SJakob Stoklund Olesen MachineBasicBlock *Succ1 = Head->succ_begin()[1];
440f8a63a15SJakob Stoklund Olesen
441f8a63a15SJakob Stoklund Olesen // Canonicalize so Succ0 has MBB as its single predecessor.
442f8a63a15SJakob Stoklund Olesen if (Succ0->pred_size() != 1)
443f8a63a15SJakob Stoklund Olesen std::swap(Succ0, Succ1);
444f8a63a15SJakob Stoklund Olesen
445f8a63a15SJakob Stoklund Olesen if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
446f8a63a15SJakob Stoklund Olesen return false;
447f8a63a15SJakob Stoklund Olesen
448f8a63a15SJakob Stoklund Olesen Tail = Succ0->succ_begin()[0];
449f8a63a15SJakob Stoklund Olesen
450f8a63a15SJakob Stoklund Olesen // This is not a triangle.
451f8a63a15SJakob Stoklund Olesen if (Tail != Succ1) {
452f8a63a15SJakob Stoklund Olesen // Check for a diamond. We won't deal with any critical edges.
453f8a63a15SJakob Stoklund Olesen if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
454f8a63a15SJakob Stoklund Olesen Succ1->succ_begin()[0] != Tail)
455f8a63a15SJakob Stoklund Olesen return false;
456d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
45725528d6dSFrancis Visoiu Mistrih << printMBBReference(*Succ0) << "/"
45825528d6dSFrancis Visoiu Mistrih << printMBBReference(*Succ1) << " -> "
45925528d6dSFrancis Visoiu Mistrih << printMBBReference(*Tail) << '\n');
460f8a63a15SJakob Stoklund Olesen
461f8a63a15SJakob Stoklund Olesen // Live-in physregs are tricky to get right when speculating code.
462f8a63a15SJakob Stoklund Olesen if (!Tail->livein_empty()) {
463d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
464f8a63a15SJakob Stoklund Olesen return false;
465f8a63a15SJakob Stoklund Olesen }
466f8a63a15SJakob Stoklund Olesen } else {
467d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
46825528d6dSFrancis Visoiu Mistrih << printMBBReference(*Succ0) << " -> "
46925528d6dSFrancis Visoiu Mistrih << printMBBReference(*Tail) << '\n');
470f8a63a15SJakob Stoklund Olesen }
471f8a63a15SJakob Stoklund Olesen
472f8a63a15SJakob Stoklund Olesen // This is a triangle or a diamond.
473be699bf3SThomas Raoux // Skip if we cannot predicate and there are no phis skip as there must be
474be699bf3SThomas Raoux // side effects that can only be handled with predication.
475be699bf3SThomas Raoux if (!Predicate && (Tail->empty() || !Tail->front().isPHI())) {
476d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "No phis in tail.\n");
477f8a63a15SJakob Stoklund Olesen return false;
478f8a63a15SJakob Stoklund Olesen }
479f8a63a15SJakob Stoklund Olesen
480f8a63a15SJakob Stoklund Olesen // The branch we're looking to eliminate must be analyzable.
481f8a63a15SJakob Stoklund Olesen Cond.clear();
48271c30a14SJacques Pienaar if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
483d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
484f8a63a15SJakob Stoklund Olesen return false;
485f8a63a15SJakob Stoklund Olesen }
486f8a63a15SJakob Stoklund Olesen
487f8a63a15SJakob Stoklund Olesen // This is weird, probably some sort of degenerate CFG.
488f8a63a15SJakob Stoklund Olesen if (!TBB) {
489020041d9SKrzysztof Parzyszek LLVM_DEBUG(dbgs() << "analyzeBranch didn't find conditional branch.\n");
490f8a63a15SJakob Stoklund Olesen return false;
491f8a63a15SJakob Stoklund Olesen }
492f8a63a15SJakob Stoklund Olesen
493295e346dSEli Friedman // Make sure the analyzed branch is conditional; one of the successors
494295e346dSEli Friedman // could be a landing pad. (Empty landing pads can be generated on Windows.)
495295e346dSEli Friedman if (Cond.empty()) {
496020041d9SKrzysztof Parzyszek LLVM_DEBUG(dbgs() << "analyzeBranch found an unconditional branch.\n");
497295e346dSEli Friedman return false;
498295e346dSEli Friedman }
499295e346dSEli Friedman
500020041d9SKrzysztof Parzyszek // analyzeBranch doesn't set FBB on a fall-through branch.
501f8a63a15SJakob Stoklund Olesen // Make sure it is always set.
502f8a63a15SJakob Stoklund Olesen FBB = TBB == Succ0 ? Succ1 : Succ0;
503f8a63a15SJakob Stoklund Olesen
504f8a63a15SJakob Stoklund Olesen // Any phis in the tail block must be convertible to selects.
505f8a63a15SJakob Stoklund Olesen PHIs.clear();
5060a99062cSJakob Stoklund Olesen MachineBasicBlock *TPred = getTPred();
5070a99062cSJakob Stoklund Olesen MachineBasicBlock *FPred = getFPred();
508f8a63a15SJakob Stoklund Olesen for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
509f8a63a15SJakob Stoklund Olesen I != E && I->isPHI(); ++I) {
510f8a63a15SJakob Stoklund Olesen PHIs.push_back(&*I);
511f8a63a15SJakob Stoklund Olesen PHIInfo &PI = PHIs.back();
512f8a63a15SJakob Stoklund Olesen // Find PHI operands corresponding to TPred and FPred.
513f8a63a15SJakob Stoklund Olesen for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
514f8a63a15SJakob Stoklund Olesen if (PI.PHI->getOperand(i+1).getMBB() == TPred)
515f8a63a15SJakob Stoklund Olesen PI.TReg = PI.PHI->getOperand(i).getReg();
516f8a63a15SJakob Stoklund Olesen if (PI.PHI->getOperand(i+1).getMBB() == FPred)
517f8a63a15SJakob Stoklund Olesen PI.FReg = PI.PHI->getOperand(i).getReg();
518f8a63a15SJakob Stoklund Olesen }
5192bea69bfSDaniel Sanders assert(Register::isVirtualRegister(PI.TReg) && "Bad PHI");
5202bea69bfSDaniel Sanders assert(Register::isVirtualRegister(PI.FReg) && "Bad PHI");
521f8a63a15SJakob Stoklund Olesen
522f8a63a15SJakob Stoklund Olesen // Get target information.
52367a87753SAmara Emerson if (!TII->canInsertSelect(*Head, Cond, PI.PHI->getOperand(0).getReg(),
52467a87753SAmara Emerson PI.TReg, PI.FReg, PI.CondCycles, PI.TCycles,
52567a87753SAmara Emerson PI.FCycles)) {
526d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
527f8a63a15SJakob Stoklund Olesen return false;
528f8a63a15SJakob Stoklund Olesen }
529f8a63a15SJakob Stoklund Olesen }
530f8a63a15SJakob Stoklund Olesen
531f8a63a15SJakob Stoklund Olesen // Check that the conditional instructions can be speculated.
532f8a63a15SJakob Stoklund Olesen InsertAfter.clear();
533f8a63a15SJakob Stoklund Olesen ClobberedRegUnits.reset();
534be699bf3SThomas Raoux if (Predicate) {
535be699bf3SThomas Raoux if (TBB != Tail && !canPredicateInstrs(TBB))
536be699bf3SThomas Raoux return false;
537be699bf3SThomas Raoux if (FBB != Tail && !canPredicateInstrs(FBB))
538be699bf3SThomas Raoux return false;
539be699bf3SThomas Raoux } else {
540f8a63a15SJakob Stoklund Olesen if (TBB != Tail && !canSpeculateInstrs(TBB))
541f8a63a15SJakob Stoklund Olesen return false;
542f8a63a15SJakob Stoklund Olesen if (FBB != Tail && !canSpeculateInstrs(FBB))
543f8a63a15SJakob Stoklund Olesen return false;
544be699bf3SThomas Raoux }
545f8a63a15SJakob Stoklund Olesen
546f8a63a15SJakob Stoklund Olesen // Try to find a valid insertion point for the speculated instructions in the
547f8a63a15SJakob Stoklund Olesen // head basic block.
548f8a63a15SJakob Stoklund Olesen if (!findInsertionPoint())
549f8a63a15SJakob Stoklund Olesen return false;
550f8a63a15SJakob Stoklund Olesen
551d0af1d96SJakob Stoklund Olesen if (isTriangle())
552d0af1d96SJakob Stoklund Olesen ++NumTrianglesSeen;
553d0af1d96SJakob Stoklund Olesen else
554d0af1d96SJakob Stoklund Olesen ++NumDiamondsSeen;
555f8a63a15SJakob Stoklund Olesen return true;
556f8a63a15SJakob Stoklund Olesen }
557f8a63a15SJakob Stoklund Olesen
558421569b2SJon Roelofs /// \return true iff the two registers are known to have the same value.
hasSameValue(const MachineRegisterInfo & MRI,const TargetInstrInfo * TII,Register TReg,Register FReg)559421569b2SJon Roelofs static bool hasSameValue(const MachineRegisterInfo &MRI,
560421569b2SJon Roelofs const TargetInstrInfo *TII, Register TReg,
561421569b2SJon Roelofs Register FReg) {
562421569b2SJon Roelofs if (TReg == FReg)
563421569b2SJon Roelofs return true;
564421569b2SJon Roelofs
565421569b2SJon Roelofs if (!TReg.isVirtual() || !FReg.isVirtual())
566421569b2SJon Roelofs return false;
567421569b2SJon Roelofs
568421569b2SJon Roelofs const MachineInstr *TDef = MRI.getUniqueVRegDef(TReg);
569421569b2SJon Roelofs const MachineInstr *FDef = MRI.getUniqueVRegDef(FReg);
570421569b2SJon Roelofs if (!TDef || !FDef)
571421569b2SJon Roelofs return false;
572421569b2SJon Roelofs
573421569b2SJon Roelofs // If there are side-effects, all bets are off.
574421569b2SJon Roelofs if (TDef->hasUnmodeledSideEffects())
575421569b2SJon Roelofs return false;
576421569b2SJon Roelofs
577421569b2SJon Roelofs // If the instruction could modify memory, or there may be some intervening
578421569b2SJon Roelofs // store between the two, we can't consider them to be equal.
579*8d0383ebSMatt Arsenault if (TDef->mayLoadOrStore() && !TDef->isDereferenceableInvariantLoad())
580421569b2SJon Roelofs return false;
581421569b2SJon Roelofs
582421569b2SJon Roelofs // We also can't guarantee that they are the same if, for example, the
583421569b2SJon Roelofs // instructions are both a copy from a physical reg, because some other
584421569b2SJon Roelofs // instruction may have modified the value in that reg between the two
585421569b2SJon Roelofs // defining insts.
586421569b2SJon Roelofs if (any_of(TDef->uses(), [](const MachineOperand &MO) {
587421569b2SJon Roelofs return MO.isReg() && MO.getReg().isPhysical();
588421569b2SJon Roelofs }))
589421569b2SJon Roelofs return false;
590421569b2SJon Roelofs
591421569b2SJon Roelofs // Check whether the two defining instructions produce the same value(s).
592421569b2SJon Roelofs if (!TII->produceSameValue(*TDef, *FDef, &MRI))
593421569b2SJon Roelofs return false;
594421569b2SJon Roelofs
595421569b2SJon Roelofs // Further, check that the two defs come from corresponding operands.
596421569b2SJon Roelofs int TIdx = TDef->findRegisterDefOperandIdx(TReg);
597421569b2SJon Roelofs int FIdx = FDef->findRegisterDefOperandIdx(FReg);
598421569b2SJon Roelofs if (TIdx == -1 || FIdx == -1)
599421569b2SJon Roelofs return false;
600421569b2SJon Roelofs
601421569b2SJon Roelofs return TIdx == FIdx;
602421569b2SJon Roelofs }
603421569b2SJon Roelofs
60483a927d8SJakob Stoklund Olesen /// replacePHIInstrs - Completely replace PHI instructions with selects.
60583a927d8SJakob Stoklund Olesen /// This is possible when the only Tail predecessors are the if-converted
60683a927d8SJakob Stoklund Olesen /// blocks.
replacePHIInstrs()60783a927d8SJakob Stoklund Olesen void SSAIfConv::replacePHIInstrs() {
60883a927d8SJakob Stoklund Olesen assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
609f8a63a15SJakob Stoklund Olesen MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
610f8a63a15SJakob Stoklund Olesen assert(FirstTerm != Head->end() && "No terminators");
611f8a63a15SJakob Stoklund Olesen DebugLoc HeadDL = FirstTerm->getDebugLoc();
612f8a63a15SJakob Stoklund Olesen
613f8a63a15SJakob Stoklund Olesen // Convert all PHIs to select instructions inserted before FirstTerm.
614f8a63a15SJakob Stoklund Olesen for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
615f8a63a15SJakob Stoklund Olesen PHIInfo &PI = PHIs[i];
616d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
6170c476111SDaniel Sanders Register DstReg = PI.PHI->getOperand(0).getReg();
618421569b2SJon Roelofs if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
619421569b2SJon Roelofs // We do not need the select instruction if both incoming values are
620421569b2SJon Roelofs // equal, but we do need a COPY.
621421569b2SJon Roelofs BuildMI(*Head, FirstTerm, HeadDL, TII->get(TargetOpcode::COPY), DstReg)
622421569b2SJon Roelofs .addReg(PI.TReg);
623421569b2SJon Roelofs } else {
624421569b2SJon Roelofs TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg,
625421569b2SJon Roelofs PI.FReg);
626421569b2SJon Roelofs }
627d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
628f8a63a15SJakob Stoklund Olesen PI.PHI->eraseFromParent();
629c0196b1bSCraig Topper PI.PHI = nullptr;
630f8a63a15SJakob Stoklund Olesen }
63183a927d8SJakob Stoklund Olesen }
63283a927d8SJakob Stoklund Olesen
63383a927d8SJakob Stoklund Olesen /// rewritePHIOperands - When there are additional Tail predecessors, insert
63483a927d8SJakob Stoklund Olesen /// select instructions in Head and rewrite PHI operands to use the selects.
63583a927d8SJakob Stoklund Olesen /// Keep the PHI instructions in Tail to handle the other predecessors.
rewritePHIOperands()63683a927d8SJakob Stoklund Olesen void SSAIfConv::rewritePHIOperands() {
63783a927d8SJakob Stoklund Olesen MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
63883a927d8SJakob Stoklund Olesen assert(FirstTerm != Head->end() && "No terminators");
63983a927d8SJakob Stoklund Olesen DebugLoc HeadDL = FirstTerm->getDebugLoc();
64083a927d8SJakob Stoklund Olesen
64183a927d8SJakob Stoklund Olesen // Convert all PHIs to select instructions inserted before FirstTerm.
64283a927d8SJakob Stoklund Olesen for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
64383a927d8SJakob Stoklund Olesen PHIInfo &PI = PHIs[i];
644e0b3499dSYi Jiang unsigned DstReg = 0;
645e0b3499dSYi Jiang
646d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
647421569b2SJon Roelofs if (hasSameValue(*MRI, TII, PI.TReg, PI.FReg)) {
648e0b3499dSYi Jiang // We do not need the select instruction if both incoming values are
649e0b3499dSYi Jiang // equal.
650e0b3499dSYi Jiang DstReg = PI.TReg;
651e0b3499dSYi Jiang } else {
6520c476111SDaniel Sanders Register PHIDst = PI.PHI->getOperand(0).getReg();
653e0b3499dSYi Jiang DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
654e0b3499dSYi Jiang TII->insertSelect(*Head, FirstTerm, HeadDL,
655e0b3499dSYi Jiang DstReg, Cond, PI.TReg, PI.FReg);
656d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
657e0b3499dSYi Jiang }
65883a927d8SJakob Stoklund Olesen
65983a927d8SJakob Stoklund Olesen // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
66083a927d8SJakob Stoklund Olesen for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
66183a927d8SJakob Stoklund Olesen MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
66283a927d8SJakob Stoklund Olesen if (MBB == getTPred()) {
66383a927d8SJakob Stoklund Olesen PI.PHI->getOperand(i-1).setMBB(Head);
66483a927d8SJakob Stoklund Olesen PI.PHI->getOperand(i-2).setReg(DstReg);
66583a927d8SJakob Stoklund Olesen } else if (MBB == getFPred()) {
66637b37838SShengchen Kan PI.PHI->removeOperand(i-1);
66737b37838SShengchen Kan PI.PHI->removeOperand(i-2);
66883a927d8SJakob Stoklund Olesen }
66983a927d8SJakob Stoklund Olesen }
670d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " --> " << *PI.PHI);
67183a927d8SJakob Stoklund Olesen }
67283a927d8SJakob Stoklund Olesen }
67383a927d8SJakob Stoklund Olesen
67483a927d8SJakob Stoklund Olesen /// convertIf - Execute the if conversion after canConvertIf has determined the
67583a927d8SJakob Stoklund Olesen /// feasibility.
67683a927d8SJakob Stoklund Olesen ///
67783a927d8SJakob Stoklund Olesen /// Any basic blocks erased will be added to RemovedBlocks.
67883a927d8SJakob Stoklund Olesen ///
convertIf(SmallVectorImpl<MachineBasicBlock * > & RemovedBlocks,bool Predicate)679be699bf3SThomas Raoux void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemovedBlocks,
680be699bf3SThomas Raoux bool Predicate) {
68183a927d8SJakob Stoklund Olesen assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
68283a927d8SJakob Stoklund Olesen
683d0af1d96SJakob Stoklund Olesen // Update statistics.
684d0af1d96SJakob Stoklund Olesen if (isTriangle())
685d0af1d96SJakob Stoklund Olesen ++NumTrianglesConv;
686d0af1d96SJakob Stoklund Olesen else
687d0af1d96SJakob Stoklund Olesen ++NumDiamondsConv;
688d0af1d96SJakob Stoklund Olesen
68983a927d8SJakob Stoklund Olesen // Move all instructions into Head, except for the terminators.
690be699bf3SThomas Raoux if (TBB != Tail) {
691be699bf3SThomas Raoux if (Predicate)
692be699bf3SThomas Raoux PredicateBlock(TBB, /*ReversePredicate=*/false);
69383a927d8SJakob Stoklund Olesen Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
694be699bf3SThomas Raoux }
695be699bf3SThomas Raoux if (FBB != Tail) {
696be699bf3SThomas Raoux if (Predicate)
697be699bf3SThomas Raoux PredicateBlock(FBB, /*ReversePredicate=*/true);
69883a927d8SJakob Stoklund Olesen Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
699be699bf3SThomas Raoux }
70083a927d8SJakob Stoklund Olesen // Are there extra Tail predecessors?
70183a927d8SJakob Stoklund Olesen bool ExtraPreds = Tail->pred_size() != 2;
70283a927d8SJakob Stoklund Olesen if (ExtraPreds)
70383a927d8SJakob Stoklund Olesen rewritePHIOperands();
70483a927d8SJakob Stoklund Olesen else
70583a927d8SJakob Stoklund Olesen replacePHIInstrs();
706f8a63a15SJakob Stoklund Olesen
707f8a63a15SJakob Stoklund Olesen // Fix up the CFG, temporarily leave Head without any successors.
708f8a63a15SJakob Stoklund Olesen Head->removeSuccessor(TBB);
709c106989fSCong Hou Head->removeSuccessor(FBB, true);
710f8a63a15SJakob Stoklund Olesen if (TBB != Tail)
711c106989fSCong Hou TBB->removeSuccessor(Tail, true);
712f8a63a15SJakob Stoklund Olesen if (FBB != Tail)
713c106989fSCong Hou FBB->removeSuccessor(Tail, true);
714f8a63a15SJakob Stoklund Olesen
715f8a63a15SJakob Stoklund Olesen // Fix up Head's terminators.
716f8a63a15SJakob Stoklund Olesen // It should become a single branch or a fallthrough.
71783a927d8SJakob Stoklund Olesen DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
7181b9fc8edSMatt Arsenault TII->removeBranch(*Head);
719f8a63a15SJakob Stoklund Olesen
720f8a63a15SJakob Stoklund Olesen // Erase the now empty conditional blocks. It is likely that Head can fall
721f8a63a15SJakob Stoklund Olesen // through to Tail, and we can join the two blocks.
72202638392SJakob Stoklund Olesen if (TBB != Tail) {
72302638392SJakob Stoklund Olesen RemovedBlocks.push_back(TBB);
72402638392SJakob Stoklund Olesen TBB->eraseFromParent();
72502638392SJakob Stoklund Olesen }
72602638392SJakob Stoklund Olesen if (FBB != Tail) {
72702638392SJakob Stoklund Olesen RemovedBlocks.push_back(FBB);
72802638392SJakob Stoklund Olesen FBB->eraseFromParent();
72902638392SJakob Stoklund Olesen }
730f8a63a15SJakob Stoklund Olesen
731f8a63a15SJakob Stoklund Olesen assert(Head->succ_empty() && "Additional head successors?");
73283a927d8SJakob Stoklund Olesen if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
733f8a63a15SJakob Stoklund Olesen // Splice Tail onto the end of Head.
734d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
735d34e60caSNicola Zaghen << " into head " << printMBBReference(*Head) << '\n');
736f8a63a15SJakob Stoklund Olesen Head->splice(Head->end(), Tail,
737f8a63a15SJakob Stoklund Olesen Tail->begin(), Tail->end());
738f8a63a15SJakob Stoklund Olesen Head->transferSuccessorsAndUpdatePHIs(Tail);
73902638392SJakob Stoklund Olesen RemovedBlocks.push_back(Tail);
74002638392SJakob Stoklund Olesen Tail->eraseFromParent();
741f8a63a15SJakob Stoklund Olesen } else {
742f8a63a15SJakob Stoklund Olesen // We need a branch to Tail, let code placement work it out later.
743d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
744f8a63a15SJakob Stoklund Olesen SmallVector<MachineOperand, 0> EmptyCond;
745e8e0f5caSMatt Arsenault TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
746f8a63a15SJakob Stoklund Olesen Head->addSuccessor(Tail);
747f8a63a15SJakob Stoklund Olesen }
748d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << *Head);
749f8a63a15SJakob Stoklund Olesen }
750f8a63a15SJakob Stoklund Olesen
751f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
752f8a63a15SJakob Stoklund Olesen // EarlyIfConverter Pass
753f8a63a15SJakob Stoklund Olesen //===----------------------------------------------------------------------===//
754f8a63a15SJakob Stoklund Olesen
755f8a63a15SJakob Stoklund Olesen namespace {
756f8a63a15SJakob Stoklund Olesen class EarlyIfConverter : public MachineFunctionPass {
757f8a63a15SJakob Stoklund Olesen const TargetInstrInfo *TII;
758f8a63a15SJakob Stoklund Olesen const TargetRegisterInfo *TRI;
75911759457SPete Cooper MCSchedModel SchedModel;
760f8a63a15SJakob Stoklund Olesen MachineRegisterInfo *MRI;
76102638392SJakob Stoklund Olesen MachineDominatorTree *DomTree;
762bc90a4eaSJakob Stoklund Olesen MachineLoopInfo *Loops;
763f9029fefSJakob Stoklund Olesen MachineTraceMetrics *Traces;
764f9029fefSJakob Stoklund Olesen MachineTraceMetrics::Ensemble *MinInstr;
765f8a63a15SJakob Stoklund Olesen SSAIfConv IfConv;
766f8a63a15SJakob Stoklund Olesen
767f8a63a15SJakob Stoklund Olesen public:
768f8a63a15SJakob Stoklund Olesen static char ID;
EarlyIfConverter()769f8a63a15SJakob Stoklund Olesen EarlyIfConverter() : MachineFunctionPass(ID) {}
7704584cd54SCraig Topper void getAnalysisUsage(AnalysisUsage &AU) const override;
7714584cd54SCraig Topper bool runOnMachineFunction(MachineFunction &MF) override;
getPassName() const772117296c0SMehdi Amini StringRef getPassName() const override { return "Early If-Conversion"; }
773f8a63a15SJakob Stoklund Olesen
774f8a63a15SJakob Stoklund Olesen private:
775f8a63a15SJakob Stoklund Olesen bool tryConvertIf(MachineBasicBlock*);
776f9029fefSJakob Stoklund Olesen void invalidateTraces();
777f9029fefSJakob Stoklund Olesen bool shouldConvertIf();
778f8a63a15SJakob Stoklund Olesen };
779f8a63a15SJakob Stoklund Olesen } // end anonymous namespace
780f8a63a15SJakob Stoklund Olesen
781f8a63a15SJakob Stoklund Olesen char EarlyIfConverter::ID = 0;
782f8a63a15SJakob Stoklund Olesen char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
783f8a63a15SJakob Stoklund Olesen
7841527baabSMatthias Braun INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
7851527baabSMatthias Braun "Early If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)786f8a63a15SJakob Stoklund Olesen INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
78702638392SJakob Stoklund Olesen INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
788f9029fefSJakob Stoklund Olesen INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
7891527baabSMatthias Braun INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
7901527baabSMatthias Braun "Early If Converter", false, false)
791f8a63a15SJakob Stoklund Olesen
792f8a63a15SJakob Stoklund Olesen void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
793f8a63a15SJakob Stoklund Olesen AU.addRequired<MachineBranchProbabilityInfo>();
79402638392SJakob Stoklund Olesen AU.addRequired<MachineDominatorTree>();
79502638392SJakob Stoklund Olesen AU.addPreserved<MachineDominatorTree>();
796bc90a4eaSJakob Stoklund Olesen AU.addRequired<MachineLoopInfo>();
797bc90a4eaSJakob Stoklund Olesen AU.addPreserved<MachineLoopInfo>();
798f9029fefSJakob Stoklund Olesen AU.addRequired<MachineTraceMetrics>();
799f9029fefSJakob Stoklund Olesen AU.addPreserved<MachineTraceMetrics>();
800f8a63a15SJakob Stoklund Olesen MachineFunctionPass::getAnalysisUsage(AU);
801f8a63a15SJakob Stoklund Olesen }
802f8a63a15SJakob Stoklund Olesen
803be699bf3SThomas Raoux namespace {
80402638392SJakob Stoklund Olesen /// Update the dominator tree after if-conversion erased some blocks.
updateDomTree(MachineDominatorTree * DomTree,const SSAIfConv & IfConv,ArrayRef<MachineBasicBlock * > Removed)805be699bf3SThomas Raoux void updateDomTree(MachineDominatorTree *DomTree, const SSAIfConv &IfConv,
806be699bf3SThomas Raoux ArrayRef<MachineBasicBlock *> Removed) {
80702638392SJakob Stoklund Olesen // convertIf can remove TBB, FBB, and Tail can be merged into Head.
80802638392SJakob Stoklund Olesen // TBB and FBB should not dominate any blocks.
80902638392SJakob Stoklund Olesen // Tail children should be transferred to Head.
81002638392SJakob Stoklund Olesen MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
8119e6d1f4bSKazu Hirata for (auto *B : Removed) {
812be699bf3SThomas Raoux MachineDomTreeNode *Node = DomTree->getNode(B);
81302638392SJakob Stoklund Olesen assert(Node != HeadNode && "Cannot erase the head node");
81402638392SJakob Stoklund Olesen while (Node->getNumChildren()) {
81502638392SJakob Stoklund Olesen assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
81676c5cb05SNicolai Hähnle DomTree->changeImmediateDominator(Node->back(), HeadNode);
81702638392SJakob Stoklund Olesen }
818be699bf3SThomas Raoux DomTree->eraseNode(B);
81902638392SJakob Stoklund Olesen }
820f8a63a15SJakob Stoklund Olesen }
821f8a63a15SJakob Stoklund Olesen
822bc90a4eaSJakob Stoklund Olesen /// Update LoopInfo after if-conversion.
updateLoops(MachineLoopInfo * Loops,ArrayRef<MachineBasicBlock * > Removed)823be699bf3SThomas Raoux void updateLoops(MachineLoopInfo *Loops,
824be699bf3SThomas Raoux ArrayRef<MachineBasicBlock *> Removed) {
825bc90a4eaSJakob Stoklund Olesen if (!Loops)
826bc90a4eaSJakob Stoklund Olesen return;
827bc90a4eaSJakob Stoklund Olesen // If-conversion doesn't change loop structure, and it doesn't mess with back
828bc90a4eaSJakob Stoklund Olesen // edges, so updating LoopInfo is simply removing the dead blocks.
8299e6d1f4bSKazu Hirata for (auto *B : Removed)
830be699bf3SThomas Raoux Loops->removeBlock(B);
831bc90a4eaSJakob Stoklund Olesen }
832be699bf3SThomas Raoux } // namespace
833bc90a4eaSJakob Stoklund Olesen
834f9029fefSJakob Stoklund Olesen /// Invalidate MachineTraceMetrics before if-conversion.
invalidateTraces()835f9029fefSJakob Stoklund Olesen void EarlyIfConverter::invalidateTraces() {
836a12a7d5fSJakob Stoklund Olesen Traces->verifyAnalysis();
837f9029fefSJakob Stoklund Olesen Traces->invalidate(IfConv.Head);
838f9029fefSJakob Stoklund Olesen Traces->invalidate(IfConv.Tail);
839f9029fefSJakob Stoklund Olesen Traces->invalidate(IfConv.TBB);
840f9029fefSJakob Stoklund Olesen Traces->invalidate(IfConv.FBB);
841a12a7d5fSJakob Stoklund Olesen Traces->verifyAnalysis();
842f9029fefSJakob Stoklund Olesen }
843f9029fefSJakob Stoklund Olesen
844bc55bfdeSJakob Stoklund Olesen // Adjust cycles with downward saturation.
adjCycles(unsigned Cyc,int Delta)845bc55bfdeSJakob Stoklund Olesen static unsigned adjCycles(unsigned Cyc, int Delta) {
846bc55bfdeSJakob Stoklund Olesen if (Delta < 0 && Cyc + Delta > Cyc)
847bc55bfdeSJakob Stoklund Olesen return 0;
848bc55bfdeSJakob Stoklund Olesen return Cyc + Delta;
849bc55bfdeSJakob Stoklund Olesen }
850bc55bfdeSJakob Stoklund Olesen
851b15f2bd3SJon Roelofs namespace {
852b15f2bd3SJon Roelofs /// Helper class to simplify emission of cycle counts into optimization remarks.
853b15f2bd3SJon Roelofs struct Cycles {
854b15f2bd3SJon Roelofs const char *Key;
855b15f2bd3SJon Roelofs unsigned Value;
856b15f2bd3SJon Roelofs };
operator <<(Remark & R,Cycles C)857b15f2bd3SJon Roelofs template <typename Remark> Remark &operator<<(Remark &R, Cycles C) {
858b15f2bd3SJon Roelofs return R << ore::NV(C.Key, C.Value) << (C.Value == 1 ? " cycle" : " cycles");
859b15f2bd3SJon Roelofs }
860b15f2bd3SJon Roelofs } // anonymous namespace
861b15f2bd3SJon Roelofs
862f9029fefSJakob Stoklund Olesen /// Apply cost model and heuristics to the if-conversion in IfConv.
863f9029fefSJakob Stoklund Olesen /// Return true if the conversion is a good idea.
864f9029fefSJakob Stoklund Olesen ///
shouldConvertIf()865f9029fefSJakob Stoklund Olesen bool EarlyIfConverter::shouldConvertIf() {
866fa8a26f9SJakob Stoklund Olesen // Stress testing mode disables all cost considerations.
867fa8a26f9SJakob Stoklund Olesen if (Stress)
868fa8a26f9SJakob Stoklund Olesen return true;
869fa8a26f9SJakob Stoklund Olesen
870f9029fefSJakob Stoklund Olesen if (!MinInstr)
871f9029fefSJakob Stoklund Olesen MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
87275d9d515SJakob Stoklund Olesen
873bc55bfdeSJakob Stoklund Olesen MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
874bc55bfdeSJakob Stoklund Olesen MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
875d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
876bc55bfdeSJakob Stoklund Olesen unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
877bc55bfdeSJakob Stoklund Olesen FBBTrace.getCriticalPath());
878bc55bfdeSJakob Stoklund Olesen
879bc55bfdeSJakob Stoklund Olesen // Set a somewhat arbitrary limit on the critical path extension we accept.
88011759457SPete Cooper unsigned CritLimit = SchedModel.MispredictPenalty/2;
881bc55bfdeSJakob Stoklund Olesen
882b15f2bd3SJon Roelofs MachineBasicBlock &MBB = *IfConv.Head;
883b15f2bd3SJon Roelofs MachineOptimizationRemarkEmitter MORE(*MBB.getParent(), nullptr);
884b15f2bd3SJon Roelofs
885bc55bfdeSJakob Stoklund Olesen // If-conversion only makes sense when there is unexploited ILP. Compute the
886bc55bfdeSJakob Stoklund Olesen // maximum-ILP resource length of the trace after if-conversion. Compare it
887bc55bfdeSJakob Stoklund Olesen // to the shortest critical path.
888bc55bfdeSJakob Stoklund Olesen SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
889bc55bfdeSJakob Stoklund Olesen if (IfConv.TBB != IfConv.Tail)
890bc55bfdeSJakob Stoklund Olesen ExtraBlocks.push_back(IfConv.TBB);
891bc55bfdeSJakob Stoklund Olesen unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
892d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Resource length " << ResLength
893bc55bfdeSJakob Stoklund Olesen << ", minimal critical path " << MinCrit << '\n');
894bc55bfdeSJakob Stoklund Olesen if (ResLength > MinCrit + CritLimit) {
895d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
896b15f2bd3SJon Roelofs MORE.emit([&]() {
897b15f2bd3SJon Roelofs MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
898b15f2bd3SJon Roelofs MBB.findDebugLoc(MBB.back()), &MBB);
899b15f2bd3SJon Roelofs R << "did not if-convert branch: the resulting critical path ("
900b15f2bd3SJon Roelofs << Cycles{"ResLength", ResLength}
901b15f2bd3SJon Roelofs << ") would extend the shorter leg's critical path ("
902b15f2bd3SJon Roelofs << Cycles{"MinCrit", MinCrit} << ") by more than the threshold of "
903b15f2bd3SJon Roelofs << Cycles{"CritLimit", CritLimit}
904b15f2bd3SJon Roelofs << ", which cannot be hidden by available ILP.";
905b15f2bd3SJon Roelofs return R;
906b15f2bd3SJon Roelofs });
90775d9d515SJakob Stoklund Olesen return false;
90875d9d515SJakob Stoklund Olesen }
909bc55bfdeSJakob Stoklund Olesen
910bc55bfdeSJakob Stoklund Olesen // Assume that the depth of the first head terminator will also be the depth
911bc55bfdeSJakob Stoklund Olesen // of the select instruction inserted, as determined by the flag dependency.
912bc55bfdeSJakob Stoklund Olesen // TBB / FBB data dependencies may delay the select even more.
913bc55bfdeSJakob Stoklund Olesen MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
914bc55bfdeSJakob Stoklund Olesen unsigned BranchDepth =
915e59c8af7SDuncan P. N. Exon Smith HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
916d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
917bc55bfdeSJakob Stoklund Olesen
918bc55bfdeSJakob Stoklund Olesen // Look at all the tail phis, and compute the critical path extension caused
919bc55bfdeSJakob Stoklund Olesen // by inserting select instructions.
920bc55bfdeSJakob Stoklund Olesen MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
921b15f2bd3SJon Roelofs struct CriticalPathInfo {
9226731eb64SSimon Pilgrim unsigned Extra; // Count of extra cycles that the component adds.
9236731eb64SSimon Pilgrim unsigned Depth; // Absolute depth of the component in cycles.
924b15f2bd3SJon Roelofs };
925b15f2bd3SJon Roelofs CriticalPathInfo Cond{};
926b15f2bd3SJon Roelofs CriticalPathInfo TBlock{};
927b15f2bd3SJon Roelofs CriticalPathInfo FBlock{};
928b15f2bd3SJon Roelofs bool ShouldConvert = true;
929bc55bfdeSJakob Stoklund Olesen for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
930bc55bfdeSJakob Stoklund Olesen SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
931e59c8af7SDuncan P. N. Exon Smith unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
932e59c8af7SDuncan P. N. Exon Smith unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
933d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
934bc55bfdeSJakob Stoklund Olesen
935bc55bfdeSJakob Stoklund Olesen // The condition is pulled into the critical path.
936bc55bfdeSJakob Stoklund Olesen unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
937bc55bfdeSJakob Stoklund Olesen if (CondDepth > MaxDepth) {
938bc55bfdeSJakob Stoklund Olesen unsigned Extra = CondDepth - MaxDepth;
939d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
940b15f2bd3SJon Roelofs if (Extra > Cond.Extra)
941b15f2bd3SJon Roelofs Cond = {Extra, CondDepth};
942bc55bfdeSJakob Stoklund Olesen if (Extra > CritLimit) {
943d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
944b15f2bd3SJon Roelofs ShouldConvert = false;
945bc55bfdeSJakob Stoklund Olesen }
946bc55bfdeSJakob Stoklund Olesen }
947bc55bfdeSJakob Stoklund Olesen
948bc55bfdeSJakob Stoklund Olesen // The TBB value is pulled into the critical path.
949e59c8af7SDuncan P. N. Exon Smith unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
950bc55bfdeSJakob Stoklund Olesen if (TDepth > MaxDepth) {
951bc55bfdeSJakob Stoklund Olesen unsigned Extra = TDepth - MaxDepth;
952d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
953b15f2bd3SJon Roelofs if (Extra > TBlock.Extra)
954b15f2bd3SJon Roelofs TBlock = {Extra, TDepth};
955bc55bfdeSJakob Stoklund Olesen if (Extra > CritLimit) {
956d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
957b15f2bd3SJon Roelofs ShouldConvert = false;
958bc55bfdeSJakob Stoklund Olesen }
959bc55bfdeSJakob Stoklund Olesen }
960bc55bfdeSJakob Stoklund Olesen
961bc55bfdeSJakob Stoklund Olesen // The FBB value is pulled into the critical path.
962e59c8af7SDuncan P. N. Exon Smith unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
963bc55bfdeSJakob Stoklund Olesen if (FDepth > MaxDepth) {
964bc55bfdeSJakob Stoklund Olesen unsigned Extra = FDepth - MaxDepth;
965d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
966b15f2bd3SJon Roelofs if (Extra > FBlock.Extra)
967b15f2bd3SJon Roelofs FBlock = {Extra, FDepth};
968bc55bfdeSJakob Stoklund Olesen if (Extra > CritLimit) {
969d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
970b15f2bd3SJon Roelofs ShouldConvert = false;
971bc55bfdeSJakob Stoklund Olesen }
972bc55bfdeSJakob Stoklund Olesen }
973bc55bfdeSJakob Stoklund Olesen }
974b15f2bd3SJon Roelofs
975b15f2bd3SJon Roelofs // Organize by "short" and "long" legs, since the diagnostics get confusing
976b15f2bd3SJon Roelofs // when referring to the "true" and "false" sides of the branch, given that
977b15f2bd3SJon Roelofs // those don't always correlate with what the user wrote in source-terms.
978b15f2bd3SJon Roelofs const CriticalPathInfo Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
979b15f2bd3SJon Roelofs const CriticalPathInfo Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
980b15f2bd3SJon Roelofs
981b15f2bd3SJon Roelofs if (ShouldConvert) {
982b15f2bd3SJon Roelofs MORE.emit([&]() {
983b15f2bd3SJon Roelofs MachineOptimizationRemark R(DEBUG_TYPE, "IfConversion",
984b15f2bd3SJon Roelofs MBB.back().getDebugLoc(), &MBB);
985b15f2bd3SJon Roelofs R << "performing if-conversion on branch: the condition adds "
986b15f2bd3SJon Roelofs << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
987b15f2bd3SJon Roelofs if (Short.Extra > 0)
988b15f2bd3SJon Roelofs R << ", and the short leg adds another "
989b15f2bd3SJon Roelofs << Cycles{"ShortCycles", Short.Extra};
990b15f2bd3SJon Roelofs if (Long.Extra > 0)
991b15f2bd3SJon Roelofs R << ", and the long leg adds another "
992b15f2bd3SJon Roelofs << Cycles{"LongCycles", Long.Extra};
993b15f2bd3SJon Roelofs R << ", each staying under the threshold of "
994b15f2bd3SJon Roelofs << Cycles{"CritLimit", CritLimit} << ".";
995b15f2bd3SJon Roelofs return R;
996b15f2bd3SJon Roelofs });
997b15f2bd3SJon Roelofs } else {
998b15f2bd3SJon Roelofs MORE.emit([&]() {
999b15f2bd3SJon Roelofs MachineOptimizationRemarkMissed R(DEBUG_TYPE, "IfConversion",
1000b15f2bd3SJon Roelofs MBB.back().getDebugLoc(), &MBB);
1001b15f2bd3SJon Roelofs R << "did not if-convert branch: the condition would add "
1002b15f2bd3SJon Roelofs << Cycles{"CondCycles", Cond.Extra} << " to the critical path";
1003b15f2bd3SJon Roelofs if (Cond.Extra > CritLimit)
1004b15f2bd3SJon Roelofs R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1005b15f2bd3SJon Roelofs if (Short.Extra > 0) {
1006b15f2bd3SJon Roelofs R << ", and the short leg would add another "
1007b15f2bd3SJon Roelofs << Cycles{"ShortCycles", Short.Extra};
1008b15f2bd3SJon Roelofs if (Short.Extra > CritLimit)
1009b15f2bd3SJon Roelofs R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1010b15f2bd3SJon Roelofs }
1011b15f2bd3SJon Roelofs if (Long.Extra > 0) {
1012b15f2bd3SJon Roelofs R << ", and the long leg would add another "
1013b15f2bd3SJon Roelofs << Cycles{"LongCycles", Long.Extra};
1014b15f2bd3SJon Roelofs if (Long.Extra > CritLimit)
1015b15f2bd3SJon Roelofs R << " exceeding the limit of " << Cycles{"CritLimit", CritLimit};
1016b15f2bd3SJon Roelofs }
1017b15f2bd3SJon Roelofs R << ".";
1018b15f2bd3SJon Roelofs return R;
1019b15f2bd3SJon Roelofs });
1020b15f2bd3SJon Roelofs }
1021b15f2bd3SJon Roelofs
1022b15f2bd3SJon Roelofs return ShouldConvert;
1023f9029fefSJakob Stoklund Olesen }
1024f9029fefSJakob Stoklund Olesen
102502638392SJakob Stoklund Olesen /// Attempt repeated if-conversion on MBB, return true if successful.
102602638392SJakob Stoklund Olesen ///
tryConvertIf(MachineBasicBlock * MBB)102702638392SJakob Stoklund Olesen bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
102802638392SJakob Stoklund Olesen bool Changed = false;
1029f9029fefSJakob Stoklund Olesen while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
103002638392SJakob Stoklund Olesen // If-convert MBB and update analyses.
1031f9029fefSJakob Stoklund Olesen invalidateTraces();
103202638392SJakob Stoklund Olesen SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
103302638392SJakob Stoklund Olesen IfConv.convertIf(RemovedBlocks);
103402638392SJakob Stoklund Olesen Changed = true;
1035be699bf3SThomas Raoux updateDomTree(DomTree, IfConv, RemovedBlocks);
1036be699bf3SThomas Raoux updateLoops(Loops, RemovedBlocks);
103702638392SJakob Stoklund Olesen }
103802638392SJakob Stoklund Olesen return Changed;
103902638392SJakob Stoklund Olesen }
1040f8a63a15SJakob Stoklund Olesen
runOnMachineFunction(MachineFunction & MF)1041f8a63a15SJakob Stoklund Olesen bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
1042d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
1043c8c2920aSDavid Blaikie << "********** Function: " << MF.getName() << '\n');
1044f1caa283SMatthias Braun if (skipFunction(MF.getFunction()))
104550271f78SAndrew Kaylor return false;
104650271f78SAndrew Kaylor
10476b0fcfeeSEric Christopher // Only run if conversion if the target wants it.
10483d4276f0SEric Christopher const TargetSubtargetInfo &STI = MF.getSubtarget();
10493d4276f0SEric Christopher if (!STI.enableEarlyIfConversion())
10509eff5178SEric Christopher return false;
10516b0fcfeeSEric Christopher
10523d4276f0SEric Christopher TII = STI.getInstrInfo();
10533d4276f0SEric Christopher TRI = STI.getRegisterInfo();
10543d4276f0SEric Christopher SchedModel = STI.getSchedModel();
1055f8a63a15SJakob Stoklund Olesen MRI = &MF.getRegInfo();
105602638392SJakob Stoklund Olesen DomTree = &getAnalysis<MachineDominatorTree>();
1057bc90a4eaSJakob Stoklund Olesen Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1058f9029fefSJakob Stoklund Olesen Traces = &getAnalysis<MachineTraceMetrics>();
1059c0196b1bSCraig Topper MinInstr = nullptr;
1060f8a63a15SJakob Stoklund Olesen
1061f8a63a15SJakob Stoklund Olesen bool Changed = false;
1062f8a63a15SJakob Stoklund Olesen IfConv.runOnMachineFunction(MF);
1063f8a63a15SJakob Stoklund Olesen
106402638392SJakob Stoklund Olesen // Visit blocks in dominator tree post-order. The post-order enables nested
106502638392SJakob Stoklund Olesen // if-conversion in a single pass. The tryConvertIf() function may erase
106602638392SJakob Stoklund Olesen // blocks, but only blocks dominated by the head block. This makes it safe to
106702638392SJakob Stoklund Olesen // update the dominator tree while the post-order iterator is still active.
10689e6d1f4bSKazu Hirata for (auto *DomNode : post_order(DomTree))
106925db4f41SDaniel Berlin if (tryConvertIf(DomNode->getBlock()))
1070f8a63a15SJakob Stoklund Olesen Changed = true;
1071f8a63a15SJakob Stoklund Olesen
1072f8a63a15SJakob Stoklund Olesen return Changed;
1073f8a63a15SJakob Stoklund Olesen }
1074be699bf3SThomas Raoux
1075be699bf3SThomas Raoux //===----------------------------------------------------------------------===//
1076be699bf3SThomas Raoux // EarlyIfPredicator Pass
1077be699bf3SThomas Raoux //===----------------------------------------------------------------------===//
1078be699bf3SThomas Raoux
1079be699bf3SThomas Raoux namespace {
1080be699bf3SThomas Raoux class EarlyIfPredicator : public MachineFunctionPass {
1081be699bf3SThomas Raoux const TargetInstrInfo *TII;
1082be699bf3SThomas Raoux const TargetRegisterInfo *TRI;
1083be699bf3SThomas Raoux TargetSchedModel SchedModel;
1084be699bf3SThomas Raoux MachineRegisterInfo *MRI;
1085be699bf3SThomas Raoux MachineDominatorTree *DomTree;
10861408e7e1Sshkzhang MachineBranchProbabilityInfo *MBPI;
1087be699bf3SThomas Raoux MachineLoopInfo *Loops;
1088be699bf3SThomas Raoux SSAIfConv IfConv;
1089be699bf3SThomas Raoux
1090be699bf3SThomas Raoux public:
1091be699bf3SThomas Raoux static char ID;
EarlyIfPredicator()1092be699bf3SThomas Raoux EarlyIfPredicator() : MachineFunctionPass(ID) {}
1093be699bf3SThomas Raoux void getAnalysisUsage(AnalysisUsage &AU) const override;
1094be699bf3SThomas Raoux bool runOnMachineFunction(MachineFunction &MF) override;
getPassName() const1095be699bf3SThomas Raoux StringRef getPassName() const override { return "Early If-predicator"; }
1096be699bf3SThomas Raoux
1097be699bf3SThomas Raoux protected:
1098be699bf3SThomas Raoux bool tryConvertIf(MachineBasicBlock *);
1099be699bf3SThomas Raoux bool shouldConvertIf();
1100be699bf3SThomas Raoux };
1101be699bf3SThomas Raoux } // end anonymous namespace
1102be699bf3SThomas Raoux
1103be699bf3SThomas Raoux #undef DEBUG_TYPE
1104be699bf3SThomas Raoux #define DEBUG_TYPE "early-if-predicator"
1105be699bf3SThomas Raoux
1106be699bf3SThomas Raoux char EarlyIfPredicator::ID = 0;
1107be699bf3SThomas Raoux char &llvm::EarlyIfPredicatorID = EarlyIfPredicator::ID;
1108be699bf3SThomas Raoux
1109be699bf3SThomas Raoux INITIALIZE_PASS_BEGIN(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator",
1110be699bf3SThomas Raoux false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)1111be699bf3SThomas Raoux INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
11121408e7e1Sshkzhang INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1113be699bf3SThomas Raoux INITIALIZE_PASS_END(EarlyIfPredicator, DEBUG_TYPE, "Early If Predicator", false,
1114be699bf3SThomas Raoux false)
1115be699bf3SThomas Raoux
1116be699bf3SThomas Raoux void EarlyIfPredicator::getAnalysisUsage(AnalysisUsage &AU) const {
11171408e7e1Sshkzhang AU.addRequired<MachineBranchProbabilityInfo>();
1118be699bf3SThomas Raoux AU.addRequired<MachineDominatorTree>();
1119be699bf3SThomas Raoux AU.addPreserved<MachineDominatorTree>();
1120be699bf3SThomas Raoux AU.addRequired<MachineLoopInfo>();
1121be699bf3SThomas Raoux AU.addPreserved<MachineLoopInfo>();
1122be699bf3SThomas Raoux MachineFunctionPass::getAnalysisUsage(AU);
1123be699bf3SThomas Raoux }
1124be699bf3SThomas Raoux
1125be699bf3SThomas Raoux /// Apply the target heuristic to decide if the transformation is profitable.
shouldConvertIf()1126be699bf3SThomas Raoux bool EarlyIfPredicator::shouldConvertIf() {
11271408e7e1Sshkzhang auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
1128be699bf3SThomas Raoux if (IfConv.isTriangle()) {
1129be699bf3SThomas Raoux MachineBasicBlock &IfBlock =
1130be699bf3SThomas Raoux (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
1131be699bf3SThomas Raoux
1132be699bf3SThomas Raoux unsigned ExtraPredCost = 0;
1133be699bf3SThomas Raoux unsigned Cycles = 0;
1134be699bf3SThomas Raoux for (MachineInstr &I : IfBlock) {
1135be699bf3SThomas Raoux unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1136be699bf3SThomas Raoux if (NumCycles > 1)
1137be699bf3SThomas Raoux Cycles += NumCycles - 1;
1138be699bf3SThomas Raoux ExtraPredCost += TII->getPredicationCost(I);
1139be699bf3SThomas Raoux }
1140be699bf3SThomas Raoux
1141be699bf3SThomas Raoux return TII->isProfitableToIfCvt(IfBlock, Cycles, ExtraPredCost,
11421408e7e1Sshkzhang TrueProbability);
1143be699bf3SThomas Raoux }
1144be699bf3SThomas Raoux unsigned TExtra = 0;
1145be699bf3SThomas Raoux unsigned FExtra = 0;
1146be699bf3SThomas Raoux unsigned TCycle = 0;
1147be699bf3SThomas Raoux unsigned FCycle = 0;
1148be699bf3SThomas Raoux for (MachineInstr &I : *IfConv.TBB) {
1149be699bf3SThomas Raoux unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1150be699bf3SThomas Raoux if (NumCycles > 1)
1151be699bf3SThomas Raoux TCycle += NumCycles - 1;
1152be699bf3SThomas Raoux TExtra += TII->getPredicationCost(I);
1153be699bf3SThomas Raoux }
1154be699bf3SThomas Raoux for (MachineInstr &I : *IfConv.FBB) {
1155be699bf3SThomas Raoux unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
1156be699bf3SThomas Raoux if (NumCycles > 1)
1157be699bf3SThomas Raoux FCycle += NumCycles - 1;
1158be699bf3SThomas Raoux FExtra += TII->getPredicationCost(I);
1159be699bf3SThomas Raoux }
1160be699bf3SThomas Raoux return TII->isProfitableToIfCvt(*IfConv.TBB, TCycle, TExtra, *IfConv.FBB,
11611408e7e1Sshkzhang FCycle, FExtra, TrueProbability);
1162be699bf3SThomas Raoux }
1163be699bf3SThomas Raoux
1164be699bf3SThomas Raoux /// Attempt repeated if-conversion on MBB, return true if successful.
1165be699bf3SThomas Raoux ///
tryConvertIf(MachineBasicBlock * MBB)1166be699bf3SThomas Raoux bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *MBB) {
1167be699bf3SThomas Raoux bool Changed = false;
1168be699bf3SThomas Raoux while (IfConv.canConvertIf(MBB, /*Predicate*/ true) && shouldConvertIf()) {
1169be699bf3SThomas Raoux // If-convert MBB and update analyses.
1170be699bf3SThomas Raoux SmallVector<MachineBasicBlock *, 4> RemovedBlocks;
1171be699bf3SThomas Raoux IfConv.convertIf(RemovedBlocks, /*Predicate*/ true);
1172be699bf3SThomas Raoux Changed = true;
1173be699bf3SThomas Raoux updateDomTree(DomTree, IfConv, RemovedBlocks);
1174be699bf3SThomas Raoux updateLoops(Loops, RemovedBlocks);
1175be699bf3SThomas Raoux }
1176be699bf3SThomas Raoux return Changed;
1177be699bf3SThomas Raoux }
1178be699bf3SThomas Raoux
runOnMachineFunction(MachineFunction & MF)1179be699bf3SThomas Raoux bool EarlyIfPredicator::runOnMachineFunction(MachineFunction &MF) {
1180be699bf3SThomas Raoux LLVM_DEBUG(dbgs() << "********** EARLY IF-PREDICATOR **********\n"
1181be699bf3SThomas Raoux << "********** Function: " << MF.getName() << '\n');
1182be699bf3SThomas Raoux if (skipFunction(MF.getFunction()))
1183be699bf3SThomas Raoux return false;
1184be699bf3SThomas Raoux
1185be699bf3SThomas Raoux const TargetSubtargetInfo &STI = MF.getSubtarget();
1186be699bf3SThomas Raoux TII = STI.getInstrInfo();
1187be699bf3SThomas Raoux TRI = STI.getRegisterInfo();
1188be699bf3SThomas Raoux MRI = &MF.getRegInfo();
1189be699bf3SThomas Raoux SchedModel.init(&STI);
1190be699bf3SThomas Raoux DomTree = &getAnalysis<MachineDominatorTree>();
1191be699bf3SThomas Raoux Loops = getAnalysisIfAvailable<MachineLoopInfo>();
11921408e7e1Sshkzhang MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1193be699bf3SThomas Raoux
1194be699bf3SThomas Raoux bool Changed = false;
1195be699bf3SThomas Raoux IfConv.runOnMachineFunction(MF);
1196be699bf3SThomas Raoux
1197be699bf3SThomas Raoux // Visit blocks in dominator tree post-order. The post-order enables nested
1198be699bf3SThomas Raoux // if-conversion in a single pass. The tryConvertIf() function may erase
1199be699bf3SThomas Raoux // blocks, but only blocks dominated by the head block. This makes it safe to
1200be699bf3SThomas Raoux // update the dominator tree while the post-order iterator is still active.
12019e6d1f4bSKazu Hirata for (auto *DomNode : post_order(DomTree))
1202be699bf3SThomas Raoux if (tryConvertIf(DomNode->getBlock()))
1203be699bf3SThomas Raoux Changed = true;
1204be699bf3SThomas Raoux
1205be699bf3SThomas Raoux return Changed;
1206be699bf3SThomas Raoux }
1207