1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Early if-conversion is for out-of-order CPUs that don't have a lot of
11 // predicable instructions. The goal is to eliminate conditional branches that
14 // Instructions from both sides of the branch are executed specutatively, and a
15 // cmov instruction selects the result.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "early-ifcvt"
20 #include "MachineTraceMetrics.h"
21 #include "llvm/Function.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SparseSet.h"
27 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/MC/MCInstrItineraries.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
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 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 // The SSAIfConv class performs if-conversion on SSA form machine code after
60 // determining if it is possible. The class contains no heuristics; external
61 // code should be used to determine when if-conversion is a good idea.
63 // SSAIfConv can convert both triangles and diamonds:
65 // Triangle: Head Diamond: Head
73 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
74 // Head block, and phis in the Tail block are converted to select instructions.
78 const TargetInstrInfo *TII;
79 const TargetRegisterInfo *TRI;
80 MachineRegisterInfo *MRI;
83 /// The block containing the conditional branch.
84 MachineBasicBlock *Head;
86 /// The block containing phis after the if-then-else.
87 MachineBasicBlock *Tail;
89 /// The 'true' conditional block as determined by AnalyzeBranch.
90 MachineBasicBlock *TBB;
92 /// The 'false' conditional block as determined by AnalyzeBranch.
93 MachineBasicBlock *FBB;
95 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
97 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
99 /// Returns the Tail predecessor for the True side.
100 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
102 /// Returns the Tail predecessor for the False side.
103 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
105 /// Information about each phi in the Tail block.
109 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
110 int CondCycles, TCycles, FCycles;
112 PHIInfo(MachineInstr *phi)
113 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
116 SmallVector<PHIInfo, 8> PHIs;
119 /// The branch condition determined by AnalyzeBranch.
120 SmallVector<MachineOperand, 4> Cond;
122 /// Instructions in Head that define values used by the conditional blocks.
123 /// The hoisted instructions must be inserted after these instructions.
124 SmallPtrSet<MachineInstr*, 8> InsertAfter;
126 /// Register units clobbered by the conditional blocks.
127 BitVector ClobberedRegUnits;
129 // Scratch pad for findInsertionPoint.
130 SparseSet<unsigned> LiveRegUnits;
132 /// Insertion point in Head for speculatively executed instructions form TBB
134 MachineBasicBlock::iterator InsertionPoint;
136 /// Return true if all non-terminator instructions in MBB can be safely
138 bool canSpeculateInstrs(MachineBasicBlock *MBB);
140 /// Find a valid insertion point in Head.
141 bool findInsertionPoint();
143 /// Replace PHI instructions in Tail with selects.
144 void replacePHIInstrs();
146 /// Insert selects and rewrite PHI operands to use them.
147 void rewritePHIOperands();
150 /// runOnMachineFunction - Initialize per-function data structures.
151 void runOnMachineFunction(MachineFunction &MF) {
152 TII = MF.getTarget().getInstrInfo();
153 TRI = MF.getTarget().getRegisterInfo();
154 MRI = &MF.getRegInfo();
155 LiveRegUnits.clear();
156 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
157 ClobberedRegUnits.clear();
158 ClobberedRegUnits.resize(TRI->getNumRegUnits());
161 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
162 /// initialize the internal state, and return true.
163 bool canConvertIf(MachineBasicBlock *MBB);
165 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
166 /// it is possible. Add any erased blocks to RemovedBlocks.
167 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
169 } // end anonymous namespace
172 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
173 /// be speculated. The terminators are not considered.
175 /// If instructions use any values that are defined in the head basic block,
176 /// the defining instructions are added to InsertAfter.
178 /// Any clobbered regunits are added to ClobberedRegUnits.
180 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
181 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
183 if (!MBB->livein_empty()) {
184 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
188 unsigned InstrCount = 0;
190 // Check all instructions, except the terminators. It is assumed that
191 // terminators never have side effects or define any used register values.
192 for (MachineBasicBlock::iterator I = MBB->begin(),
193 E = MBB->getFirstTerminator(); I != E; ++I) {
194 if (I->isDebugValue())
197 if (++InstrCount > BlockInstrLimit && !Stress) {
198 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
199 << BlockInstrLimit << " instructions.\n");
203 // There shouldn't normally be any phis in a single-predecessor block.
205 DEBUG(dbgs() << "Can't hoist: " << *I);
209 // Don't speculate loads. Note that it may be possible and desirable to
210 // speculate GOT or constant pool loads that are guaranteed not to trap,
211 // but we don't support that for now.
213 DEBUG(dbgs() << "Won't speculate load: " << *I);
217 // We never speculate stores, so an AA pointer isn't necessary.
218 bool DontMoveAcrossStore = true;
219 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
220 DEBUG(dbgs() << "Can't speculate: " << *I);
224 // Check for any dependencies on Head instructions.
225 for (MIOperands MO(I); MO.isValid(); ++MO) {
226 if (MO->isRegMask()) {
227 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
232 unsigned Reg = MO->getReg();
234 // Remember clobbered regunits.
235 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
236 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
237 ClobberedRegUnits.set(*Units);
239 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
241 MachineInstr *DefMI = MRI->getVRegDef(Reg);
242 if (!DefMI || DefMI->getParent() != Head)
244 if (InsertAfter.insert(DefMI))
245 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
246 if (DefMI->isTerminator()) {
247 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
256 /// Find an insertion point in Head for the speculated instructions. The
257 /// insertion point must be:
259 /// 1. Before any terminators.
260 /// 2. After any instructions in InsertAfter.
261 /// 3. Not have any clobbered regunits live.
263 /// This function sets InsertionPoint and returns true when successful, it
264 /// returns false if no valid insertion point could be found.
266 bool SSAIfConv::findInsertionPoint() {
267 // Keep track of live regunits before the current position.
268 // Only track RegUnits that are also in ClobberedRegUnits.
269 LiveRegUnits.clear();
270 SmallVector<unsigned, 8> Reads;
271 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
272 MachineBasicBlock::iterator I = Head->end();
273 MachineBasicBlock::iterator B = Head->begin();
276 // Some of the conditional code depends in I.
277 if (InsertAfter.count(I)) {
278 DEBUG(dbgs() << "Can't insert code after " << *I);
282 // Update live regunits.
283 for (MIOperands MO(I); MO.isValid(); ++MO) {
284 // We're ignoring regmask operands. That is conservatively correct.
287 unsigned Reg = MO->getReg();
288 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
290 // I clobbers Reg, so it isn't live before I.
292 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
293 LiveRegUnits.erase(*Units);
294 // Unless I reads Reg.
296 Reads.push_back(Reg);
298 // Anything read by I is live before I.
299 while (!Reads.empty())
300 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
302 if (ClobberedRegUnits.test(*Units))
303 LiveRegUnits.insert(*Units);
305 // We can't insert before a terminator.
306 if (I != FirstTerm && I->isTerminator())
309 // Some of the clobbered registers are live before I, not a valid insertion
311 if (!LiveRegUnits.empty()) {
313 dbgs() << "Would clobber";
314 for (SparseSet<unsigned>::const_iterator
315 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
316 dbgs() << ' ' << PrintRegUnit(*i, TRI);
317 dbgs() << " live before " << *I;
322 // This is a valid insertion point.
324 DEBUG(dbgs() << "Can insert before " << *I);
327 DEBUG(dbgs() << "No legal insertion point found.\n");
333 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
334 /// a potential candidate for if-conversion. Fill out the internal state.
336 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
338 TBB = FBB = Tail = 0;
340 if (Head->succ_size() != 2)
342 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
343 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
345 // Canonicalize so Succ0 has MBB as its single predecessor.
346 if (Succ0->pred_size() != 1)
347 std::swap(Succ0, Succ1);
349 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
352 Tail = Succ0->succ_begin()[0];
354 // This is not a triangle.
356 // Check for a diamond. We won't deal with any critical edges.
357 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
358 Succ1->succ_begin()[0] != Tail)
360 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
361 << " -> BB#" << Succ0->getNumber()
362 << "/BB#" << Succ1->getNumber()
363 << " -> BB#" << Tail->getNumber() << '\n');
365 // Live-in physregs are tricky to get right when speculating code.
366 if (!Tail->livein_empty()) {
367 DEBUG(dbgs() << "Tail has live-ins.\n");
371 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
372 << " -> BB#" << Succ0->getNumber()
373 << " -> BB#" << Tail->getNumber() << '\n');
376 // This is a triangle or a diamond.
377 // If Tail doesn't have any phis, there must be side effects.
378 if (Tail->empty() || !Tail->front().isPHI()) {
379 DEBUG(dbgs() << "No phis in tail.\n");
383 // The branch we're looking to eliminate must be analyzable.
385 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
386 DEBUG(dbgs() << "Branch not analyzable.\n");
390 // This is weird, probably some sort of degenerate CFG.
392 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
396 // AnalyzeBranch doesn't set FBB on a fall-through branch.
397 // Make sure it is always set.
398 FBB = TBB == Succ0 ? Succ1 : Succ0;
400 // Any phis in the tail block must be convertible to selects.
402 MachineBasicBlock *TPred = getTPred();
403 MachineBasicBlock *FPred = getFPred();
404 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
405 I != E && I->isPHI(); ++I) {
407 PHIInfo &PI = PHIs.back();
408 // Find PHI operands corresponding to TPred and FPred.
409 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
410 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
411 PI.TReg = PI.PHI->getOperand(i).getReg();
412 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
413 PI.FReg = PI.PHI->getOperand(i).getReg();
415 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
416 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
418 // Get target information.
419 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
420 PI.CondCycles, PI.TCycles, PI.FCycles)) {
421 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
426 // Check that the conditional instructions can be speculated.
428 ClobberedRegUnits.reset();
429 if (TBB != Tail && !canSpeculateInstrs(TBB))
431 if (FBB != Tail && !canSpeculateInstrs(FBB))
434 // Try to find a valid insertion point for the speculated instructions in the
436 if (!findInsertionPoint())
442 /// replacePHIInstrs - Completely replace PHI instructions with selects.
443 /// This is possible when the only Tail predecessors are the if-converted
445 void SSAIfConv::replacePHIInstrs() {
446 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
447 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
448 assert(FirstTerm != Head->end() && "No terminators");
449 DebugLoc HeadDL = FirstTerm->getDebugLoc();
451 // Convert all PHIs to select instructions inserted before FirstTerm.
452 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
453 PHIInfo &PI = PHIs[i];
454 DEBUG(dbgs() << "If-converting " << *PI.PHI);
455 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
456 unsigned DstReg = PI.PHI->getOperand(0).getReg();
457 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
458 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
459 PI.PHI->eraseFromParent();
464 /// rewritePHIOperands - When there are additional Tail predecessors, insert
465 /// select instructions in Head and rewrite PHI operands to use the selects.
466 /// Keep the PHI instructions in Tail to handle the other predecessors.
467 void SSAIfConv::rewritePHIOperands() {
468 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
469 assert(FirstTerm != Head->end() && "No terminators");
470 DebugLoc HeadDL = FirstTerm->getDebugLoc();
472 // Convert all PHIs to select instructions inserted before FirstTerm.
473 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
474 PHIInfo &PI = PHIs[i];
475 DEBUG(dbgs() << "If-converting " << *PI.PHI);
476 unsigned PHIDst = PI.PHI->getOperand(0).getReg();
477 unsigned DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
478 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
479 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
481 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
482 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
483 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
484 if (MBB == getTPred()) {
485 PI.PHI->getOperand(i-1).setMBB(Head);
486 PI.PHI->getOperand(i-2).setReg(DstReg);
487 } else if (MBB == getFPred()) {
488 PI.PHI->RemoveOperand(i-1);
489 PI.PHI->RemoveOperand(i-2);
492 DEBUG(dbgs() << " --> " << *PI.PHI);
496 /// convertIf - Execute the if conversion after canConvertIf has determined the
499 /// Any basic blocks erased will be added to RemovedBlocks.
501 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
502 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
504 // Move all instructions into Head, except for the terminators.
506 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
508 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
510 // Are there extra Tail predecessors?
511 bool ExtraPreds = Tail->pred_size() != 2;
513 rewritePHIOperands();
517 // Fix up the CFG, temporarily leave Head without any successors.
518 Head->removeSuccessor(TBB);
519 Head->removeSuccessor(FBB);
521 TBB->removeSuccessor(Tail);
523 FBB->removeSuccessor(Tail);
525 // Fix up Head's terminators.
526 // It should become a single branch or a fallthrough.
527 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
528 TII->RemoveBranch(*Head);
530 // Erase the now empty conditional blocks. It is likely that Head can fall
531 // through to Tail, and we can join the two blocks.
533 RemovedBlocks.push_back(TBB);
534 TBB->eraseFromParent();
537 RemovedBlocks.push_back(FBB);
538 FBB->eraseFromParent();
541 assert(Head->succ_empty() && "Additional head successors?");
542 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
543 // Splice Tail onto the end of Head.
544 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
545 << " into head BB#" << Head->getNumber() << '\n');
546 Head->splice(Head->end(), Tail,
547 Tail->begin(), Tail->end());
548 Head->transferSuccessorsAndUpdatePHIs(Tail);
549 RemovedBlocks.push_back(Tail);
550 Tail->eraseFromParent();
552 // We need a branch to Tail, let code placement work it out later.
553 DEBUG(dbgs() << "Converting to unconditional branch.\n");
554 SmallVector<MachineOperand, 0> EmptyCond;
555 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
556 Head->addSuccessor(Tail);
558 DEBUG(dbgs() << *Head);
562 //===----------------------------------------------------------------------===//
563 // EarlyIfConverter Pass
564 //===----------------------------------------------------------------------===//
567 class EarlyIfConverter : public MachineFunctionPass {
568 const TargetInstrInfo *TII;
569 const TargetRegisterInfo *TRI;
570 const MCSchedModel *SchedModel;
571 MachineRegisterInfo *MRI;
572 MachineDominatorTree *DomTree;
573 MachineLoopInfo *Loops;
574 MachineTraceMetrics *Traces;
575 MachineTraceMetrics::Ensemble *MinInstr;
580 EarlyIfConverter() : MachineFunctionPass(ID) {}
581 void getAnalysisUsage(AnalysisUsage &AU) const;
582 bool runOnMachineFunction(MachineFunction &MF);
585 bool tryConvertIf(MachineBasicBlock*);
586 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
587 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
588 void invalidateTraces();
589 bool shouldConvertIf();
591 } // end anonymous namespace
593 char EarlyIfConverter::ID = 0;
594 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
596 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
597 "early-ifcvt", "Early If Converter", false, false)
598 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
599 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
600 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
601 INITIALIZE_PASS_END(EarlyIfConverter,
602 "early-ifcvt", "Early If Converter", false, false)
604 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
605 AU.addRequired<MachineBranchProbabilityInfo>();
606 AU.addRequired<MachineDominatorTree>();
607 AU.addPreserved<MachineDominatorTree>();
608 AU.addRequired<MachineLoopInfo>();
609 AU.addPreserved<MachineLoopInfo>();
610 AU.addRequired<MachineTraceMetrics>();
611 AU.addPreserved<MachineTraceMetrics>();
612 MachineFunctionPass::getAnalysisUsage(AU);
615 /// Update the dominator tree after if-conversion erased some blocks.
616 void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
617 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
618 // TBB and FBB should not dominate any blocks.
619 // Tail children should be transferred to Head.
620 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
621 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
622 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
623 assert(Node != HeadNode && "Cannot erase the head node");
624 while (Node->getNumChildren()) {
625 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
626 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
628 DomTree->eraseNode(Removed[i]);
632 /// Update LoopInfo after if-conversion.
633 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
636 // If-conversion doesn't change loop structure, and it doesn't mess with back
637 // edges, so updating LoopInfo is simply removing the dead blocks.
638 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
639 Loops->removeBlock(Removed[i]);
642 /// Invalidate MachineTraceMetrics before if-conversion.
643 void EarlyIfConverter::invalidateTraces() {
644 Traces->verifyAnalysis();
645 Traces->invalidate(IfConv.Head);
646 Traces->invalidate(IfConv.Tail);
647 Traces->invalidate(IfConv.TBB);
648 Traces->invalidate(IfConv.FBB);
649 Traces->verifyAnalysis();
652 // Adjust cycles with downward saturation.
653 static unsigned adjCycles(unsigned Cyc, int Delta) {
654 if (Delta < 0 && Cyc + Delta > Cyc)
659 /// Apply cost model and heuristics to the if-conversion in IfConv.
660 /// Return true if the conversion is a good idea.
662 bool EarlyIfConverter::shouldConvertIf() {
663 // Stress testing mode disables all cost considerations.
668 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
670 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
671 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
672 DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
673 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
674 FBBTrace.getCriticalPath());
676 // Set a somewhat arbitrary limit on the critical path extension we accept.
677 unsigned CritLimit = SchedModel->MispredictPenalty/2;
679 // If-conversion only makes sense when there is unexploited ILP. Compute the
680 // maximum-ILP resource length of the trace after if-conversion. Compare it
681 // to the shortest critical path.
682 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
683 if (IfConv.TBB != IfConv.Tail)
684 ExtraBlocks.push_back(IfConv.TBB);
685 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
686 DEBUG(dbgs() << "Resource length " << ResLength
687 << ", minimal critical path " << MinCrit << '\n');
688 if (ResLength > MinCrit + CritLimit) {
689 DEBUG(dbgs() << "Not enough available ILP.\n");
693 // Assume that the depth of the first head terminator will also be the depth
694 // of the select instruction inserted, as determined by the flag dependency.
695 // TBB / FBB data dependencies may delay the select even more.
696 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
697 unsigned BranchDepth =
698 HeadTrace.getInstrCycles(IfConv.Head->getFirstTerminator()).Depth;
699 DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
701 // Look at all the tail phis, and compute the critical path extension caused
702 // by inserting select instructions.
703 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
704 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
705 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
706 unsigned Slack = TailTrace.getInstrSlack(PI.PHI);
707 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(PI.PHI).Depth;
708 DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
710 // The condition is pulled into the critical path.
711 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
712 if (CondDepth > MaxDepth) {
713 unsigned Extra = CondDepth - MaxDepth;
714 DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
715 if (Extra > CritLimit) {
716 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
721 // The TBB value is pulled into the critical path.
722 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(PI.PHI), PI.TCycles);
723 if (TDepth > MaxDepth) {
724 unsigned Extra = TDepth - MaxDepth;
725 DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
726 if (Extra > CritLimit) {
727 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
732 // The FBB value is pulled into the critical path.
733 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(PI.PHI), PI.FCycles);
734 if (FDepth > MaxDepth) {
735 unsigned Extra = FDepth - MaxDepth;
736 DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
737 if (Extra > CritLimit) {
738 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
746 /// Attempt repeated if-conversion on MBB, return true if successful.
748 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
749 bool Changed = false;
750 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
751 // If-convert MBB and update analyses.
753 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
754 IfConv.convertIf(RemovedBlocks);
756 updateDomTree(RemovedBlocks);
757 updateLoops(RemovedBlocks);
762 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
763 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
764 << "********** Function: "
765 << ((Value*)MF.getFunction())->getName() << '\n');
766 TII = MF.getTarget().getInstrInfo();
767 TRI = MF.getTarget().getRegisterInfo();
768 SchedModel = MF.getTarget().getInstrItineraryData()->SchedModel;
769 MRI = &MF.getRegInfo();
770 DomTree = &getAnalysis<MachineDominatorTree>();
771 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
772 Traces = &getAnalysis<MachineTraceMetrics>();
775 bool Changed = false;
776 IfConv.runOnMachineFunction(MF);
778 // Visit blocks in dominator tree post-order. The post-order enables nested
779 // if-conversion in a single pass. The tryConvertIf() function may erase
780 // blocks, but only blocks dominated by the head block. This makes it safe to
781 // update the dominator tree while the post-order iterator is still active.
782 for (po_iterator<MachineDominatorTree*>
783 I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
784 if (tryConvertIf(I->getBlock()))
787 MF.verify(this, "After early if-conversion");