Rework of the new interface for shrink wrapping
[oota-llvm.git] / lib / CodeGen / ShrinkWrap.cpp
1 //===-- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ---===//
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 looks for safe point where the prologue and epilogue can be
11 // inserted.
12 // The safe point for the prologue (resp. epilogue) is called Save
13 // (resp. Restore).
14 // A point is safe for prologue (resp. epilogue) if and only if
15 // it 1) dominates (resp. post-dominates) all the frame related operations and
16 // between 2) two executions of the Save (resp. Restore) point there is an
17 // execution of the Restore (resp. Save) point.
18 //
19 // For instance, the following points are safe:
20 // for (int i = 0; i < 10; ++i) {
21 //   Save
22 //   ...
23 //   Restore
24 // }
25 // Indeed, the execution looks like Save -> Restore -> Save -> Restore ...
26 // And the following points are not:
27 // for (int i = 0; i < 10; ++i) {
28 //   Save
29 //   ...
30 // }
31 // for (int i = 0; i < 10; ++i) {
32 //   ...
33 //   Restore
34 // }
35 // Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
36 //
37 // This pass also ensures that the safe points are 3) cheaper than the regular
38 // entry and exits blocks.
39 //
40 // Property #1 is ensured via the use of MachineDominatorTree and
41 // MachinePostDominatorTree.
42 // Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both
43 // points must be in the same loop.
44 // Property #3 is ensured via the MachineBlockFrequencyInfo.
45 //
46 // If this pass found points matching all this properties, then
47 // MachineFrameInfo is updated this that information.
48 //===----------------------------------------------------------------------===//
49 #include "llvm/ADT/Statistic.h"
50 // To check for profitability.
51 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
52 // For property #1 for Save.
53 #include "llvm/CodeGen/MachineDominators.h"
54 #include "llvm/CodeGen/MachineFunctionPass.h"
55 // To record the result of the analysis.
56 #include "llvm/CodeGen/MachineFrameInfo.h"
57 // For property #2.
58 #include "llvm/CodeGen/MachineLoopInfo.h"
59 // For property #1 for Restore.
60 #include "llvm/CodeGen/MachinePostDominators.h"
61 #include "llvm/CodeGen/Passes.h"
62 // To know about callee-saved.
63 #include "llvm/CodeGen/RegisterClassInfo.h"
64 #include "llvm/Support/Debug.h"
65 // To query the target about frame lowering.
66 #include "llvm/Target/TargetFrameLowering.h"
67 // To know about frame setup operation.
68 #include "llvm/Target/TargetInstrInfo.h"
69 // To access TargetInstrInfo.
70 #include "llvm/Target/TargetSubtargetInfo.h"
71
72 #define DEBUG_TYPE "shrink-wrap"
73
74 using namespace llvm;
75
76 STATISTIC(NumFunc, "Number of functions");
77 STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
78 STATISTIC(NumCandidatesDropped,
79           "Number of shrink-wrapping candidates dropped because of frequency");
80
81 static cl::opt<cl::boolOrDefault>
82     EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
83                         cl::desc("enable the shrink-wrapping pass"));
84
85 namespace {
86 /// \brief Class to determine where the safe point to insert the
87 /// prologue and epilogue are.
88 /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
89 /// shrink-wrapping term for prologue/epilogue placement, this pass
90 /// does not rely on expensive data-flow analysis. Instead we use the
91 /// dominance properties and loop information to decide which point
92 /// are safe for such insertion.
93 class ShrinkWrap : public MachineFunctionPass {
94   /// Hold callee-saved information.
95   RegisterClassInfo RCI;
96   MachineDominatorTree *MDT;
97   MachinePostDominatorTree *MPDT;
98   /// Current safe point found for the prologue.
99   /// The prologue will be inserted before the first instruction
100   /// in this basic block.
101   MachineBasicBlock *Save;
102   /// Current safe point found for the epilogue.
103   /// The epilogue will be inserted before the first terminator instruction
104   /// in this basic block.
105   MachineBasicBlock *Restore;
106   /// Hold the information of the basic block frequency.
107   /// Use to check the profitability of the new points.
108   MachineBlockFrequencyInfo *MBFI;
109   /// Hold the loop information. Used to determine if Save and Restore
110   /// are in the same loop.
111   MachineLoopInfo *MLI;
112   /// Frequency of the Entry block.
113   uint64_t EntryFreq;
114   /// Current opcode for frame setup.
115   unsigned FrameSetupOpcode;
116   /// Current opcode for frame destroy.
117   unsigned FrameDestroyOpcode;
118   /// Entry block.
119   const MachineBasicBlock *Entry;
120
121   /// \brief Check if \p MI uses or defines a callee-saved register or
122   /// a frame index. If this is the case, this means \p MI must happen
123   /// after Save and before Restore.
124   bool useOrDefCSROrFI(const MachineInstr &MI) const;
125
126   /// \brief Update the Save and Restore points such that \p MBB is in
127   /// the region that is dominated by Save and post-dominated by Restore
128   /// and Save and Restore still match the safe point definition.
129   /// Such point may not exist and Save and/or Restore may be null after
130   /// this call.
131   void updateSaveRestorePoints(MachineBasicBlock &MBB);
132
133   /// \brief Initialize the pass for \p MF.
134   void init(MachineFunction &MF) {
135     RCI.runOnMachineFunction(MF);
136     MDT = &getAnalysis<MachineDominatorTree>();
137     MPDT = &getAnalysis<MachinePostDominatorTree>();
138     Save = nullptr;
139     Restore = nullptr;
140     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
141     MLI = &getAnalysis<MachineLoopInfo>();
142     EntryFreq = MBFI->getEntryFreq();
143     const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
144     FrameSetupOpcode = TII.getCallFrameSetupOpcode();
145     FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
146     Entry = &MF.front();
147
148     ++NumFunc;
149   }
150
151   /// Check whether or not Save and Restore points are still interesting for
152   /// shrink-wrapping.
153   bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
154
155   /// \brief Check if shrink wrapping is enabled for this target and function.
156   static bool isShrinkWrapEnabled(const MachineFunction &MF);
157   
158 public:
159   static char ID;
160
161   ShrinkWrap() : MachineFunctionPass(ID) {
162     initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
163   }
164
165   void getAnalysisUsage(AnalysisUsage &AU) const override {
166     AU.setPreservesAll();
167     AU.addRequired<MachineBlockFrequencyInfo>();
168     AU.addRequired<MachineDominatorTree>();
169     AU.addRequired<MachinePostDominatorTree>();
170     AU.addRequired<MachineLoopInfo>();
171     MachineFunctionPass::getAnalysisUsage(AU);
172   }
173
174   const char *getPassName() const override {
175     return "Shrink Wrapping analysis";
176   }
177
178   /// \brief Perform the shrink-wrapping analysis and update
179   /// the MachineFrameInfo attached to \p MF with the results.
180   bool runOnMachineFunction(MachineFunction &MF) override;
181 };
182 } // End anonymous namespace.
183
184 char ShrinkWrap::ID = 0;
185 char &llvm::ShrinkWrapID = ShrinkWrap::ID;
186
187 INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false,
188                       false)
189 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
190 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
191 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
192 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
193 INITIALIZE_PASS_END(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, false)
194
195 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI) const {
196   if (MI.getOpcode() == FrameSetupOpcode ||
197       MI.getOpcode() == FrameDestroyOpcode) {
198     DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
199     return true;
200   }
201   for (const MachineOperand &MO : MI.operands()) {
202     bool UseCSR = false;
203     if (MO.isReg()) {
204       unsigned PhysReg = MO.getReg();
205       if (!PhysReg)
206         continue;
207       assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
208              "Unallocated register?!");
209       UseCSR = RCI.getLastCalleeSavedAlias(PhysReg);
210     }
211     // TODO: Handle regmask more accurately.
212     // For now, be conservative about them.
213     if (UseCSR || MO.isFI() || MO.isRegMask()) {
214       DEBUG(dbgs() << "Use or define CSR(" << UseCSR << ") or FI(" << MO.isFI()
215                    << "): " << MI << '\n');
216       return true;
217     }
218   }
219   return false;
220 }
221
222 /// \brief Helper function to find the immediate (post) dominator.
223 template <typename ListOfBBs, typename DominanceAnalysis>
224 MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
225                             DominanceAnalysis &Dom) {
226   MachineBasicBlock *IDom = &Block;
227   for (MachineBasicBlock *BB : BBs) {
228     IDom = Dom.findNearestCommonDominator(IDom, BB);
229     if (!IDom)
230       break;
231   }
232   return IDom;
233 }
234
235 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB) {
236   // Get rid of the easy cases first.
237   if (!Save)
238     Save = &MBB;
239   else
240     Save = MDT->findNearestCommonDominator(Save, &MBB);
241
242   if (!Save) {
243     DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
244     return;
245   }
246
247   if (!Restore)
248     Restore = &MBB;
249   else
250     Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
251
252   // Make sure we would be able to insert the restore code before the
253   // terminator.
254   if (Restore == &MBB) {
255     for (const MachineInstr &Terminator : MBB.terminators()) {
256       if (!useOrDefCSROrFI(Terminator))
257         continue;
258       // One of the terminator needs to happen before the restore point.
259       if (MBB.succ_empty()) {
260         Restore = nullptr;
261         break;
262       }
263       // Look for a restore point that post-dominates all the successors.
264       // The immediate post-dominator is what we are looking for.
265       Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
266       break;
267     }
268   }
269
270   if (!Restore) {
271     DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
272     return;
273   }
274
275   // Make sure Save and Restore are suitable for shrink-wrapping:
276   // 1. all path from Save needs to lead to Restore before exiting.
277   // 2. all path to Restore needs to go through Save from Entry.
278   // We achieve that by making sure that:
279   // A. Save dominates Restore.
280   // B. Restore post-dominates Save.
281   // C. Save and Restore are in the same loop.
282   bool SaveDominatesRestore = false;
283   bool RestorePostDominatesSave = false;
284   while (Save && Restore &&
285          (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
286           !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
287           MLI->getLoopFor(Save) != MLI->getLoopFor(Restore))) {
288     // Fix (A).
289     if (!SaveDominatesRestore) {
290       Save = MDT->findNearestCommonDominator(Save, Restore);
291       continue;
292     }
293     // Fix (B).
294     if (!RestorePostDominatesSave)
295       Restore = MPDT->findNearestCommonDominator(Restore, Save);
296
297     // Fix (C).
298     if (Save && Restore && Save != Restore &&
299         MLI->getLoopFor(Save) != MLI->getLoopFor(Restore)) {
300       if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
301         // Push Save outside of this loop if immediate dominator is different
302         // from save block. If immediate dominator is not different, bail out. 
303         MachineBasicBlock *IDom = FindIDom<>(*Save, Save->predecessors(), *MDT);
304         if (IDom != Save)
305           Save = IDom;
306         else {
307           Save = nullptr;
308           break;
309         }
310       }
311       else {
312         // Push Restore outside of this loop if immediate post-dominator is
313         // different from restore block. If immediate post-dominator is not
314         // different, bail out. 
315         MachineBasicBlock *IPdom =
316           FindIDom<>(*Restore, Restore->successors(), *MPDT);
317         if (IPdom != Restore)
318           Restore = IPdom; 
319         else {
320           Restore = nullptr;
321           break;
322         }
323       }      
324     }
325   }
326 }
327
328 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
329   if (MF.empty() || !isShrinkWrapEnabled(MF))
330     return false;
331
332   DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
333
334   init(MF);
335
336   for (MachineBasicBlock &MBB : MF) {
337     DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
338                  << '\n');
339
340     for (const MachineInstr &MI : MBB) {
341       if (!useOrDefCSROrFI(MI))
342         continue;
343       // Save (resp. restore) point must dominate (resp. post dominate)
344       // MI. Look for the proper basic block for those.
345       updateSaveRestorePoints(MBB);
346       // If we are at a point where we cannot improve the placement of
347       // save/restore instructions, just give up.
348       if (!ArePointsInteresting()) {
349         DEBUG(dbgs() << "No Shrink wrap candidate found\n");
350         return false;
351       }
352       // No need to look for other instructions, this basic block
353       // will already be part of the handled region.
354       break;
355     }
356   }
357   if (!ArePointsInteresting()) {
358     // If the points are not interesting at this point, then they must be null
359     // because it means we did not encounter any frame/CSR related code.
360     // Otherwise, we would have returned from the previous loop.
361     assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
362     DEBUG(dbgs() << "Nothing to shrink-wrap\n");
363     return false;
364   }
365
366   DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
367                << '\n');
368
369   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
370   do {
371     DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
372                  << Save->getNumber() << ' ' << Save->getName() << ' '
373                  << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
374                  << Restore->getNumber() << ' ' << Restore->getName() << ' '
375                  << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
376
377     bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
378     if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
379          EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
380         ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
381          TFI->canUseAsEpilogue(*Restore)))
382       break;
383     DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
384     MachineBasicBlock *NewBB;
385     if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
386       Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
387       if (!Save)
388         break;
389       NewBB = Save;
390     } else {
391       // Restore is expensive.
392       Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
393       if (!Restore)
394         break;
395       NewBB = Restore;
396     }
397     updateSaveRestorePoints(*NewBB);
398   } while (Save && Restore);
399
400   if (!ArePointsInteresting()) {
401     ++NumCandidatesDropped;
402     return false;
403   }
404
405   DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
406                << ' ' << Save->getName() << "\nRestore: "
407                << Restore->getNumber() << ' ' << Restore->getName() << '\n');
408
409   MachineFrameInfo *MFI = MF.getFrameInfo();
410   MFI->setSavePoint(Save);
411   MFI->setRestorePoint(Restore);
412   ++NumCandidates;
413   return false;
414 }
415
416 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
417   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
418
419   switch (EnableShrinkWrapOpt) {
420   case cl::BOU_UNSET:
421     return TFI->enableShrinkWrapping(MF);
422   // If EnableShrinkWrap is set, it takes precedence on whatever the
423   // target sets. The rational is that we assume we want to test
424   // something related to shrink-wrapping.
425   case cl::BOU_TRUE:
426     return true;
427   case cl::BOU_FALSE:
428     return false;
429   }
430   llvm_unreachable("Invalid shrink-wrapping state");
431 }