blob: 2d854d6b43f02cae0b1c1ddeb9baf5ae43517263 [file] [log] [blame]
Eugene Zelenko149178d2017-10-10 22:33:29 +00001//===- ShrinkWrap.cpp - Compute safe point for prolog/epilog insertion ----===//
Quentin Colombet61b305e2015-05-05 17:38:16 +00002//
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//
Quentin Colombet9a8efc02015-11-06 21:00:13 +000046// If this pass found points matching all these properties, then
Chad Rosiera1080102015-12-22 15:06:47 +000047// MachineFrameInfo is updated with this information.
Eugene Zelenko149178d2017-10-10 22:33:29 +000048//
Quentin Colombet61b305e2015-05-05 17:38:16 +000049//===----------------------------------------------------------------------===//
Eugene Zelenko149178d2017-10-10 22:33:29 +000050
Quentin Colombet9a8efc02015-11-06 21:00:13 +000051#include "llvm/ADT/BitVector.h"
Quentin Colombet9ed52e92016-01-07 01:23:49 +000052#include "llvm/ADT/PostOrderIterator.h"
Quentin Colombet9a8efc02015-11-06 21:00:13 +000053#include "llvm/ADT/SetVector.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000054#include "llvm/ADT/SmallVector.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000055#include "llvm/ADT/Statistic.h"
Florian Hahn515acd62018-03-02 12:24:25 +000056#include "llvm/Analysis/CFG.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000057#include "llvm/CodeGen/MachineBasicBlock.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000058#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000059#include "llvm/CodeGen/MachineDominators.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000060#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000061#include "llvm/CodeGen/MachineFunction.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000062#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000063#include "llvm/CodeGen/MachineInstr.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000064#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000065#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000066#include "llvm/CodeGen/MachinePostDominators.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000067#include "llvm/CodeGen/RegisterClassInfo.h"
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +000068#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000069#include "llvm/CodeGen/TargetFrameLowering.h"
70#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000071#include "llvm/CodeGen/TargetRegisterInfo.h"
72#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000073#include "llvm/IR/Attributes.h"
74#include "llvm/IR/Function.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000075#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000076#include "llvm/Pass.h"
77#include "llvm/Support/CommandLine.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000078#include "llvm/Support/Debug.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000079#include "llvm/Support/ErrorHandling.h"
80#include "llvm/Support/raw_ostream.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000081#include "llvm/Target/TargetMachine.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000082#include <cassert>
83#include <cstdint>
84#include <memory>
Quentin Colombet61b305e2015-05-05 17:38:16 +000085
86using namespace llvm;
87
Eugene Zelenko149178d2017-10-10 22:33:29 +000088#define DEBUG_TYPE "shrink-wrap"
89
Quentin Colombet61b305e2015-05-05 17:38:16 +000090STATISTIC(NumFunc, "Number of functions");
91STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
92STATISTIC(NumCandidatesDropped,
93 "Number of shrink-wrapping candidates dropped because of frequency");
94
Kit Bartond3cc1672015-08-31 18:26:45 +000095static cl::opt<cl::boolOrDefault>
Eugene Zelenko149178d2017-10-10 22:33:29 +000096EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
97 cl::desc("enable the shrink-wrapping pass"));
Kit Bartond3cc1672015-08-31 18:26:45 +000098
Quentin Colombet61b305e2015-05-05 17:38:16 +000099namespace {
Eugene Zelenko149178d2017-10-10 22:33:29 +0000100
Quentin Colombet61b305e2015-05-05 17:38:16 +0000101/// \brief Class to determine where the safe point to insert the
102/// prologue and epilogue are.
103/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
104/// shrink-wrapping term for prologue/epilogue placement, this pass
105/// does not rely on expensive data-flow analysis. Instead we use the
106/// dominance properties and loop information to decide which point
107/// are safe for such insertion.
108class ShrinkWrap : public MachineFunctionPass {
109 /// Hold callee-saved information.
110 RegisterClassInfo RCI;
111 MachineDominatorTree *MDT;
112 MachinePostDominatorTree *MPDT;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000113
Quentin Colombet61b305e2015-05-05 17:38:16 +0000114 /// Current safe point found for the prologue.
115 /// The prologue will be inserted before the first instruction
116 /// in this basic block.
117 MachineBasicBlock *Save;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000118
Quentin Colombet61b305e2015-05-05 17:38:16 +0000119 /// Current safe point found for the epilogue.
120 /// The epilogue will be inserted before the first terminator instruction
121 /// in this basic block.
122 MachineBasicBlock *Restore;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000123
Quentin Colombet61b305e2015-05-05 17:38:16 +0000124 /// Hold the information of the basic block frequency.
125 /// Use to check the profitability of the new points.
126 MachineBlockFrequencyInfo *MBFI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000127
Quentin Colombet61b305e2015-05-05 17:38:16 +0000128 /// Hold the loop information. Used to determine if Save and Restore
129 /// are in the same loop.
130 MachineLoopInfo *MLI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000131
Quentin Colombet61b305e2015-05-05 17:38:16 +0000132 /// Frequency of the Entry block.
133 uint64_t EntryFreq;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000134
Quentin Colombet61b305e2015-05-05 17:38:16 +0000135 /// Current opcode for frame setup.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000136 unsigned FrameSetupOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000137
Quentin Colombet61b305e2015-05-05 17:38:16 +0000138 /// Current opcode for frame destroy.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000139 unsigned FrameDestroyOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000140
Quentin Colombet61b305e2015-05-05 17:38:16 +0000141 /// Entry block.
142 const MachineBasicBlock *Entry;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000143
144 using SetOfRegs = SmallSetVector<unsigned, 16>;
145
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000146 /// Registers that need to be saved for the current function.
147 mutable SetOfRegs CurrentCSRs;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000148
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000149 /// Current MachineFunction.
150 MachineFunction *MachineFunc;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000151
152 /// \brief Check if \p MI uses or defines a callee-saved register or
153 /// a frame index. If this is the case, this means \p MI must happen
154 /// after Save and before Restore.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000155 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000156
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000157 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000158 if (CurrentCSRs.empty()) {
159 BitVector SavedRegs;
160 const TargetFrameLowering *TFI =
161 MachineFunc->getSubtarget().getFrameLowering();
162
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000163 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000164
165 for (int Reg = SavedRegs.find_first(); Reg != -1;
166 Reg = SavedRegs.find_next(Reg))
167 CurrentCSRs.insert((unsigned)Reg);
168 }
169 return CurrentCSRs;
170 }
171
Quentin Colombet61b305e2015-05-05 17:38:16 +0000172 /// \brief Update the Save and Restore points such that \p MBB is in
173 /// the region that is dominated by Save and post-dominated by Restore
174 /// and Save and Restore still match the safe point definition.
175 /// Such point may not exist and Save and/or Restore may be null after
176 /// this call.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000177 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000178
179 /// \brief Initialize the pass for \p MF.
180 void init(MachineFunction &MF) {
181 RCI.runOnMachineFunction(MF);
182 MDT = &getAnalysis<MachineDominatorTree>();
183 MPDT = &getAnalysis<MachinePostDominatorTree>();
184 Save = nullptr;
185 Restore = nullptr;
186 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
187 MLI = &getAnalysis<MachineLoopInfo>();
188 EntryFreq = MBFI->getEntryFreq();
189 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
190 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
191 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
192 Entry = &MF.front();
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000193 CurrentCSRs.clear();
194 MachineFunc = &MF;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000195
196 ++NumFunc;
197 }
198
199 /// Check whether or not Save and Restore points are still interesting for
200 /// shrink-wrapping.
201 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
202
Kit Bartond3cc1672015-08-31 18:26:45 +0000203 /// \brief Check if shrink wrapping is enabled for this target and function.
204 static bool isShrinkWrapEnabled(const MachineFunction &MF);
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000205
Quentin Colombet61b305e2015-05-05 17:38:16 +0000206public:
207 static char ID;
208
209 ShrinkWrap() : MachineFunctionPass(ID) {
210 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
211 }
212
213 void getAnalysisUsage(AnalysisUsage &AU) const override {
214 AU.setPreservesAll();
215 AU.addRequired<MachineBlockFrequencyInfo>();
216 AU.addRequired<MachineDominatorTree>();
217 AU.addRequired<MachinePostDominatorTree>();
218 AU.addRequired<MachineLoopInfo>();
219 MachineFunctionPass::getAnalysisUsage(AU);
220 }
221
Mehdi Amini117296c2016-10-01 02:56:57 +0000222 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000223
224 /// \brief Perform the shrink-wrapping analysis and update
225 /// the MachineFrameInfo attached to \p MF with the results.
226 bool runOnMachineFunction(MachineFunction &MF) override;
227};
Eugene Zelenko149178d2017-10-10 22:33:29 +0000228
229} // end anonymous namespace
Quentin Colombet61b305e2015-05-05 17:38:16 +0000230
231char ShrinkWrap::ID = 0;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000232
Quentin Colombet61b305e2015-05-05 17:38:16 +0000233char &llvm::ShrinkWrapID = ShrinkWrap::ID;
234
Matthias Braun1527baa2017-05-25 21:26:32 +0000235INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000236INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
237INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
238INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
239INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000240INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000241
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000242bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
243 RegScavenger *RS) const {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000244 if (MI.getOpcode() == FrameSetupOpcode ||
245 MI.getOpcode() == FrameDestroyOpcode) {
246 DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
247 return true;
248 }
249 for (const MachineOperand &MO : MI.operands()) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000250 bool UseOrDefCSR = false;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000251 if (MO.isReg()) {
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000252 // Ignore instructions like DBG_VALUE which don't read/def the register.
253 if (!MO.isDef() && !MO.readsReg())
254 continue;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000255 unsigned PhysReg = MO.getReg();
256 if (!PhysReg)
257 continue;
258 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
259 "Unallocated register?!");
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000260 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
261 } else if (MO.isRegMask()) {
262 // Check if this regmask clobbers any of the CSRs.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000263 for (unsigned Reg : getCurrentCSRs(RS)) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000264 if (MO.clobbersPhysReg(Reg)) {
265 UseOrDefCSR = true;
266 break;
267 }
268 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000269 }
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000270 // Skip FrameIndex operands in DBG_VALUE instructions.
271 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000272 DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
273 << MO.isFI() << "): " << MI << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000274 return true;
275 }
276 }
277 return false;
278}
279
280/// \brief Helper function to find the immediate (post) dominator.
281template <typename ListOfBBs, typename DominanceAnalysis>
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000282static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
283 DominanceAnalysis &Dom) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000284 MachineBasicBlock *IDom = &Block;
285 for (MachineBasicBlock *BB : BBs) {
286 IDom = Dom.findNearestCommonDominator(IDom, BB);
287 if (!IDom)
288 break;
289 }
Michael Kuperstein037c9982016-01-06 18:40:11 +0000290 if (IDom == &Block)
291 return nullptr;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000292 return IDom;
293}
294
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000295void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
296 RegScavenger *RS) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000297 // Get rid of the easy cases first.
298 if (!Save)
299 Save = &MBB;
300 else
301 Save = MDT->findNearestCommonDominator(Save, &MBB);
302
303 if (!Save) {
304 DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
305 return;
306 }
307
308 if (!Restore)
309 Restore = &MBB;
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000310 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
311 // means the block never returns. If that's the
312 // case, we don't want to call
313 // `findNearestCommonDominator`, which will
314 // return `Restore`.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000315 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000316 else
317 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000318
319 // Make sure we would be able to insert the restore code before the
320 // terminator.
321 if (Restore == &MBB) {
322 for (const MachineInstr &Terminator : MBB.terminators()) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000323 if (!useOrDefCSROrFI(Terminator, RS))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000324 continue;
325 // One of the terminator needs to happen before the restore point.
326 if (MBB.succ_empty()) {
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000327 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000328 break;
329 }
330 // Look for a restore point that post-dominates all the successors.
331 // The immediate post-dominator is what we are looking for.
332 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
333 break;
334 }
335 }
336
337 if (!Restore) {
338 DEBUG(dbgs() << "Restore point needs to be spanned on several blocks\n");
339 return;
340 }
341
342 // Make sure Save and Restore are suitable for shrink-wrapping:
343 // 1. all path from Save needs to lead to Restore before exiting.
344 // 2. all path to Restore needs to go through Save from Entry.
345 // We achieve that by making sure that:
346 // A. Save dominates Restore.
347 // B. Restore post-dominates Save.
348 // C. Save and Restore are in the same loop.
349 bool SaveDominatesRestore = false;
350 bool RestorePostDominatesSave = false;
351 while (Save && Restore &&
352 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
353 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
Quentin Colombetb82786e2015-12-15 03:28:11 +0000354 // Post-dominance is not enough in loops to ensure that all uses/defs
355 // are after the prologue and before the epilogue at runtime.
356 // E.g.,
357 // while(1) {
358 // Save
359 // Restore
360 // if (...)
361 // break;
362 // use/def CSRs
363 // }
364 // All the uses/defs of CSRs are dominated by Save and post-dominated
365 // by Restore. However, the CSRs uses are still reachable after
366 // Restore and before Save are executed.
367 //
368 // For now, just push the restore/save points outside of loops.
369 // FIXME: Refine the criteria to still find interesting cases
370 // for loops.
371 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000372 // Fix (A).
373 if (!SaveDominatesRestore) {
374 Save = MDT->findNearestCommonDominator(Save, Restore);
375 continue;
376 }
377 // Fix (B).
378 if (!RestorePostDominatesSave)
379 Restore = MPDT->findNearestCommonDominator(Restore, Save);
380
381 // Fix (C).
Quentin Colombetb82786e2015-12-15 03:28:11 +0000382 if (Save && Restore &&
383 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Kit Bartona7bf96a2015-08-06 19:01:57 +0000384 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
385 // Push Save outside of this loop if immediate dominator is different
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000386 // from save block. If immediate dominator is not different, bail out.
Michael Kuperstein037c9982016-01-06 18:40:11 +0000387 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
388 if (!Save)
Kit Bartona7bf96a2015-08-06 19:01:57 +0000389 break;
Quentin Colombetb82786e2015-12-15 03:28:11 +0000390 } else {
Quentin Colombetdc29c972015-09-15 18:19:39 +0000391 // If the loop does not exit, there is no point in looking
392 // for a post-dominator outside the loop.
393 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
394 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
Quentin Colombetb4c68862015-09-17 23:21:34 +0000395 // Push Restore outside of this loop.
396 // Look for the immediate post-dominator of the loop exits.
397 MachineBasicBlock *IPdom = Restore;
398 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
399 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
400 if (!IPdom)
401 break;
Quentin Colombetdc29c972015-09-15 18:19:39 +0000402 }
Quentin Colombetb4c68862015-09-17 23:21:34 +0000403 // If the immediate post-dominator is not in a less nested loop,
404 // then we are stuck in a program with an infinite loop.
405 // In that case, we will not find a safe point, hence, bail out.
406 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000407 Restore = IPdom;
Kit Bartona7bf96a2015-08-06 19:01:57 +0000408 else {
409 Restore = nullptr;
410 break;
411 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000412 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000413 }
414 }
415}
416
417bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000418 if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000419 return false;
Kit Bartond3cc1672015-08-31 18:26:45 +0000420
Quentin Colombet61b305e2015-05-05 17:38:16 +0000421 DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
422
423 init(MF);
424
Florian Hahn515acd62018-03-02 12:24:25 +0000425 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
426 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000427 // If MF is irreducible, a block may be in a loop without
428 // MachineLoopInfo reporting it. I.e., we may use the
429 // post-dominance property in loops, which lead to incorrect
430 // results. Moreover, we may miss that the prologue and
431 // epilogue are not in the same loop, leading to unbalanced
432 // construction/deconstruction of the stack frame.
433 DEBUG(dbgs() << "Irreducible CFGs are not supported yet\n");
434 return false;
435 }
436
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000437 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
438 std::unique_ptr<RegScavenger> RS(
439 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
440
Quentin Colombet61b305e2015-05-05 17:38:16 +0000441 for (MachineBasicBlock &MBB : MF) {
442 DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' ' << MBB.getName()
443 << '\n');
444
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000445 if (MBB.isEHFuncletEntry()) {
446 DEBUG(dbgs() << "EH Funclets are not supported yet.\n");
447 return false;
448 }
449
Quentin Colombet508f6822018-03-20 02:44:40 +0000450 if (MBB.isEHPad()) {
451 // Push the prologue and epilogue outside of
452 // the region that may throw by making sure
453 // that all the landing pads are at least at the
454 // boundary of the save and restore points.
455 // The problem with exceptions is that the throw
456 // is not properly modeled and in particular, a
457 // basic block can jump out from the middle.
458 updateSaveRestorePoints(MBB, RS.get());
459 if (!ArePointsInteresting()) {
460 DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n");
461 return false;
462 }
463 continue;
464 }
465
Quentin Colombet61b305e2015-05-05 17:38:16 +0000466 for (const MachineInstr &MI : MBB) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000467 if (!useOrDefCSROrFI(MI, RS.get()))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000468 continue;
469 // Save (resp. restore) point must dominate (resp. post dominate)
470 // MI. Look for the proper basic block for those.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000471 updateSaveRestorePoints(MBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000472 // If we are at a point where we cannot improve the placement of
473 // save/restore instructions, just give up.
474 if (!ArePointsInteresting()) {
475 DEBUG(dbgs() << "No Shrink wrap candidate found\n");
476 return false;
477 }
478 // No need to look for other instructions, this basic block
479 // will already be part of the handled region.
480 break;
481 }
482 }
483 if (!ArePointsInteresting()) {
484 // If the points are not interesting at this point, then they must be null
485 // because it means we did not encounter any frame/CSR related code.
486 // Otherwise, we would have returned from the previous loop.
487 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
488 DEBUG(dbgs() << "Nothing to shrink-wrap\n");
489 return false;
490 }
491
492 DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
493 << '\n');
494
Quentin Colombet80835882015-05-27 06:25:48 +0000495 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000496 do {
497 DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
498 << Save->getNumber() << ' ' << Save->getName() << ' '
499 << MBFI->getBlockFreq(Save).getFrequency() << "\nRestore: "
500 << Restore->getNumber() << ' ' << Restore->getName() << ' '
501 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
502
Quentin Colombet80835882015-05-27 06:25:48 +0000503 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
504 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
505 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
506 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
507 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000508 break;
Quentin Colombet80835882015-05-27 06:25:48 +0000509 DEBUG(dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000510 MachineBasicBlock *NewBB;
Quentin Colombet80835882015-05-27 06:25:48 +0000511 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000512 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
513 if (!Save)
514 break;
515 NewBB = Save;
516 } else {
517 // Restore is expensive.
518 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
519 if (!Restore)
520 break;
521 NewBB = Restore;
522 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000523 updateSaveRestorePoints(*NewBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000524 } while (Save && Restore);
525
526 if (!ArePointsInteresting()) {
527 ++NumCandidatesDropped;
528 return false;
529 }
530
531 DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: " << Save->getNumber()
532 << ' ' << Save->getName() << "\nRestore: "
533 << Restore->getNumber() << ' ' << Restore->getName() << '\n');
534
Matthias Braun941a7052016-07-28 18:40:00 +0000535 MachineFrameInfo &MFI = MF.getFrameInfo();
536 MFI.setSavePoint(Save);
537 MFI.setRestorePoint(Restore);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000538 ++NumCandidates;
539 return false;
540}
Kit Bartond3cc1672015-08-31 18:26:45 +0000541
542bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
543 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
544
545 switch (EnableShrinkWrapOpt) {
546 case cl::BOU_UNSET:
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000547 return TFI->enableShrinkWrapping(MF) &&
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000548 // Windows with CFI has some limitations that make it impossible
549 // to use shrink-wrapping.
550 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
551 // Sanitizers look at the value of the stack at the location
552 // of the crash. Since a crash can happen anywhere, the
553 // frame must be lowered before anything else happen for the
554 // sanitizers to be able to get a correct stack frame.
Matthias Braunf1caa282017-12-15 22:22:58 +0000555 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
556 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
557 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
558 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
Kit Bartond3cc1672015-08-31 18:26:45 +0000559 // If EnableShrinkWrap is set, it takes precedence on whatever the
560 // target sets. The rational is that we assume we want to test
561 // something related to shrink-wrapping.
562 case cl::BOU_TRUE:
563 return true;
564 case cl::BOU_FALSE:
565 return false;
566 }
567 llvm_unreachable("Invalid shrink-wrapping state");
568}