blob: 447440cd8e8561306d2dfc1c44cb9a63d279ee62 [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
20#include <algorithm>
21
22#include "X86.h"
23#include "X86InstrInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000024#include "X86MachineFunctionInfo.h"
David L Kreitzer99775c12016-04-12 21:45:09 +000025#include "X86Subtarget.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
Frederic Riss263b7722015-10-08 15:45:08 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Function.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetInstrInfo.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "x86-cf-opt"
40
Benjamin Kramer970eac42015-02-06 17:51:54 +000041static cl::opt<bool>
42 NoX86CFOpt("no-x86-call-frame-opt",
43 cl::desc("Avoid optimizing x86 call frames for size"),
44 cl::init(false), cl::Hidden);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000045
46namespace {
47class X86CallFrameOptimization : public MachineFunctionPass {
48public:
49 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
50
51 bool runOnMachineFunction(MachineFunction &MF) override;
52
53private:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000054 // Information we know about a particular call site
55 struct CallContext {
56 CallContext()
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000057 : FrameSetup(nullptr), Call(nullptr), SPCopy(nullptr), ExpectedDist(0),
David L Kreitzer99775c12016-04-12 21:45:09 +000058 MovVector(4, nullptr), NoStackParams(false), UsePush(false) {}
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000059
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000060 // Iterator referring to the frame setup instruction
61 MachineBasicBlock::iterator FrameSetup;
62
63 // Actual call instruction
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000064 MachineInstr *Call;
65
66 // A copy of the stack pointer
67 MachineInstr *SPCopy;
68
69 // The total displacement of all passed parameters
70 int64_t ExpectedDist;
71
72 // The sequence of movs used to pass the parameters
73 SmallVector<MachineInstr *, 4> MovVector;
74
Michael Kupersteindb95d042015-02-12 08:36:35 +000075 // True if this call site has no stack parameters
76 bool NoStackParams;
77
David L Kreitzer99775c12016-04-12 21:45:09 +000078 // True if this call site can use push instructions
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000079 bool UsePush;
80 };
81
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000082 typedef SmallVector<CallContext, 8> ContextVector;
Michael Kupersteindb95d042015-02-12 08:36:35 +000083
84 bool isLegal(MachineFunction &MF);
Michael Kupersteindadb8472015-07-16 13:54:14 +000085
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000086 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
Michael Kupersteindb95d042015-02-12 08:36:35 +000087
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000088 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
89 MachineBasicBlock::iterator I, CallContext &Context);
90
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000091 bool adjustCallSequence(MachineFunction &MF, const CallContext &Context);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000092
93 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
94 unsigned Reg);
95
Michael Kupersteindadb8472015-07-16 13:54:14 +000096 enum InstClassification { Convert, Skip, Exit };
97
98 InstClassification classifyInstruction(MachineBasicBlock &MBB,
99 MachineBasicBlock::iterator MI,
100 const X86RegisterInfo &RegInfo,
101 DenseSet<unsigned int> &UsedRegs);
102
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000103 const char *getPassName() const override { return "X86 Optimize Call Frame"; }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000104
105 const TargetInstrInfo *TII;
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000106 const X86FrameLowering *TFL;
107 const X86Subtarget *STI;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000108 const MachineRegisterInfo *MRI;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000109 unsigned SlotSize;
110 unsigned Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000111 static char ID;
112};
113
114char X86CallFrameOptimization::ID = 0;
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000115} // end anonymous namespace
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000116
117FunctionPass *llvm::createX86CallFrameOptimization() {
118 return new X86CallFrameOptimization();
119}
120
Michael Kupersteindadb8472015-07-16 13:54:14 +0000121// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000122// Also returns false in cases where it's potentially legal, but
123// we don't even want to try.
124bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000125 if (NoX86CFOpt.getValue())
126 return false;
127
128 // We currently only support call sequences where *all* parameters.
129 // are passed on the stack.
130 // No point in running this in 64-bit mode, since some arguments are
131 // passed in-register in all common calling conventions, so the pattern
132 // we're looking for will never match.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000133 if (STI->is64Bit())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000134 return false;
135
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000136 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
137 // in the compact unwind encoding that Darwin uses. So, bail if there
138 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000139 if (STI->isTargetDarwin() &&
140 (!MF.getMMI().getLandingPads().empty() ||
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000141 (MF.getFunction()->needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000142 return false;
143
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000144 // You would expect straight-line code between call-frame setup and
145 // call-frame destroy. You would be wrong. There are circumstances (e.g.
146 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
147 // end up with the setup and the destroy in different basic blocks.
148 // This is bad, and breaks SP adjustment.
149 // So, check that all of the frames in the function are closed inside
150 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000151 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
152 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000153 for (MachineBasicBlock &BB : MF) {
154 bool InsideFrameSequence = false;
155 for (MachineInstr &MI : BB) {
156 if (MI.getOpcode() == FrameSetupOpcode) {
157 if (InsideFrameSequence)
158 return false;
159 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000160 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000161 if (!InsideFrameSequence)
162 return false;
163 InsideFrameSequence = false;
164 }
165 }
166
167 if (InsideFrameSequence)
168 return false;
169 }
170
Michael Kupersteindb95d042015-02-12 08:36:35 +0000171 return true;
172}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000173
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000174// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000175// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000176bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
177 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000178 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000179 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000180 // a win or a loss, and requires a heuristic.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000181 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
182 if (CannotReserveFrame)
183 return true;
184
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000185 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000186
Michael Kupersteindb95d042015-02-12 08:36:35 +0000187 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000188 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000189 // Call sites where no parameters are passed on the stack
190 // do not affect the cost, since there needs to be no
191 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000192 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000193 continue;
194
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000195 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000196 // If we don't use pushes for a particular call site,
197 // we pay for not having a reserved call frame with an
198 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
199 // depending on the size of the constant.
200 // TODO: Callee-pop functions should have a smaller penalty, because
201 // an add is needed even with a reserved call frame.
202 Advantage -= 6;
203 } else {
204 // We can use pushes. First, account for the fixed costs.
205 // We'll need a add after the call.
206 Advantage -= 3;
207 // If we have to realign the stack, we'll also need and sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000208 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000209 Advantage -= 3;
210 // Now, for each push, we save ~3 bytes. For small constants, we actually,
211 // save more (up to 5 bytes), but 3 should be a good approximation.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000212 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000213 }
214 }
215
David L Kreitzer99775c12016-04-12 21:45:09 +0000216 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000217}
218
219bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000220 STI = &MF.getSubtarget<X86Subtarget>();
221 TII = STI->getInstrInfo();
222 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000223 MRI = &MF.getRegInfo();
224
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000225 const X86RegisterInfo &RegInfo =
226 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
227 SlotSize = RegInfo.getSlotSize();
228 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
229 Log2SlotSize = Log2_32(SlotSize);
230
Michael Kupersteindb95d042015-02-12 08:36:35 +0000231 if (!isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000232 return false;
233
Matthias Braunfa3872e2015-05-18 20:27:55 +0000234 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000235
236 bool Changed = false;
237
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000238 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000239
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000240 for (auto &MBB : MF)
241 for (auto &MI : MBB)
242 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000243 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000244 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000245 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000246 }
247
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000248 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000249 return false;
250
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000251 for (auto CC : CallSeqVector)
252 if (CC.UsePush)
253 Changed |= adjustCallSequence(MF, CC);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000254
255 return Changed;
256}
257
Michael Kupersteindadb8472015-07-16 13:54:14 +0000258X86CallFrameOptimization::InstClassification
259X86CallFrameOptimization::classifyInstruction(
260 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
261 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
262 if (MI == MBB.end())
263 return Exit;
264
265 // The instructions we actually care about are movs onto the stack
266 int Opcode = MI->getOpcode();
267 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr)
268 return Convert;
269
270 // Not all calling conventions have only stack MOVs between the stack
271 // adjust and the call.
272
273 // We want to tolerate other instructions, to cover more cases.
274 // In particular:
275 // a) PCrel calls, where we expect an additional COPY of the basereg.
276 // b) Passing frame-index addresses.
277 // c) Calling conventions that have inreg parameters. These generate
278 // both copies and movs into registers.
279 // To avoid creating lots of special cases, allow any instruction
280 // that does not write into memory, does not def or use the stack
281 // pointer, and does not def any register that was used by a preceding
282 // push.
283 // (Reading from memory is allowed, even if referenced through a
284 // frame index, since these will get adjusted properly in PEI)
285
286 // The reason for the last condition is that the pushes can't replace
287 // the movs in place, because the order must be reversed.
288 // So if we have a MOV32mr that uses EDX, then an instruction that defs
289 // EDX, and then the call, after the transformation the push will use
290 // the modified version of EDX, and not the original one.
291 // Since we are still in SSA form at this point, we only need to
292 // make sure we don't clobber any *physical* registers that were
293 // used by an earlier mov that will become a push.
294
295 if (MI->isCall() || MI->mayStore())
296 return Exit;
297
298 for (const MachineOperand &MO : MI->operands()) {
299 if (!MO.isReg())
300 continue;
301 unsigned int Reg = MO.getReg();
302 if (!RegInfo.isPhysicalRegister(Reg))
303 continue;
304 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
305 return Exit;
306 if (MO.isDef()) {
307 for (unsigned int U : UsedRegs)
308 if (RegInfo.regsOverlap(Reg, U))
309 return Exit;
310 }
311 }
312
313 return Skip;
314}
315
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000316void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
317 MachineBasicBlock &MBB,
318 MachineBasicBlock::iterator I,
319 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000320 // Check that this particular call sequence is amenable to the
321 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000322 const X86RegisterInfo &RegInfo =
323 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Matthias Braunfa3872e2015-05-18 20:27:55 +0000324 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000325
326 // We expect to enter this at the beginning of a call sequence
327 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
328 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000329 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000330
Michael Kupersteindb95d042015-02-12 08:36:35 +0000331 // How much do we adjust the stack? This puts an upper bound on
332 // the number of parameters actually passed on it.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000333 unsigned int MaxAdjust =
334 FrameSetup->getOperand(0).getImm() >> Log2SlotSize;
Michael Kupersteindadb8472015-07-16 13:54:14 +0000335
Michael Kupersteindb95d042015-02-12 08:36:35 +0000336 // A zero adjustment means no stack parameters
337 if (!MaxAdjust) {
338 Context.NoStackParams = true;
339 return;
340 }
341
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000342 // For globals in PIC mode, we can have some LEAs here.
343 // Ignore them, they don't bother us.
344 // TODO: Extend this to something that covers more cases.
345 while (I->getOpcode() == X86::LEA32r)
346 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000347
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000348 // We expect a copy instruction here.
349 // TODO: The copy instruction is a lowering artifact.
350 // We should also support a copy-less version, where the stack
351 // pointer is used directly.
352 if (!I->isCopy() || !I->getOperand(0).isReg())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000353 return;
354 Context.SPCopy = I++;
Saleem Abdulrasool6bc5ed32015-08-09 20:39:09 +0000355
356 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000357
358 // Scan the call setup sequence for the pattern we're looking for.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000359 // We only handle a simple case - a sequence of store instructions that
360 // push a sequence of stack-slot-aligned values onto the stack, with
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000361 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000362 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000363 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000364
Michael Kupersteindadb8472015-07-16 13:54:14 +0000365 InstClassification Classification;
366 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000367
Michael Kupersteindadb8472015-07-16 13:54:14 +0000368 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
369 Exit) {
370 if (Classification == Skip) {
371 ++I;
372 continue;
373 }
374
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000375 // We know the instruction has a supported store opcode.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000376 // We only want movs of the form:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000377 // mov imm/reg, k(%StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000378 // If we run into something else, bail.
379 // Note that AddrBaseReg may, counter to its name, not be a register,
380 // but rather a frame index.
381 // TODO: Support the fi case. This should probably work now that we
382 // have the infrastructure to track the stack pointer within a call
383 // sequence.
384 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
385 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
386 !I->getOperand(X86::AddrScaleAmt).isImm() ||
387 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
388 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
389 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
390 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000391 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000392
393 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000394 assert(StackDisp >= 0 &&
395 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000396
397 // We really don't want to consider the unaligned case.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000398 if (StackDisp & (SlotSize - 1))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000399 return;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000400 StackDisp >>= Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000401
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000402 assert((size_t)StackDisp < Context.MovVector.size() &&
403 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000404
405 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000406 if (Context.MovVector[StackDisp] != nullptr)
407 return;
408 Context.MovVector[StackDisp] = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000409
Michael Kupersteindadb8472015-07-16 13:54:14 +0000410 for (const MachineOperand &MO : I->uses()) {
411 if (!MO.isReg())
412 continue;
413 unsigned int Reg = MO.getReg();
414 if (RegInfo.isPhysicalRegister(Reg))
415 UsedRegs.insert(Reg);
416 }
417
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000418 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000419 }
420
Michael Kupersteindadb8472015-07-16 13:54:14 +0000421 // We now expect the end of the sequence. If we stopped early,
422 // or reached the end of the block without finding a call, bail.
423 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000424 return;
425
426 Context.Call = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000427 if ((++I)->getOpcode() != FrameDestroyOpcode)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000428 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000429
430 // Now, go through the vector, and see that we don't have any gaps,
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000431 // but only a series of MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000432 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000433 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000434 if (*MMI == nullptr)
435 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000436
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000437 // If the call had no parameters, do nothing
438 if (MMI == Context.MovVector.begin())
439 return;
440
441 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000442 // Make sure it's not a gap
443 for (; MMI != MME; ++MMI)
444 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000445 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000446
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000447 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000448}
449
450bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000451 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000452 // Ok, we can in fact do the transformation for this call.
453 // Do not remove the FrameSetup instruction, but adjust the parameters.
454 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000455 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
456 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000457 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000458
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000459 DebugLoc DL = FrameSetup->getDebugLoc();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000460 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000461 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000462 // replace uses.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000463 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000464 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000465 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000466 MachineBasicBlock::iterator Push = nullptr;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000467 unsigned PushOpcode;
468 switch (MOV->getOpcode()) {
469 default:
470 llvm_unreachable("Unexpected Opcode!");
471 case X86::MOV32mi:
472 PushOpcode = X86::PUSHi32;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000473 // If the operand is a small (8-bit) immediate, we can use a
474 // PUSH instruction with a shorter encoding.
475 // Note that isImm() may fail even though this is a MOVmi, because
476 // the operand can also be a symbol.
477 if (PushOp.isImm()) {
478 int64_t Val = PushOp.getImm();
479 if (isInt<8>(Val))
480 PushOpcode = X86::PUSH32i8;
481 }
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000482 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000483 .addOperand(PushOp);
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000484 break;
485 case X86::MOV32mr:
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000486 unsigned int Reg = PushOp.getReg();
487
488 // If PUSHrmm is not slow on this target, try to fold the source of the
489 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000490 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000491
492 // Check that this is legal to fold. Right now, we're extremely
493 // conservative about that.
494 MachineInstr *DefMov = nullptr;
495 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000496 PushOpcode = X86::PUSH32rmm;
497 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000498
499 unsigned NumOps = DefMov->getDesc().getNumOperands();
500 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
501 Push->addOperand(DefMov->getOperand(i));
502
503 DefMov->eraseFromParent();
504 } else {
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000505 PushOpcode = X86::PUSH32r;
506 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000507 .addReg(Reg)
508 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000509 }
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000510 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000511 }
512
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000513 // For debugging, when using SP-based CFA, we need to adjust the CFA
514 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000515 // TODO: This is needed only if we require precise CFA.
516 if (!TFL->hasFP(MF))
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000517 TFL->BuildCFI(
518 MBB, std::next(Push), DL,
519 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000520
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000521 MBB.erase(MOV);
522 }
523
524 // The stack-pointer copy is no longer used in the call sequences.
525 // There should not be any other users, but we can't commit to that, so:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000526 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
527 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000528
529 // Once we've done this, we need to make sure PEI doesn't assume a reserved
530 // frame.
531 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
532 FuncInfo->setHasPushSequences(true);
533
534 return true;
535}
536
537MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
538 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
539 // Do an extremely restricted form of load folding.
540 // ISel will often create patterns like:
541 // movl 4(%edi), %eax
542 // movl 8(%edi), %ecx
543 // movl 12(%edi), %edx
544 // movl %edx, 8(%esp)
545 // movl %ecx, 4(%esp)
546 // movl %eax, (%esp)
547 // call
548 // Get rid of those with prejudice.
549 if (!TargetRegisterInfo::isVirtualRegister(Reg))
550 return nullptr;
551
552 // Make sure this is the only use of Reg.
553 if (!MRI->hasOneNonDBGUse(Reg))
554 return nullptr;
555
556 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
557
558 // Make sure the def is a MOV from memory.
559 // If the def is an another block, give up.
560 if (DefMI->getOpcode() != X86::MOV32rm ||
561 DefMI->getParent() != FrameSetup->getParent())
562 return nullptr;
563
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000564 // Make sure we don't have any instructions between DefMI and the
565 // push that make folding the load illegal.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000566 for (auto I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000567 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000568 return nullptr;
569
570 return DefMI;
571}