048ff8913af892722ce83beef1499b128f88644e
[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 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
54
55 //===----------------------------------------------------------------------===//
56 //                                 SSAIfConv
57 //===----------------------------------------------------------------------===//
58 //
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.
62 //
63 // SSAIfConv can convert both triangles and diamonds:
64 //
65 //   Triangle: Head              Diamond: Head
66 //              | \                       /  \_
67 //              |  \                     /    |
68 //              |  [TF]BB              FBB    TBB
69 //              |  /                     \    /
70 //              | /                       \  /
71 //             Tail                       Tail
72 //
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.
75 //
76 namespace {
77 class SSAIfConv {
78   const TargetInstrInfo *TII;
79   const TargetRegisterInfo *TRI;
80   MachineRegisterInfo *MRI;
81
82 public:
83   /// The block containing the conditional branch.
84   MachineBasicBlock *Head;
85
86   /// The block containing phis after the if-then-else.
87   MachineBasicBlock *Tail;
88
89   /// The 'true' conditional block as determined by AnalyzeBranch.
90   MachineBasicBlock *TBB;
91
92   /// The 'false' conditional block as determined by AnalyzeBranch.
93   MachineBasicBlock *FBB;
94
95   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
96   /// equal to Tail.
97   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
98
99   /// Returns the Tail predecessor for the True side.
100   MachineBasicBlock *getTPred() const { return TBB == Tail ? Head : TBB; }
101
102   /// Returns the Tail predecessor for the  False side.
103   MachineBasicBlock *getFPred() const { return FBB == Tail ? Head : FBB; }
104
105   /// Information about each phi in the Tail block.
106   struct PHIInfo {
107     MachineInstr *PHI;
108     unsigned TReg, FReg;
109     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
110     int CondCycles, TCycles, FCycles;
111
112     PHIInfo(MachineInstr *phi)
113       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
114   };
115
116   SmallVector<PHIInfo, 8> PHIs;
117
118 private:
119   /// The branch condition determined by AnalyzeBranch.
120   SmallVector<MachineOperand, 4> Cond;
121
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;
125
126   /// Register units clobbered by the conditional blocks.
127   BitVector ClobberedRegUnits;
128
129   // Scratch pad for findInsertionPoint.
130   SparseSet<unsigned> LiveRegUnits;
131
132   /// Insertion point in Head for speculatively executed instructions form TBB
133   /// and FBB.
134   MachineBasicBlock::iterator InsertionPoint;
135
136   /// Return true if all non-terminator instructions in MBB can be safely
137   /// speculated.
138   bool canSpeculateInstrs(MachineBasicBlock *MBB);
139
140   /// Find a valid insertion point in Head.
141   bool findInsertionPoint();
142
143   /// Replace PHI instructions in Tail with selects.
144   void replacePHIInstrs();
145
146   /// Insert selects and rewrite PHI operands to use them.
147   void rewritePHIOperands();
148
149 public:
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());
159   }
160
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);
164
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);
168 };
169 } // end anonymous namespace
170
171
172 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
173 /// be speculated. The terminators are not considered.
174 ///
175 /// If instructions use any values that are defined in the head basic block,
176 /// the defining instructions are added to InsertAfter.
177 ///
178 /// Any clobbered regunits are added to ClobberedRegUnits.
179 ///
180 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
181   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
182   // get right.
183   if (!MBB->livein_empty()) {
184     DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
185     return false;
186   }
187
188   unsigned InstrCount = 0;
189
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())
195       continue;
196
197     if (++InstrCount > BlockInstrLimit && !Stress) {
198       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
199                    << BlockInstrLimit << " instructions.\n");
200       return false;
201     }
202
203     // There shouldn't normally be any phis in a single-predecessor block.
204     if (I->isPHI()) {
205       DEBUG(dbgs() << "Can't hoist: " << *I);
206       return false;
207     }
208
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.
212     if (I->mayLoad()) {
213       DEBUG(dbgs() << "Won't speculate load: " << *I);
214       return false;
215     }
216
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);
221       return false;
222     }
223
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);
228         return false;
229       }
230       if (!MO->isReg())
231         continue;
232       unsigned Reg = MO->getReg();
233
234       // Remember clobbered regunits.
235       if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
236         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
237           ClobberedRegUnits.set(*Units);
238
239       if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
240         continue;
241       MachineInstr *DefMI = MRI->getVRegDef(Reg);
242       if (!DefMI || DefMI->getParent() != Head)
243         continue;
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");
248         return false;
249       }
250     }
251   }
252   return true;
253 }
254
255
256 /// Find an insertion point in Head for the speculated instructions. The
257 /// insertion point must be:
258 ///
259 /// 1. Before any terminators.
260 /// 2. After any instructions in InsertAfter.
261 /// 3. Not have any clobbered regunits live.
262 ///
263 /// This function sets InsertionPoint and returns true when successful, it
264 /// returns false if no valid insertion point could be found.
265 ///
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();
274   while (I != B) {
275     --I;
276     // Some of the conditional code depends in I.
277     if (InsertAfter.count(I)) {
278       DEBUG(dbgs() << "Can't insert code after " << *I);
279       return false;
280     }
281
282     // Update live regunits.
283     for (MIOperands MO(I); MO.isValid(); ++MO) {
284       // We're ignoring regmask operands. That is conservatively correct.
285       if (!MO->isReg())
286         continue;
287       unsigned Reg = MO->getReg();
288       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
289         continue;
290       // I clobbers Reg, so it isn't live before I.
291       if (MO->isDef())
292         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
293           LiveRegUnits.erase(*Units);
294       // Unless I reads Reg.
295       if (MO->readsReg())
296         Reads.push_back(Reg);
297     }
298     // Anything read by I is live before I.
299     while (!Reads.empty())
300       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
301            ++Units)
302         if (ClobberedRegUnits.test(*Units))
303           LiveRegUnits.insert(*Units);
304
305     // We can't insert before a terminator.
306     if (I != FirstTerm && I->isTerminator())
307       continue;
308
309     // Some of the clobbered registers are live before I, not a valid insertion
310     // point.
311     if (!LiveRegUnits.empty()) {
312       DEBUG({
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;
318       });
319       continue;
320     }
321
322     // This is a valid insertion point.
323     InsertionPoint = I;
324     DEBUG(dbgs() << "Can insert before " << *I);
325     return true;
326   }
327   DEBUG(dbgs() << "No legal insertion point found.\n");
328   return false;
329 }
330
331
332
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.
335 ///
336 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
337   Head = MBB;
338   TBB = FBB = Tail = 0;
339
340   if (Head->succ_size() != 2)
341     return false;
342   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
343   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
344
345   // Canonicalize so Succ0 has MBB as its single predecessor.
346   if (Succ0->pred_size() != 1)
347     std::swap(Succ0, Succ1);
348
349   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
350     return false;
351
352   Tail = Succ0->succ_begin()[0];
353
354   // This is not a triangle.
355   if (Tail != Succ1) {
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)
359       return false;
360     DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
361                  << " -> BB#" << Succ0->getNumber()
362                  << "/BB#" << Succ1->getNumber()
363                  << " -> BB#" << Tail->getNumber() << '\n');
364
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");
368       return false;
369     }
370   } else {
371     DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
372                  << " -> BB#" << Succ0->getNumber()
373                  << " -> BB#" << Tail->getNumber() << '\n');
374   }
375
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");
380     return false;
381   }
382
383   // The branch we're looking to eliminate must be analyzable.
384   Cond.clear();
385   if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
386     DEBUG(dbgs() << "Branch not analyzable.\n");
387     return false;
388   }
389
390   // This is weird, probably some sort of degenerate CFG.
391   if (!TBB) {
392     DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
393     return false;
394   }
395
396   // AnalyzeBranch doesn't set FBB on a fall-through branch.
397   // Make sure it is always set.
398   FBB = TBB == Succ0 ? Succ1 : Succ0;
399
400   // Any phis in the tail block must be convertible to selects.
401   PHIs.clear();
402   MachineBasicBlock *TPred = getTPred();
403   MachineBasicBlock *FPred = getFPred();
404   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
405        I != E && I->isPHI(); ++I) {
406     PHIs.push_back(&*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();
414     }
415     assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
416     assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
417
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);
422       return false;
423     }
424   }
425
426   // Check that the conditional instructions can be speculated.
427   InsertAfter.clear();
428   ClobberedRegUnits.reset();
429   if (TBB != Tail && !canSpeculateInstrs(TBB))
430     return false;
431   if (FBB != Tail && !canSpeculateInstrs(FBB))
432     return false;
433
434   // Try to find a valid insertion point for the speculated instructions in the
435   // head basic block.
436   if (!findInsertionPoint())
437     return false;
438
439   return true;
440 }
441
442 /// replacePHIInstrs - Completely replace PHI instructions with selects.
443 /// This is possible when the only Tail predecessors are the if-converted
444 /// blocks.
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();
450
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();
460     PI.PHI = 0;
461   }
462 }
463
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();
471
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));
480
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);
490       }
491     }
492     DEBUG(dbgs() << "          --> " << *PI.PHI);
493   }
494 }
495
496 /// convertIf - Execute the if conversion after canConvertIf has determined the
497 /// feasibility.
498 ///
499 /// Any basic blocks erased will be added to RemovedBlocks.
500 ///
501 void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock*> &RemovedBlocks) {
502   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
503
504   // Move all instructions into Head, except for the terminators.
505   if (TBB != Tail)
506     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
507   if (FBB != Tail)
508     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
509
510   // Are there extra Tail predecessors?
511   bool ExtraPreds = Tail->pred_size() != 2;
512   if (ExtraPreds)
513     rewritePHIOperands();
514   else
515     replacePHIInstrs();
516
517   // Fix up the CFG, temporarily leave Head without any successors.
518   Head->removeSuccessor(TBB);
519   Head->removeSuccessor(FBB);
520   if (TBB != Tail)
521     TBB->removeSuccessor(Tail);
522   if (FBB != Tail)
523     FBB->removeSuccessor(Tail);
524
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);
529
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.
532   if (TBB != Tail) {
533     RemovedBlocks.push_back(TBB);
534     TBB->eraseFromParent();
535   }
536   if (FBB != Tail) {
537     RemovedBlocks.push_back(FBB);
538     FBB->eraseFromParent();
539   }
540
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();
551   } else {
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);
557   }
558   DEBUG(dbgs() << *Head);
559 }
560
561
562 //===----------------------------------------------------------------------===//
563 //                           EarlyIfConverter Pass
564 //===----------------------------------------------------------------------===//
565
566 namespace {
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;
576   SSAIfConv IfConv;
577
578 public:
579   static char ID;
580   EarlyIfConverter() : MachineFunctionPass(ID) {}
581   void getAnalysisUsage(AnalysisUsage &AU) const;
582   bool runOnMachineFunction(MachineFunction &MF);
583
584 private:
585   bool tryConvertIf(MachineBasicBlock*);
586   void updateDomTree(ArrayRef<MachineBasicBlock*> Removed);
587   void updateLoops(ArrayRef<MachineBasicBlock*> Removed);
588   void invalidateTraces();
589   bool shouldConvertIf();
590 };
591 } // end anonymous namespace
592
593 char EarlyIfConverter::ID = 0;
594 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
595
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)
603
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);
613 }
614
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);
627     }
628     DomTree->eraseNode(Removed[i]);
629   }
630 }
631
632 /// Update LoopInfo after if-conversion.
633 void EarlyIfConverter::updateLoops(ArrayRef<MachineBasicBlock*> Removed) {
634   if (!Loops)
635     return;
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]);
640 }
641
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();
650 }
651
652 // Adjust cycles with downward saturation.
653 static unsigned adjCycles(unsigned Cyc, int Delta) {
654   if (Delta < 0 && Cyc + Delta > Cyc)
655     return 0;
656   return Cyc + Delta;
657 }
658
659 /// Apply cost model and heuristics to the if-conversion in IfConv.
660 /// Return true if the conversion is a good idea.
661 ///
662 bool EarlyIfConverter::shouldConvertIf() {
663   // Stress testing mode disables all cost considerations.
664   if (Stress)
665     return true;
666
667   if (!MinInstr)
668     MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
669
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());
675
676   // Set a somewhat arbitrary limit on the critical path extension we accept.
677   unsigned CritLimit = SchedModel->MispredictPenalty/2;
678
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");
690     return false;
691   }
692
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');
700
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);
709
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');
717         return false;
718       }
719     }
720
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');
728         return false;
729       }
730     }
731
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');
739         return false;
740       }
741     }
742   }
743   return true;
744 }
745
746 /// Attempt repeated if-conversion on MBB, return true if successful.
747 ///
748 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
749   bool Changed = false;
750   while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
751     // If-convert MBB and update analyses.
752     invalidateTraces();
753     SmallVector<MachineBasicBlock*, 4> RemovedBlocks;
754     IfConv.convertIf(RemovedBlocks);
755     Changed = true;
756     updateDomTree(RemovedBlocks);
757     updateLoops(RemovedBlocks);
758   }
759   return Changed;
760 }
761
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>();
773   MinInstr = 0;
774
775   bool Changed = false;
776   IfConv.runOnMachineFunction(MF);
777
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()))
785       Changed = true;
786
787   MF.verify(this, "After early if-conversion");
788   return Changed;
789 }