1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
3 // 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
7 //===----------------------------------------------------------------------===//
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
13 // Instructions from both sides of the branch are executed specutatively, and a
14 // cmov instruction selects the result.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/MachineTraceMetrics.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetRegisterInfo.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "early-ifcvt"
43 // Absolute maximum number of instructions allowed per speculated block.
44 // This bypasses all other heuristics, so it should be set fairly high.
45 static cl::opt
<unsigned>
46 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden
,
47 cl::desc("Maximum number of instructions per speculated block."));
49 // Stress testing mode - disable heuristics.
50 static cl::opt
<bool> Stress("stress-early-ifcvt", cl::Hidden
,
51 cl::desc("Turn all knobs to 11"));
53 STATISTIC(NumDiamondsSeen
, "Number of diamonds");
54 STATISTIC(NumDiamondsConv
, "Number of diamonds converted");
55 STATISTIC(NumTrianglesSeen
, "Number of triangles");
56 STATISTIC(NumTrianglesConv
, "Number of triangles converted");
58 //===----------------------------------------------------------------------===//
60 //===----------------------------------------------------------------------===//
62 // The SSAIfConv class performs if-conversion on SSA form machine code after
63 // determining if it is possible. The class contains no heuristics; external
64 // code should be used to determine when if-conversion is a good idea.
66 // SSAIfConv can convert both triangles and diamonds:
68 // Triangle: Head Diamond: Head
76 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
77 // Head block, and phis in the Tail block are converted to select instructions.
81 const TargetInstrInfo
*TII
;
82 const TargetRegisterInfo
*TRI
;
83 MachineRegisterInfo
*MRI
;
86 /// The block containing the conditional branch.
87 MachineBasicBlock
*Head
;
89 /// The block containing phis after the if-then-else.
90 MachineBasicBlock
*Tail
;
92 /// The 'true' conditional block as determined by AnalyzeBranch.
93 MachineBasicBlock
*TBB
;
95 /// The 'false' conditional block as determined by AnalyzeBranch.
96 MachineBasicBlock
*FBB
;
98 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
100 bool isTriangle() const { return TBB
== Tail
|| FBB
== Tail
; }
102 /// Returns the Tail predecessor for the True side.
103 MachineBasicBlock
*getTPred() const { return TBB
== Tail
? Head
: TBB
; }
105 /// Returns the Tail predecessor for the False side.
106 MachineBasicBlock
*getFPred() const { return FBB
== Tail
? Head
: FBB
; }
108 /// Information about each phi in the Tail block.
112 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
113 int CondCycles
, TCycles
, FCycles
;
115 PHIInfo(MachineInstr
*phi
)
116 : PHI(phi
), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
119 SmallVector
<PHIInfo
, 8> PHIs
;
122 /// The branch condition determined by AnalyzeBranch.
123 SmallVector
<MachineOperand
, 4> Cond
;
125 /// 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
;
129 /// Register units clobbered by the conditional blocks.
130 BitVector ClobberedRegUnits
;
132 // Scratch pad for findInsertionPoint.
133 SparseSet
<unsigned> LiveRegUnits
;
135 /// Insertion point in Head for speculatively executed instructions form TBB
137 MachineBasicBlock::iterator InsertionPoint
;
139 /// Return true if all non-terminator instructions in MBB can be safely
141 bool canSpeculateInstrs(MachineBasicBlock
*MBB
);
143 /// Find a valid insertion point in Head.
144 bool findInsertionPoint();
146 /// Replace PHI instructions in Tail with selects.
147 void replacePHIInstrs();
149 /// Insert selects and rewrite PHI operands to use them.
150 void rewritePHIOperands();
153 /// runOnMachineFunction - Initialize per-function data structures.
154 void runOnMachineFunction(MachineFunction
&MF
) {
155 TII
= MF
.getSubtarget().getInstrInfo();
156 TRI
= MF
.getSubtarget().getRegisterInfo();
157 MRI
= &MF
.getRegInfo();
158 LiveRegUnits
.clear();
159 LiveRegUnits
.setUniverse(TRI
->getNumRegUnits());
160 ClobberedRegUnits
.clear();
161 ClobberedRegUnits
.resize(TRI
->getNumRegUnits());
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
);
168 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
169 /// it is possible. Add any erased blocks to RemovedBlocks.
170 void convertIf(SmallVectorImpl
<MachineBasicBlock
*> &RemovedBlocks
);
172 } // end anonymous namespace
175 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
176 /// be speculated. The terminators are not considered.
178 /// If instructions use any values that are defined in the head basic block,
179 /// the defining instructions are added to InsertAfter.
181 /// Any clobbered regunits are added to ClobberedRegUnits.
183 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock
*MBB
) {
184 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
186 if (!MBB
->livein_empty()) {
187 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has live-ins.\n");
191 unsigned InstrCount
= 0;
193 // Check all instructions, except the terminators. It is assumed that
194 // terminators never have side effects or define any used register values.
195 for (MachineBasicBlock::iterator I
= MBB
->begin(),
196 E
= MBB
->getFirstTerminator(); I
!= E
; ++I
) {
197 if (I
->isDebugInstr())
200 if (++InstrCount
> BlockInstrLimit
&& !Stress
) {
201 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " has more than "
202 << BlockInstrLimit
<< " instructions.\n");
206 // There shouldn't normally be any phis in a single-predecessor block.
208 LLVM_DEBUG(dbgs() << "Can't hoist: " << *I
);
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.
216 LLVM_DEBUG(dbgs() << "Won't speculate load: " << *I
);
220 // We never speculate stores, so an AA pointer isn't necessary.
221 bool DontMoveAcrossStore
= true;
222 if (!I
->isSafeToMove(nullptr, DontMoveAcrossStore
)) {
223 LLVM_DEBUG(dbgs() << "Can't speculate: " << *I
);
227 // Check for any dependencies on Head instructions.
228 for (const MachineOperand
&MO
: I
->operands()) {
229 if (MO
.isRegMask()) {
230 LLVM_DEBUG(dbgs() << "Won't speculate regmask: " << *I
);
235 unsigned Reg
= MO
.getReg();
237 // Remember clobbered regunits.
238 if (MO
.isDef() && TargetRegisterInfo::isPhysicalRegister(Reg
))
239 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
)
240 ClobberedRegUnits
.set(*Units
);
242 if (!MO
.readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg
))
244 MachineInstr
*DefMI
= MRI
->getVRegDef(Reg
);
245 if (!DefMI
|| DefMI
->getParent() != Head
)
247 if (InsertAfter
.insert(DefMI
).second
)
248 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << " depends on "
250 if (DefMI
->isTerminator()) {
251 LLVM_DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
260 /// Find an insertion point in Head for the speculated instructions. The
261 /// insertion point must be:
263 /// 1. Before any terminators.
264 /// 2. After any instructions in InsertAfter.
265 /// 3. Not have any clobbered regunits live.
267 /// This function sets InsertionPoint and returns true when successful, it
268 /// returns false if no valid insertion point could be found.
270 bool 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();
280 // Some of the conditional code depends in I.
281 if (InsertAfter
.count(&*I
)) {
282 LLVM_DEBUG(dbgs() << "Can't insert code after " << *I
);
286 // Update live regunits.
287 for (const MachineOperand
&MO
: I
->operands()) {
288 // We're ignoring regmask operands. That is conservatively correct.
291 unsigned Reg
= MO
.getReg();
292 if (!TargetRegisterInfo::isPhysicalRegister(Reg
))
294 // I clobbers Reg, so it isn't live before I.
296 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
)
297 LiveRegUnits
.erase(*Units
);
298 // Unless I reads Reg.
300 Reads
.push_back(Reg
);
302 // Anything read by I is live before I.
303 while (!Reads
.empty())
304 for (MCRegUnitIterator
Units(Reads
.pop_back_val(), TRI
); Units
.isValid();
306 if (ClobberedRegUnits
.test(*Units
))
307 LiveRegUnits
.insert(*Units
);
309 // We can't insert before a terminator.
310 if (I
!= FirstTerm
&& I
->isTerminator())
313 // Some of the clobbered registers are live before I, not a valid insertion
315 if (!LiveRegUnits
.empty()) {
317 dbgs() << "Would clobber";
318 for (SparseSet
<unsigned>::const_iterator
319 i
= LiveRegUnits
.begin(), e
= LiveRegUnits
.end(); i
!= e
; ++i
)
320 dbgs() << ' ' << printRegUnit(*i
, TRI
);
321 dbgs() << " live before " << *I
;
326 // This is a valid insertion point.
328 LLVM_DEBUG(dbgs() << "Can insert before " << *I
);
331 LLVM_DEBUG(dbgs() << "No legal insertion point found.\n");
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.
340 bool SSAIfConv::canConvertIf(MachineBasicBlock
*MBB
) {
342 TBB
= FBB
= Tail
= nullptr;
344 if (Head
->succ_size() != 2)
346 MachineBasicBlock
*Succ0
= Head
->succ_begin()[0];
347 MachineBasicBlock
*Succ1
= Head
->succ_begin()[1];
349 // Canonicalize so Succ0 has MBB as its single predecessor.
350 if (Succ0
->pred_size() != 1)
351 std::swap(Succ0
, Succ1
);
353 if (Succ0
->pred_size() != 1 || Succ0
->succ_size() != 1)
356 Tail
= Succ0
->succ_begin()[0];
358 // This is not a triangle.
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
)
364 LLVM_DEBUG(dbgs() << "\nDiamond: " << printMBBReference(*Head
) << " -> "
365 << printMBBReference(*Succ0
) << "/"
366 << printMBBReference(*Succ1
) << " -> "
367 << printMBBReference(*Tail
) << '\n');
369 // Live-in physregs are tricky to get right when speculating code.
370 if (!Tail
->livein_empty()) {
371 LLVM_DEBUG(dbgs() << "Tail has live-ins.\n");
375 LLVM_DEBUG(dbgs() << "\nTriangle: " << printMBBReference(*Head
) << " -> "
376 << printMBBReference(*Succ0
) << " -> "
377 << printMBBReference(*Tail
) << '\n');
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()) {
383 LLVM_DEBUG(dbgs() << "No phis in tail.\n");
387 // The branch we're looking to eliminate must be analyzable.
389 if (TII
->analyzeBranch(*Head
, TBB
, FBB
, Cond
)) {
390 LLVM_DEBUG(dbgs() << "Branch not analyzable.\n");
394 // This is weird, probably some sort of degenerate CFG.
396 LLVM_DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
400 // 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.)
403 LLVM_DEBUG(dbgs() << "AnalyzeBranch found an unconditional branch.\n");
407 // AnalyzeBranch doesn't set FBB on a fall-through branch.
408 // Make sure it is always set.
409 FBB
= TBB
== Succ0
? Succ1
: Succ0
;
411 // Any phis in the tail block must be convertible to selects.
413 MachineBasicBlock
*TPred
= getTPred();
414 MachineBasicBlock
*FPred
= getFPred();
415 for (MachineBasicBlock::iterator I
= Tail
->begin(), E
= Tail
->end();
416 I
!= E
&& I
->isPHI(); ++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();
426 assert(TargetRegisterInfo::isVirtualRegister(PI
.TReg
) && "Bad PHI");
427 assert(TargetRegisterInfo::isVirtualRegister(PI
.FReg
) && "Bad PHI");
429 // Get target information.
430 if (!TII
->canInsertSelect(*Head
, Cond
, PI
.TReg
, PI
.FReg
,
431 PI
.CondCycles
, PI
.TCycles
, PI
.FCycles
)) {
432 LLVM_DEBUG(dbgs() << "Can't convert: " << *PI
.PHI
);
437 // Check that the conditional instructions can be speculated.
439 ClobberedRegUnits
.reset();
440 if (TBB
!= Tail
&& !canSpeculateInstrs(TBB
))
442 if (FBB
!= Tail
&& !canSpeculateInstrs(FBB
))
445 // Try to find a valid insertion point for the speculated instructions in the
447 if (!findInsertionPoint())
457 /// replacePHIInstrs - Completely replace PHI instructions with selects.
458 /// This is possible when the only Tail predecessors are the if-converted
460 void SSAIfConv::replacePHIInstrs() {
461 assert(Tail
->pred_size() == 2 && "Cannot replace PHIs");
462 MachineBasicBlock::iterator FirstTerm
= Head
->getFirstTerminator();
463 assert(FirstTerm
!= Head
->end() && "No terminators");
464 DebugLoc HeadDL
= FirstTerm
->getDebugLoc();
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
];
469 LLVM_DEBUG(dbgs() << "If-converting " << *PI
.PHI
);
470 unsigned DstReg
= PI
.PHI
->getOperand(0).getReg();
471 TII
->insertSelect(*Head
, FirstTerm
, HeadDL
, DstReg
, Cond
, PI
.TReg
, PI
.FReg
);
472 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm
));
473 PI
.PHI
->eraseFromParent();
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.
481 void SSAIfConv::rewritePHIOperands() {
482 MachineBasicBlock::iterator FirstTerm
= Head
->getFirstTerminator();
483 assert(FirstTerm
!= Head
->end() && "No terminators");
484 DebugLoc HeadDL
= FirstTerm
->getDebugLoc();
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
];
491 LLVM_DEBUG(dbgs() << "If-converting " << *PI
.PHI
);
492 if (PI
.TReg
== PI
.FReg
) {
493 // We do not need the select instruction if both incoming values are
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
);
501 LLVM_DEBUG(dbgs() << " --> " << *std::prev(FirstTerm
));
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);
515 LLVM_DEBUG(dbgs() << " --> " << *PI
.PHI
);
519 /// convertIf - Execute the if conversion after canConvertIf has determined the
522 /// Any basic blocks erased will be added to RemovedBlocks.
524 void SSAIfConv::convertIf(SmallVectorImpl
<MachineBasicBlock
*> &RemovedBlocks
) {
525 assert(Head
&& Tail
&& TBB
&& FBB
&& "Call canConvertIf first.");
527 // Update statistics.
533 // Move all instructions into Head, except for the terminators.
535 Head
->splice(InsertionPoint
, TBB
, TBB
->begin(), TBB
->getFirstTerminator());
537 Head
->splice(InsertionPoint
, FBB
, FBB
->begin(), FBB
->getFirstTerminator());
539 // Are there extra Tail predecessors?
540 bool ExtraPreds
= Tail
->pred_size() != 2;
542 rewritePHIOperands();
546 // Fix up the CFG, temporarily leave Head without any successors.
547 Head
->removeSuccessor(TBB
);
548 Head
->removeSuccessor(FBB
, true);
550 TBB
->removeSuccessor(Tail
, true);
552 FBB
->removeSuccessor(Tail
, true);
554 // Fix up Head's terminators.
555 // It should become a single branch or a fallthrough.
556 DebugLoc HeadDL
= Head
->getFirstTerminator()->getDebugLoc();
557 TII
->removeBranch(*Head
);
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.
562 RemovedBlocks
.push_back(TBB
);
563 TBB
->eraseFromParent();
566 RemovedBlocks
.push_back(FBB
);
567 FBB
->eraseFromParent();
570 assert(Head
->succ_empty() && "Additional head successors?");
571 if (!ExtraPreds
&& Head
->isLayoutSuccessor(Tail
)) {
572 // Splice Tail onto the end of Head.
573 LLVM_DEBUG(dbgs() << "Joining tail " << printMBBReference(*Tail
)
574 << " into head " << printMBBReference(*Head
) << '\n');
575 Head
->splice(Head
->end(), Tail
,
576 Tail
->begin(), Tail
->end());
577 Head
->transferSuccessorsAndUpdatePHIs(Tail
);
578 RemovedBlocks
.push_back(Tail
);
579 Tail
->eraseFromParent();
581 // We need a branch to Tail, let code placement work it out later.
582 LLVM_DEBUG(dbgs() << "Converting to unconditional branch.\n");
583 SmallVector
<MachineOperand
, 0> EmptyCond
;
584 TII
->insertBranch(*Head
, Tail
, nullptr, EmptyCond
, HeadDL
);
585 Head
->addSuccessor(Tail
);
587 LLVM_DEBUG(dbgs() << *Head
);
591 //===----------------------------------------------------------------------===//
592 // EarlyIfConverter Pass
593 //===----------------------------------------------------------------------===//
596 class EarlyIfConverter
: public MachineFunctionPass
{
597 const TargetInstrInfo
*TII
;
598 const TargetRegisterInfo
*TRI
;
599 MCSchedModel SchedModel
;
600 MachineRegisterInfo
*MRI
;
601 MachineDominatorTree
*DomTree
;
602 MachineLoopInfo
*Loops
;
603 MachineTraceMetrics
*Traces
;
604 MachineTraceMetrics::Ensemble
*MinInstr
;
609 EarlyIfConverter() : MachineFunctionPass(ID
) {}
610 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
611 bool runOnMachineFunction(MachineFunction
&MF
) override
;
612 StringRef
getPassName() const override
{ return "Early If-Conversion"; }
615 bool tryConvertIf(MachineBasicBlock
*);
616 void updateDomTree(ArrayRef
<MachineBasicBlock
*> Removed
);
617 void updateLoops(ArrayRef
<MachineBasicBlock
*> Removed
);
618 void invalidateTraces();
619 bool shouldConvertIf();
621 } // end anonymous namespace
623 char EarlyIfConverter::ID
= 0;
624 char &llvm::EarlyIfConverterID
= EarlyIfConverter::ID
;
626 INITIALIZE_PASS_BEGIN(EarlyIfConverter
, DEBUG_TYPE
,
627 "Early If Converter", false, false)
628 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
629 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
630 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics
)
631 INITIALIZE_PASS_END(EarlyIfConverter
, DEBUG_TYPE
,
632 "Early If Converter", false, false)
634 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage
&AU
) const {
635 AU
.addRequired
<MachineBranchProbabilityInfo
>();
636 AU
.addRequired
<MachineDominatorTree
>();
637 AU
.addPreserved
<MachineDominatorTree
>();
638 AU
.addRequired
<MachineLoopInfo
>();
639 AU
.addPreserved
<MachineLoopInfo
>();
640 AU
.addRequired
<MachineTraceMetrics
>();
641 AU
.addPreserved
<MachineTraceMetrics
>();
642 MachineFunctionPass::getAnalysisUsage(AU
);
645 /// Update the dominator tree after if-conversion erased some blocks.
646 void 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
);
658 DomTree
->eraseNode(Removed
[i
]);
662 /// Update LoopInfo after if-conversion.
663 void EarlyIfConverter::updateLoops(ArrayRef
<MachineBasicBlock
*> Removed
) {
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
]);
672 /// Invalidate MachineTraceMetrics before if-conversion.
673 void EarlyIfConverter::invalidateTraces() {
674 Traces
->verifyAnalysis();
675 Traces
->invalidate(IfConv
.Head
);
676 Traces
->invalidate(IfConv
.Tail
);
677 Traces
->invalidate(IfConv
.TBB
);
678 Traces
->invalidate(IfConv
.FBB
);
679 Traces
->verifyAnalysis();
682 // Adjust cycles with downward saturation.
683 static unsigned adjCycles(unsigned Cyc
, int Delta
) {
684 if (Delta
< 0 && Cyc
+ Delta
> Cyc
)
689 /// Apply cost model and heuristics to the if-conversion in IfConv.
690 /// Return true if the conversion is a good idea.
692 bool EarlyIfConverter::shouldConvertIf() {
693 // Stress testing mode disables all cost considerations.
698 MinInstr
= Traces
->getEnsemble(MachineTraceMetrics::TS_MinInstrCount
);
700 MachineTraceMetrics::Trace TBBTrace
= MinInstr
->getTrace(IfConv
.getTPred());
701 MachineTraceMetrics::Trace FBBTrace
= MinInstr
->getTrace(IfConv
.getFPred());
702 LLVM_DEBUG(dbgs() << "TBB: " << TBBTrace
<< "FBB: " << FBBTrace
);
703 unsigned MinCrit
= std::min(TBBTrace
.getCriticalPath(),
704 FBBTrace
.getCriticalPath());
706 // Set a somewhat arbitrary limit on the critical path extension we accept.
707 unsigned CritLimit
= SchedModel
.MispredictPenalty
/2;
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
);
716 LLVM_DEBUG(dbgs() << "Resource length " << ResLength
717 << ", minimal critical path " << MinCrit
<< '\n');
718 if (ResLength
> MinCrit
+ CritLimit
) {
719 LLVM_DEBUG(dbgs() << "Not enough available ILP.\n");
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
=
728 HeadTrace
.getInstrCycles(*IfConv
.Head
->getFirstTerminator()).Depth
;
729 LLVM_DEBUG(dbgs() << "Branch depth: " << BranchDepth
<< '\n');
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
];
736 unsigned Slack
= TailTrace
.getInstrSlack(*PI
.PHI
);
737 unsigned MaxDepth
= Slack
+ TailTrace
.getInstrCycles(*PI
.PHI
).Depth
;
738 LLVM_DEBUG(dbgs() << "Slack " << Slack
<< ":\t" << *PI
.PHI
);
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
;
744 LLVM_DEBUG(dbgs() << "Condition adds " << Extra
<< " cycles.\n");
745 if (Extra
> CritLimit
) {
746 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
751 // The TBB value is pulled into the critical path.
752 unsigned TDepth
= adjCycles(TBBTrace
.getPHIDepth(*PI
.PHI
), PI
.TCycles
);
753 if (TDepth
> MaxDepth
) {
754 unsigned Extra
= TDepth
- MaxDepth
;
755 LLVM_DEBUG(dbgs() << "TBB data adds " << Extra
<< " cycles.\n");
756 if (Extra
> CritLimit
) {
757 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
762 // The FBB value is pulled into the critical path.
763 unsigned FDepth
= adjCycles(FBBTrace
.getPHIDepth(*PI
.PHI
), PI
.FCycles
);
764 if (FDepth
> MaxDepth
) {
765 unsigned Extra
= FDepth
- MaxDepth
;
766 LLVM_DEBUG(dbgs() << "FBB data adds " << Extra
<< " cycles.\n");
767 if (Extra
> CritLimit
) {
768 LLVM_DEBUG(dbgs() << "Exceeds limit of " << CritLimit
<< '\n');
776 /// Attempt repeated if-conversion on MBB, return true if successful.
778 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock
*MBB
) {
779 bool Changed
= false;
780 while (IfConv
.canConvertIf(MBB
) && shouldConvertIf()) {
781 // If-convert MBB and update analyses.
783 SmallVector
<MachineBasicBlock
*, 4> RemovedBlocks
;
784 IfConv
.convertIf(RemovedBlocks
);
786 updateDomTree(RemovedBlocks
);
787 updateLoops(RemovedBlocks
);
792 bool EarlyIfConverter::runOnMachineFunction(MachineFunction
&MF
) {
793 LLVM_DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
794 << "********** Function: " << MF
.getName() << '\n');
795 if (skipFunction(MF
.getFunction()))
798 // Only run if conversion if the target wants it.
799 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
800 if (!STI
.enableEarlyIfConversion())
803 TII
= STI
.getInstrInfo();
804 TRI
= STI
.getRegisterInfo();
805 SchedModel
= STI
.getSchedModel();
806 MRI
= &MF
.getRegInfo();
807 DomTree
= &getAnalysis
<MachineDominatorTree
>();
808 Loops
= getAnalysisIfAvailable
<MachineLoopInfo
>();
809 Traces
= &getAnalysis
<MachineTraceMetrics
>();
812 bool Changed
= false;
813 IfConv
.runOnMachineFunction(MF
);
815 // 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.
819 for (auto DomNode
: post_order(DomTree
))
820 if (tryConvertIf(DomNode
->getBlock()))