1 //===-- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for safe point where the prologue and epilogue can be
12 // The safe point for the prologue (resp. epilogue) is called Save
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.
19 // For instance, the following points are safe:
20 // for (int i = 0; i < 10; ++i) {
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) {
31 // for (int i = 0; i < 10; ++i) {
35 // Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
37 // This pass also ensures that the safe points are 3) cheaper than the regular
38 // entry and exits blocks.
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.
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"
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"
72 #define DEBUG_TYPE "shrink-wrap"
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");
81 static cl::opt<cl::boolOrDefault>
82 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
83 cl::desc("enable the shrink-wrapping pass"));
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.
114 /// Current opcode for frame setup.
115 unsigned FrameSetupOpcode;
116 /// Current opcode for frame destroy.
117 unsigned FrameDestroyOpcode;
119 const MachineBasicBlock *Entry;
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;
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
131 void updateSaveRestorePoints(MachineBasicBlock &MBB);
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>();
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();
151 /// Check whether or not Save and Restore points are still interesting for
153 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
155 /// \brief Check if shrink wrapping is enabled for this target and function.
156 static bool isShrinkWrapEnabled(const MachineFunction &MF);
161 ShrinkWrap() : MachineFunctionPass(ID) {
162 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
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);
174 const char *getPassName() const override {
175 return "Shrink Wrapping analysis";
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;
182 } // End anonymous namespace.
184 char ShrinkWrap::ID = 0;
185 char &llvm::ShrinkWrapID = ShrinkWrap::ID;
187 INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", 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)
195 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI) const {
196 if (MI.getOpcode() == FrameSetupOpcode ||
197 MI.getOpcode() == FrameDestroyOpcode) {
198 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
201 for (const MachineOperand &MO : MI.operands()) {
204 unsigned PhysReg = MO.getReg();
207 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
208 "Unallocated register?!");
209 UseCSR = RCI.getLastCalleeSavedAlias(PhysReg);
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');
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);
235 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB) {
236 // Get rid of the easy cases first.
240 Save = MDT->findNearestCommonDominator(Save, &MBB);
243 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
250 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
252 // Make sure we would be able to insert the restore code before the
254 if (Restore == &MBB) {
255 for (const MachineInstr &Terminator : MBB.terminators()) {
256 if (!useOrDefCSROrFI(Terminator))
258 // One of the terminator needs to happen before the restore point.
259 if (MBB.succ_empty()) {
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);
271 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
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))) {
289 if (!SaveDominatesRestore) {
290 Save = MDT->findNearestCommonDominator(Save, Restore);
294 if (!RestorePostDominatesSave)
295 Restore = MPDT->findNearestCommonDominator(Restore, Save);
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);
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)
328 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
329 if (MF.empty() || !isShrinkWrapEnabled(MF))
332 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
336 for (MachineBasicBlock &MBB : MF) {
337 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
340 for (const MachineInstr &MI : MBB) {
341 if (!useOrDefCSROrFI(MI))
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");
352 // No need to look for other instructions, this basic block
353 // will already be part of the handled region.
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");
366 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
369 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
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');
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)))
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);
391 // Restore is expensive.
392 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
397 updateSaveRestorePoints(*NewBB);
398 } while (Save && Restore);
400 if (!ArePointsInteresting()) {
401 ++NumCandidatesDropped;
405 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
406 << ' ' << Save->getName() << "\nRestore: "
407 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
409 MachineFrameInfo *MFI = MF.getFrameInfo();
410 MFI->setSavePoint(Save);
411 MFI->setRestorePoint(Restore);
416 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
417 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
419 switch (EnableShrinkWrapOpt) {
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.
430 llvm_unreachable("Invalid shrink-wrapping state");