Begin adding static dependence information to passes, which will allow us to
[oota-llvm.git] / lib / CodeGen / MachineSink.cpp
1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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 // This pass moves instructions into successor blocks when possible, so that
11 // they aren't executed on paths where their results aren't needed.
12 //
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "machine-sink"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 static cl::opt<bool> 
36 SplitEdges("machine-sink-split",
37            cl::desc("Split critical edges during machine sinking"),
38            cl::init(true), cl::Hidden);
39
40 STATISTIC(NumSunk,      "Number of machine instructions sunk");
41 STATISTIC(NumSplit,     "Number of critical edges split");
42 STATISTIC(NumCoalesces, "Number of copies coalesced");
43
44 namespace {
45   class MachineSinking : public MachineFunctionPass {
46     const TargetInstrInfo *TII;
47     const TargetRegisterInfo *TRI;
48     MachineRegisterInfo  *MRI;  // Machine register information
49     MachineDominatorTree *DT;   // Machine dominator tree
50     MachineLoopInfo *LI;
51     AliasAnalysis *AA;
52     BitVector AllocatableSet;   // Which physregs are allocatable?
53
54     // Remember which edges have been considered for breaking.
55     SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
56     CEBCandidates;
57
58   public:
59     static char ID; // Pass identification
60     MachineSinking() : MachineFunctionPass(ID) {}
61
62     virtual bool runOnMachineFunction(MachineFunction &MF);
63
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       MachineFunctionPass::getAnalysisUsage(AU);
67       AU.addRequired<AliasAnalysis>();
68       AU.addRequired<MachineDominatorTree>();
69       AU.addRequired<MachineLoopInfo>();
70       AU.addPreserved<MachineDominatorTree>();
71       AU.addPreserved<MachineLoopInfo>();
72     }
73
74     virtual void releaseMemory() {
75       CEBCandidates.clear();
76     }
77
78   private:
79     bool ProcessBlock(MachineBasicBlock &MBB);
80     bool isWorthBreakingCriticalEdge(MachineInstr *MI,
81                                      MachineBasicBlock *From,
82                                      MachineBasicBlock *To);
83     MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
84                                          MachineBasicBlock *From,
85                                          MachineBasicBlock *To,
86                                          bool BreakPHIEdge);
87     bool SinkInstruction(MachineInstr *MI, bool &SawStore);
88     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
89                                  MachineBasicBlock *DefMBB,
90                                  bool &BreakPHIEdge, bool &LocalUse) const;
91     bool PerformTrivialForwardCoalescing(MachineInstr *MI,
92                                          MachineBasicBlock *MBB);
93   };
94 } // end anonymous namespace
95
96 char MachineSinking::ID = 0;
97 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
98                 "Machine code sinking", false, false)
99 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
100 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
101 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
102 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
103                 "Machine code sinking", false, false)
104
105 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
106
107 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
108                                                      MachineBasicBlock *MBB) {
109   if (!MI->isCopy())
110     return false;
111
112   unsigned SrcReg = MI->getOperand(1).getReg();
113   unsigned DstReg = MI->getOperand(0).getReg();
114   if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
115       !TargetRegisterInfo::isVirtualRegister(DstReg) ||
116       !MRI->hasOneNonDBGUse(SrcReg))
117     return false;
118
119   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
120   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
121   if (SRC != DRC)
122     return false;
123
124   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
125   if (DefMI->isCopyLike())
126     return false;
127   DEBUG(dbgs() << "Coalescing: " << *DefMI);
128   DEBUG(dbgs() << "*** to: " << *MI);
129   MRI->replaceRegWith(DstReg, SrcReg);
130   MI->eraseFromParent();
131   ++NumCoalesces;
132   return true;
133 }
134
135 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
136 /// occur in blocks dominated by the specified block. If any use is in the
137 /// definition block, then return false since it is never legal to move def
138 /// after uses.
139 bool
140 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
141                                         MachineBasicBlock *MBB,
142                                         MachineBasicBlock *DefMBB,
143                                         bool &BreakPHIEdge,
144                                         bool &LocalUse) const {
145   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
146          "Only makes sense for vregs");
147
148   if (MRI->use_nodbg_empty(Reg))
149     return true;
150
151   // Ignoring debug uses is necessary so debug info doesn't affect the code.
152   // This may leave a referencing dbg_value in the original block, before
153   // the definition of the vreg.  Dwarf generator handles this although the
154   // user might not get the right info at runtime.
155
156   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
157   // into and they are all PHI nodes. In this case, machine-sink must break
158   // the critical edge first. e.g.
159   //
160   // BB#1: derived from LLVM BB %bb4.preheader
161   //   Predecessors according to CFG: BB#0
162   //     ...
163   //     %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
164   //     ...
165   //     JE_4 <BB#37>, %EFLAGS<imp-use>
166   //   Successors according to CFG: BB#37 BB#2
167   //
168   // BB#2: derived from LLVM BB %bb.nph
169   //   Predecessors according to CFG: BB#0 BB#1
170   //     %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
171   BreakPHIEdge = true;
172   for (MachineRegisterInfo::use_nodbg_iterator
173          I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
174        I != E; ++I) {
175     MachineInstr *UseInst = &*I;
176     MachineBasicBlock *UseBlock = UseInst->getParent();
177     if (!(UseBlock == MBB && UseInst->isPHI() &&
178           UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
179       BreakPHIEdge = false;
180       break;
181     }
182   }
183   if (BreakPHIEdge)
184     return true;
185
186   for (MachineRegisterInfo::use_nodbg_iterator
187          I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
188        I != E; ++I) {
189     // Determine the block of the use.
190     MachineInstr *UseInst = &*I;
191     MachineBasicBlock *UseBlock = UseInst->getParent();
192     if (UseInst->isPHI()) {
193       // PHI nodes use the operand in the predecessor block, not the block with
194       // the PHI.
195       UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
196     } else if (UseBlock == DefMBB) {
197       LocalUse = true;
198       return false;
199     }
200
201     // Check that it dominates.
202     if (!DT->dominates(MBB, UseBlock))
203       return false;
204   }
205
206   return true;
207 }
208
209 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
210   DEBUG(dbgs() << "******** Machine Sinking ********\n");
211
212   const TargetMachine &TM = MF.getTarget();
213   TII = TM.getInstrInfo();
214   TRI = TM.getRegisterInfo();
215   MRI = &MF.getRegInfo();
216   DT = &getAnalysis<MachineDominatorTree>();
217   LI = &getAnalysis<MachineLoopInfo>();
218   AA = &getAnalysis<AliasAnalysis>();
219   AllocatableSet = TRI->getAllocatableSet(MF);
220
221   bool EverMadeChange = false;
222
223   while (1) {
224     bool MadeChange = false;
225
226     // Process all basic blocks.
227     CEBCandidates.clear();
228     for (MachineFunction::iterator I = MF.begin(), E = MF.end();
229          I != E; ++I)
230       MadeChange |= ProcessBlock(*I);
231
232     // If this iteration over the code changed anything, keep iterating.
233     if (!MadeChange) break;
234     EverMadeChange = true;
235   }
236   return EverMadeChange;
237 }
238
239 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
240   // Can't sink anything out of a block that has less than two successors.
241   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
242
243   // Don't bother sinking code out of unreachable blocks. In addition to being
244   // unprofitable, it can also lead to infinite looping, because in an
245   // unreachable loop there may be nowhere to stop.
246   if (!DT->isReachableFromEntry(&MBB)) return false;
247
248   bool MadeChange = false;
249
250   // Walk the basic block bottom-up.  Remember if we saw a store.
251   MachineBasicBlock::iterator I = MBB.end();
252   --I;
253   bool ProcessedBegin, SawStore = false;
254   do {
255     MachineInstr *MI = I;  // The instruction to sink.
256
257     // Predecrement I (if it's not begin) so that it isn't invalidated by
258     // sinking.
259     ProcessedBegin = I == MBB.begin();
260     if (!ProcessedBegin)
261       --I;
262
263     if (MI->isDebugValue())
264       continue;
265
266     if (PerformTrivialForwardCoalescing(MI, &MBB))
267       continue;
268
269     if (SinkInstruction(MI, SawStore))
270       ++NumSunk, MadeChange = true;
271
272     // If we just processed the first instruction in the block, we're done.
273   } while (!ProcessedBegin);
274
275   return MadeChange;
276 }
277
278 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
279                                                  MachineBasicBlock *From,
280                                                  MachineBasicBlock *To) {
281   // FIXME: Need much better heuristics.
282
283   // If the pass has already considered breaking this edge (during this pass
284   // through the function), then let's go ahead and break it. This means
285   // sinking multiple "cheap" instructions into the same block.
286   if (!CEBCandidates.insert(std::make_pair(From, To)))
287     return true;
288
289   if (!MI->isCopy() && !MI->getDesc().isAsCheapAsAMove())
290     return true;
291
292   // MI is cheap, we probably don't want to break the critical edge for it.
293   // However, if this would allow some definitions of its source operands
294   // to be sunk then it's probably worth it.
295   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
296     const MachineOperand &MO = MI->getOperand(i);
297     if (!MO.isReg()) continue;
298     unsigned Reg = MO.getReg();
299     if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
300       continue;
301     if (MRI->hasOneNonDBGUse(Reg))
302       return true;
303   }
304
305   return false;
306 }
307
308 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
309                                                      MachineBasicBlock *FromBB,
310                                                      MachineBasicBlock *ToBB,
311                                                      bool BreakPHIEdge) {
312   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
313     return 0;
314
315   // Avoid breaking back edge. From == To means backedge for single BB loop.
316   if (!SplitEdges || FromBB == ToBB)
317     return 0;
318
319   // Check for backedges of more "complex" loops.
320   if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
321       LI->isLoopHeader(ToBB))
322     return 0;
323
324   // It's not always legal to break critical edges and sink the computation
325   // to the edge.
326   //
327   // BB#1:
328   // v1024
329   // Beq BB#3
330   // <fallthrough>
331   // BB#2:
332   // ... no uses of v1024
333   // <fallthrough>
334   // BB#3:
335   // ...
336   //       = v1024
337   //
338   // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
339   //
340   // BB#1:
341   // ...
342   // Bne BB#2
343   // BB#4:
344   // v1024 =
345   // B BB#3
346   // BB#2:
347   // ... no uses of v1024
348   // <fallthrough>
349   // BB#3:
350   // ...
351   //       = v1024
352   //
353   // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
354   // flow. We need to ensure the new basic block where the computation is
355   // sunk to dominates all the uses.
356   // It's only legal to break critical edge and sink the computation to the
357   // new block if all the predecessors of "To", except for "From", are
358   // not dominated by "From". Given SSA property, this means these
359   // predecessors are dominated by "To".
360   //
361   // There is no need to do this check if all the uses are PHI nodes. PHI
362   // sources are only defined on the specific predecessor edges.
363   if (!BreakPHIEdge) {
364     for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
365            E = ToBB->pred_end(); PI != E; ++PI) {
366       if (*PI == FromBB)
367         continue;
368       if (!DT->dominates(ToBB, *PI))
369         return 0;
370     }
371   }
372
373   return FromBB->SplitCriticalEdge(ToBB, this);
374 }
375
376 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
377   return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
378 }
379
380 /// SinkInstruction - Determine whether it is safe to sink the specified machine
381 /// instruction out of its current block into a successor.
382 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
383   // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
384   // be close to the source to make it easier to coalesce.
385   if (AvoidsSinking(MI, MRI))
386     return false;
387
388   // Check if it's safe to move the instruction.
389   if (!MI->isSafeToMove(TII, AA, SawStore))
390     return false;
391
392   // FIXME: This should include support for sinking instructions within the
393   // block they are currently in to shorten the live ranges.  We often get
394   // instructions sunk into the top of a large block, but it would be better to
395   // also sink them down before their first use in the block.  This xform has to
396   // be careful not to *increase* register pressure though, e.g. sinking
397   // "x = y + z" down if it kills y and z would increase the live ranges of y
398   // and z and only shrink the live range of x.
399
400   // Loop over all the operands of the specified instruction.  If there is
401   // anything we can't handle, bail out.
402   MachineBasicBlock *ParentBlock = MI->getParent();
403
404   // SuccToSinkTo - This is the successor to sink this instruction to, once we
405   // decide.
406   MachineBasicBlock *SuccToSinkTo = 0;
407
408   bool BreakPHIEdge = false;
409   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
410     const MachineOperand &MO = MI->getOperand(i);
411     if (!MO.isReg()) continue;  // Ignore non-register operands.
412
413     unsigned Reg = MO.getReg();
414     if (Reg == 0) continue;
415
416     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
417       if (MO.isUse()) {
418         // If the physreg has no defs anywhere, it's just an ambient register
419         // and we can freely move its uses. Alternatively, if it's allocatable,
420         // it could get allocated to something with a def during allocation.
421         if (!MRI->def_empty(Reg))
422           return false;
423
424         if (AllocatableSet.test(Reg))
425           return false;
426
427         // Check for a def among the register's aliases too.
428         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
429           unsigned AliasReg = *Alias;
430           if (!MRI->def_empty(AliasReg))
431             return false;
432
433           if (AllocatableSet.test(AliasReg))
434             return false;
435         }
436       } else if (!MO.isDead()) {
437         // A def that isn't dead. We can't move it.
438         return false;
439       }
440     } else {
441       // Virtual register uses are always safe to sink.
442       if (MO.isUse()) continue;
443
444       // If it's not safe to move defs of the register class, then abort.
445       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
446         return false;
447
448       // FIXME: This picks a successor to sink into based on having one
449       // successor that dominates all the uses.  However, there are cases where
450       // sinking can happen but where the sink point isn't a successor.  For
451       // example:
452       //
453       //   x = computation
454       //   if () {} else {}
455       //   use x
456       //
457       // the instruction could be sunk over the whole diamond for the
458       // if/then/else (or loop, etc), allowing it to be sunk into other blocks
459       // after that.
460
461       // Virtual register defs can only be sunk if all their uses are in blocks
462       // dominated by one of the successors.
463       if (SuccToSinkTo) {
464         // If a previous operand picked a block to sink to, then this operand
465         // must be sinkable to the same block.
466         bool LocalUse = false;
467         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
468                                      BreakPHIEdge, LocalUse))
469           return false;
470
471         continue;
472       }
473
474       // Otherwise, we should look at all the successors and decide which one
475       // we should sink to.
476       for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
477            E = ParentBlock->succ_end(); SI != E; ++SI) {
478         bool LocalUse = false;
479         if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock,
480                                     BreakPHIEdge, LocalUse)) {
481           SuccToSinkTo = *SI;
482           break;
483         }
484         if (LocalUse)
485           // Def is used locally, it's never safe to move this def.
486           return false;
487       }
488
489       // If we couldn't find a block to sink to, ignore this instruction.
490       if (SuccToSinkTo == 0)
491         return false;
492     }
493   }
494
495   // If there are no outputs, it must have side-effects.
496   if (SuccToSinkTo == 0)
497     return false;
498
499   // It's not safe to sink instructions to EH landing pad. Control flow into
500   // landing pad is implicitly defined.
501   if (SuccToSinkTo->isLandingPad())
502     return false;
503
504   // It is not possible to sink an instruction into its own block.  This can
505   // happen with loops.
506   if (MI->getParent() == SuccToSinkTo)
507     return false;
508
509   // If the instruction to move defines a dead physical register which is live
510   // when leaving the basic block, don't move it because it could turn into a
511   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
512   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
513     const MachineOperand &MO = MI->getOperand(I);
514     if (!MO.isReg()) continue;
515     unsigned Reg = MO.getReg();
516     if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
517     if (SuccToSinkTo->isLiveIn(Reg))
518       return false;
519   }
520
521   DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
522
523   // If the block has multiple predecessors, this would introduce computation on
524   // a path that it doesn't already exist.  We could split the critical edge,
525   // but for now we just punt.
526   if (SuccToSinkTo->pred_size() > 1) {
527     // We cannot sink a load across a critical edge - there may be stores in
528     // other code paths.
529     bool TryBreak = false;
530     bool store = true;
531     if (!MI->isSafeToMove(TII, AA, store)) {
532       DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
533       TryBreak = true;
534     }
535
536     // We don't want to sink across a critical edge if we don't dominate the
537     // successor. We could be introducing calculations to new code paths.
538     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
539       DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
540       TryBreak = true;
541     }
542
543     // Don't sink instructions into a loop.
544     if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
545       DEBUG(dbgs() << " *** NOTE: Loop header found\n");
546       TryBreak = true;
547     }
548
549     // Otherwise we are OK with sinking along a critical edge.
550     if (!TryBreak)
551       DEBUG(dbgs() << "Sinking along critical edge.\n");
552     else {
553       MachineBasicBlock *NewSucc =
554         SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
555       if (!NewSucc) {
556         DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
557                         "break critical edge\n");
558         return false;
559       } else {
560         DEBUG(dbgs() << " *** Splitting critical edge:"
561               " BB#" << ParentBlock->getNumber()
562               << " -- BB#" << NewSucc->getNumber()
563               << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
564         SuccToSinkTo = NewSucc;
565         ++NumSplit;
566         BreakPHIEdge = false;
567       }
568     }
569   }
570
571   if (BreakPHIEdge) {
572     // BreakPHIEdge is true if all the uses are in the successor MBB being
573     // sunken into and they are all PHI nodes. In this case, machine-sink must
574     // break the critical edge first.
575     MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
576                                                    SuccToSinkTo, BreakPHIEdge);
577     if (!NewSucc) {
578       DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
579             "break critical edge\n");
580       return false;
581     }
582
583     DEBUG(dbgs() << " *** Splitting critical edge:"
584           " BB#" << ParentBlock->getNumber()
585           << " -- BB#" << NewSucc->getNumber()
586           << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
587     SuccToSinkTo = NewSucc;
588     ++NumSplit;
589   }
590
591   // Determine where to insert into. Skip phi nodes.
592   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
593   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
594     ++InsertPos;
595
596   // Move the instruction.
597   SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
598                        ++MachineBasicBlock::iterator(MI));
599
600   // Conservatively, clear any kill flags, since it's possible that they are no
601   // longer correct.
602   MI->clearKillInfo();
603
604   return true;
605 }