f575b249aa15f1368be0ac8956e7c846131c2af4
[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 "llvm/Function.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SparseSet.h"
25 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35
36 using namespace llvm;
37
38 // Absolute maximum number of instructions allowed per speculated block.
39 // This bypasses all other heuristics, so it should be set fairly high.
40 static cl::opt<unsigned>
41 BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden,
42   cl::desc("Maximum number of instructions per speculated block."));
43
44 // Stress testing mode - disable heuristics.
45 static cl::opt<bool> Stress("stress-early-ifcvt", cl::Hidden,
46   cl::desc("Turn all knobs to 11"));
47
48 typedef SmallSetVector<MachineBasicBlock*, 8> BlockSetVector;
49
50 //===----------------------------------------------------------------------===//
51 //                                 SSAIfConv
52 //===----------------------------------------------------------------------===//
53 //
54 // The SSAIfConv class performs if-conversion on SSA form machine code after
55 // determining if it is possible. The class contains no heuristics; external
56 // code should be used to determine when if-conversion is a good idea.
57 //
58 // SSAIfConv can convert both triangles and diamonds:
59 //
60 //   Triangle: Head              Diamond: Head
61 //              | \                       /  \_
62 //              |  \                     /    |
63 //              |  [TF]BB              FBB    TBB
64 //              |  /                     \    /
65 //              | /                       \  /
66 //             Tail                       Tail
67 //
68 // Instructions in the conditional blocks TBB and/or FBB are spliced into the
69 // Head block, and phis in the Tail block are converted to select instructions.
70 //
71 namespace {
72 class SSAIfConv {
73   const TargetInstrInfo *TII;
74   const TargetRegisterInfo *TRI;
75   MachineRegisterInfo *MRI;
76
77   /// The block containing the conditional branch.
78   MachineBasicBlock *Head;
79
80   /// The block containing phis after the if-then-else.
81   MachineBasicBlock *Tail;
82
83   /// The 'true' conditional block as determined by AnalyzeBranch.
84   MachineBasicBlock *TBB;
85
86   /// The 'false' conditional block as determined by AnalyzeBranch.
87   MachineBasicBlock *FBB;
88
89   /// isTriangle - When there is no 'else' block, either TBB or FBB will be
90   /// equal to Tail.
91   bool isTriangle() const { return TBB == Tail || FBB == Tail; }
92
93   /// The branch condition determined by AnalyzeBranch.
94   SmallVector<MachineOperand, 4> Cond;
95
96   /// Information about each phi in the Tail block.
97   struct PHIInfo {
98     MachineInstr *PHI;
99     unsigned TReg, FReg;
100     // Latencies from Cond+Branch, TReg, and FReg to DstReg.
101     int CondCycles, TCycles, FCycles;
102
103     PHIInfo(MachineInstr *phi)
104       : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
105   };
106
107   SmallVector<PHIInfo, 8> PHIs;
108
109   /// Instructions in Head that define values used by the conditional blocks.
110   /// The hoisted instructions must be inserted after these instructions.
111   SmallPtrSet<MachineInstr*, 8> InsertAfter;
112
113   /// Register units clobbered by the conditional blocks.
114   BitVector ClobberedRegUnits;
115
116   // Scratch pad for findInsertionPoint.
117   SparseSet<unsigned> LiveRegUnits;
118
119   /// Insertion point in Head for speculatively executed instructions form TBB
120   /// and FBB.
121   MachineBasicBlock::iterator InsertionPoint;
122
123   /// Return true if all non-terminator instructions in MBB can be safely
124   /// speculated.
125   bool canSpeculateInstrs(MachineBasicBlock *MBB);
126
127   /// Find a valid insertion point in Head.
128   bool findInsertionPoint();
129
130 public:
131   /// runOnMachineFunction - Initialize per-function data structures.
132   void runOnMachineFunction(MachineFunction &MF) {
133     TII = MF.getTarget().getInstrInfo();
134     TRI = MF.getTarget().getRegisterInfo();
135     MRI = &MF.getRegInfo();
136     LiveRegUnits.clear();
137     LiveRegUnits.setUniverse(TRI->getNumRegUnits());
138     ClobberedRegUnits.clear();
139     ClobberedRegUnits.resize(TRI->getNumRegUnits());
140   }
141
142   /// canConvertIf - If the sub-CFG headed by MBB can be if-converted,
143   /// initialize the internal state, and return true.
144   bool canConvertIf(MachineBasicBlock *MBB);
145
146   /// convertIf - If-convert the last block passed to canConvertIf(), assuming
147   /// it is possible. Remove any erased blocks from WorkList
148   void convertIf(BlockSetVector &WorkList);
149 };
150 } // end anonymous namespace
151
152
153 /// canSpeculateInstrs - Returns true if all the instructions in MBB can safely
154 /// be speculated. The terminators are not considered.
155 ///
156 /// If instructions use any values that are defined in the head basic block,
157 /// the defining instructions are added to InsertAfter.
158 ///
159 /// Any clobbered regunits are added to ClobberedRegUnits.
160 ///
161 bool SSAIfConv::canSpeculateInstrs(MachineBasicBlock *MBB) {
162   // Reject any live-in physregs. It's probably CPSR/EFLAGS, and very hard to
163   // get right.
164   if (!MBB->livein_empty()) {
165     DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has live-ins.\n");
166     return false;
167   }
168
169   unsigned InstrCount = 0;
170   for (MachineBasicBlock::iterator I = MBB->begin(),
171        E = MBB->getFirstTerminator(); I != E; ++I) {
172     if (I->isDebugValue())
173       continue;
174
175     if (++InstrCount > BlockInstrLimit && !Stress) {
176       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " has more than "
177                    << BlockInstrLimit << " instructions.\n");
178       return false;
179     }
180
181     // There shouldn't normally be any phis in a single-predecessor block.
182     if (I->isPHI()) {
183       DEBUG(dbgs() << "Can't hoist: " << *I);
184       return false;
185     }
186
187     // Don't speculate loads. Note that it may be possible and desirable to
188     // speculate GOT or constant pool loads that are guaranteed not to trap,
189     // but we don't support that for now.
190     if (I->mayLoad()) {
191       DEBUG(dbgs() << "Won't speculate load: " << *I);
192       return false;
193     }
194
195     // We never speculate stores, so an AA pointer isn't necessary.
196     bool DontMoveAcrossStore = true;
197     if (!I->isSafeToMove(TII, 0, DontMoveAcrossStore)) {
198       DEBUG(dbgs() << "Can't speculate: " << *I);
199       return false;
200     }
201
202     // Check for any dependencies on Head instructions.
203     for (MIOperands MO(I); MO.isValid(); ++MO) {
204       if (MO->isRegMask()) {
205         DEBUG(dbgs() << "Won't speculate regmask: " << *I);
206         return false;
207       }
208       if (!MO->isReg())
209         continue;
210       unsigned Reg = MO->getReg();
211
212       // Remember clobbered regunits.
213       if (MO->isDef() && TargetRegisterInfo::isPhysicalRegister(Reg))
214         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
215           ClobberedRegUnits.set(*Units);
216
217       if (!MO->readsReg() || !TargetRegisterInfo::isVirtualRegister(Reg))
218         continue;
219       MachineInstr *DefMI = MRI->getVRegDef(Reg);
220       if (!DefMI || DefMI->getParent() != Head)
221         continue;
222       if (InsertAfter.insert(DefMI))
223         DEBUG(dbgs() << "BB#" << MBB->getNumber() << " depends on " << *DefMI);
224       if (DefMI->isTerminator()) {
225         DEBUG(dbgs() << "Can't insert instructions below terminator.\n");
226         return false;
227       }
228     }
229   }
230   return true;
231 }
232
233
234 /// Find an insertion point in Head for the speculated instructions. The
235 /// insertion point must be:
236 ///
237 /// 1. Before any terminators.
238 /// 2. After any instructions in InsertAfter.
239 /// 3. Not have any clobbered regunits live.
240 ///
241 /// This function sets InsertionPoint and returns true when successful, it
242 /// returns false if no valid insertion point could be found.
243 ///
244 bool SSAIfConv::findInsertionPoint() {
245   // Keep track of live regunits before the current position.
246   // Only track RegUnits that are also in ClobberedRegUnits.
247   LiveRegUnits.clear();
248   SmallVector<unsigned, 8> Reads;
249   MachineBasicBlock::iterator FirstTerm = Head->getFirstTerminator();
250   MachineBasicBlock::iterator I = Head->end();
251   MachineBasicBlock::iterator B = Head->begin();
252   while (I != B) {
253     --I;
254     // Some of the conditional code depends in I.
255     if (InsertAfter.count(I)) {
256       DEBUG(dbgs() << "Can't insert code after " << *I);
257       return false;
258     }
259
260     // Update live regunits.
261     for (MIOperands MO(I); MO.isValid(); ++MO) {
262       // We're ignoring regmask operands. That is conservatively correct.
263       if (!MO->isReg())
264         continue;
265       unsigned Reg = MO->getReg();
266       if (!TargetRegisterInfo::isPhysicalRegister(Reg))
267         continue;
268       // I clobbers Reg, so it isn't live before I.
269       if (MO->isDef())
270         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
271           LiveRegUnits.erase(*Units);
272       // Unless I reads Reg.
273       if (MO->readsReg())
274         Reads.push_back(Reg);
275     }
276     // Anything read by I is live before I.
277     while (!Reads.empty())
278       for (MCRegUnitIterator Units(Reads.pop_back_val(), TRI); Units.isValid();
279            ++Units)
280         if (ClobberedRegUnits.test(*Units))
281           LiveRegUnits.insert(*Units);
282
283     // We can't insert before a terminator.
284     if (I != FirstTerm && I->isTerminator())
285       continue;
286
287     // Some of the clobbered registers are live before I, not a valid insertion
288     // point.
289     if (!LiveRegUnits.empty()) {
290       DEBUG({
291         dbgs() << "Would clobber";
292         for (SparseSet<unsigned>::const_iterator
293              i = LiveRegUnits.begin(), e = LiveRegUnits.end(); i != e; ++i)
294           dbgs() << ' ' << PrintRegUnit(*i, TRI);
295         dbgs() << " live before " << *I;
296       });
297       continue;
298     }
299
300     // This is a valid insertion point.
301     InsertionPoint = I;
302     DEBUG(dbgs() << "Can insert before " << *I);
303     return true;
304   }
305   DEBUG(dbgs() << "No legal insertion point found.\n");
306   return false;
307 }
308
309
310
311 /// canConvertIf - analyze the sub-cfg rooted in MBB, and return true if it is
312 /// a potential candidate for if-conversion. Fill out the internal state.
313 ///
314 bool SSAIfConv::canConvertIf(MachineBasicBlock *MBB) {
315   Head = MBB;
316   TBB = FBB = Tail = 0;
317
318   if (Head->succ_size() != 2)
319     return false;
320   MachineBasicBlock *Succ0 = Head->succ_begin()[0];
321   MachineBasicBlock *Succ1 = Head->succ_begin()[1];
322
323   // Canonicalize so Succ0 has MBB as its single predecessor.
324   if (Succ0->pred_size() != 1)
325     std::swap(Succ0, Succ1);
326
327   if (Succ0->pred_size() != 1 || Succ0->succ_size() != 1)
328     return false;
329
330   // We could support additional Tail predecessors by updating phis instead of
331   // eliminating them. Let's see an example where it matters first.
332   Tail = Succ0->succ_begin()[0];
333   if (Tail->pred_size() != 2)
334     return false;
335
336   // This is not a triangle.
337   if (Tail != Succ1) {
338     // Check for a diamond. We won't deal with any critical edges.
339     if (Succ1->pred_size() != 1 || Succ1->succ_size() != 1 ||
340         Succ1->succ_begin()[0] != Tail)
341       return false;
342     DEBUG(dbgs() << "\nDiamond: BB#" << Head->getNumber()
343                  << " -> BB#" << Succ0->getNumber()
344                  << "/BB#" << Succ1->getNumber()
345                  << " -> BB#" << Tail->getNumber() << '\n');
346
347     // Live-in physregs are tricky to get right when speculating code.
348     if (!Tail->livein_empty()) {
349       DEBUG(dbgs() << "Tail has live-ins.\n");
350       return false;
351     }
352   } else {
353     DEBUG(dbgs() << "\nTriangle: BB#" << Head->getNumber()
354                  << " -> BB#" << Succ0->getNumber()
355                  << " -> BB#" << Tail->getNumber() << '\n');
356   }
357
358   // This is a triangle or a diamond.
359   // If Tail doesn't have any phis, there must be side effects.
360   if (Tail->empty() || !Tail->front().isPHI()) {
361     DEBUG(dbgs() << "No phis in tail.\n");
362     return false;
363   }
364
365   // The branch we're looking to eliminate must be analyzable.
366   Cond.clear();
367   if (TII->AnalyzeBranch(*Head, TBB, FBB, Cond)) {
368     DEBUG(dbgs() << "Branch not analyzable.\n");
369     return false;
370   }
371
372   // This is weird, probably some sort of degenerate CFG.
373   if (!TBB) {
374     DEBUG(dbgs() << "AnalyzeBranch didn't find conditional branch.\n");
375     return false;
376   }
377
378   // AnalyzeBranch doesn't set FBB on a fall-through branch.
379   // Make sure it is always set.
380   FBB = TBB == Succ0 ? Succ1 : Succ0;
381
382   // Any phis in the tail block must be convertible to selects.
383   PHIs.clear();
384   MachineBasicBlock *TPred = TBB == Tail ? Head : TBB;
385   MachineBasicBlock *FPred = FBB == Tail ? Head : FBB;
386   for (MachineBasicBlock::iterator I = Tail->begin(), E = Tail->end();
387        I != E && I->isPHI(); ++I) {
388     PHIs.push_back(&*I);
389     PHIInfo &PI = PHIs.back();
390     // Find PHI operands corresponding to TPred and FPred.
391     for (unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
392       if (PI.PHI->getOperand(i+1).getMBB() == TPred)
393         PI.TReg = PI.PHI->getOperand(i).getReg();
394       if (PI.PHI->getOperand(i+1).getMBB() == FPred)
395         PI.FReg = PI.PHI->getOperand(i).getReg();
396     }
397     assert(TargetRegisterInfo::isVirtualRegister(PI.TReg) && "Bad PHI");
398     assert(TargetRegisterInfo::isVirtualRegister(PI.FReg) && "Bad PHI");
399
400     // Get target information.
401     if (!TII->canInsertSelect(*Head, Cond, PI.TReg, PI.FReg,
402                               PI.CondCycles, PI.TCycles, PI.FCycles)) {
403       DEBUG(dbgs() << "Can't convert: " << *PI.PHI);
404       return false;
405     }
406   }
407
408   // Check that the conditional instructions can be speculated.
409   InsertAfter.clear();
410   ClobberedRegUnits.reset();
411   if (TBB != Tail && !canSpeculateInstrs(TBB))
412     return false;
413   if (FBB != Tail && !canSpeculateInstrs(FBB))
414     return false;
415
416   // Try to find a valid insertion point for the speculated instructions in the
417   // head basic block.
418   if (!findInsertionPoint())
419     return false;
420
421   return true;
422 }
423
424
425 static void eraseBlock(BlockSetVector &WorkList, MachineBasicBlock *MBB) {
426   WorkList.remove(MBB);
427   MBB->eraseFromParent();
428 }
429
430
431 /// convertIf - Execute the if conversion after canConvertIf has determined the
432 /// feasibility.
433 ///
434 /// Any basic blocks erased will also be removed from WorkList.
435 ///
436 void SSAIfConv::convertIf(BlockSetVector &WorkList) {
437   assert(Head && Tail && TBB && FBB && "Call canConvertIf first.");
438
439   // Move all instructions into Head, except for the terminators.
440   if (TBB != Tail)
441     Head->splice(InsertionPoint, TBB, TBB->begin(), TBB->getFirstTerminator());
442   if (FBB != Tail)
443     Head->splice(InsertionPoint, FBB, FBB->begin(), FBB->getFirstTerminator());
444
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   // Fix up the CFG, temporarily leave Head without any successors.
462   Head->removeSuccessor(TBB);
463   Head->removeSuccessor(FBB);
464   if (TBB != Tail)
465     TBB->removeSuccessor(Tail);
466   if (FBB != Tail)
467     FBB->removeSuccessor(Tail);
468
469   // Fix up Head's terminators.
470   // It should become a single branch or a fallthrough.
471   TII->RemoveBranch(*Head);
472
473   // Erase the now empty conditional blocks. It is likely that Head can fall
474   // through to Tail, and we can join the two blocks.
475   if (TBB != Tail)
476     eraseBlock(WorkList, TBB);
477   if (FBB != Tail)
478     eraseBlock(WorkList, FBB);
479
480   assert(Head->succ_empty() && "Additional head successors?");
481   if (Head->isLayoutSuccessor(Tail)) {
482     // Splice Tail onto the end of Head.
483     DEBUG(dbgs() << "Joining tail BB#" << Tail->getNumber()
484                  << " into head BB#" << Head->getNumber() << '\n');
485     Head->splice(Head->end(), Tail,
486                      Tail->begin(), Tail->end());
487     Head->transferSuccessorsAndUpdatePHIs(Tail);
488     eraseBlock(WorkList, Tail);
489
490   } else {
491     // We need a branch to Tail, let code placement work it out later.
492     DEBUG(dbgs() << "Converting to unconditional branch.\n");
493     SmallVector<MachineOperand, 0> EmptyCond;
494     TII->InsertBranch(*Head, Tail, 0, EmptyCond, HeadDL);
495     Head->addSuccessor(Tail);
496   }
497   DEBUG(dbgs() << *Head);
498 }
499
500
501 //===----------------------------------------------------------------------===//
502 //                           EarlyIfConverter Pass
503 //===----------------------------------------------------------------------===//
504
505 namespace {
506 class EarlyIfConverter : public MachineFunctionPass {
507   const TargetInstrInfo *TII;
508   const TargetRegisterInfo *TRI;
509   MachineRegisterInfo *MRI;
510   SSAIfConv IfConv;
511
512   // Worklist of head blocks to try for if-conversion.
513   BlockSetVector WorkList;
514
515 public:
516   static char ID;
517   EarlyIfConverter() : MachineFunctionPass(ID) {}
518   void getAnalysisUsage(AnalysisUsage &AU) const;
519   bool runOnMachineFunction(MachineFunction &MF);
520
521 private:
522   bool tryConvertIf(MachineBasicBlock*);
523 };
524 } // end anonymous namespace
525
526 char EarlyIfConverter::ID = 0;
527 char &llvm::EarlyIfConverterID = EarlyIfConverter::ID;
528
529 INITIALIZE_PASS_BEGIN(EarlyIfConverter,
530                       "early-ifcvt", "Early If Converter", false, false)
531 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
532 INITIALIZE_PASS_END(EarlyIfConverter,
533                       "early-ifcvt", "Early If Converter", false, false)
534
535 void EarlyIfConverter::getAnalysisUsage(AnalysisUsage &AU) const {
536   AU.addRequired<MachineBranchProbabilityInfo>();
537   MachineFunctionPass::getAnalysisUsage(AU);
538 }
539
540 /// Attempt repeated if-conversion on MBB, return true if successful.
541 /// Update WorkList with new opportunities.
542 ///
543 bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *MBB) {
544   if (!IfConv.canConvertIf(MBB))
545     return false;
546
547   // Repeatedly if-convert MBB, joining Head and Tail may expose more
548   // opportunities.
549   do IfConv.convertIf(WorkList);
550   while (IfConv.canConvertIf(MBB));
551
552   // It is possible that MBB is now itself a conditional block that can be
553   // if-converted.
554   if (MBB->pred_size() == 1 && MBB->succ_size() == 1)
555     WorkList.insert(MBB->pred_begin()[0]);
556   WorkList.remove(MBB);
557   return true;
558 }
559
560
561 bool EarlyIfConverter::runOnMachineFunction(MachineFunction &MF) {
562   DEBUG(dbgs() << "********** EARLY IF-CONVERSION **********\n"
563                << "********** Function: "
564                << ((Value*)MF.getFunction())->getName() << '\n');
565   TII = MF.getTarget().getInstrInfo();
566   TRI = MF.getTarget().getRegisterInfo();
567   MRI = &MF.getRegInfo();
568
569   bool Changed = false;
570   IfConv.runOnMachineFunction(MF);
571
572   for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
573        ++MFI)
574     if (tryConvertIf(MFI))
575       Changed = true;
576
577   DEBUG(dbgs() << "Revisiting " << WorkList.size() << " blocks.\n");
578   while (!WorkList.empty())
579     tryConvertIf(WorkList.pop_back_val());
580
581   MF.verify(this, "After early if-conversion");
582   return Changed;
583 }