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 these properties, then
47 // MachineFrameInfo is updated this that information.
48 //===----------------------------------------------------------------------===//
49 #include "llvm/ADT/BitVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/Statistic.h"
52 // To check for profitability.
53 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
54 // For property #1 for Save.
55 #include "llvm/CodeGen/MachineDominators.h"
56 #include "llvm/CodeGen/MachineFunctionPass.h"
57 // To record the result of the analysis.
58 #include "llvm/CodeGen/MachineFrameInfo.h"
60 #include "llvm/CodeGen/MachineLoopInfo.h"
61 // For property #1 for Restore.
62 #include "llvm/CodeGen/MachinePostDominators.h"
63 #include "llvm/CodeGen/Passes.h"
64 // To know about callee-saved.
65 #include "llvm/CodeGen/RegisterClassInfo.h"
66 #include "llvm/Support/Debug.h"
67 // To query the target about frame lowering.
68 #include "llvm/Target/TargetFrameLowering.h"
69 // To know about frame setup operation.
70 #include "llvm/Target/TargetInstrInfo.h"
71 // To access TargetInstrInfo.
72 #include "llvm/Target/TargetSubtargetInfo.h"
74 #define DEBUG_TYPE "shrink-wrap"
78 STATISTIC(NumFunc, "Number of functions");
79 STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
80 STATISTIC(NumCandidatesDropped,
81 "Number of shrink-wrapping candidates dropped because of frequency");
83 static cl::opt<cl::boolOrDefault>
84 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
85 cl::desc("enable the shrink-wrapping pass"));
88 /// \brief Class to determine where the safe point to insert the
89 /// prologue and epilogue are.
90 /// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
91 /// shrink-wrapping term for prologue/epilogue placement, this pass
92 /// does not rely on expensive data-flow analysis. Instead we use the
93 /// dominance properties and loop information to decide which point
94 /// are safe for such insertion.
95 class ShrinkWrap : public MachineFunctionPass {
96 /// Hold callee-saved information.
97 RegisterClassInfo RCI;
98 MachineDominatorTree *MDT;
99 MachinePostDominatorTree *MPDT;
100 /// Current safe point found for the prologue.
101 /// The prologue will be inserted before the first instruction
102 /// in this basic block.
103 MachineBasicBlock *Save;
104 /// Current safe point found for the epilogue.
105 /// The epilogue will be inserted before the first terminator instruction
106 /// in this basic block.
107 MachineBasicBlock *Restore;
108 /// Hold the information of the basic block frequency.
109 /// Use to check the profitability of the new points.
110 MachineBlockFrequencyInfo *MBFI;
111 /// Hold the loop information. Used to determine if Save and Restore
112 /// are in the same loop.
113 MachineLoopInfo *MLI;
114 /// Frequency of the Entry block.
116 /// Current opcode for frame setup.
117 unsigned FrameSetupOpcode;
118 /// Current opcode for frame destroy.
119 unsigned FrameDestroyOpcode;
121 const MachineBasicBlock *Entry;
122 typedef SmallSetVector<unsigned, 16> SetOfRegs;
123 /// Registers that need to be saved for the current function.
124 mutable SetOfRegs CurrentCSRs;
125 /// Current MachineFunction.
126 MachineFunction *MachineFunc;
128 /// \brief Check if \p MI uses or defines a callee-saved register or
129 /// a frame index. If this is the case, this means \p MI must happen
130 /// after Save and before Restore.
131 bool useOrDefCSROrFI(const MachineInstr &MI) const;
133 const SetOfRegs &getCurrentCSRs() const {
134 if (CurrentCSRs.empty()) {
136 const TargetFrameLowering *TFI =
137 MachineFunc->getSubtarget().getFrameLowering();
139 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, nullptr);
141 for (int Reg = SavedRegs.find_first(); Reg != -1;
142 Reg = SavedRegs.find_next(Reg))
143 CurrentCSRs.insert((unsigned)Reg);
148 /// \brief Update the Save and Restore points such that \p MBB is in
149 /// the region that is dominated by Save and post-dominated by Restore
150 /// and Save and Restore still match the safe point definition.
151 /// Such point may not exist and Save and/or Restore may be null after
153 void updateSaveRestorePoints(MachineBasicBlock &MBB);
155 /// \brief Initialize the pass for \p MF.
156 void init(MachineFunction &MF) {
157 RCI.runOnMachineFunction(MF);
158 MDT = &getAnalysis<MachineDominatorTree>();
159 MPDT = &getAnalysis<MachinePostDominatorTree>();
162 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
163 MLI = &getAnalysis<MachineLoopInfo>();
164 EntryFreq = MBFI->getEntryFreq();
165 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
166 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
167 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
175 /// Check whether or not Save and Restore points are still interesting for
177 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
179 /// \brief Check if shrink wrapping is enabled for this target and function.
180 static bool isShrinkWrapEnabled(const MachineFunction &MF);
185 ShrinkWrap() : MachineFunctionPass(ID) {
186 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
189 void getAnalysisUsage(AnalysisUsage &AU) const override {
190 AU.setPreservesAll();
191 AU.addRequired<MachineBlockFrequencyInfo>();
192 AU.addRequired<MachineDominatorTree>();
193 AU.addRequired<MachinePostDominatorTree>();
194 AU.addRequired<MachineLoopInfo>();
195 MachineFunctionPass::getAnalysisUsage(AU);
198 const char *getPassName() const override {
199 return "Shrink Wrapping analysis";
202 /// \brief Perform the shrink-wrapping analysis and update
203 /// the MachineFrameInfo attached to \p MF with the results.
204 bool runOnMachineFunction(MachineFunction &MF) override;
206 } // End anonymous namespace.
208 char ShrinkWrap::ID = 0;
209 char &llvm::ShrinkWrapID = ShrinkWrap::ID;
211 INITIALIZE_PASS_BEGIN(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false,
213 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
214 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
215 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
216 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
217 INITIALIZE_PASS_END(ShrinkWrap, "shrink-wrap", "Shrink Wrap Pass", false, false)
219 bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI) const {
220 if (MI.getOpcode() == FrameSetupOpcode ||
221 MI.getOpcode() == FrameDestroyOpcode) {
222 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
225 for (const MachineOperand &MO : MI.operands()) {
226 bool UseOrDefCSR = false;
228 unsigned PhysReg = MO.getReg();
231 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
232 "Unallocated register?!");
233 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
234 } else if (MO.isRegMask()) {
235 // Check if this regmask clobbers any of the CSRs.
236 for (unsigned Reg : getCurrentCSRs()) {
237 if (MO.clobbersPhysReg(Reg)) {
243 if (UseOrDefCSR || MO.isFI()) {
244 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
245 << MO.isFI() << "): " << MI << '\n');
252 /// \brief Helper function to find the immediate (post) dominator.
253 template <typename ListOfBBs, typename DominanceAnalysis>
254 MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
255 DominanceAnalysis &Dom) {
256 MachineBasicBlock *IDom = &Block;
257 for (MachineBasicBlock *BB : BBs) {
258 IDom = Dom.findNearestCommonDominator(IDom, BB);
265 void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB) {
266 // Get rid of the easy cases first.
270 Save = MDT->findNearestCommonDominator(Save, &MBB);
273 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
280 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
282 // Make sure we would be able to insert the restore code before the
284 if (Restore == &MBB) {
285 for (const MachineInstr &Terminator : MBB.terminators()) {
286 if (!useOrDefCSROrFI(Terminator))
288 // One of the terminator needs to happen before the restore point.
289 if (MBB.succ_empty()) {
293 // Look for a restore point that post-dominates all the successors.
294 // The immediate post-dominator is what we are looking for.
295 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
301 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
305 // Make sure Save and Restore are suitable for shrink-wrapping:
306 // 1. all path from Save needs to lead to Restore before exiting.
307 // 2. all path to Restore needs to go through Save from Entry.
308 // We achieve that by making sure that:
309 // A. Save dominates Restore.
310 // B. Restore post-dominates Save.
311 // C. Save and Restore are in the same loop.
312 bool SaveDominatesRestore = false;
313 bool RestorePostDominatesSave = false;
314 while (Save && Restore &&
315 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
316 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
317 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore))) {
319 if (!SaveDominatesRestore) {
320 Save = MDT->findNearestCommonDominator(Save, Restore);
324 if (!RestorePostDominatesSave)
325 Restore = MPDT->findNearestCommonDominator(Restore, Save);
328 if (Save && Restore && Save != Restore &&
329 MLI->getLoopFor(Save) != MLI->getLoopFor(Restore)) {
330 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
331 // Push Save outside of this loop if immediate dominator is different
332 // from save block. If immediate dominator is not different, bail out.
333 MachineBasicBlock *IDom = FindIDom<>(*Save, Save->predecessors(), *MDT);
342 // If the loop does not exit, there is no point in looking
343 // for a post-dominator outside the loop.
344 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
345 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
346 // Push Restore outside of this loop.
347 // Look for the immediate post-dominator of the loop exits.
348 MachineBasicBlock *IPdom = Restore;
349 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
350 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
354 // If the immediate post-dominator is not in a less nested loop,
355 // then we are stuck in a program with an infinite loop.
356 // In that case, we will not find a safe point, hence, bail out.
357 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
368 bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
369 if (MF.empty() || !isShrinkWrapEnabled(MF))
372 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
376 for (MachineBasicBlock &MBB : MF) {
377 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
380 for (const MachineInstr &MI : MBB) {
381 if (!useOrDefCSROrFI(MI))
383 // Save (resp. restore) point must dominate (resp. post dominate)
384 // MI. Look for the proper basic block for those.
385 updateSaveRestorePoints(MBB);
386 // If we are at a point where we cannot improve the placement of
387 // save/restore instructions, just give up.
388 if (!ArePointsInteresting()) {
389 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
392 // No need to look for other instructions, this basic block
393 // will already be part of the handled region.
397 if (!ArePointsInteresting()) {
398 // If the points are not interesting at this point, then they must be null
399 // because it means we did not encounter any frame/CSR related code.
400 // Otherwise, we would have returned from the previous loop.
401 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
402 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
406 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
409 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
411 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
412 << Save->getNumber() << ' ' << Save->getName() << ' '
413 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
414 << Restore->getNumber() << ' ' << Restore->getName() << ' '
415 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
417 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
418 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
419 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
420 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
421 TFI->canUseAsEpilogue(*Restore)))
423 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
424 MachineBasicBlock *NewBB;
425 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
426 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
431 // Restore is expensive.
432 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
437 updateSaveRestorePoints(*NewBB);
438 } while (Save && Restore);
440 if (!ArePointsInteresting()) {
441 ++NumCandidatesDropped;
445 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
446 << ' ' << Save->getName() << "\nRestore: "
447 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
449 MachineFrameInfo *MFI = MF.getFrameInfo();
450 MFI->setSavePoint(Save);
451 MFI->setRestorePoint(Restore);
456 bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
457 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
459 switch (EnableShrinkWrapOpt) {
461 return TFI->enableShrinkWrapping(MF);
462 // If EnableShrinkWrap is set, it takes precedence on whatever the
463 // target sets. The rational is that we assume we want to test
464 // something related to shrink-wrapping.
470 llvm_unreachable("Invalid shrink-wrapping state");