blob: b8f088dfbe589fe76de9d6b5ac1c3602d0bf7cb7 [file] [log] [blame]
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001//===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
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 file defines a pass that optimizes call sequences on x86.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000011// Currently, it converts movs of function parameters onto the stack into
Michael Kuperstein13fbd452015-02-01 16:56:04 +000012// pushes. This is beneficial for two main reasons:
David L Kreitzerd5cb3412016-04-19 17:43:44 +000013// 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
Michael Kuperstein13fbd452015-02-01 16:56:04 +000014// 2) It is possible to push memory arguments directly. So, if the
David L Kreitzer99775c12016-04-12 21:45:09 +000015// the transformation is performed pre-reg-alloc, it can help relieve
Michael Kuperstein13fbd452015-02-01 16:56:04 +000016// register pressure.
17//
18//===----------------------------------------------------------------------===//
19
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000020#include "MCTargetDesc/X86BaseInfo.h"
21#include "X86FrameLowering.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000022#include "X86InstrInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000023#include "X86MachineFunctionInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000024#include "X86RegisterInfo.h"
David L Kreitzer99775c12016-04-12 21:45:09 +000025#include "X86Subtarget.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000026#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000032#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000033#include "llvm/CodeGen/MachineInstr.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000035#include "llvm/CodeGen/MachineOperand.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000037#include "llvm/IR/DebugLoc.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000038#include "llvm/IR/Function.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000039#include "llvm/MC/MCDwarf.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/MathExtras.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000043#include "llvm/Target/TargetInstrInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000044#include "llvm/Target/TargetRegisterInfo.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
Michael Kuperstein13fbd452015-02-01 16:56:04 +000049
50using namespace llvm;
51
52#define DEBUG_TYPE "x86-cf-opt"
53
Benjamin Kramer970eac42015-02-06 17:51:54 +000054static cl::opt<bool>
55 NoX86CFOpt("no-x86-call-frame-opt",
56 cl::desc("Avoid optimizing x86 call frames for size"),
57 cl::init(false), cl::Hidden);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000058
59namespace {
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000060
Michael Kuperstein13fbd452015-02-01 16:56:04 +000061class X86CallFrameOptimization : public MachineFunctionPass {
62public:
63 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
64
65 bool runOnMachineFunction(MachineFunction &MF) override;
66
67private:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000068 // Information we know about a particular call site
69 struct CallContext {
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000070 CallContext() : FrameSetup(nullptr), MovVector(4, nullptr) {}
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000071
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000072 // Iterator referring to the frame setup instruction
73 MachineBasicBlock::iterator FrameSetup;
74
75 // Actual call instruction
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000076 MachineInstr *Call = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000077
78 // A copy of the stack pointer
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000079 MachineInstr *SPCopy = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000080
81 // The total displacement of all passed parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000082 int64_t ExpectedDist = 0;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000083
84 // The sequence of movs used to pass the parameters
85 SmallVector<MachineInstr *, 4> MovVector;
86
Michael Kupersteindb95d042015-02-12 08:36:35 +000087 // True if this call site has no stack parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000088 bool NoStackParams = false;
Michael Kupersteindb95d042015-02-12 08:36:35 +000089
David L Kreitzer99775c12016-04-12 21:45:09 +000090 // True if this call site can use push instructions
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000091 bool UsePush = false;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000092 };
93
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000094 typedef SmallVector<CallContext, 8> ContextVector;
Michael Kupersteindb95d042015-02-12 08:36:35 +000095
96 bool isLegal(MachineFunction &MF);
Michael Kupersteindadb8472015-07-16 13:54:14 +000097
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000098 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
Michael Kupersteindb95d042015-02-12 08:36:35 +000099
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000100 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
101 MachineBasicBlock::iterator I, CallContext &Context);
102
Hans Wennborg501e7392016-05-05 16:39:31 +0000103 void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000104
105 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
106 unsigned Reg);
107
Michael Kupersteindadb8472015-07-16 13:54:14 +0000108 enum InstClassification { Convert, Skip, Exit };
109
110 InstClassification classifyInstruction(MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator MI,
112 const X86RegisterInfo &RegInfo,
113 DenseSet<unsigned int> &UsedRegs);
114
Mehdi Amini117296c2016-10-01 02:56:57 +0000115 StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000116
117 const TargetInstrInfo *TII;
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000118 const X86FrameLowering *TFL;
119 const X86Subtarget *STI;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000120 MachineRegisterInfo *MRI;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000121 unsigned SlotSize;
122 unsigned Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000123 static char ID;
124};
125
126char X86CallFrameOptimization::ID = 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000127
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000128} // end anonymous namespace
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000129
Michael Kupersteindadb8472015-07-16 13:54:14 +0000130// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000131// Also returns false in cases where it's potentially legal, but
132// we don't even want to try.
133bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000134 if (NoX86CFOpt.getValue())
135 return false;
136
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000137 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
138 // in the compact unwind encoding that Darwin uses. So, bail if there
139 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000140 if (STI->isTargetDarwin() &&
Matthias Braund0ee66c2016-12-01 19:32:15 +0000141 (!MF.getLandingPads().empty() ||
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000142 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000143 return false;
144
David L Kreitzer0fe46322016-05-02 13:45:25 +0000145 // It is not valid to change the stack pointer outside the prolog/epilog
146 // on 64-bit Windows.
147 if (STI->isTargetWin64())
148 return false;
149
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000150 // You would expect straight-line code between call-frame setup and
151 // call-frame destroy. You would be wrong. There are circumstances (e.g.
152 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
153 // end up with the setup and the destroy in different basic blocks.
154 // This is bad, and breaks SP adjustment.
155 // So, check that all of the frames in the function are closed inside
156 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000157 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
158 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000159 for (MachineBasicBlock &BB : MF) {
160 bool InsideFrameSequence = false;
161 for (MachineInstr &MI : BB) {
162 if (MI.getOpcode() == FrameSetupOpcode) {
163 if (InsideFrameSequence)
164 return false;
165 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000166 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000167 if (!InsideFrameSequence)
168 return false;
169 InsideFrameSequence = false;
170 }
171 }
172
173 if (InsideFrameSequence)
174 return false;
175 }
176
Michael Kupersteindb95d042015-02-12 08:36:35 +0000177 return true;
178}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000179
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000180// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000181// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000182bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
183 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000184 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000185 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000186 // a win or a loss, and requires a heuristic.
Matthias Braun941a7052016-07-28 18:40:00 +0000187 bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000188 if (CannotReserveFrame)
189 return true;
190
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000191 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000192
Michael Kupersteindb95d042015-02-12 08:36:35 +0000193 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000194 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000195 // Call sites where no parameters are passed on the stack
196 // do not affect the cost, since there needs to be no
197 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000198 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000199 continue;
200
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000201 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000202 // If we don't use pushes for a particular call site,
203 // we pay for not having a reserved call frame with an
204 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
205 // depending on the size of the constant.
206 // TODO: Callee-pop functions should have a smaller penalty, because
207 // an add is needed even with a reserved call frame.
208 Advantage -= 6;
209 } else {
210 // We can use pushes. First, account for the fixed costs.
211 // We'll need a add after the call.
212 Advantage -= 3;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000213 // If we have to realign the stack, we'll also need a sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000214 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000215 Advantage -= 3;
216 // Now, for each push, we save ~3 bytes. For small constants, we actually,
217 // save more (up to 5 bytes), but 3 should be a good approximation.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000218 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000219 }
220 }
221
David L Kreitzer99775c12016-04-12 21:45:09 +0000222 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000223}
224
225bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000226 STI = &MF.getSubtarget<X86Subtarget>();
227 TII = STI->getInstrInfo();
228 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000229 MRI = &MF.getRegInfo();
230
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000231 const X86RegisterInfo &RegInfo =
232 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
233 SlotSize = RegInfo.getSlotSize();
234 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
235 Log2SlotSize = Log2_32(SlotSize);
236
Andrew Kaylor81901d62016-08-18 22:49:51 +0000237 if (skipFunction(*MF.getFunction()) || !isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000238 return false;
239
Matthias Braunfa3872e2015-05-18 20:27:55 +0000240 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000241
242 bool Changed = false;
243
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000244 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000245
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000246 for (auto &MBB : MF)
247 for (auto &MI : MBB)
248 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000249 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000250 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000251 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000252 }
253
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000254 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000255 return false;
256
Hans Wennborg501e7392016-05-05 16:39:31 +0000257 for (auto CC : CallSeqVector) {
258 if (CC.UsePush) {
259 adjustCallSequence(MF, CC);
260 Changed = true;
261 }
262 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000263
264 return Changed;
265}
266
Michael Kupersteindadb8472015-07-16 13:54:14 +0000267X86CallFrameOptimization::InstClassification
268X86CallFrameOptimization::classifyInstruction(
269 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
270 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
271 if (MI == MBB.end())
272 return Exit;
273
274 // The instructions we actually care about are movs onto the stack
275 int Opcode = MI->getOpcode();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000276 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr ||
277 Opcode == X86::MOV64mi32 || Opcode == X86::MOV64mr)
Michael Kupersteindadb8472015-07-16 13:54:14 +0000278 return Convert;
279
280 // Not all calling conventions have only stack MOVs between the stack
281 // adjust and the call.
282
283 // We want to tolerate other instructions, to cover more cases.
284 // In particular:
285 // a) PCrel calls, where we expect an additional COPY of the basereg.
286 // b) Passing frame-index addresses.
287 // c) Calling conventions that have inreg parameters. These generate
288 // both copies and movs into registers.
289 // To avoid creating lots of special cases, allow any instruction
290 // that does not write into memory, does not def or use the stack
291 // pointer, and does not def any register that was used by a preceding
292 // push.
293 // (Reading from memory is allowed, even if referenced through a
294 // frame index, since these will get adjusted properly in PEI)
295
296 // The reason for the last condition is that the pushes can't replace
297 // the movs in place, because the order must be reversed.
298 // So if we have a MOV32mr that uses EDX, then an instruction that defs
299 // EDX, and then the call, after the transformation the push will use
300 // the modified version of EDX, and not the original one.
301 // Since we are still in SSA form at this point, we only need to
302 // make sure we don't clobber any *physical* registers that were
303 // used by an earlier mov that will become a push.
304
305 if (MI->isCall() || MI->mayStore())
306 return Exit;
307
308 for (const MachineOperand &MO : MI->operands()) {
309 if (!MO.isReg())
310 continue;
311 unsigned int Reg = MO.getReg();
312 if (!RegInfo.isPhysicalRegister(Reg))
313 continue;
314 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
315 return Exit;
316 if (MO.isDef()) {
317 for (unsigned int U : UsedRegs)
318 if (RegInfo.regsOverlap(Reg, U))
319 return Exit;
320 }
321 }
322
323 return Skip;
324}
325
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000326void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
327 MachineBasicBlock &MBB,
328 MachineBasicBlock::iterator I,
329 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000330 // Check that this particular call sequence is amenable to the
331 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000332 const X86RegisterInfo &RegInfo =
333 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Matthias Braunfa3872e2015-05-18 20:27:55 +0000334 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000335
336 // We expect to enter this at the beginning of a call sequence
337 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
338 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000339 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000340
Michael Kupersteindb95d042015-02-12 08:36:35 +0000341 // How much do we adjust the stack? This puts an upper bound on
342 // the number of parameters actually passed on it.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000343 unsigned int MaxAdjust =
344 FrameSetup->getOperand(0).getImm() >> Log2SlotSize;
Michael Kupersteindadb8472015-07-16 13:54:14 +0000345
Michael Kupersteindb95d042015-02-12 08:36:35 +0000346 // A zero adjustment means no stack parameters
347 if (!MaxAdjust) {
348 Context.NoStackParams = true;
349 return;
350 }
351
Michael Kuperstein5842b202016-12-07 19:31:08 +0000352 // Skip over DEBUG_VALUE.
353 // For globals in PIC mode, we can have some LEAs here. Skip them as well.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000354 // TODO: Extend this to something that covers more cases.
Michael Kuperstein5842b202016-12-07 19:31:08 +0000355 while (I->getOpcode() == X86::LEA32r || I->isDebugValue())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000356 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000357
Nico Webereb9488b2016-07-13 21:38:27 +0000358 unsigned StackPtr = RegInfo.getStackRegister();
359 // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
360 // register here. If it's there, use that virtual register as stack pointer
361 // instead.
362 if (I->isCopy() && I->getOperand(0).isReg() && I->getOperand(1).isReg() &&
363 I->getOperand(1).getReg() == StackPtr) {
364 Context.SPCopy = &*I++;
365 StackPtr = Context.SPCopy->getOperand(0).getReg();
366 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000367
368 // Scan the call setup sequence for the pattern we're looking for.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000369 // We only handle a simple case - a sequence of store instructions that
370 // push a sequence of stack-slot-aligned values onto the stack, with
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000371 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000372 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000373 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000374
Michael Kupersteindadb8472015-07-16 13:54:14 +0000375 InstClassification Classification;
376 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000377
Michael Kupersteindadb8472015-07-16 13:54:14 +0000378 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
379 Exit) {
380 if (Classification == Skip) {
381 ++I;
382 continue;
383 }
384
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000385 // We know the instruction has a supported store opcode.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000386 // We only want movs of the form:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000387 // mov imm/reg, k(%StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000388 // If we run into something else, bail.
389 // Note that AddrBaseReg may, counter to its name, not be a register,
390 // but rather a frame index.
391 // TODO: Support the fi case. This should probably work now that we
392 // have the infrastructure to track the stack pointer within a call
393 // sequence.
394 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
395 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
396 !I->getOperand(X86::AddrScaleAmt).isImm() ||
397 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
398 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
399 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
400 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000401 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000402
403 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000404 assert(StackDisp >= 0 &&
405 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000406
407 // We really don't want to consider the unaligned case.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000408 if (StackDisp & (SlotSize - 1))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000409 return;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000410 StackDisp >>= Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000411
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000412 assert((size_t)StackDisp < Context.MovVector.size() &&
413 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000414
415 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000416 if (Context.MovVector[StackDisp] != nullptr)
417 return;
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000418 Context.MovVector[StackDisp] = &*I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000419
Michael Kupersteindadb8472015-07-16 13:54:14 +0000420 for (const MachineOperand &MO : I->uses()) {
421 if (!MO.isReg())
422 continue;
423 unsigned int Reg = MO.getReg();
424 if (RegInfo.isPhysicalRegister(Reg))
425 UsedRegs.insert(Reg);
426 }
427
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000428 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000429 }
430
Michael Kupersteindadb8472015-07-16 13:54:14 +0000431 // We now expect the end of the sequence. If we stopped early,
432 // or reached the end of the block without finding a call, bail.
433 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000434 return;
435
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000436 Context.Call = &*I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000437 if ((++I)->getOpcode() != FrameDestroyOpcode)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000438 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000439
440 // Now, go through the vector, and see that we don't have any gaps,
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000441 // but only a series of MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000442 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000443 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000444 if (*MMI == nullptr)
445 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000446
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000447 // If the call had no parameters, do nothing
448 if (MMI == Context.MovVector.begin())
449 return;
450
451 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000452 // Make sure it's not a gap
453 for (; MMI != MME; ++MMI)
454 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000455 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000456
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000457 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000458}
459
Hans Wennborg501e7392016-05-05 16:39:31 +0000460void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000461 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000462 // Ok, we can in fact do the transformation for this call.
463 // Do not remove the FrameSetup instruction, but adjust the parameters.
464 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000465 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
466 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000467 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000468
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000469 DebugLoc DL = FrameSetup->getDebugLoc();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000470 bool Is64Bit = STI->is64Bit();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000471 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000472 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000473 // replace uses.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000474 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000475 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000476 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000477 MachineBasicBlock::iterator Push = nullptr;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000478 unsigned PushOpcode;
479 switch (MOV->getOpcode()) {
480 default:
481 llvm_unreachable("Unexpected Opcode!");
482 case X86::MOV32mi:
David L Kreitzer0fe46322016-05-02 13:45:25 +0000483 case X86::MOV64mi32:
484 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000485 // If the operand is a small (8-bit) immediate, we can use a
486 // PUSH instruction with a shorter encoding.
487 // Note that isImm() may fail even though this is a MOVmi, because
488 // the operand can also be a symbol.
489 if (PushOp.isImm()) {
490 int64_t Val = PushOp.getImm();
491 if (isInt<8>(Val))
David L Kreitzer0fe46322016-05-02 13:45:25 +0000492 PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000493 }
Diana Picus116bbab2017-01-13 09:58:52 +0000494 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000495 break;
496 case X86::MOV32mr:
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000497 case X86::MOV64mr: {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000498 unsigned int Reg = PushOp.getReg();
499
David L Kreitzer0fe46322016-05-02 13:45:25 +0000500 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
501 // in preparation for the PUSH64. The upper 32 bits can be undef.
502 if (Is64Bit && MOV->getOpcode() == X86::MOV32mr) {
503 unsigned UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
504 Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
505 BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
506 BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
Diana Picus116bbab2017-01-13 09:58:52 +0000507 .addReg(UndefReg)
508 .add(PushOp)
509 .addImm(X86::sub_32bit);
David L Kreitzer0fe46322016-05-02 13:45:25 +0000510 }
511
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000512 // If PUSHrmm is not slow on this target, try to fold the source of the
513 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000514 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000515
516 // Check that this is legal to fold. Right now, we're extremely
517 // conservative about that.
518 MachineInstr *DefMov = nullptr;
519 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000520 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000521 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000522
523 unsigned NumOps = DefMov->getDesc().getNumOperands();
524 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
525 Push->addOperand(DefMov->getOperand(i));
526
527 DefMov->eraseFromParent();
528 } else {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000529 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000530 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000531 .addReg(Reg)
532 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000533 }
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000534 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000535 }
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000536 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000537
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000538 // For debugging, when using SP-based CFA, we need to adjust the CFA
539 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000540 // TODO: This is needed only if we require precise CFA.
541 if (!TFL->hasFP(MF))
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000542 TFL->BuildCFI(
543 MBB, std::next(Push), DL,
544 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000545
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000546 MBB.erase(MOV);
547 }
548
549 // The stack-pointer copy is no longer used in the call sequences.
550 // There should not be any other users, but we can't commit to that, so:
Nico Webereb9488b2016-07-13 21:38:27 +0000551 if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000552 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000553
554 // Once we've done this, we need to make sure PEI doesn't assume a reserved
555 // frame.
556 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
557 FuncInfo->setHasPushSequences(true);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000558}
559
560MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
561 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
562 // Do an extremely restricted form of load folding.
563 // ISel will often create patterns like:
564 // movl 4(%edi), %eax
565 // movl 8(%edi), %ecx
566 // movl 12(%edi), %edx
567 // movl %edx, 8(%esp)
568 // movl %ecx, 4(%esp)
569 // movl %eax, (%esp)
570 // call
571 // Get rid of those with prejudice.
572 if (!TargetRegisterInfo::isVirtualRegister(Reg))
573 return nullptr;
574
575 // Make sure this is the only use of Reg.
576 if (!MRI->hasOneNonDBGUse(Reg))
577 return nullptr;
578
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000579 MachineInstr &DefMI = *MRI->getVRegDef(Reg);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000580
581 // Make sure the def is a MOV from memory.
David L Kreitzer29711c02016-06-30 21:43:11 +0000582 // If the def is in another block, give up.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000583 if ((DefMI.getOpcode() != X86::MOV32rm &&
584 DefMI.getOpcode() != X86::MOV64rm) ||
585 DefMI.getParent() != FrameSetup->getParent())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000586 return nullptr;
587
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000588 // Make sure we don't have any instructions between DefMI and the
589 // push that make folding the load illegal.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000590 for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000591 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000592 return nullptr;
593
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000594 return &DefMI;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000595}
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000596
597FunctionPass *llvm::createX86CallFrameOptimization() {
598 return new X86CallFrameOptimization();
599}