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 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 // The SSAIfConv class performs if-conversion on SSA form machine code after
58 // determining if it is possible. The class contains no heuristics; external
59 // code should be used to determine when if-conversion is a good idea.
61 // SSAIfConv can convert both triangles and diamonds:
63 // Triangle: Head Diamond: Head
71 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
72 // Head block, and phis in the Tail block are converted to select instructions.
76 const TargetInstrInfo *TII;
77 const TargetRegisterInfo *TRI;
78 MachineRegisterInfo *MRI;
81 /// The block containing the conditional branch.
82 MachineBasicBlock *Head;
84 /// The block containing phis after the if-then-else.
85 MachineBasicBlock *Tail;
87 /// The 'true' conditional block as determined by AnalyzeBranch.
88 MachineBasicBlock *TBB;
90 /// The 'false' conditional block as determined by AnalyzeBranch.
91 MachineBasicBlock *FBB;
93 /// isTriangle - When there is no 'else' block, either TBB or FBB will be
95 bool isTriangle() const { return TBB == Tail || FBB == Tail; }
97 /// Returns the Tail predecessor for the True side.
98 MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
100 /// Returns the Tail predecessor for the False side.
101 MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
103 /// Information about each phi in the Tail block.
107 // Latencies from Cond+Branch, TReg, and FReg to DstReg.
108 int CondCycles, TCycles, FCycles;
110 PHIInfo(MachineInstr *phi)
111 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
114 SmallVector<PHIInfo, 8> PHIs;
117 /// The branch condition determined by AnalyzeBranch.
118 SmallVector<MachineOperand, 4> Cond;
120 /// Instructions in Head that define values used by the conditional blocks.
121 /// The hoisted instructions must be inserted after these instructions.
122 SmallPtrSet<MachineInstr*, 8> InsertAfter;
124 /// Register units clobbered by the conditional blocks.
125 BitVector ClobberedRegUnits;
127 // Scratch pad for findInsertionPoint.
128 SparseSet<unsigned> LiveRegUnits;
130 /// Insertion point in Head for speculatively executed instructions form TBB
132 MachineBasicBlock::iterator InsertionPoint;
134 /// Return true if all non-terminator instructions in MBB can be safely
136 bool canSpeculateInstrs(MachineBasicBlock *MBB);
138 /// Find a valid insertion point in Head.
139 bool findInsertionPoint();
141 /// Replace PHI instructions in Tail with selects.
142 void replacePHIInstrs();
144 /// Insert selects and rewrite PHI operands to use them.
145 void rewritePHIOperands();
148 /// runOnMachineFunction - Initialize per-function data structures.
149 void runOnMachineFunction(MachineFunction &MF) {
150 TII = MF.getTarget().getInstrInfo();
151 TRI = MF.getTarget().getRegisterInfo();
152 MRI = &MF.getRegInfo();
153 LiveRegUnits.clear();
154 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
155 ClobberedRegUnits.clear();
156 ClobberedRegUnits.resize(TRI->getNumRegUnits());
159 /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
160 /// initialize the internal state, and return true.
161 bool canConvertIf(MachineBasicBlock *MBB);
163 /// convertIf - If-convert the last block passed to canConvertIf(), assuming
164 /// it is possible. Add any erased blocks to RemovedBlocks.
165 void convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks);
167 } // end anonymous namespace
170 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
171 /// be speculated. The terminators are not considered.
173 /// If instructions use any values that are defined in the head basic block,
174 /// the defining instructions are added to InsertAfter.
176 /// Any clobbered regunits are added to ClobberedRegUnits.
178 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
179 // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
181 if (!MBB->livein_empty()) {
182 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
186 unsigned InstrCount = 0;
188 // Check all instructions, except the terminators. It is assumed that
189 // terminators never have side effects or define any used register values.
190 for (MachineBasicBlock::iterator I = MBB->begin(),
191 E = MBB->getFirstTerminator(); I != E; ++I) {
192 if (I->isDebugValue())
195 if (++InstrCount > BlockInstrLimit && !Stress) {
196 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
197 << BlockInstrLimit << " instructions.\n");
201 // There shouldn't normally be any phis in a single-predecessor block.
203 DEBUG(dbgs() << "Can't hoist: " << *I);
207 // Don't speculate loads. Note that it may be possible and desirable to
208 // speculate GOT or constant pool loads that are guaranteed not to trap,
209 // but we don't support that for now.
211 DEBUG(dbgs() << "Won't speculate load: " << *I);
215 // We never speculate stores, so an AA pointer isn't necessary.
216 bool DontMoveAcrossStore = true;
217 if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
218 DEBUG(dbgs() << "Can't speculate: " << *I);
222 // Check for any dependencies on Head instructions.
223 for (MIOperands MO(I); MO.isValid(); ++MO) {
224 if (MO->isRegMask()) {
225 DEBUG(dbgs() << "Won't speculate regmask: " << *I);
230 unsigned Reg = MO->getReg();
232 // Remember clobbered regunits.
233 if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
234 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
235 ClobberedRegUnits.set(*Units);
237 if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
239 MachineInstr *DefMI = MRI->getVRegDef(Reg);
240 if (!DefMI || DefMI->getParent() != Head)
242 if (InsertAfter.insert(DefMI))
243 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
244 if (DefMI->isTerminator()) {
245 DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
254 /// Find an insertion point in Head for the speculated instructions. The
255 /// insertion point must be:
257 /// 1. Before any terminators.
258 /// 2. After any instructions in InsertAfter.
259 /// 3. Not have any clobbered regunits live.
261 /// This function sets InsertionPoint and returns true when successful, it
262 /// returns false if no valid insertion point could be found.
264 bool SSAIfConv::findInsertionPoint() {
265 // Keep track of live regunits before the current position.
266 // Only track RegUnits that are also in ClobberedRegUnits.
267 LiveRegUnits.clear();
268 SmallVector<unsigned, 8> Reads;
269 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
270 MachineBasicBlock::iterator I = Head->end();
271 MachineBasicBlock::iterator B = Head->begin();
274 // Some of the conditional code depends in I.
275 if (InsertAfter.count(I)) {
276 DEBUG(dbgs() << "Can't insert code after " << *I);
280 // Update live regunits.
281 for (MIOperands MO(I); MO.isValid(); ++MO) {
282 // We're ignoring regmask operands. That is conservatively correct.
285 unsigned Reg = MO->getReg();
286 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
288 // I clobbers Reg, so it isn't live before I.
290 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
291 LiveRegUnits.erase(*Units);
292 // Unless I reads Reg.
294 Reads.push_back(Reg);
296 // Anything read by I is live before I.
297 while (!Reads.empty())
298 for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
300 if (ClobberedRegUnits.test(*Units))
301 LiveRegUnits.insert(*Units);
303 // We can't insert before a terminator.
304 if (I != FirstTerm && I->isTerminator())
307 // Some of the clobbered registers are live before I, not a valid insertion
309 if (!LiveRegUnits.empty()) {
311 dbgs() << "Would clobber";
312 for (SparseSet<unsigned>::const_iterator
313 i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
314 dbgs() << ' ' << PrintRegUnit(*i, TRI);
315 dbgs() << " live before " << *I;
320 // This is a valid insertion point.
322 DEBUG(dbgs() << "Can insert before " << *I);
325 DEBUG(dbgs() << "No legal insertion point found.\n");
331 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
332 /// a potential candidate for if-conversion. Fill out the internal state.
334 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
336 TBB = FBB = Tail = 0;
338 if (Head->succ_size() != 2)
340 MachineBasicBlock *Succ0 = Head->succ_begin()[0];
341 MachineBasicBlock *Succ1 = Head->succ_begin()[1];
343 // Canonicalize so Succ0 has MBB as its single predecessor.
344 if (Succ0->pred_size() != 1)
345 std::swap(Succ0, Succ1);
347 if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
350 Tail = Succ0->succ_begin()[0];
352 // This is not a triangle.
354 // Check for a diamond. We won't deal with any critical edges.
355 if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
356 Succ1->succ_begin()[0] != Tail)
358 DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
359 << " -> BB#" << Succ0->getNumber()
360 << "/BB#" << Succ1->getNumber()
361 << " -> BB#" << Tail->getNumber() << '\n');
363 // Live-in physregs are tricky to get right when speculating code.
364 if (!Tail->livein_empty()) {
365 DEBUG(dbgs() << "Tail has live-ins.\n");
369 DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
370 << " -> BB#" << Succ0->getNumber()
371 << " -> BB#" << Tail->getNumber() << '\n');
374 // This is a triangle or a diamond.
375 // If Tail doesn't have any phis, there must be side effects.
376 if (Tail->empty() || !Tail->front().isPHI()) {
377 DEBUG(dbgs() << "No phis in tail.\n");
381 // The branch we're looking to eliminate must be analyzable.
383 if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
384 DEBUG(dbgs() << "Branch not analyzable.\n");
388 // This is weird, probably some sort of degenerate CFG.
390 DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
394 // AnalyzeBranch doesn't set FBB on a fall-through branch.
395 // Make sure it is always set.
396 FBB = TBB == Succ0 ? Succ1 : Succ0;
398 // Any phis in the tail block must be convertible to selects.
400 MachineBasicBlock *TPred = getTPred();
401 MachineBasicBlock *FPred = getFPred();
402 for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
403 I != E && I->isPHI(); ++I) {
405 PHIInfo &PI = PHIs.back();
406 // Find PHI operands corresponding to TPred and FPred.
407 for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
408 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
409 PI.TReg = PI.PHI->getOperand(i).getReg();
410 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
411 PI.FReg = PI.PHI->getOperand(i).getReg();
413 assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
414 assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
416 // Get target information.
417 if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
418 PI.CondCycles, PI.TCycles, PI.FCycles)) {
419 DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
424 // Check that the conditional instructions can be speculated.
426 ClobberedRegUnits.reset();
427 if (TBB != Tail && !canSpeculateInstrs(TBB))
429 if (FBB != Tail && !canSpeculateInstrs(FBB))
432 // Try to find a valid insertion point for the speculated instructions in the
434 if (!findInsertionPoint())
440 /// replacePHIInstrs - Completely replace PHI instructions with selects.
441 /// This is possible when the only Tail predecessors are the if-converted
443 void SSAIfConv::replacePHIInstrs() {
444 assert(Tail->pred_size() == 2 && "Cannot replace PHIs");
445 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
446 assert(FirstTerm != Head->end() && "No terminators");
447 DebugLoc HeadDL = FirstTerm->getDebugLoc();
449 // Convert all PHIs to select instructions inserted before FirstTerm.
450 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
451 PHIInfo &PI = PHIs[i];
452 DEBUG(dbgs() << "If-converting " << *PI.PHI);
453 assert(PI.PHI->getNumOperands() == 5 && "Unexpected PHI operands.");
454 unsigned DstReg = PI.PHI->getOperand(0).getReg();
455 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
456 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
457 PI.PHI->eraseFromParent();
462 /// rewritePHIOperands - When there are additional Tail predecessors, insert
463 /// select instructions in Head and rewrite PHI operands to use the selects.
464 /// Keep the PHI instructions in Tail to handle the other predecessors.
465 void SSAIfConv::rewritePHIOperands() {
466 MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
467 assert(FirstTerm != Head->end() && "No terminators");
468 DebugLoc HeadDL = FirstTerm->getDebugLoc();
470 // Convert all PHIs to select instructions inserted before FirstTerm.
471 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
472 PHIInfo &PI = PHIs[i];
473 DEBUG(dbgs() << "If-converting " << *PI.PHI);
474 unsigned PHIDst = PI.PHI->getOperand(0).getReg();
475 unsigned DstReg = MRI->createVirtualRegister(MRI->getRegClass(PHIDst));
476 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
477 DEBUG(dbgs() << " --> " << *llvm::prior(FirstTerm));
479 // Rewrite PHI operands TPred -> (DstReg, Head), remove FPred.
480 for (unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
481 MachineBasicBlock *MBB = PI.PHI->getOperand(i-1).getMBB();
482 if (MBB == getTPred()) {
483 PI.PHI->getOperand(i-1).setMBB(Head);
484 PI.PHI->getOperand(i-2).setReg(DstReg);
485 } else if (MBB == getFPred()) {
486 PI.PHI->RemoveOperand(i-1);
487 PI.PHI->RemoveOperand(i-2);
490 DEBUG(dbgs() << " --> " << *PI.PHI);
494 /// convertIf - Execute the if conversion after canConvertIf has determined the
497 /// Any basic blocks erased will be added to RemovedBlocks.
499 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
500 assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
502 // Move all instructions into Head, except for the terminators.
504 Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
506 Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
508 // Are there extra Tail predecessors?
509 bool ExtraPreds = Tail->pred_size() != 2;
511 rewritePHIOperands();
515 // Fix up the CFG, temporarily leave Head without any successors.
516 Head->removeSuccessor(TBB);
517 Head->removeSuccessor(FBB);
519 TBB->removeSuccessor(Tail);
521 FBB->removeSuccessor(Tail);
523 // Fix up Head's terminators.
524 // It should become a single branch or a fallthrough.
525 DebugLoc HeadDL = Head->getFirstTerminator()->getDebugLoc();
526 TII->RemoveBranch(*Head);
528 // Erase the now empty conditional blocks. It is likely that Head can fall
529 // through to Tail, and we can join the two blocks.
531 RemovedBlocks.push_back(TBB);
532 TBB->eraseFromParent();
535 RemovedBlocks.push_back(FBB);
536 FBB->eraseFromParent();
539 assert(Head->succ_empty() && "Additional head successors?");
540 if (!ExtraPreds && Head->isLayoutSuccessor(Tail)) {
541 // Splice Tail onto the end of Head.
542 DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
543 << " into head BB#" << Head->getNumber() << '\n');
544 Head->splice(Head->end(), Tail,
545 Tail->begin(), Tail->end());
546 Head->transferSuccessorsAndUpdatePHIs(Tail);
547 RemovedBlocks.push_back(Tail);
548 Tail->eraseFromParent();
550 // We need a branch to Tail, let code placement work it out later.
551 DEBUG(dbgs() << "Converting to unconditional branch.\n");
552 SmallVector<MachineOperand, 0> EmptyCond;
553 TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
554 Head->addSuccessor(Tail);
556 DEBUG(dbgs() << *Head);
560 //===----------------------------------------------------------------------===//
561 // EarlyIfConverter Pass
562 //===----------------------------------------------------------------------===//
565 class EarlyIfConverter : public MachineFunctionPass {
566 const TargetInstrInfo *TII;
567 const TargetRegisterInfo *TRI;
568 const MCSchedModel *SchedModel;
569 MachineRegisterInfo *MRI;
570 MachineDominatorTree *DomTree;
571 MachineLoopInfo *Loops;
572 MachineTraceMetrics *Traces;
573 MachineTraceMetrics::Ensemble *MinInstr;
578 EarlyIfConverter() : MachineFunctionPass(ID) {}
579 void getAnalysisUsage(AnalysisUsage &AU) const;
580 bool runOnMachineFunction(MachineFunction &MF);
583 bool tryConvertIf(MachineBasicBlock*);
584 void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
585 void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
586 void invalidateTraces();
587 bool shouldConvertIf();
589 } // end anonymous namespace
591 char EarlyIfConverter::ID = 0;
592 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
594 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
595 "early-ifcvt", "Early If Converter", false, false)
596 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
597 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
598 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
599 INITIALIZE_PASS_END(EarlyIfConverter,
600 "early-ifcvt", "Early If Converter", false, false)
602 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
603 AU.addRequired<MachineBranchProbabilityInfo>();
604 AU.addRequired<MachineDominatorTree>();
605 AU.addPreserved<MachineDominatorTree>();
606 AU.addRequired<MachineLoopInfo>();
607 AU.addPreserved<MachineLoopInfo>();
608 AU.addRequired<MachineTraceMetrics>();
609 AU.addPreserved<MachineTraceMetrics>();
610 MachineFunctionPass::getAnalysisUsage(AU);
613 /// Update the dominator tree after if-conversion erased some blocks.
614 void EarlyIfConverter::updateDomTree(ArrayRef<MachineBasicBlock*> Removed) {
615 // convertIf can remove TBB, FBB, and Tail can be merged into Head.
616 // TBB and FBB should not dominate any blocks.
617 // Tail children should be transferred to Head.
618 MachineDomTreeNode *HeadNode = DomTree->getNode(IfConv.Head);
619 for (unsigned i = 0, e = Removed.size(); i != e; ++i) {
620 MachineDomTreeNode *Node = DomTree->getNode(Removed[i]);
621 assert(Node != HeadNode && "Cannot erase the head node");
622 while (Node->getNumChildren()) {
623 assert(Node->getBlock() == IfConv.Tail && "Unexpected children");
624 DomTree->changeImmediateDominator(Node->getChildren().back(), HeadNode);
626 DomTree->eraseNode(Removed[i]);
630 /// Update LoopInfo after if-conversion.
631 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
634 // If-conversion doesn't change loop structure, and it doesn't mess with back
635 // edges, so updating LoopInfo is simply removing the dead blocks.
636 for (unsigned i = 0, e = Removed.size(); i != e; ++i)
637 Loops->removeBlock(Removed[i]);
640 /// Invalidate MachineTraceMetrics before if-conversion.
641 void EarlyIfConverter::invalidateTraces() {
642 Traces->verifyAnalysis();
643 Traces->invalidate(IfConv.Head);
644 Traces->invalidate(IfConv.Tail);
645 Traces->invalidate(IfConv.TBB);
646 Traces->invalidate(IfConv.FBB);
647 Traces->verifyAnalysis();
650 // Adjust cycles with downward saturation.
651 static unsigned adjCycles(unsigned Cyc, int Delta) {
652 if (Delta < 0 && Cyc + Delta > Cyc)
657 /// Apply cost model and heuristics to the if-conversion in IfConv.
658 /// Return true if the conversion is a good idea.
660 bool EarlyIfConverter::shouldConvertIf() {
661 // Stress testing mode disables all cost considerations.
666 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
668 MachineTraceMetrics::Trace TBBTrace = MinInstr->getTrace(IfConv.getTPred());
669 MachineTraceMetrics::Trace FBBTrace = MinInstr->getTrace(IfConv.getFPred());
670 DEBUG(dbgs() << "TBB: " << TBBTrace << "FBB: " << FBBTrace);
671 unsigned MinCrit = std::min(TBBTrace.getCriticalPath(),
672 FBBTrace.getCriticalPath());
674 // Set a somewhat arbitrary limit on the critical path extension we accept.
675 unsigned CritLimit = SchedModel->MispredictPenalty/2;
677 // If-conversion only makes sense when there is unexploited ILP. Compute the
678 // maximum-ILP resource length of the trace after if-conversion. Compare it
679 // to the shortest critical path.
680 SmallVector<const MachineBasicBlock*, 1> ExtraBlocks;
681 if (IfConv.TBB != IfConv.Tail)
682 ExtraBlocks.push_back(IfConv.TBB);
683 unsigned ResLength = FBBTrace.getResourceLength(ExtraBlocks);
684 DEBUG(dbgs() << "Resource length " << ResLength
685 << ", minimal critical path " << MinCrit << '\n');
686 if (ResLength > MinCrit + CritLimit) {
687 DEBUG(dbgs() << "Not enough available ILP.\n");
691 // Assume that the depth of the first head terminator will also be the depth
692 // of the select instruction inserted, as determined by the flag dependency.
693 // TBB / FBB data dependencies may delay the select even more.
694 MachineTraceMetrics::Trace HeadTrace = MinInstr->getTrace(IfConv.Head);
695 unsigned BranchDepth =
696 HeadTrace.getInstrCycles(IfConv.Head->getFirstTerminator()).Depth;
697 DEBUG(dbgs() << "Branch depth: " << BranchDepth << '\n');
699 // Look at all the tail phis, and compute the critical path extension caused
700 // by inserting select instructions.
701 MachineTraceMetrics::Trace TailTrace = MinInstr->getTrace(IfConv.Tail);
702 for (unsigned i = 0, e = IfConv.PHIs.size(); i != e; ++i) {
703 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
704 unsigned Slack = TailTrace.getInstrSlack(PI.PHI);
705 unsigned MaxDepth = Slack + TailTrace.getInstrCycles(PI.PHI).Depth;
706 DEBUG(dbgs() << "Slack " << Slack << ":\t" << *PI.PHI);
708 // The condition is pulled into the critical path.
709 unsigned CondDepth = adjCycles(BranchDepth, PI.CondCycles);
710 if (CondDepth > MaxDepth) {
711 unsigned Extra = CondDepth - MaxDepth;
712 DEBUG(dbgs() << "Condition adds " << Extra << " cycles.\n");
713 if (Extra > CritLimit) {
714 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
719 // The TBB value is pulled into the critical path.
720 unsigned TDepth = adjCycles(TBBTrace.getPHIDepth(PI.PHI), PI.TCycles);
721 if (TDepth > MaxDepth) {
722 unsigned Extra = TDepth - MaxDepth;
723 DEBUG(dbgs() << "TBB data adds " << Extra << " cycles.\n");
724 if (Extra > CritLimit) {
725 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
730 // The FBB value is pulled into the critical path.
731 unsigned FDepth = adjCycles(FBBTrace.getPHIDepth(PI.PHI), PI.FCycles);
732 if (FDepth > MaxDepth) {
733 unsigned Extra = FDepth - MaxDepth;
734 DEBUG(dbgs() << "FBB data adds " << Extra << " cycles.\n");
735 if (Extra > CritLimit) {
736 DEBUG(dbgs() << "Exceeds limit of " << CritLimit << '\n');
744 /// Attempt repeated if-conversion on MBB, return true if successful.
746 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
747 bool Changed = false;
748 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
749 // If-convert MBB and update analyses.
751 SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
752 IfConv.convertIf(RemovedBlocks);
754 updateDomTree(RemovedBlocks);
755 updateLoops(RemovedBlocks);
760 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
761 DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
762 << "********** Function: "
763 << ((Value*)MF.getFunction())->getName() << '\n');
764 TII = MF.getTarget().getInstrInfo();
765 TRI = MF.getTarget().getRegisterInfo();
766 SchedModel = MF.getTarget().getInstrItineraryData()->SchedModel;
767 MRI = &MF.getRegInfo();
768 DomTree = &getAnalysis<MachineDominatorTree>();
769 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
770 Traces = &getAnalysis<MachineTraceMetrics>();
773 bool Changed = false;
774 IfConv.runOnMachineFunction(MF);
776 // Visit blocks in dominator tree post-order. The post-order enables nested
777 // if-conversion in a single pass. The tryConvertIf() function may erase
778 // blocks, but only blocks dominated by the head block. This makes it safe to
779 // update the dominator tree while the post-order iterator is still active.
780 for (po_iterator<MachineDominatorTree*>
781 I = po_begin(DomTree), E = po_end(DomTree); I != E; ++I)
782 if (tryConvertIf(I->getBlock()))
785 MF.verify(this, "After early if-conversion");