blob: 0a83760befaa3942e0c25e3e55c434882dade4b5 [file] [log] [blame]
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +00001//===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Early if-conversion is for out-of-order CPUs that don't have a lot of
10// predicable instructions. The goal is to eliminate conditional branches that
11// may mispredict.
12//
13// Instructions from both sides of the branch are executed specutatively, and a
14// cmov instruction selects the result.
15//
16//===----------------------------------------------------------------------===//
17
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000018#include "llvm/ADT/BitVector.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000019#include "llvm/ADT/PostOrderIterator.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000020#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +000023#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000024#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000025#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen965665b2013-01-17 01:06:04 +000030#include "llvm/CodeGen/MachineTraceMetrics.h"
31#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000032#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000033#include "llvm/CodeGen/TargetRegisterInfo.h"
34#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "early-ifcvt"
42
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000043// Absolute maximum number of instructions allowed per speculated block.
44// This bypasses all other heuristics, so it should be set fairly high.
45static cl::opt<unsigned>
46BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
47 cl::desc("Maximum number of instructions per speculated block."));
48
49// Stress testing mode - disable heuristics.
50static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
51 cl::desc("Turn all knobs to 11"));
52
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +000053STATISTIC(NumDiamondsSeen, "Number of diamonds");
54STATISTIC(NumDiamondsConv, "Number of diamonds converted");
55STATISTIC(NumTrianglesSeen, "Number of triangles");
56STATISTIC(NumTrianglesConv, "Number of triangles converted");
57
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000058//===----------------------------------------------------------------------===//
59// SSAIfConv
60//===----------------------------------------------------------------------===//
61//
62// The SSAIfConv class performs if-conversion on SSA form machine code after
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000063// determining if it is possible. The class contains no heuristics; external
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000064// code should be used to determine when if-conversion is a good idea.
65//
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000066// SSAIfConv can convert both triangles and diamonds:
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000067//
68// Triangle: Head Diamond: Head
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000069// | \ / \_
70// | \ / |
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000071// | [TF]BB FBB TBB
72// | / \ /
73// | / \ /
74// Tail Tail
75//
76// Instructions in the conditional blocks TBB and/or FBB are spliced into the
Matt Beaumont-Gay11d08b22012-07-04 01:09:45 +000077// Head block, and phis in the Tail block are converted to select instructions.
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000078//
79namespace {
80class SSAIfConv {
81 const TargetInstrInfo *TII;
82 const TargetRegisterInfo *TRI;
83 MachineRegisterInfo *MRI;
84
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +000085public:
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +000086 /// The block containing the conditional branch.
87 MachineBasicBlock *Head;
88
89 /// The block containing phis after the if-then-else.
90 MachineBasicBlock *Tail;
91
92 /// The 'true' conditional block as determined by AnalyzeBranch.
93 MachineBasicBlock *TBB;
94
95 /// The 'false' conditional block as determined by AnalyzeBranch.
96 MachineBasicBlock *FBB;
97
98 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
99 /// equal to Tail.
100 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
101
Jakob Stoklund Olesen0a990622012-08-10 20:19:17 +0000102 /// Returns the Tail predecessor for the True side.
103 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
104
105 /// Returns the Tail predecessor for the False side.
106 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
107
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000108 /// Information about each phi in the Tail block.
109 struct PHIInfo {
110 MachineInstr *PHI;
111 unsigned TReg, FReg;
112 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
113 int CondCycles, TCycles, FCycles;
114
115 PHIInfo(MachineInstr *phi)
116 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
117 };
118
119 SmallVector<PHIInfo, 8> PHIs;
120
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000121private:
122 /// The branch condition determined by AnalyzeBranch.
123 SmallVector<MachineOperand, 4> Cond;
124
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000125 /// Instructions in Head that define values used by the conditional blocks.
126 /// The hoisted instructions must be inserted after these instructions.
127 SmallPtrSet<MachineInstr*, 8> InsertAfter;
128
129 /// Register units clobbered by the conditional blocks.
130 BitVector ClobberedRegUnits;
131
132 // Scratch pad for findInsertionPoint.
133 SparseSet<unsigned> LiveRegUnits;
134
135 /// Insertion point in Head for speculatively executed instructions form TBB
136 /// and FBB.
137 MachineBasicBlock::iterator InsertionPoint;
138
139 /// Return true if all non-terminator instructions in MBB can be safely
140 /// speculated.
141 bool canSpeculateInstrs(MachineBasicBlock *MBB);
142
143 /// Find a valid insertion point in Head.
144 bool findInsertionPoint();
145
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000146 /// Replace PHI instructions in Tail with selects.
147 void replacePHIInstrs();
148
149 /// Insert selects and rewrite PHI operands to use them.
150 void rewritePHIOperands();
151
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000152public:
153 /// runOnMachineFunction - Initialize per-function data structures.
154 void runOnMachineFunction(MachineFunction &MF) {
Eric Christopherfc6de422014-08-05 02:39:49 +0000155 TII = MF.getSubtarget().getInstrInfo();
156 TRI = MF.getSubtarget().getRegisterInfo();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000157 MRI = &MF.getRegInfo();
158 LiveRegUnits.clear();
159 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
160 ClobberedRegUnits.clear();
161 ClobberedRegUnits.resize(TRI->getNumRegUnits());
162 }
163
164 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
165 /// initialize the internal state, and return true.
166 bool canConvertIf(MachineBasicBlock *MBB);
167
168 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000169 /// it is possible. Add any erased blocks to RemovedBlocks.
170 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000171};
172} // end anonymous namespace
173
174
175/// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
176/// be speculated. The terminators are not considered.
177///
178/// If instructions use any values that are defined in the head basic block,
179/// the defining instructions are added to InsertAfter.
180///
181/// Any clobbered regunits are added to ClobberedRegUnits.
182///
183bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
184 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
185 // get right.
186 if (!MBB->livein_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000187 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has live-ins.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000188 return false;
189 }
190
191 unsigned InstrCount = 0;
Jakob Stoklund Olesen3f1bb932012-07-06 02:31:22 +0000192
193 // Check all instructions, except the terminators. It is assumed that
194 // terminators never have side effects or define any used register values.
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000195 for (MachineBasicBlock::iterator I = MBB->begin(),
196 E = MBB->getFirstTerminator(); I != E; ++I) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000197 if (I->isDebugInstr())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000198 continue;
199
200 if (++InstrCount > BlockInstrLimit && !Stress) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000201 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " has more than "
202 << BlockInstrLimit << " instructions.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000203 return false;
204 }
205
206 // There shouldn't normally be any phis in a single-predecessor block.
207 if (I->isPHI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000208 LLVM_DEBUG(dbgs() << "Can't hoist: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000209 return false;
210 }
211
212 // Don't speculate loads. Note that it may be possible and desirable to
213 // speculate GOT or constant pool loads that are guaranteed not to trap,
214 // but we don't support that for now.
215 if (I->mayLoad()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000216 LLVM_DEBUG(dbgs() << "Won't speculate load: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000217 return false;
218 }
219
220 // We never speculate stores, so an AA pointer isn't necessary.
221 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000222 if (!I->isSafeToMove(nullptr, DontMoveAcrossStore)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000223 LLVM_DEBUG(dbgs() << "Can't speculate: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000224 return false;
225 }
226
227 // Check for any dependencies on Head instructions.
Matthias Braun27a6cfd2015-05-29 02:59:59 +0000228 for (const MachineOperand &MO : I->operands()) {
Matthias Braune41e1462015-05-29 02:56:46 +0000229 if (MO.isRegMask()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000230 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000231 return false;
232 }
Matthias Braune41e1462015-05-29 02:56:46 +0000233 if (!MO.isReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000234 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000235 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000236
237 // Remember clobbered regunits.
Matthias Braune41e1462015-05-29 02:56:46 +0000238 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000239 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
240 ClobberedRegUnits.set(*Units);
241
Matthias Braune41e1462015-05-29 02:56:46 +0000242 if (!MO.readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000243 continue;
244 MachineInstr *DefMI = MRI->getVRegDef(Reg);
245 if (!DefMI || DefMI->getParent() != Head)
246 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000247 if (InsertAfter.insert(DefMI).second)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000248 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " depends on "
249 << *DefMI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000250 if (DefMI->isTerminator()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000251 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000252 return false;
253 }
254 }
255 }
256 return true;
257}
258
259
260/// Find an insertion point in Head for the speculated instructions. The
261/// insertion point must be:
262///
263/// 1. Before any terminators.
264/// 2. After any instructions in InsertAfter.
265/// 3. Not have any clobbered regunits live.
266///
267/// This function sets InsertionPoint and returns true when successful, it
268/// returns false if no valid insertion point could be found.
269///
270bool SSAIfConv::findInsertionPoint() {
271 // Keep track of live regunits before the current position.
272 // Only track RegUnits that are also in ClobberedRegUnits.
273 LiveRegUnits.clear();
274 SmallVector<unsigned, 8> Reads;
275 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
276 MachineBasicBlock::iterator I = Head->end();
277 MachineBasicBlock::iterator B = Head->begin();
278 while (I != B) {
279 --I;
280 // Some of the conditional code depends in I.
Duncan P. N. Exon Smith395bd9c2016-02-22 02:53:42 +0000281 if (InsertAfter.count(&*I)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000282 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000283 return false;
284 }
285
286 // Update live regunits.
Matthias Braune41e1462015-05-29 02:56:46 +0000287 for (const MachineOperand &MO : I->operands()) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000288 // We're ignoring regmask operands. That is conservatively correct.
Matthias Braune41e1462015-05-29 02:56:46 +0000289 if (!MO.isReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000290 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000291 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000292 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
293 continue;
294 // I clobbers Reg, so it isn't live before I.
Matthias Braune41e1462015-05-29 02:56:46 +0000295 if (MO.isDef())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000296 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
297 LiveRegUnits.erase(*Units);
298 // Unless I reads Reg.
Matthias Braune41e1462015-05-29 02:56:46 +0000299 if (MO.readsReg())
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000300 Reads.push_back(Reg);
301 }
302 // Anything read by I is live before I.
303 while (!Reads.empty())
304 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
305 ++Units)
306 if (ClobberedRegUnits.test(*Units))
307 LiveRegUnits.insert(*Units);
308
309 // We can't insert before a terminator.
310 if (I != FirstTerm && I->isTerminator())
311 continue;
312
313 // Some of the clobbered registers are live before I, not a valid insertion
314 // point.
315 if (!LiveRegUnits.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000316 LLVM_DEBUG({
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000317 dbgs() << "Would clobber";
318 for (SparseSet<unsigned>::const_iterator
319 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +0000320 dbgs() << ' ' << printRegUnit(*i, TRI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000321 dbgs() << " live before " << *I;
322 });
323 continue;
324 }
325
326 // This is a valid insertion point.
327 InsertionPoint = I;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000328 LLVM_DEBUG(dbgs() << "Can insert before " << *I);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000329 return true;
330 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000331 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000332 return false;
333}
334
335
336
337/// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
338/// a potential candidate for if-conversion. Fill out the internal state.
339///
340bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
341 Head = MBB;
Craig Topperc0196b12014-04-14 00:51:57 +0000342 TBB = FBB = Tail = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000343
344 if (Head->succ_size() != 2)
345 return false;
346 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
347 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
348
349 // Canonicalize so Succ0 has MBB as its single predecessor.
350 if (Succ0->pred_size() != 1)
351 std::swap(Succ0, Succ1);
352
353 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
354 return false;
355
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000356 Tail = Succ0->succ_begin()[0];
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000357
358 // This is not a triangle.
359 if (Tail != Succ1) {
360 // Check for a diamond. We won't deal with any critical edges.
361 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
362 Succ1->succ_begin()[0] != Tail)
363 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000364 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head) << " -> "
365 << printMBBReference(*Succ0) << "/"
366 << printMBBReference(*Succ1) << " -> "
367 << printMBBReference(*Tail) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000368
369 // Live-in physregs are tricky to get right when speculating code.
370 if (!Tail->livein_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000371 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000372 return false;
373 }
374 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000375 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head) << " -> "
376 << printMBBReference(*Succ0) << " -> "
377 << printMBBReference(*Tail) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000378 }
379
380 // This is a triangle or a diamond.
381 // If Tail doesn't have any phis, there must be side effects.
382 if (Tail->empty() || !Tail->front().isPHI()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000383 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000384 return false;
385 }
386
387 // The branch we're looking to eliminate must be analyzable.
388 Cond.clear();
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000389 if (TII->analyzeBranch(*Head, TBB, FBB, Cond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000390 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000391 return false;
392 }
393
394 // This is weird, probably some sort of degenerate CFG.
395 if (!TBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000396 LLVM_DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000397 return false;
398 }
399
Eli Friedman295e3462019-01-15 00:19:46 +0000400 // Make sure the analyzed branch is conditional; one of the successors
401 // could be a landing pad. (Empty landing pads can be generated on Windows.)
402 if (Cond.empty()) {
403 LLVM_DEBUG(dbgs() << "AnalyzeBranch found an unconditional branch.\n");
404 return false;
405 }
406
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000407 // AnalyzeBranch doesn't set FBB on a fall-through branch.
408 // Make sure it is always set.
409 FBB = TBB == Succ0 ? Succ1 : Succ0;
410
411 // Any phis in the tail block must be convertible to selects.
412 PHIs.clear();
Jakob Stoklund Olesen0a990622012-08-10 20:19:17 +0000413 MachineBasicBlock *TPred = getTPred();
414 MachineBasicBlock *FPred = getFPred();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000415 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
416 I != E && I->isPHI(); ++I) {
417 PHIs.push_back(&*I);
418 PHIInfo &PI = PHIs.back();
419 // Find PHI operands corresponding to TPred and FPred.
420 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
421 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
422 PI.TReg = PI.PHI->getOperand(i).getReg();
423 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
424 PI.FReg = PI.PHI->getOperand(i).getReg();
425 }
426 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
427 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
428
429 // Get target information.
430 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
431 PI.CondCycles, PI.TCycles, PI.FCycles)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000433 return false;
434 }
435 }
436
437 // Check that the conditional instructions can be speculated.
438 InsertAfter.clear();
439 ClobberedRegUnits.reset();
440 if (TBB != Tail && !canSpeculateInstrs(TBB))
441 return false;
442 if (FBB != Tail && !canSpeculateInstrs(FBB))
443 return false;
444
445 // Try to find a valid insertion point for the speculated instructions in the
446 // head basic block.
447 if (!findInsertionPoint())
448 return false;
449
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +0000450 if (isTriangle())
451 ++NumTrianglesSeen;
452 else
453 ++NumDiamondsSeen;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000454 return true;
455}
456
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000457/// replacePHIInstrs - Completely replace PHI instructions with selects.
458/// This is possible when the only Tail predecessors are the if-converted
459/// blocks.
460void SSAIfConv::replacePHIInstrs() {
461 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000462 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
463 assert(FirstTerm != Head->end() && "No terminators");
464 DebugLoc HeadDL = FirstTerm->getDebugLoc();
465
466 // Convert all PHIs to select instructions inserted before FirstTerm.
467 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
468 PHIInfo &PI = PHIs[i];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000469 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000470 unsigned DstReg = PI.PHI->getOperand(0).getReg();
471 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000472 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000473 PI.PHI->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +0000474 PI.PHI = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000475 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000476}
477
478/// rewritePHIOperands - When there are additional Tail predecessors, insert
479/// select instructions in Head and rewrite PHI operands to use the selects.
480/// Keep the PHI instructions in Tail to handle the other predecessors.
481void SSAIfConv::rewritePHIOperands() {
482 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
483 assert(FirstTerm != Head->end() && "No terminators");
484 DebugLoc HeadDL = FirstTerm->getDebugLoc();
485
486 // Convert all PHIs to select instructions inserted before FirstTerm.
487 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
488 PHIInfo &PI = PHIs[i];
Yi Jiange0b34992015-06-18 22:34:09 +0000489 unsigned DstReg = 0;
Junmo Park67bb3f12016-01-29 01:39:39 +0000490
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000491 LLVM_DEBUG(dbgs() << "If-converting " << *PI.PHI);
Yi Jiange0b34992015-06-18 22:34:09 +0000492 if (PI.TReg == PI.FReg) {
493 // We do not need the select instruction if both incoming values are
494 // equal.
495 DstReg = PI.TReg;
496 } else {
497 unsigned PHIDst = PI.PHI->getOperand(0).getReg();
498 DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
499 TII->insertSelect(*Head, FirstTerm, HeadDL,
500 DstReg, Cond, PI.TReg, PI.FReg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000501 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm));
Yi Jiange0b34992015-06-18 22:34:09 +0000502 }
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000503
504 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
505 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
506 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
507 if (MBB == getTPred()) {
508 PI.PHI->getOperand(i-1).setMBB(Head);
509 PI.PHI->getOperand(i-2).setReg(DstReg);
510 } else if (MBB == getFPred()) {
511 PI.PHI->RemoveOperand(i-1);
512 PI.PHI->RemoveOperand(i-2);
513 }
514 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(dbgs() << " --> " << *PI.PHI);
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000516 }
517}
518
519/// convertIf - Execute the if conversion after canConvertIf has determined the
520/// feasibility.
521///
522/// Any basic blocks erased will be added to RemovedBlocks.
523///
524void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
525 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
526
Jakob Stoklund Olesend0af1d92012-08-13 21:03:27 +0000527 // Update statistics.
528 if (isTriangle())
529 ++NumTrianglesConv;
530 else
531 ++NumDiamondsConv;
532
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000533 // Move all instructions into Head, except for the terminators.
534 if (TBB != Tail)
535 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
536 if (FBB != Tail)
537 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
538
539 // Are there extra Tail predecessors?
540 bool ExtraPreds = Tail->pred_size() != 2;
541 if (ExtraPreds)
542 rewritePHIOperands();
543 else
544 replacePHIInstrs();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000545
546 // Fix up the CFG, temporarily leave Head without any successors.
547 Head->removeSuccessor(TBB);
Cong Houc1069892015-12-13 09:26:17 +0000548 Head->removeSuccessor(FBB, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000549 if (TBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000550 TBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000551 if (FBB != Tail)
Cong Houc1069892015-12-13 09:26:17 +0000552 FBB->removeSuccessor(Tail, true);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000553
554 // Fix up Head's terminators.
555 // It should become a single branch or a fallthrough.
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000556 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000557 TII->removeBranch(*Head);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000558
559 // Erase the now empty conditional blocks. It is likely that Head can fall
560 // through to Tail, and we can join the two blocks.
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000561 if (TBB != Tail) {
562 RemovedBlocks.push_back(TBB);
563 TBB->eraseFromParent();
564 }
565 if (FBB != Tail) {
566 RemovedBlocks.push_back(FBB);
567 FBB->eraseFromParent();
568 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000569
570 assert(Head->succ_empty() && "Additional head successors?");
Jakob Stoklund Olesen83a927d2012-08-13 20:49:04 +0000571 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000572 // Splice Tail onto the end of Head.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000573 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail)
574 << " into head " << printMBBReference(*Head) << '\n');
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000575 Head->splice(Head->end(), Tail,
576 Tail->begin(), Tail->end());
577 Head->transferSuccessorsAndUpdatePHIs(Tail);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000578 RemovedBlocks.push_back(Tail);
579 Tail->eraseFromParent();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000580 } else {
581 // We need a branch to Tail, let code placement work it out later.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000583 SmallVector<MachineOperand, 0> EmptyCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000584 TII->insertBranch(*Head, Tail, nullptr, EmptyCond, HeadDL);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000585 Head->addSuccessor(Tail);
586 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000587 LLVM_DEBUG(dbgs() << *Head);
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000588}
589
590
591//===----------------------------------------------------------------------===//
592// EarlyIfConverter Pass
593//===----------------------------------------------------------------------===//
594
595namespace {
596class EarlyIfConverter : public MachineFunctionPass {
597 const TargetInstrInfo *TII;
598 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +0000599 MCSchedModel SchedModel;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000600 MachineRegisterInfo *MRI;
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000601 MachineDominatorTree *DomTree;
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000602 MachineLoopInfo *Loops;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000603 MachineTraceMetrics *Traces;
604 MachineTraceMetrics::Ensemble *MinInstr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000605 SSAIfConv IfConv;
606
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000607public:
608 static char ID;
609 EarlyIfConverter() : MachineFunctionPass(ID) {}
Craig Topper4584cd52014-03-07 09:26:03 +0000610 void getAnalysisUsage(AnalysisUsage &AU) const override;
611 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000612 StringRef getPassName() const override { return "Early If-Conversion"; }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000613
614private:
615 bool tryConvertIf(MachineBasicBlock*);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000616 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000617 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000618 void invalidateTraces();
619 bool shouldConvertIf();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000620};
621} // end anonymous namespace
622
623char EarlyIfConverter::ID = 0;
624char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
625
Matthias Braun1527baa2017-05-25 21:26:32 +0000626INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE,
627 "Early If Converter", false, false)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000628INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000629INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000630INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun1527baa2017-05-25 21:26:32 +0000631INITIALIZE_PASS_END(EarlyIfConverter, DEBUG_TYPE,
632 "Early If Converter", false, false)
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000633
634void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
635 AU.addRequired<MachineBranchProbabilityInfo>();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000636 AU.addRequired<MachineDominatorTree>();
637 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000638 AU.addRequired<MachineLoopInfo>();
639 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000640 AU.addRequired<MachineTraceMetrics>();
641 AU.addPreserved<MachineTraceMetrics>();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000642 MachineFunctionPass::getAnalysisUsage(AU);
643}
644
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000645/// Update the dominator tree after if-conversion erased some blocks.
646void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
647 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
648 // TBB and FBB should not dominate any blocks.
649 // Tail children should be transferred to Head.
650 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
651 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
652 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
653 assert(Node != HeadNode && "Cannot erase the head node");
654 while (Node->getNumChildren()) {
655 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
656 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
657 }
658 DomTree->eraseNode(Removed[i]);
659 }
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000660}
661
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000662/// Update LoopInfo after if-conversion.
663void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
664 if (!Loops)
665 return;
666 // If-conversion doesn't change loop structure, and it doesn't mess with back
667 // edges, so updating LoopInfo is simply removing the dead blocks.
668 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
669 Loops->removeBlock(Removed[i]);
670}
671
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000672/// Invalidate MachineTraceMetrics before if-conversion.
673void EarlyIfConverter::invalidateTraces() {
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000674 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000675 Traces->invalidate(IfConv.Head);
676 Traces->invalidate(IfConv.Tail);
677 Traces->invalidate(IfConv.TBB);
678 Traces->invalidate(IfConv.FBB);
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000679 Traces->verifyAnalysis();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000680}
681
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000682// Adjust cycles with downward saturation.
683static unsigned adjCycles(unsigned Cyc, int Delta) {
684 if (Delta < 0 && Cyc + Delta > Cyc)
685 return 0;
686 return Cyc + Delta;
687}
688
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000689/// Apply cost model and heuristics to the if-conversion in IfConv.
690/// Return true if the conversion is a good idea.
691///
692bool EarlyIfConverter::shouldConvertIf() {
Jakob Stoklund Olesenfa8a26f2012-08-08 18:24:23 +0000693 // Stress testing mode disables all cost considerations.
694 if (Stress)
695 return true;
696
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000697 if (!MinInstr)
698 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000699
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000700 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
701 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000702 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000703 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
704 FBBTrace.getCriticalPath());
705
706 // Set a somewhat arbitrary limit on the critical path extension we accept.
Pete Cooper11759452014-09-02 17:43:54 +0000707 unsigned CritLimit = SchedModel.MispredictPenalty/2;
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000708
709 // If-conversion only makes sense when there is unexploited ILP. Compute the
710 // maximum-ILP resource length of the trace after if-conversion. Compare it
711 // to the shortest critical path.
712 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
713 if (IfConv.TBB != IfConv.Tail)
714 ExtraBlocks.push_back(IfConv.TBB);
715 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000716 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
717 << ", minimal critical path " << MinCrit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000718 if (ResLength > MinCrit + CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000719 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +0000720 return false;
721 }
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000722
723 // Assume that the depth of the first head terminator will also be the depth
724 // of the select instruction inserted, as determined by the flag dependency.
725 // TBB / FBB data dependencies may delay the select even more.
726 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
727 unsigned BranchDepth =
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000728 HeadTrace.getInstrCycles(*IfConv.Head->getFirstTerminator()).Depth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000729 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000730
731 // Look at all the tail phis, and compute the critical path extension caused
732 // by inserting select instructions.
733 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
734 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
735 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000736 unsigned Slack = TailTrace.getInstrSlack(*PI.PHI);
737 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(*PI.PHI).Depth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000738 LLVM_DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000739
740 // The condition is pulled into the critical path.
741 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
742 if (CondDepth > MaxDepth) {
743 unsigned Extra = CondDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000744 LLVM_DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000745 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000746 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000747 return false;
748 }
749 }
750
751 // The TBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000752 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(*PI.PHI), PI.TCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000753 if (TDepth > MaxDepth) {
754 unsigned Extra = TDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000755 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000756 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000757 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000758 return false;
759 }
760 }
761
762 // The FBB value is pulled into the critical path.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000763 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(*PI.PHI), PI.FCycles);
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000764 if (FDepth > MaxDepth) {
765 unsigned Extra = FDepth - MaxDepth;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000767 if (Extra > CritLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000768 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
Jakob Stoklund Olesenbc55bfd2012-08-10 22:27:31 +0000769 return false;
770 }
771 }
772 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000773 return true;
774}
775
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000776/// Attempt repeated if-conversion on MBB, return true if successful.
777///
778bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
779 bool Changed = false;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000780 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000781 // If-convert MBB and update analyses.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000782 invalidateTraces();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000783 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
784 IfConv.convertIf(RemovedBlocks);
785 Changed = true;
786 updateDomTree(RemovedBlocks);
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000787 updateLoops(RemovedBlocks);
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000788 }
789 return Changed;
790}
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000791
792bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000793 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
794 << "********** Function: " << MF.getName() << '\n');
Matthias Braunf1caa282017-12-15 22:22:58 +0000795 if (skipFunction(MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +0000796 return false;
797
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000798 // Only run if conversion if the target wants it.
Eric Christopher3d4276f2015-01-27 07:31:29 +0000799 const TargetSubtargetInfo &STI = MF.getSubtarget();
800 if (!STI.enableEarlyIfConversion())
Eric Christopher9eff5178f2014-05-22 17:49:33 +0000801 return false;
Eric Christopher6b0fcfe2014-05-21 23:40:26 +0000802
Eric Christopher3d4276f2015-01-27 07:31:29 +0000803 TII = STI.getInstrInfo();
804 TRI = STI.getRegisterInfo();
805 SchedModel = STI.getSchedModel();
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000806 MRI = &MF.getRegInfo();
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000807 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenbc90a4e2012-07-10 22:39:56 +0000808 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000809 Traces = &getAnalysis<MachineTraceMetrics>();
Craig Topperc0196b12014-04-14 00:51:57 +0000810 MinInstr = nullptr;
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000811
812 bool Changed = false;
813 IfConv.runOnMachineFunction(MF);
814
Jakob Stoklund Olesen02638392012-07-10 22:18:23 +0000815 // Visit blocks in dominator tree post-order. The post-order enables nested
816 // if-conversion in a single pass. The tryConvertIf() function may erase
817 // blocks, but only blocks dominated by the head block. This makes it safe to
818 // update the dominator tree while the post-order iterator is still active.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000819 for (auto DomNode : post_order(DomTree))
820 if (tryConvertIf(DomNode->getBlock()))
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000821 Changed = true;
822
Jakob Stoklund Olesenf8a63a12012-07-04 00:09:54 +0000823 return Changed;
824}