blob: 412a00095b9b650de798aec5da46ea8eab9ab4b0 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Quentin Colombet61b305e2015-05-05 17:38:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass looks for safe point where the prologue and epilogue can be
10// inserted.
11// The safe point for the prologue (resp. epilogue) is called Save
12// (resp. Restore).
13// A point is safe for prologue (resp. epilogue) if and only if
14// it 1) dominates (resp. post-dominates) all the frame related operations and
15// between 2) two executions of the Save (resp. Restore) point there is an
16// execution of the Restore (resp. Save) point.
17//
18// For instance, the following points are safe:
19// for (int i = 0; i < 10; ++i) {
20// Save
21// ...
22// Restore
23// }
24// Indeed, the execution looks like Save -> Restore -> Save -> Restore ...
25// And the following points are not:
26// for (int i = 0; i < 10; ++i) {
27// Save
28// ...
29// }
30// for (int i = 0; i < 10; ++i) {
31// ...
32// Restore
33// }
34// Indeed, the execution looks like Save -> Save -> ... -> Restore -> Restore.
35//
36// This pass also ensures that the safe points are 3) cheaper than the regular
37// entry and exits blocks.
38//
39// Property #1 is ensured via the use of MachineDominatorTree and
40// MachinePostDominatorTree.
41// Property #2 is ensured via property #1 and MachineLoopInfo, i.e., both
42// points must be in the same loop.
43// Property #3 is ensured via the MachineBlockFrequencyInfo.
44//
Quentin Colombet9a8efc02015-11-06 21:00:13 +000045// If this pass found points matching all these properties, then
Chad Rosiera1080102015-12-22 15:06:47 +000046// MachineFrameInfo is updated with this information.
Eugene Zelenko149178d2017-10-10 22:33:29 +000047//
Quentin Colombet61b305e2015-05-05 17:38:16 +000048//===----------------------------------------------------------------------===//
Eugene Zelenko149178d2017-10-10 22:33:29 +000049
Quentin Colombet9a8efc02015-11-06 21:00:13 +000050#include "llvm/ADT/BitVector.h"
Quentin Colombet9ed52e92016-01-07 01:23:49 +000051#include "llvm/ADT/PostOrderIterator.h"
Quentin Colombet9a8efc02015-11-06 21:00:13 +000052#include "llvm/ADT/SetVector.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000053#include "llvm/ADT/SmallVector.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000054#include "llvm/ADT/Statistic.h"
Florian Hahn515acd62018-03-02 12:24:25 +000055#include "llvm/Analysis/CFG.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000056#include "llvm/CodeGen/MachineBasicBlock.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000057#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000058#include "llvm/CodeGen/MachineDominators.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000059#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000060#include "llvm/CodeGen/MachineFunction.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000061#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000062#include "llvm/CodeGen/MachineInstr.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000063#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000064#include "llvm/CodeGen/MachineOperand.h"
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +000065#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.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"
Momchil Velikove256ab82018-04-17 08:37:38 +000071#include "llvm/CodeGen/TargetLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000072#include "llvm/CodeGen/TargetRegisterInfo.h"
73#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000074#include "llvm/IR/Attributes.h"
75#include "llvm/IR/Function.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000076#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000077#include "llvm/Pass.h"
78#include "llvm/Support/CommandLine.h"
Quentin Colombet61b305e2015-05-05 17:38:16 +000079#include "llvm/Support/Debug.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000080#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/raw_ostream.h"
Quentin Colombet94dc1e02015-11-12 18:13:42 +000082#include "llvm/Target/TargetMachine.h"
Eugene Zelenko149178d2017-10-10 22:33:29 +000083#include <cassert>
84#include <cstdint>
85#include <memory>
Quentin Colombet61b305e2015-05-05 17:38:16 +000086
87using namespace llvm;
88
Eugene Zelenko149178d2017-10-10 22:33:29 +000089#define DEBUG_TYPE "shrink-wrap"
90
Quentin Colombet61b305e2015-05-05 17:38:16 +000091STATISTIC(NumFunc, "Number of functions");
92STATISTIC(NumCandidates, "Number of shrink-wrapping candidates");
93STATISTIC(NumCandidatesDropped,
94 "Number of shrink-wrapping candidates dropped because of frequency");
95
Kit Bartond3cc1672015-08-31 18:26:45 +000096static cl::opt<cl::boolOrDefault>
Eugene Zelenko149178d2017-10-10 22:33:29 +000097EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
98 cl::desc("enable the shrink-wrapping pass"));
Kit Bartond3cc1672015-08-31 18:26:45 +000099
Quentin Colombet61b305e2015-05-05 17:38:16 +0000100namespace {
Eugene Zelenko149178d2017-10-10 22:33:29 +0000101
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000102/// Class to determine where the safe point to insert the
Quentin Colombet61b305e2015-05-05 17:38:16 +0000103/// prologue and epilogue are.
104/// Unlike the paper from Fred C. Chow, PLDI'88, that introduces the
105/// shrink-wrapping term for prologue/epilogue placement, this pass
106/// does not rely on expensive data-flow analysis. Instead we use the
107/// dominance properties and loop information to decide which point
108/// are safe for such insertion.
109class ShrinkWrap : public MachineFunctionPass {
110 /// Hold callee-saved information.
111 RegisterClassInfo RCI;
112 MachineDominatorTree *MDT;
113 MachinePostDominatorTree *MPDT;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000114
Quentin Colombet61b305e2015-05-05 17:38:16 +0000115 /// Current safe point found for the prologue.
116 /// The prologue will be inserted before the first instruction
117 /// in this basic block.
118 MachineBasicBlock *Save;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000119
Quentin Colombet61b305e2015-05-05 17:38:16 +0000120 /// Current safe point found for the epilogue.
121 /// The epilogue will be inserted before the first terminator instruction
122 /// in this basic block.
123 MachineBasicBlock *Restore;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000124
Quentin Colombet61b305e2015-05-05 17:38:16 +0000125 /// Hold the information of the basic block frequency.
126 /// Use to check the profitability of the new points.
127 MachineBlockFrequencyInfo *MBFI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000128
Quentin Colombet61b305e2015-05-05 17:38:16 +0000129 /// Hold the loop information. Used to determine if Save and Restore
130 /// are in the same loop.
131 MachineLoopInfo *MLI;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000132
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000133 // Emit remarks.
134 MachineOptimizationRemarkEmitter *ORE = nullptr;
135
Quentin Colombet61b305e2015-05-05 17:38:16 +0000136 /// Frequency of the Entry block.
137 uint64_t EntryFreq;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000138
Quentin Colombet61b305e2015-05-05 17:38:16 +0000139 /// Current opcode for frame setup.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000140 unsigned FrameSetupOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000141
Quentin Colombet61b305e2015-05-05 17:38:16 +0000142 /// Current opcode for frame destroy.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000143 unsigned FrameDestroyOpcode;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000144
Momchil Velikove256ab82018-04-17 08:37:38 +0000145 /// Stack pointer register, used by llvm.{savestack,restorestack}
146 unsigned SP;
147
Quentin Colombet61b305e2015-05-05 17:38:16 +0000148 /// Entry block.
149 const MachineBasicBlock *Entry;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000150
151 using SetOfRegs = SmallSetVector<unsigned, 16>;
152
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000153 /// Registers that need to be saved for the current function.
154 mutable SetOfRegs CurrentCSRs;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000155
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000156 /// Current MachineFunction.
157 MachineFunction *MachineFunc;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000158
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000159 /// Check if \p MI uses or defines a callee-saved register or
Quentin Colombet61b305e2015-05-05 17:38:16 +0000160 /// a frame index. If this is the case, this means \p MI must happen
161 /// after Save and before Restore.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000162 bool useOrDefCSROrFI(const MachineInstr &MI, RegScavenger *RS) const;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000163
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000164 const SetOfRegs &getCurrentCSRs(RegScavenger *RS) const {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000165 if (CurrentCSRs.empty()) {
166 BitVector SavedRegs;
167 const TargetFrameLowering *TFI =
168 MachineFunc->getSubtarget().getFrameLowering();
169
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000170 TFI->determineCalleeSaves(*MachineFunc, SavedRegs, RS);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000171
172 for (int Reg = SavedRegs.find_first(); Reg != -1;
173 Reg = SavedRegs.find_next(Reg))
174 CurrentCSRs.insert((unsigned)Reg);
175 }
176 return CurrentCSRs;
177 }
178
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000179 /// Update the Save and Restore points such that \p MBB is in
Quentin Colombet61b305e2015-05-05 17:38:16 +0000180 /// the region that is dominated by Save and post-dominated by Restore
181 /// and Save and Restore still match the safe point definition.
182 /// Such point may not exist and Save and/or Restore may be null after
183 /// this call.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000184 void updateSaveRestorePoints(MachineBasicBlock &MBB, RegScavenger *RS);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000185
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000186 /// Initialize the pass for \p MF.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000187 void init(MachineFunction &MF) {
188 RCI.runOnMachineFunction(MF);
189 MDT = &getAnalysis<MachineDominatorTree>();
190 MPDT = &getAnalysis<MachinePostDominatorTree>();
191 Save = nullptr;
192 Restore = nullptr;
193 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
194 MLI = &getAnalysis<MachineLoopInfo>();
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000195 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000196 EntryFreq = MBFI->getEntryFreq();
Momchil Velikove256ab82018-04-17 08:37:38 +0000197 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
198 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000199 FrameSetupOpcode = TII.getCallFrameSetupOpcode();
200 FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
Momchil Velikove256ab82018-04-17 08:37:38 +0000201 SP = Subtarget.getTargetLowering()->getStackPointerRegisterToSaveRestore();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000202 Entry = &MF.front();
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000203 CurrentCSRs.clear();
204 MachineFunc = &MF;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000205
206 ++NumFunc;
207 }
208
209 /// Check whether or not Save and Restore points are still interesting for
210 /// shrink-wrapping.
211 bool ArePointsInteresting() const { return Save != Entry && Save && Restore; }
212
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000213 /// Check if shrink wrapping is enabled for this target and function.
Kit Bartond3cc1672015-08-31 18:26:45 +0000214 static bool isShrinkWrapEnabled(const MachineFunction &MF);
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000215
Quentin Colombet61b305e2015-05-05 17:38:16 +0000216public:
217 static char ID;
218
219 ShrinkWrap() : MachineFunctionPass(ID) {
220 initializeShrinkWrapPass(*PassRegistry::getPassRegistry());
221 }
222
223 void getAnalysisUsage(AnalysisUsage &AU) const override {
224 AU.setPreservesAll();
225 AU.addRequired<MachineBlockFrequencyInfo>();
226 AU.addRequired<MachineDominatorTree>();
227 AU.addRequired<MachinePostDominatorTree>();
228 AU.addRequired<MachineLoopInfo>();
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000229 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000230 MachineFunctionPass::getAnalysisUsage(AU);
231 }
232
Jun Bum Lim7ab1b322018-04-03 18:17:34 +0000233 MachineFunctionProperties getRequiredProperties() const override {
234 return MachineFunctionProperties().set(
235 MachineFunctionProperties::Property::NoVRegs);
236 }
237
Mehdi Amini117296c2016-10-01 02:56:57 +0000238 StringRef getPassName() const override { return "Shrink Wrapping analysis"; }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000239
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240 /// Perform the shrink-wrapping analysis and update
Quentin Colombet61b305e2015-05-05 17:38:16 +0000241 /// the MachineFrameInfo attached to \p MF with the results.
242 bool runOnMachineFunction(MachineFunction &MF) override;
243};
Eugene Zelenko149178d2017-10-10 22:33:29 +0000244
245} // end anonymous namespace
Quentin Colombet61b305e2015-05-05 17:38:16 +0000246
247char ShrinkWrap::ID = 0;
Eugene Zelenko149178d2017-10-10 22:33:29 +0000248
Quentin Colombet61b305e2015-05-05 17:38:16 +0000249char &llvm::ShrinkWrapID = ShrinkWrap::ID;
250
Matthias Braun1527baa2017-05-25 21:26:32 +0000251INITIALIZE_PASS_BEGIN(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000252INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
253INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
254INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
255INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000256INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000257INITIALIZE_PASS_END(ShrinkWrap, DEBUG_TYPE, "Shrink Wrap Pass", false, false)
Quentin Colombet61b305e2015-05-05 17:38:16 +0000258
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000259bool ShrinkWrap::useOrDefCSROrFI(const MachineInstr &MI,
260 RegScavenger *RS) const {
Diogo N. Sampaio0be2d252019-06-13 13:56:19 +0000261 // This prevents premature stack popping when occurs a indirect stack
262 // access. It is overly aggressive for the moment.
263 // TODO: - Obvious non-stack loads and store, such as global values,
264 // are known to not access the stack.
265 // - Further, data dependency and alias analysis can validate
266 // that load and stores never derive from the stack pointer.
267 if (MI.mayLoadOrStore())
268 return true;
269
Quentin Colombet61b305e2015-05-05 17:38:16 +0000270 if (MI.getOpcode() == FrameSetupOpcode ||
271 MI.getOpcode() == FrameDestroyOpcode) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000272 LLVM_DEBUG(dbgs() << "Frame instruction: " << MI << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000273 return true;
274 }
275 for (const MachineOperand &MO : MI.operands()) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000276 bool UseOrDefCSR = false;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000277 if (MO.isReg()) {
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000278 // Ignore instructions like DBG_VALUE which don't read/def the register.
279 if (!MO.isDef() && !MO.readsReg())
280 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000281 Register PhysReg = MO.getReg();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000282 if (!PhysReg)
283 continue;
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000284 assert(Register::isPhysicalRegister(PhysReg) && "Unallocated register?!");
Momchil Velikove256ab82018-04-17 08:37:38 +0000285 // The stack pointer is not normally described as a callee-saved register
286 // in calling convention definitions, so we need to watch for it
287 // separately. An SP mentioned by a call instruction, we can ignore,
288 // though, as it's harmless and we do not want to effectively disable tail
289 // calls by forcing the restore point to post-dominate them.
290 UseOrDefCSR = (!MI.isCall() && PhysReg == SP) ||
291 RCI.getLastCalleeSavedAlias(PhysReg);
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000292 } else if (MO.isRegMask()) {
293 // Check if this regmask clobbers any of the CSRs.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000294 for (unsigned Reg : getCurrentCSRs(RS)) {
Quentin Colombet9a8efc02015-11-06 21:00:13 +0000295 if (MO.clobbersPhysReg(Reg)) {
296 UseOrDefCSR = true;
297 break;
298 }
299 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000300 }
Francis Visoiu Mistrih54a9e7a2018-01-16 18:55:26 +0000301 // Skip FrameIndex operands in DBG_VALUE instructions.
302 if (UseOrDefCSR || (MO.isFI() && !MI.isDebugValue())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000303 LLVM_DEBUG(dbgs() << "Use or define CSR(" << UseOrDefCSR << ") or FI("
304 << MO.isFI() << "): " << MI << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000305 return true;
306 }
307 }
308 return false;
309}
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311/// Helper function to find the immediate (post) dominator.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000312template <typename ListOfBBs, typename DominanceAnalysis>
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000313static MachineBasicBlock *FindIDom(MachineBasicBlock &Block, ListOfBBs BBs,
314 DominanceAnalysis &Dom) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000315 MachineBasicBlock *IDom = &Block;
316 for (MachineBasicBlock *BB : BBs) {
317 IDom = Dom.findNearestCommonDominator(IDom, BB);
318 if (!IDom)
319 break;
320 }
Michael Kuperstein037c9982016-01-06 18:40:11 +0000321 if (IDom == &Block)
322 return nullptr;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000323 return IDom;
324}
325
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000326void ShrinkWrap::updateSaveRestorePoints(MachineBasicBlock &MBB,
327 RegScavenger *RS) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000328 // Get rid of the easy cases first.
329 if (!Save)
330 Save = &MBB;
331 else
332 Save = MDT->findNearestCommonDominator(Save, &MBB);
333
334 if (!Save) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000335 LLVM_DEBUG(dbgs() << "Found a block that is not reachable from Entry\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000336 return;
337 }
338
339 if (!Restore)
340 Restore = &MBB;
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000341 else if (MPDT->getNode(&MBB)) // If the block is not in the post dom tree, it
342 // means the block never returns. If that's the
343 // case, we don't want to call
344 // `findNearestCommonDominator`, which will
345 // return `Restore`.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000346 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000347 else
348 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000349
350 // Make sure we would be able to insert the restore code before the
351 // terminator.
352 if (Restore == &MBB) {
353 for (const MachineInstr &Terminator : MBB.terminators()) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000354 if (!useOrDefCSROrFI(Terminator, RS))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000355 continue;
356 // One of the terminator needs to happen before the restore point.
357 if (MBB.succ_empty()) {
Francis Visoiu Mistrihebbc7152017-05-15 23:13:35 +0000358 Restore = nullptr; // Abort, we can't find a restore point in this case.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000359 break;
360 }
361 // Look for a restore point that post-dominates all the successors.
362 // The immediate post-dominator is what we are looking for.
363 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
364 break;
365 }
366 }
367
368 if (!Restore) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000369 LLVM_DEBUG(
370 dbgs() << "Restore point needs to be spanned on several blocks\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000371 return;
372 }
373
374 // Make sure Save and Restore are suitable for shrink-wrapping:
375 // 1. all path from Save needs to lead to Restore before exiting.
376 // 2. all path to Restore needs to go through Save from Entry.
377 // We achieve that by making sure that:
378 // A. Save dominates Restore.
379 // B. Restore post-dominates Save.
380 // C. Save and Restore are in the same loop.
381 bool SaveDominatesRestore = false;
382 bool RestorePostDominatesSave = false;
383 while (Save && Restore &&
384 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
385 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
Quentin Colombetb82786e2015-12-15 03:28:11 +0000386 // Post-dominance is not enough in loops to ensure that all uses/defs
387 // are after the prologue and before the epilogue at runtime.
388 // E.g.,
389 // while(1) {
390 // Save
391 // Restore
392 // if (...)
393 // break;
394 // use/def CSRs
395 // }
396 // All the uses/defs of CSRs are dominated by Save and post-dominated
397 // by Restore. However, the CSRs uses are still reachable after
398 // Restore and before Save are executed.
399 //
400 // For now, just push the restore/save points outside of loops.
401 // FIXME: Refine the criteria to still find interesting cases
402 // for loops.
403 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000404 // Fix (A).
405 if (!SaveDominatesRestore) {
406 Save = MDT->findNearestCommonDominator(Save, Restore);
407 continue;
408 }
409 // Fix (B).
410 if (!RestorePostDominatesSave)
411 Restore = MPDT->findNearestCommonDominator(Restore, Save);
412
413 // Fix (C).
Quentin Colombetb82786e2015-12-15 03:28:11 +0000414 if (Save && Restore &&
415 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
Kit Bartona7bf96a2015-08-06 19:01:57 +0000416 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
417 // Push Save outside of this loop if immediate dominator is different
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000418 // from save block. If immediate dominator is not different, bail out.
Michael Kuperstein037c9982016-01-06 18:40:11 +0000419 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
420 if (!Save)
Kit Bartona7bf96a2015-08-06 19:01:57 +0000421 break;
Quentin Colombetb82786e2015-12-15 03:28:11 +0000422 } else {
Quentin Colombetdc29c972015-09-15 18:19:39 +0000423 // If the loop does not exit, there is no point in looking
424 // for a post-dominator outside the loop.
425 SmallVector<MachineBasicBlock*, 4> ExitBlocks;
426 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
Quentin Colombetb4c68862015-09-17 23:21:34 +0000427 // Push Restore outside of this loop.
428 // Look for the immediate post-dominator of the loop exits.
429 MachineBasicBlock *IPdom = Restore;
430 for (MachineBasicBlock *LoopExitBB: ExitBlocks) {
431 IPdom = FindIDom<>(*IPdom, LoopExitBB->successors(), *MPDT);
432 if (!IPdom)
433 break;
Quentin Colombetdc29c972015-09-15 18:19:39 +0000434 }
Quentin Colombetb4c68862015-09-17 23:21:34 +0000435 // If the immediate post-dominator is not in a less nested loop,
436 // then we are stuck in a program with an infinite loop.
437 // In that case, we will not find a safe point, hence, bail out.
438 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000439 Restore = IPdom;
Kit Bartona7bf96a2015-08-06 19:01:57 +0000440 else {
441 Restore = nullptr;
442 break;
443 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000444 }
Quentin Colombet61b305e2015-05-05 17:38:16 +0000445 }
446 }
447}
448
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000449static bool giveUpWithRemarks(MachineOptimizationRemarkEmitter *ORE,
450 StringRef RemarkName, StringRef RemarkMessage,
451 const DiagnosticLocation &Loc,
452 const MachineBasicBlock *MBB) {
453 ORE->emit([&]() {
454 return MachineOptimizationRemarkMissed(DEBUG_TYPE, RemarkName, Loc, MBB)
455 << RemarkMessage;
456 });
457
458 LLVM_DEBUG(dbgs() << RemarkMessage << '\n');
459 return false;
460}
461
Quentin Colombet61b305e2015-05-05 17:38:16 +0000462bool ShrinkWrap::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000463 if (skipFunction(MF.getFunction()) || MF.empty() || !isShrinkWrapEnabled(MF))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000464 return false;
Kit Bartond3cc1672015-08-31 18:26:45 +0000465
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000466 LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000467
468 init(MF);
469
Florian Hahn515acd62018-03-02 12:24:25 +0000470 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
471 if (containsIrreducibleCFG<MachineBasicBlock *>(RPOT, *MLI)) {
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000472 // If MF is irreducible, a block may be in a loop without
473 // MachineLoopInfo reporting it. I.e., we may use the
474 // post-dominance property in loops, which lead to incorrect
475 // results. Moreover, we may miss that the prologue and
476 // epilogue are not in the same loop, leading to unbalanced
477 // construction/deconstruction of the stack frame.
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000478 return giveUpWithRemarks(ORE, "UnsupportedIrreducibleCFG",
479 "Irreducible CFGs are not supported yet.",
480 MF.getFunction().getSubprogram(), &MF.front());
Quentin Colombet9ed52e92016-01-07 01:23:49 +0000481 }
482
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000483 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
484 std::unique_ptr<RegScavenger> RS(
485 TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr);
486
Quentin Colombet61b305e2015-05-05 17:38:16 +0000487 for (MachineBasicBlock &MBB : MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000488 LLVM_DEBUG(dbgs() << "Look into: " << MBB.getNumber() << ' '
489 << MBB.getName() << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000490
Francis Visoiu Mistrihca69b3b2018-06-05 00:27:24 +0000491 if (MBB.isEHFuncletEntry())
492 return giveUpWithRemarks(ORE, "UnsupportedEHFunclets",
493 "EH Funclets are not supported yet.",
494 MBB.front().getDebugLoc(), &MBB);
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000495
Quentin Colombet508f6822018-03-20 02:44:40 +0000496 if (MBB.isEHPad()) {
497 // Push the prologue and epilogue outside of
498 // the region that may throw by making sure
499 // that all the landing pads are at least at the
500 // boundary of the save and restore points.
501 // The problem with exceptions is that the throw
502 // is not properly modeled and in particular, a
503 // basic block can jump out from the middle.
504 updateSaveRestorePoints(MBB, RS.get());
505 if (!ArePointsInteresting()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000506 LLVM_DEBUG(dbgs() << "EHPad prevents shrink-wrapping\n");
Quentin Colombet508f6822018-03-20 02:44:40 +0000507 return false;
508 }
509 continue;
510 }
511
Quentin Colombet61b305e2015-05-05 17:38:16 +0000512 for (const MachineInstr &MI : MBB) {
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000513 if (!useOrDefCSROrFI(MI, RS.get()))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000514 continue;
515 // Save (resp. restore) point must dominate (resp. post dominate)
516 // MI. Look for the proper basic block for those.
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000517 updateSaveRestorePoints(MBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000518 // If we are at a point where we cannot improve the placement of
519 // save/restore instructions, just give up.
520 if (!ArePointsInteresting()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000521 LLVM_DEBUG(dbgs() << "No Shrink wrap candidate found\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000522 return false;
523 }
524 // No need to look for other instructions, this basic block
525 // will already be part of the handled region.
526 break;
527 }
528 }
529 if (!ArePointsInteresting()) {
530 // If the points are not interesting at this point, then they must be null
531 // because it means we did not encounter any frame/CSR related code.
532 // Otherwise, we would have returned from the previous loop.
533 assert(!Save && !Restore && "We miss a shrink-wrap opportunity?!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000534 LLVM_DEBUG(dbgs() << "Nothing to shrink-wrap\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000535 return false;
536 }
537
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000538 LLVM_DEBUG(dbgs() << "\n ** Results **\nFrequency of the Entry: " << EntryFreq
539 << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000540
Quentin Colombet80835882015-05-27 06:25:48 +0000541 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000542 do {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000543 LLVM_DEBUG(dbgs() << "Shrink wrap candidates (#, Name, Freq):\nSave: "
544 << Save->getNumber() << ' ' << Save->getName() << ' '
545 << MBFI->getBlockFreq(Save).getFrequency()
546 << "\nRestore: " << Restore->getNumber() << ' '
547 << Restore->getName() << ' '
548 << MBFI->getBlockFreq(Restore).getFrequency() << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000549
Quentin Colombet80835882015-05-27 06:25:48 +0000550 bool IsSaveCheap, TargetCanUseSaveAsPrologue = false;
551 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
552 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
553 ((TargetCanUseSaveAsPrologue = TFI->canUseAsPrologue(*Save)) &&
554 TFI->canUseAsEpilogue(*Restore)))
Quentin Colombet61b305e2015-05-05 17:38:16 +0000555 break;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000556 LLVM_DEBUG(
557 dbgs() << "New points are too expensive or invalid for the target\n");
Quentin Colombet61b305e2015-05-05 17:38:16 +0000558 MachineBasicBlock *NewBB;
Quentin Colombet80835882015-05-27 06:25:48 +0000559 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
Quentin Colombet61b305e2015-05-05 17:38:16 +0000560 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
561 if (!Save)
562 break;
563 NewBB = Save;
564 } else {
565 // Restore is expensive.
566 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
567 if (!Restore)
568 break;
569 NewBB = Restore;
570 }
Arnaud A. de Grandmaison4e89e9f2015-11-20 21:54:27 +0000571 updateSaveRestorePoints(*NewBB, RS.get());
Quentin Colombet61b305e2015-05-05 17:38:16 +0000572 } while (Save && Restore);
573
574 if (!ArePointsInteresting()) {
575 ++NumCandidatesDropped;
576 return false;
577 }
578
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000579 LLVM_DEBUG(dbgs() << "Final shrink wrap candidates:\nSave: "
580 << Save->getNumber() << ' ' << Save->getName()
581 << "\nRestore: " << Restore->getNumber() << ' '
582 << Restore->getName() << '\n');
Quentin Colombet61b305e2015-05-05 17:38:16 +0000583
Matthias Braun941a7052016-07-28 18:40:00 +0000584 MachineFrameInfo &MFI = MF.getFrameInfo();
585 MFI.setSavePoint(Save);
586 MFI.setRestorePoint(Restore);
Quentin Colombet61b305e2015-05-05 17:38:16 +0000587 ++NumCandidates;
588 return false;
589}
Kit Bartond3cc1672015-08-31 18:26:45 +0000590
591bool ShrinkWrap::isShrinkWrapEnabled(const MachineFunction &MF) {
592 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
593
594 switch (EnableShrinkWrapOpt) {
595 case cl::BOU_UNSET:
Quentin Colombet94dc1e02015-11-12 18:13:42 +0000596 return TFI->enableShrinkWrapping(MF) &&
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000597 // Windows with CFI has some limitations that make it impossible
598 // to use shrink-wrapping.
599 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
600 // Sanitizers look at the value of the stack at the location
601 // of the crash. Since a crash can happen anywhere, the
602 // frame must be lowered before anything else happen for the
603 // sanitizers to be able to get a correct stack frame.
Matthias Braunf1caa282017-12-15 22:22:58 +0000604 !(MF.getFunction().hasFnAttribute(Attribute::SanitizeAddress) ||
605 MF.getFunction().hasFnAttribute(Attribute::SanitizeThread) ||
606 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemory) ||
607 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress));
Kit Bartond3cc1672015-08-31 18:26:45 +0000608 // If EnableShrinkWrap is set, it takes precedence on whatever the
609 // target sets. The rational is that we assume we want to test
610 // something related to shrink-wrapping.
611 case cl::BOU_TRUE:
612 return true;
613 case cl::BOU_FALSE:
614 return false;
615 }
616 llvm_unreachable("Invalid shrink-wrapping state");
617}