blob: e3031b8946417744f75ffa3655c2d4164ad52ef7 [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:
13// 1) The push instruction encoding is much smaller than an esp-relative mov
14// 2) It is possible to push memory arguments directly. So, if the
15// the transformation is preformed pre-reg-alloc, it can help relieve
16// register pressure.
17//
18//===----------------------------------------------------------------------===//
19
20#include <algorithm>
21
22#include "X86.h"
23#include "X86InstrInfo.h"
24#include "X86Subtarget.h"
25#include "X86MachineFunctionInfo.h"
26#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),
Hans Wennborg13958b72015-07-22 20:46:11 +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
78 // True of this callsite 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;
106 const TargetFrameLowering *TFL;
107 const MachineRegisterInfo *MRI;
108 static char ID;
109};
110
111char X86CallFrameOptimization::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000112}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000113
114FunctionPass *llvm::createX86CallFrameOptimization() {
115 return new X86CallFrameOptimization();
116}
117
Michael Kupersteindadb8472015-07-16 13:54:14 +0000118// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000119// Also returns false in cases where it's potentially legal, but
120// we don't even want to try.
121bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000122 if (NoX86CFOpt.getValue())
123 return false;
124
125 // We currently only support call sequences where *all* parameters.
126 // are passed on the stack.
127 // No point in running this in 64-bit mode, since some arguments are
128 // passed in-register in all common calling conventions, so the pattern
129 // we're looking for will never match.
Eric Christopher4369c9b2015-02-20 08:01:52 +0000130 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000131 if (STI.is64Bit())
132 return false;
133
Frederic Riss263b7722015-10-08 15:45:08 +0000134 // We can't encode multiple DW_CFA_GNU_args_size in the compact
135 // unwind encoding that Darwin uses.
136 if (STI.isTargetDarwin() && !MF.getMMI().getLandingPads().empty())
137 return false;
138
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000139 // You would expect straight-line code between call-frame setup and
140 // call-frame destroy. You would be wrong. There are circumstances (e.g.
141 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
142 // end up with the setup and the destroy in different basic blocks.
143 // This is bad, and breaks SP adjustment.
144 // So, check that all of the frames in the function are closed inside
145 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000146 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
147 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000148 for (MachineBasicBlock &BB : MF) {
149 bool InsideFrameSequence = false;
150 for (MachineInstr &MI : BB) {
151 if (MI.getOpcode() == FrameSetupOpcode) {
152 if (InsideFrameSequence)
153 return false;
154 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000155 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000156 if (!InsideFrameSequence)
157 return false;
158 InsideFrameSequence = false;
159 }
160 }
161
162 if (InsideFrameSequence)
163 return false;
164 }
165
Michael Kupersteindb95d042015-02-12 08:36:35 +0000166 return true;
167}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000168
Michael Kupersteindb95d042015-02-12 08:36:35 +0000169// Check whether this trasnformation is profitable for a particular
170// function - in terms of code size.
171bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000172 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000173 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000174 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000175 // a win or a loss, and requires a heuristic.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000176 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
177 if (CannotReserveFrame)
178 return true;
179
Michael Kupersteindb95d042015-02-12 08:36:35 +0000180 // Don't do this when not optimizing for size.
Sanjay Patel924879a2015-08-04 15:49:57 +0000181 if (!MF.getFunction()->optForSize())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000182 return false;
183
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000184 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000185
Michael Kupersteindb95d042015-02-12 08:36:35 +0000186 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000187 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000188 // Call sites where no parameters are passed on the stack
189 // do not affect the cost, since there needs to be no
190 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000191 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000192 continue;
193
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000194 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000195 // If we don't use pushes for a particular call site,
196 // we pay for not having a reserved call frame with an
197 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
198 // depending on the size of the constant.
199 // TODO: Callee-pop functions should have a smaller penalty, because
200 // an add is needed even with a reserved call frame.
201 Advantage -= 6;
202 } else {
203 // We can use pushes. First, account for the fixed costs.
204 // We'll need a add after the call.
205 Advantage -= 3;
206 // If we have to realign the stack, we'll also need and sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000207 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000208 Advantage -= 3;
209 // Now, for each push, we save ~3 bytes. For small constants, we actually,
210 // save more (up to 5 bytes), but 3 should be a good approximation.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000211 Advantage += (CC.ExpectedDist / 4) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000212 }
213 }
214
215 return (Advantage >= 0);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000216}
217
218bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
219 TII = MF.getSubtarget().getInstrInfo();
220 TFL = MF.getSubtarget().getFrameLowering();
221 MRI = &MF.getRegInfo();
222
Michael Kupersteindb95d042015-02-12 08:36:35 +0000223 if (!isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000224 return false;
225
Matthias Braunfa3872e2015-05-18 20:27:55 +0000226 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000227
228 bool Changed = false;
229
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000230 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000231
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000232 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
233 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000234 if (I->getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000235 CallContext Context;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000236 collectCallInfo(MF, *BB, I, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000237 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000238 }
239
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000240 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000241 return false;
242
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000243 for (auto CC : CallSeqVector)
244 if (CC.UsePush)
245 Changed |= adjustCallSequence(MF, CC);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000246
247 return Changed;
248}
249
Michael Kupersteindadb8472015-07-16 13:54:14 +0000250X86CallFrameOptimization::InstClassification
251X86CallFrameOptimization::classifyInstruction(
252 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
253 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
254 if (MI == MBB.end())
255 return Exit;
256
257 // The instructions we actually care about are movs onto the stack
258 int Opcode = MI->getOpcode();
259 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr)
260 return Convert;
261
262 // Not all calling conventions have only stack MOVs between the stack
263 // adjust and the call.
264
265 // We want to tolerate other instructions, to cover more cases.
266 // In particular:
267 // a) PCrel calls, where we expect an additional COPY of the basereg.
268 // b) Passing frame-index addresses.
269 // c) Calling conventions that have inreg parameters. These generate
270 // both copies and movs into registers.
271 // To avoid creating lots of special cases, allow any instruction
272 // that does not write into memory, does not def or use the stack
273 // pointer, and does not def any register that was used by a preceding
274 // push.
275 // (Reading from memory is allowed, even if referenced through a
276 // frame index, since these will get adjusted properly in PEI)
277
278 // The reason for the last condition is that the pushes can't replace
279 // the movs in place, because the order must be reversed.
280 // So if we have a MOV32mr that uses EDX, then an instruction that defs
281 // EDX, and then the call, after the transformation the push will use
282 // the modified version of EDX, and not the original one.
283 // Since we are still in SSA form at this point, we only need to
284 // make sure we don't clobber any *physical* registers that were
285 // used by an earlier mov that will become a push.
286
287 if (MI->isCall() || MI->mayStore())
288 return Exit;
289
290 for (const MachineOperand &MO : MI->operands()) {
291 if (!MO.isReg())
292 continue;
293 unsigned int Reg = MO.getReg();
294 if (!RegInfo.isPhysicalRegister(Reg))
295 continue;
296 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
297 return Exit;
298 if (MO.isDef()) {
299 for (unsigned int U : UsedRegs)
300 if (RegInfo.regsOverlap(Reg, U))
301 return Exit;
302 }
303 }
304
305 return Skip;
306}
307
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000308void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
309 MachineBasicBlock &MBB,
310 MachineBasicBlock::iterator I,
311 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000312 // Check that this particular call sequence is amenable to the
313 // transformation.
314 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
315 MF.getSubtarget().getRegisterInfo());
Matthias Braunfa3872e2015-05-18 20:27:55 +0000316 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000317
318 // We expect to enter this at the beginning of a call sequence
319 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
320 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000321 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000322
Michael Kupersteindb95d042015-02-12 08:36:35 +0000323 // How much do we adjust the stack? This puts an upper bound on
324 // the number of parameters actually passed on it.
Michael Kupersteindadb8472015-07-16 13:54:14 +0000325 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4;
326
Michael Kupersteindb95d042015-02-12 08:36:35 +0000327 // A zero adjustment means no stack parameters
328 if (!MaxAdjust) {
329 Context.NoStackParams = true;
330 return;
331 }
332
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000333 // For globals in PIC mode, we can have some LEAs here.
334 // Ignore them, they don't bother us.
335 // TODO: Extend this to something that covers more cases.
336 while (I->getOpcode() == X86::LEA32r)
337 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000338
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000339 // We expect a copy instruction here.
340 // TODO: The copy instruction is a lowering artifact.
341 // We should also support a copy-less version, where the stack
342 // pointer is used directly.
343 if (!I->isCopy() || !I->getOperand(0).isReg())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000344 return;
345 Context.SPCopy = I++;
Saleem Abdulrasool6bc5ed32015-08-09 20:39:09 +0000346
347 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000348
349 // Scan the call setup sequence for the pattern we're looking for.
350 // We only handle a simple case - a sequence of MOV32mi or MOV32mr
351 // instructions, that push a sequence of 32-bit values onto the stack, with
352 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000353 if (MaxAdjust > 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000354 Context.MovVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000355
Michael Kupersteindadb8472015-07-16 13:54:14 +0000356 InstClassification Classification;
357 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000358
Michael Kupersteindadb8472015-07-16 13:54:14 +0000359 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
360 Exit) {
361 if (Classification == Skip) {
362 ++I;
363 continue;
364 }
365
366 // We know the instruction is a MOV32mi/MOV32mr.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000367 // We only want movs of the form:
368 // movl imm/r32, k(%esp)
369 // If we run into something else, bail.
370 // Note that AddrBaseReg may, counter to its name, not be a register,
371 // but rather a frame index.
372 // TODO: Support the fi case. This should probably work now that we
373 // have the infrastructure to track the stack pointer within a call
374 // sequence.
375 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
376 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
377 !I->getOperand(X86::AddrScaleAmt).isImm() ||
378 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
379 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
380 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
381 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000382 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000383
384 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000385 assert(StackDisp >= 0 &&
386 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000387
388 // We really don't want to consider the unaligned case.
389 if (StackDisp % 4)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000390 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000391 StackDisp /= 4;
392
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000393 assert((size_t)StackDisp < Context.MovVector.size() &&
394 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000395
396 // If the same stack slot is being filled twice, something's fishy.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000397 if (Context.MovVector[StackDisp] != nullptr)
398 return;
399 Context.MovVector[StackDisp] = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000400
Michael Kupersteindadb8472015-07-16 13:54:14 +0000401 for (const MachineOperand &MO : I->uses()) {
402 if (!MO.isReg())
403 continue;
404 unsigned int Reg = MO.getReg();
405 if (RegInfo.isPhysicalRegister(Reg))
406 UsedRegs.insert(Reg);
407 }
408
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000409 ++I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000410 }
411
Michael Kupersteindadb8472015-07-16 13:54:14 +0000412 // We now expect the end of the sequence. If we stopped early,
413 // or reached the end of the block without finding a call, bail.
414 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000415 return;
416
417 Context.Call = I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000418 if ((++I)->getOpcode() != FrameDestroyOpcode)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000419 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000420
421 // Now, go through the vector, and see that we don't have any gaps,
422 // but only a series of 32-bit MOVs.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000423 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
424 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000425 if (*MMI == nullptr)
426 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000427
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000428 // If the call had no parameters, do nothing
429 if (MMI == Context.MovVector.begin())
430 return;
431
432 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000433 // Make sure it's not a gap
434 for (; MMI != MME; ++MMI)
435 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000436 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000437
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000438 Context.UsePush = true;
439 return;
440}
441
442bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000443 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000444 // Ok, we can in fact do the transformation for this call.
445 // Do not remove the FrameSetup instruction, but adjust the parameters.
446 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000447 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
448 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000449 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000450
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000451 DebugLoc DL = FrameSetup->getDebugLoc();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000452 // Now, iterate through the vector in reverse order, and replace the movs
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000453 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000454 // replace uses.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000455 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) {
456 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000457 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
458 if (MOV->getOpcode() == X86::MOV32mi) {
459 unsigned PushOpcode = X86::PUSHi32;
460 // If the operand is a small (8-bit) immediate, we can use a
461 // PUSH instruction with a shorter encoding.
462 // Note that isImm() may fail even though this is a MOVmi, because
463 // the operand can also be a symbol.
464 if (PushOp.isImm()) {
465 int64_t Val = PushOp.getImm();
466 if (isInt<8>(Val))
467 PushOpcode = X86::PUSH32i8;
468 }
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000469 BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).addOperand(PushOp);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000470 } else {
471 unsigned int Reg = PushOp.getReg();
472
473 // If PUSHrmm is not slow on this target, try to fold the source of the
474 // push into the instruction.
Eric Christopher4369c9b2015-02-20 08:01:52 +0000475 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000476 bool SlowPUSHrmm = ST.isAtom() || ST.isSLM();
477
478 // Check that this is legal to fold. Right now, we're extremely
479 // conservative about that.
480 MachineInstr *DefMov = nullptr;
481 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000482 MachineInstr *Push =
483 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000484
485 unsigned NumOps = DefMov->getDesc().getNumOperands();
486 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
487 Push->addOperand(DefMov->getOperand(i));
488
489 DefMov->eraseFromParent();
490 } else {
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000491 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r))
492 .addReg(Reg)
493 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000494 }
495 }
496
497 MBB.erase(MOV);
498 }
499
500 // The stack-pointer copy is no longer used in the call sequences.
501 // There should not be any other users, but we can't commit to that, so:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000502 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
503 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000504
505 // Once we've done this, we need to make sure PEI doesn't assume a reserved
506 // frame.
507 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
508 FuncInfo->setHasPushSequences(true);
509
510 return true;
511}
512
513MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
514 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
515 // Do an extremely restricted form of load folding.
516 // ISel will often create patterns like:
517 // movl 4(%edi), %eax
518 // movl 8(%edi), %ecx
519 // movl 12(%edi), %edx
520 // movl %edx, 8(%esp)
521 // movl %ecx, 4(%esp)
522 // movl %eax, (%esp)
523 // call
524 // Get rid of those with prejudice.
525 if (!TargetRegisterInfo::isVirtualRegister(Reg))
526 return nullptr;
527
528 // Make sure this is the only use of Reg.
529 if (!MRI->hasOneNonDBGUse(Reg))
530 return nullptr;
531
532 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
533
534 // Make sure the def is a MOV from memory.
535 // If the def is an another block, give up.
536 if (DefMI->getOpcode() != X86::MOV32rm ||
537 DefMI->getParent() != FrameSetup->getParent())
538 return nullptr;
539
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000540 // Make sure we don't have any instructions between DefMI and the
541 // push that make folding the load illegal.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000542 for (auto I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000543 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000544 return nullptr;
545
546 return DefMI;
547}