Delete dead typedef.
[oota-llvm.git] / lib / CodeGen / EarlyIfConversion.cpp
1 //===-- EarlyIfConversion.cpp - If-conversion on SSA form machine code ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // may mispredict.
13 //
14 // Instructions from both sides of the branch are executed specutatively, and a
15 // cmov instruction selects the result.
16 //
17 //===----------------------------------------------------------------------===//
18
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"
40
41 using namespace llvm;
42
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."));
48
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"));
52
53 //===----------------------------------------------------------------------===//
54 //                                 SSAIfConv
55 //===----------------------------------------------------------------------===//
56 //
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.
60 //
61 // SSAIfConv can convert both triangles and diamonds:
62 //
63 //   Triangle: Head              Diamond: Head
64 //              | \                       /  \_
65 //              |  \                     /    |
66 //              |  [TF]BB              FBB    TBB
67 //              |  /                     \    /
68 //              | /                       \  /
69 //             Tail                       Tail
70 //
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.
73 //
74 namespace {
75 class SSAIfConv {
76   const TargetInstrInfo *TII;
77   const TargetRegisterInfo *TRI;
78   MachineRegisterInfo *MRI;
79
80 public:
81   /// The block containing the conditional branch.
82   MachineBasicBlock *Head;
83
84   /// The block containing phis after the if-then-else.
85   MachineBasicBlock *Tail;
86
87   /// The 'true' conditional block as determined by AnalyzeBranch.
88   MachineBasicBlock *TBB;
89
90   /// The 'false' conditional block as determined by AnalyzeBranch.
91   MachineBasicBlock *FBB;
92
93   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
94   /// equal to Tail.
95   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
96
97   /// Returns the Tail predecessor for the True side.
98   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
99
100   /// Returns the Tail predecessor for the  False side.
101   MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
102
103   /// Information about each phi in the Tail block.
104   struct PHIInfo {
105     MachineInstr *PHI;
106     unsigned TReg, FReg;
107     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
108     int CondCycles, TCycles, FCycles;
109
110     PHIInfo(MachineInstr *phi)
111       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
112   };
113
114   SmallVector<PHIInfo, 8> PHIs;
115
116 private:
117   /// The branch condition determined by AnalyzeBranch.
118   SmallVector<MachineOperand, 4> Cond;
119
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;
123
124   /// Register units clobbered by the conditional blocks.
125   BitVector ClobberedRegUnits;
126
127   // Scratch pad for findInsertionPoint.
128   SparseSet<unsigned> LiveRegUnits;
129
130   /// Insertion point in Head for speculatively executed instructions form TBB
131   /// and FBB.
132   MachineBasicBlock::iterator InsertionPoint;
133
134   /// Return true if all non-terminator instructions in MBB can be safely
135   /// speculated.
136   bool canSpeculateInstrs(MachineBasicBlock *MBB);
137
138   /// Find a valid insertion point in Head.
139   bool findInsertionPoint();
140
141   /// Replace PHI instructions in Tail with selects.
142   void replacePHIInstrs();
143
144   /// Insert selects and rewrite PHI operands to use them.
145   void rewritePHIOperands();
146
147 public:
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());
157   }
158
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);
162
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);
166 };
167 } // end anonymous namespace
168
169
170 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
171 /// be speculated. The terminators are not considered.
172 ///
173 /// If instructions use any values that are defined in the head basic block,
174 /// the defining instructions are added to InsertAfter.
175 ///
176 /// Any clobbered regunits are added to ClobberedRegUnits.
177 ///
178 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
179   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
180   // get right.
181   if (!MBB->livein_empty()) {
182     DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
183     return false;
184   }
185
186   unsigned InstrCount = 0;
187
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())
193       continue;
194
195     if (++InstrCount > BlockInstrLimit && !Stress) {
196       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
197                    << BlockInstrLimit << " instructions.\n");
198       return false;
199     }
200
201     // There shouldn't normally be any phis in a single-predecessor block.
202     if (I->isPHI()) {
203       DEBUG(dbgs() << "Can't hoist: " << *I);
204       return false;
205     }
206
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.
210     if (I->mayLoad()) {
211       DEBUG(dbgs() << "Won't speculate load: " << *I);
212       return false;
213     }
214
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);
219       return false;
220     }
221
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);
226         return false;
227       }
228       if (!MO->isReg())
229         continue;
230       unsigned Reg = MO->getReg();
231
232       // Remember clobbered regunits.
233       if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
234         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
235           ClobberedRegUnits.set(*Units);
236
237       if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
238         continue;
239       MachineInstr *DefMI = MRI->getVRegDef(Reg);
240       if (!DefMI || DefMI->getParent() != Head)
241         continue;
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");
246         return false;
247       }
248     }
249   }
250   return true;
251 }
252
253
254 /// Find an insertion point in Head for the speculated instructions. The
255 /// insertion point must be:
256 ///
257 /// 1. Before any terminators.
258 /// 2. After any instructions in InsertAfter.
259 /// 3. Not have any clobbered regunits live.
260 ///
261 /// This function sets InsertionPoint and returns true when successful, it
262 /// returns false if no valid insertion point could be found.
263 ///
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();
272   while (I != B) {
273     --I;
274     // Some of the conditional code depends in I.
275     if (InsertAfter.count(I)) {
276       DEBUG(dbgs() << "Can't insert code after " << *I);
277       return false;
278     }
279
280     // Update live regunits.
281     for (MIOperands MO(I); MO.isValid(); ++MO) {
282       // We're ignoring regmask operands. That is conservatively correct.
283       if (!MO->isReg())
284         continue;
285       unsigned Reg = MO->getReg();
286       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
287         continue;
288       // I clobbers Reg, so it isn't live before I.
289       if (MO->isDef())
290         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
291           LiveRegUnits.erase(*Units);
292       // Unless I reads Reg.
293       if (MO->readsReg())
294         Reads.push_back(Reg);
295     }
296     // Anything read by I is live before I.
297     while (!Reads.empty())
298       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
299            ++Units)
300         if (ClobberedRegUnits.test(*Units))
301           LiveRegUnits.insert(*Units);
302
303     // We can't insert before a terminator.
304     if (I != FirstTerm && I->isTerminator())
305       continue;
306
307     // Some of the clobbered registers are live before I, not a valid insertion
308     // point.
309     if (!LiveRegUnits.empty()) {
310       DEBUG({
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;
316       });
317       continue;
318     }
319
320     // This is a valid insertion point.
321     InsertionPoint = I;
322     DEBUG(dbgs() << "Can insert before " << *I);
323     return true;
324   }
325   DEBUG(dbgs() << "No legal insertion point found.\n");
326   return false;
327 }
328
329
330
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.
333 ///
334 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
335   Head = MBB;
336   TBB = FBB = Tail = 0;
337
338   if (Head->succ_size() != 2)
339     return false;
340   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
341   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
342
343   // Canonicalize so Succ0 has MBB as its single predecessor.
344   if (Succ0->pred_size() != 1)
345     std::swap(Succ0, Succ1);
346
347   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
348     return false;
349
350   Tail = Succ0->succ_begin()[0];
351
352   // This is not a triangle.
353   if (Tail != Succ1) {
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)
357       return false;
358     DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
359                  << " -> BB#" << Succ0->getNumber()
360                  << "/BB#" << Succ1->getNumber()
361                  << " -> BB#" << Tail->getNumber() << '\n');
362
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");
366       return false;
367     }
368   } else {
369     DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
370                  << " -> BB#" << Succ0->getNumber()
371                  << " -> BB#" << Tail->getNumber() << '\n');
372   }
373
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");
378     return false;
379   }
380
381   // The branch we're looking to eliminate must be analyzable.
382   Cond.clear();
383   if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
384     DEBUG(dbgs() << "Branch not analyzable.\n");
385     return false;
386   }
387
388   // This is weird, probably some sort of degenerate CFG.
389   if (!TBB) {
390     DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
391     return false;
392   }
393
394   // AnalyzeBranch doesn't set FBB on a fall-through branch.
395   // Make sure it is always set.
396   FBB = TBB == Succ0 ? Succ1 : Succ0;
397
398   // Any phis in the tail block must be convertible to selects.
399   PHIs.clear();
400   MachineBasicBlock *TPred = getTPred();
401   MachineBasicBlock *FPred = getFPred();
402   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
403        I != E && I->isPHI(); ++I) {
404     PHIs.push_back(&*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();
412     }
413     assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
414     assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
415
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);
420       return false;
421     }
422   }
423
424   // Check that the conditional instructions can be speculated.
425   InsertAfter.clear();
426   ClobberedRegUnits.reset();
427   if (TBB != Tail && !canSpeculateInstrs(TBB))
428     return false;
429   if (FBB != Tail && !canSpeculateInstrs(FBB))
430     return false;
431
432   // Try to find a valid insertion point for the speculated instructions in the
433   // head basic block.
434   if (!findInsertionPoint())
435     return false;
436
437   return true;
438 }
439
440 /// replacePHIInstrs - Completely replace PHI instructions with selects.
441 /// This is possible when the only Tail predecessors are the if-converted
442 /// blocks.
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();
448
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();
458     PI.PHI = 0;
459   }
460 }
461
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();
469
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));
478
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);
488       }
489     }
490     DEBUG(dbgs() << "          --> " << *PI.PHI);
491   }
492 }
493
494 /// convertIf - Execute the if conversion after canConvertIf has determined the
495 /// feasibility.
496 ///
497 /// Any basic blocks erased will be added to RemovedBlocks.
498 ///
499 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
500   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
501
502   // Move all instructions into Head, except for the terminators.
503   if (TBB != Tail)
504     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
505   if (FBB != Tail)
506     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
507
508   // Are there extra Tail predecessors?
509   bool ExtraPreds = Tail->pred_size() != 2;
510   if (ExtraPreds)
511     rewritePHIOperands();
512   else
513     replacePHIInstrs();
514
515   // Fix up the CFG, temporarily leave Head without any successors.
516   Head->removeSuccessor(TBB);
517   Head->removeSuccessor(FBB);
518   if (TBB != Tail)
519     TBB->removeSuccessor(Tail);
520   if (FBB != Tail)
521     FBB->removeSuccessor(Tail);
522
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);
527
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.
530   if (TBB != Tail) {
531     RemovedBlocks.push_back(TBB);
532     TBB->eraseFromParent();
533   }
534   if (FBB != Tail) {
535     RemovedBlocks.push_back(FBB);
536     FBB->eraseFromParent();
537   }
538
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();
549   } else {
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);
555   }
556   DEBUG(dbgs() << *Head);
557 }
558
559
560 //===----------------------------------------------------------------------===//
561 //                           EarlyIfConverter Pass
562 //===----------------------------------------------------------------------===//
563
564 namespace {
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;
574   SSAIfConv IfConv;
575
576 public:
577   static char ID;
578   EarlyIfConverter() : MachineFunctionPass(ID) {}
579   void getAnalysisUsage(AnalysisUsage &AU) const;
580   bool runOnMachineFunction(MachineFunction &MF);
581
582 private:
583   bool tryConvertIf(MachineBasicBlock*);
584   void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
585   void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
586   void invalidateTraces();
587   bool shouldConvertIf();
588 };
589 } // end anonymous namespace
590
591 char EarlyIfConverter::ID = 0;
592 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
593
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)
601
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);
611 }
612
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);
625     }
626     DomTree->eraseNode(Removed[i]);
627   }
628 }
629
630 /// Update LoopInfo after if-conversion.
631 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
632   if (!Loops)
633     return;
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]);
638 }
639
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();
648 }
649
650 // Adjust cycles with downward saturation.
651 static unsigned adjCycles(unsigned Cyc, int Delta) {
652   if (Delta < 0 && Cyc + Delta > Cyc)
653     return 0;
654   return Cyc + Delta;
655 }
656
657 /// Apply cost model and heuristics to the if-conversion in IfConv.
658 /// Return true if the conversion is a good idea.
659 ///
660 bool EarlyIfConverter::shouldConvertIf() {
661   // Stress testing mode disables all cost considerations.
662   if (Stress)
663     return true;
664
665   if (!MinInstr)
666     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
667
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());
673
674   // Set a somewhat arbitrary limit on the critical path extension we accept.
675   unsigned CritLimit = SchedModel->MispredictPenalty/2;
676
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");
688     return false;
689   }
690
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');
698
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);
707
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');
715         return false;
716       }
717     }
718
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');
726         return false;
727       }
728     }
729
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');
737         return false;
738       }
739     }
740   }
741   return true;
742 }
743
744 /// Attempt repeated if-conversion on MBB, return true if successful.
745 ///
746 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
747   bool Changed = false;
748   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
749     // If-convert MBB and update analyses.
750     invalidateTraces();
751     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
752     IfConv.convertIf(RemovedBlocks);
753     Changed = true;
754     updateDomTree(RemovedBlocks);
755     updateLoops(RemovedBlocks);
756   }
757   return Changed;
758 }
759
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>();
771   MinInstr = 0;
772
773   bool Changed = false;
774   IfConv.runOnMachineFunction(MF);
775
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()))
783       Changed = true;
784
785   MF.verify(this, "After early if-conversion");
786   return Changed;
787 }