blob: b38e2bbe492c2a730a941821aed90129d8426087 [file] [log] [blame]
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001//===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
2//
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
Michael Kuperstein13fbd452015-02-01 16:56:04 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a pass that optimizes call sequences on x86.
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000010// Currently, it converts movs of function parameters onto the stack into
Michael Kuperstein13fbd452015-02-01 16:56:04 +000011// pushes. This is beneficial for two main reasons:
David L Kreitzerd5cb3412016-04-19 17:43:44 +000012// 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
Michael Kuperstein13fbd452015-02-01 16:56:04 +000013// 2) It is possible to push memory arguments directly. So, if the
David L Kreitzer99775c12016-04-12 21:45:09 +000014// the transformation is performed pre-reg-alloc, it can help relieve
Michael Kuperstein13fbd452015-02-01 16:56:04 +000015// register pressure.
16//
17//===----------------------------------------------------------------------===//
18
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000019#include "MCTargetDesc/X86BaseInfo.h"
20#include "X86FrameLowering.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000021#include "X86InstrInfo.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000022#include "X86MachineFunctionInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000023#include "X86RegisterInfo.h"
David L Kreitzer99775c12016-04-12 21:45:09 +000024#include "X86Subtarget.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000031#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000032#include "llvm/CodeGen/MachineInstr.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000034#include "llvm/CodeGen/MachineOperand.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000036#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000038#include "llvm/IR/DebugLoc.h"
Michael Kuperstein13fbd452015-02-01 16:56:04 +000039#include "llvm/IR/Function.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000040#include "llvm/MC/MCDwarf.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/MathExtras.h"
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000044#include <cassert>
45#include <cstddef>
46#include <cstdint>
47#include <iterator>
Michael Kuperstein13fbd452015-02-01 16:56:04 +000048
49using namespace llvm;
50
51#define DEBUG_TYPE "x86-cf-opt"
52
Benjamin Kramer970eac42015-02-06 17:51:54 +000053static cl::opt<bool>
54 NoX86CFOpt("no-x86-call-frame-opt",
55 cl::desc("Avoid optimizing x86 call frames for size"),
56 cl::init(false), cl::Hidden);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000057
58namespace {
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000059
Michael Kuperstein13fbd452015-02-01 16:56:04 +000060class X86CallFrameOptimization : public MachineFunctionPass {
61public:
Zvi Rackoverc6d0b6c2017-10-24 05:47:07 +000062 X86CallFrameOptimization() : MachineFunctionPass(ID) {
63 initializeX86CallFrameOptimizationPass(
64 *PassRegistry::getPassRegistry());
65 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +000066
67 bool runOnMachineFunction(MachineFunction &MF) override;
68
Zvi Rackoverc6d0b6c2017-10-24 05:47:07 +000069 static char ID;
70
Michael Kuperstein13fbd452015-02-01 16:56:04 +000071private:
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000072 // Information we know about a particular call site
73 struct CallContext {
Zvi Rackoverbf31bf72017-10-24 13:24:26 +000074 CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000075
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000076 // Iterator referring to the frame setup instruction
77 MachineBasicBlock::iterator FrameSetup;
78
79 // Actual call instruction
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000080 MachineInstr *Call = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000081
82 // A copy of the stack pointer
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000083 MachineInstr *SPCopy = nullptr;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000084
85 // The total displacement of all passed parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000086 int64_t ExpectedDist = 0;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000087
Zvi Rackoverbf31bf72017-10-24 13:24:26 +000088 // The sequence of storing instructions used to pass the parameters
89 SmallVector<MachineInstr *, 4> ArgStoreVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000090
Michael Kupersteindb95d042015-02-12 08:36:35 +000091 // True if this call site has no stack parameters
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000092 bool NoStackParams = false;
Michael Kupersteindb95d042015-02-12 08:36:35 +000093
David L Kreitzer99775c12016-04-12 21:45:09 +000094 // True if this call site can use push instructions
Eugene Zelenkofbd13c52017-02-02 22:55:55 +000095 bool UsePush = false;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +000096 };
97
Andrew Kaylore2ea93c2015-09-08 18:18:46 +000098 typedef SmallVector<CallContext, 8> ContextVector;
Michael Kupersteindb95d042015-02-12 08:36:35 +000099
100 bool isLegal(MachineFunction &MF);
Michael Kupersteindadb8472015-07-16 13:54:14 +0000101
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000102 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
Michael Kupersteindb95d042015-02-12 08:36:35 +0000103
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000104 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
105 MachineBasicBlock::iterator I, CallContext &Context);
106
Hans Wennborg501e7392016-05-05 16:39:31 +0000107 void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000108
109 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
110 unsigned Reg);
111
Michael Kupersteindadb8472015-07-16 13:54:14 +0000112 enum InstClassification { Convert, Skip, Exit };
113
114 InstClassification classifyInstruction(MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator MI,
116 const X86RegisterInfo &RegInfo,
117 DenseSet<unsigned int> &UsedRegs);
118
Mehdi Amini117296c2016-10-01 02:56:57 +0000119 StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000120
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000121 const X86InstrInfo *TII;
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000122 const X86FrameLowering *TFL;
123 const X86Subtarget *STI;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000124 MachineRegisterInfo *MRI;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000125 unsigned SlotSize;
126 unsigned Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000127};
128
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000129} // end anonymous namespace
Zvi Rackoverc6d0b6c2017-10-24 05:47:07 +0000130char X86CallFrameOptimization::ID = 0;
131INITIALIZE_PASS(X86CallFrameOptimization, DEBUG_TYPE,
132 "X86 Call Frame Optimization", false, false)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000133
Michael Kupersteindadb8472015-07-16 13:54:14 +0000134// This checks whether the transformation is legal.
Michael Kupersteindb95d042015-02-12 08:36:35 +0000135// Also returns false in cases where it's potentially legal, but
136// we don't even want to try.
137bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000138 if (NoX86CFOpt.getValue())
139 return false;
140
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000141 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
142 // in the compact unwind encoding that Darwin uses. So, bail if there
143 // is a danger of that being generated.
David L Kreitzer99775c12016-04-12 21:45:09 +0000144 if (STI->isTargetDarwin() &&
Matthias Braund0ee66c2016-12-01 19:32:15 +0000145 (!MF.getLandingPads().empty() ||
Matthias Braunf1caa282017-12-15 22:22:58 +0000146 (MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
Frederic Riss263b7722015-10-08 15:45:08 +0000147 return false;
148
David L Kreitzer0fe46322016-05-02 13:45:25 +0000149 // It is not valid to change the stack pointer outside the prolog/epilog
150 // on 64-bit Windows.
151 if (STI->isTargetWin64())
152 return false;
153
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000154 // You would expect straight-line code between call-frame setup and
155 // call-frame destroy. You would be wrong. There are circumstances (e.g.
156 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
157 // end up with the setup and the destroy in different basic blocks.
158 // This is bad, and breaks SP adjustment.
159 // So, check that all of the frames in the function are closed inside
160 // the same block, and, for good measure, that there are no nested frames.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000161 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
162 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000163 for (MachineBasicBlock &BB : MF) {
164 bool InsideFrameSequence = false;
165 for (MachineInstr &MI : BB) {
166 if (MI.getOpcode() == FrameSetupOpcode) {
167 if (InsideFrameSequence)
168 return false;
169 InsideFrameSequence = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000170 } else if (MI.getOpcode() == FrameDestroyOpcode) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000171 if (!InsideFrameSequence)
172 return false;
173 InsideFrameSequence = false;
174 }
175 }
176
177 if (InsideFrameSequence)
178 return false;
179 }
180
Michael Kupersteindb95d042015-02-12 08:36:35 +0000181 return true;
182}
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000183
Joerg Sonnenberger772bb5b2016-03-22 22:24:52 +0000184// Check whether this transformation is profitable for a particular
Michael Kupersteindb95d042015-02-12 08:36:35 +0000185// function - in terms of code size.
David L Kreitzer99775c12016-04-12 21:45:09 +0000186bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
187 ContextVector &CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000188 // This transformation is always a win when we do not expect to have
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000189 // a reserved call frame. Under other circumstances, it may be either
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000190 // a win or a loss, and requires a heuristic.
Matthias Braun941a7052016-07-28 18:40:00 +0000191 bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000192 if (CannotReserveFrame)
193 return true;
194
Reid Kleckner938bd6f2015-07-16 01:30:00 +0000195 unsigned StackAlign = TFL->getStackAlignment();
Michael Kupersteindadb8472015-07-16 13:54:14 +0000196
Michael Kupersteindb95d042015-02-12 08:36:35 +0000197 int64_t Advantage = 0;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000198 for (auto CC : CallSeqVector) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000199 // Call sites where no parameters are passed on the stack
200 // do not affect the cost, since there needs to be no
201 // stack adjustment.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000202 if (CC.NoStackParams)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000203 continue;
204
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000205 if (!CC.UsePush) {
Michael Kupersteindb95d042015-02-12 08:36:35 +0000206 // If we don't use pushes for a particular call site,
207 // we pay for not having a reserved call frame with an
208 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
209 // depending on the size of the constant.
210 // TODO: Callee-pop functions should have a smaller penalty, because
211 // an add is needed even with a reserved call frame.
212 Advantage -= 6;
213 } else {
214 // We can use pushes. First, account for the fixed costs.
215 // We'll need a add after the call.
216 Advantage -= 3;
David L Kreitzer0fe46322016-05-02 13:45:25 +0000217 // If we have to realign the stack, we'll also need a sub before
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000218 if (CC.ExpectedDist % StackAlign)
Michael Kupersteindb95d042015-02-12 08:36:35 +0000219 Advantage -= 3;
220 // Now, for each push, we save ~3 bytes. For small constants, we actually,
221 // save more (up to 5 bytes), but 3 should be a good approximation.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000222 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
Michael Kupersteindb95d042015-02-12 08:36:35 +0000223 }
224 }
225
David L Kreitzer99775c12016-04-12 21:45:09 +0000226 return Advantage >= 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000227}
228
229bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000230 STI = &MF.getSubtarget<X86Subtarget>();
231 TII = STI->getInstrInfo();
232 TFL = STI->getFrameLowering();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000233 MRI = &MF.getRegInfo();
234
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000235 const X86RegisterInfo &RegInfo =
236 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
237 SlotSize = RegInfo.getSlotSize();
238 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
239 Log2SlotSize = Log2_32(SlotSize);
240
Matthias Braunf1caa282017-12-15 22:22:58 +0000241 if (skipFunction(MF.getFunction()) || !isLegal(MF))
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000242 return false;
243
Matthias Braunfa3872e2015-05-18 20:27:55 +0000244 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000245
246 bool Changed = false;
247
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000248 ContextVector CallSeqVector;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000249
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000250 for (auto &MBB : MF)
251 for (auto &MI : MBB)
252 if (MI.getOpcode() == FrameSetupOpcode) {
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000253 CallContext Context;
Michael Kuperstein048cc3b2016-03-20 00:16:13 +0000254 collectCallInfo(MF, MBB, MI, Context);
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000255 CallSeqVector.push_back(Context);
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000256 }
257
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000258 if (!isProfitable(MF, CallSeqVector))
Michael Kupersteindb95d042015-02-12 08:36:35 +0000259 return false;
260
Hans Wennborg501e7392016-05-05 16:39:31 +0000261 for (auto CC : CallSeqVector) {
262 if (CC.UsePush) {
263 adjustCallSequence(MF, CC);
264 Changed = true;
265 }
266 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000267
268 return Changed;
269}
270
Michael Kupersteindadb8472015-07-16 13:54:14 +0000271X86CallFrameOptimization::InstClassification
272X86CallFrameOptimization::classifyInstruction(
273 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
274 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
275 if (MI == MBB.end())
276 return Exit;
277
Zvi Rackover31b101a2017-10-24 12:13:05 +0000278 // The instructions we actually care about are movs onto the stack or special
279 // cases of constant-stores to stack
280 switch (MI->getOpcode()) {
281 case X86::AND16mi8:
282 case X86::AND32mi8:
283 case X86::AND64mi8: {
284 MachineOperand ImmOp = MI->getOperand(X86::AddrNumOperands);
285 return ImmOp.getImm() == 0 ? Convert : Exit;
286 }
287 case X86::OR16mi8:
288 case X86::OR32mi8:
289 case X86::OR64mi8: {
290 MachineOperand ImmOp = MI->getOperand(X86::AddrNumOperands);
291 return ImmOp.getImm() == -1 ? Convert : Exit;
292 }
293 case X86::MOV32mi:
294 case X86::MOV32mr:
295 case X86::MOV64mi32:
296 case X86::MOV64mr:
297 return Convert;
298 }
Michael Kupersteindadb8472015-07-16 13:54:14 +0000299
300 // Not all calling conventions have only stack MOVs between the stack
301 // adjust and the call.
302
303 // We want to tolerate other instructions, to cover more cases.
304 // In particular:
305 // a) PCrel calls, where we expect an additional COPY of the basereg.
306 // b) Passing frame-index addresses.
307 // c) Calling conventions that have inreg parameters. These generate
308 // both copies and movs into registers.
309 // To avoid creating lots of special cases, allow any instruction
310 // that does not write into memory, does not def or use the stack
311 // pointer, and does not def any register that was used by a preceding
312 // push.
313 // (Reading from memory is allowed, even if referenced through a
314 // frame index, since these will get adjusted properly in PEI)
315
316 // The reason for the last condition is that the pushes can't replace
317 // the movs in place, because the order must be reversed.
318 // So if we have a MOV32mr that uses EDX, then an instruction that defs
319 // EDX, and then the call, after the transformation the push will use
320 // the modified version of EDX, and not the original one.
321 // Since we are still in SSA form at this point, we only need to
322 // make sure we don't clobber any *physical* registers that were
323 // used by an earlier mov that will become a push.
324
325 if (MI->isCall() || MI->mayStore())
326 return Exit;
327
328 for (const MachineOperand &MO : MI->operands()) {
329 if (!MO.isReg())
330 continue;
331 unsigned int Reg = MO.getReg();
332 if (!RegInfo.isPhysicalRegister(Reg))
333 continue;
334 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
335 return Exit;
336 if (MO.isDef()) {
337 for (unsigned int U : UsedRegs)
338 if (RegInfo.regsOverlap(Reg, U))
339 return Exit;
340 }
341 }
342
343 return Skip;
344}
345
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000346void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
347 MachineBasicBlock &MBB,
348 MachineBasicBlock::iterator I,
349 CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000350 // Check that this particular call sequence is amenable to the
351 // transformation.
David L Kreitzer99775c12016-04-12 21:45:09 +0000352 const X86RegisterInfo &RegInfo =
353 *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000354
355 // We expect to enter this at the beginning of a call sequence
356 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
357 MachineBasicBlock::iterator FrameSetup = I++;
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000358 Context.FrameSetup = FrameSetup;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000359
Michael Kupersteindb95d042015-02-12 08:36:35 +0000360 // How much do we adjust the stack? This puts an upper bound on
361 // the number of parameters actually passed on it.
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000362 unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
Michael Kupersteindadb8472015-07-16 13:54:14 +0000363
Michael Kupersteindb95d042015-02-12 08:36:35 +0000364 // A zero adjustment means no stack parameters
365 if (!MaxAdjust) {
366 Context.NoStackParams = true;
367 return;
368 }
369
Michael Kuperstein5842b202016-12-07 19:31:08 +0000370 // Skip over DEBUG_VALUE.
371 // For globals in PIC mode, we can have some LEAs here. Skip them as well.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000372 // TODO: Extend this to something that covers more cases.
Shiva Chen801bf7e2018-05-09 02:42:00 +0000373 while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000374 ++I;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000375
Nico Webereb9488b2016-07-13 21:38:27 +0000376 unsigned StackPtr = RegInfo.getStackRegister();
Zvi Rackover3c0d3852017-10-24 07:38:29 +0000377 auto StackPtrCopyInst = MBB.end();
Nico Webereb9488b2016-07-13 21:38:27 +0000378 // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
Zvi Rackover3c0d3852017-10-24 07:38:29 +0000379 // register. If it's there, use that virtual register as stack pointer
380 // instead. Also, we need to locate this instruction so that we can later
381 // safely ignore it while doing the conservative processing of the call chain.
382 // The COPY can be located anywhere between the call-frame setup
383 // instruction and its first use. We use the call instruction as a boundary
384 // because it is usually cheaper to check if an instruction is a call than
385 // checking if an instruction uses a register.
386 for (auto J = I; !J->isCall(); ++J)
387 if (J->isCopy() && J->getOperand(0).isReg() && J->getOperand(1).isReg() &&
388 J->getOperand(1).getReg() == StackPtr) {
389 StackPtrCopyInst = J;
390 Context.SPCopy = &*J++;
391 StackPtr = Context.SPCopy->getOperand(0).getReg();
392 break;
393 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000394
395 // Scan the call setup sequence for the pattern we're looking for.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000396 // We only handle a simple case - a sequence of store instructions that
397 // push a sequence of stack-slot-aligned values onto the stack, with
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000398 // no gaps between them.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000399 if (MaxAdjust > 4)
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000400 Context.ArgStoreVector.resize(MaxAdjust, nullptr);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000401
Michael Kupersteindadb8472015-07-16 13:54:14 +0000402 DenseSet<unsigned int> UsedRegs;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000403
Zvi Rackover3c0d3852017-10-24 07:38:29 +0000404 for (InstClassification Classification = Skip; Classification != Exit; ++I) {
405 // If this is the COPY of the stack pointer, it's ok to ignore.
406 if (I == StackPtrCopyInst)
Michael Kupersteindadb8472015-07-16 13:54:14 +0000407 continue;
Zvi Rackover3c0d3852017-10-24 07:38:29 +0000408 Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs);
409 if (Classification != Convert)
410 continue;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000411 // We know the instruction has a supported store opcode.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000412 // We only want movs of the form:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000413 // mov imm/reg, k(%StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000414 // If we run into something else, bail.
415 // Note that AddrBaseReg may, counter to its name, not be a register,
416 // but rather a frame index.
417 // TODO: Support the fi case. This should probably work now that we
418 // have the infrastructure to track the stack pointer within a call
419 // sequence.
420 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
421 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
422 !I->getOperand(X86::AddrScaleAmt).isImm() ||
423 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
424 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
425 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
426 !I->getOperand(X86::AddrDisp).isImm())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000427 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000428
429 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000430 assert(StackDisp >= 0 &&
431 "Negative stack displacement when passing parameters");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000432
433 // We really don't want to consider the unaligned case.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000434 if (StackDisp & (SlotSize - 1))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000435 return;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000436 StackDisp >>= Log2SlotSize;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000437
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000438 assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000439 "Function call has more parameters than the stack is adjusted for.");
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000440
441 // If the same stack slot is being filled twice, something's fishy.
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000442 if (Context.ArgStoreVector[StackDisp] != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000443 return;
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000444 Context.ArgStoreVector[StackDisp] = &*I;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000445
Michael Kupersteindadb8472015-07-16 13:54:14 +0000446 for (const MachineOperand &MO : I->uses()) {
447 if (!MO.isReg())
448 continue;
449 unsigned int Reg = MO.getReg();
450 if (RegInfo.isPhysicalRegister(Reg))
451 UsedRegs.insert(Reg);
452 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000453 }
454
Zvi Rackover3c0d3852017-10-24 07:38:29 +0000455 --I;
456
Michael Kupersteindadb8472015-07-16 13:54:14 +0000457 // We now expect the end of the sequence. If we stopped early,
458 // or reached the end of the block without finding a call, bail.
459 if (I == MBB.end() || !I->isCall())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000460 return;
461
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000462 Context.Call = &*I;
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000463 if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000464 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000465
466 // Now, go through the vector, and see that we don't have any gaps,
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000467 // but only a series of storing instructions.
468 auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000469 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000470 if (*MMI == nullptr)
471 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000472
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000473 // If the call had no parameters, do nothing
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000474 if (MMI == Context.ArgStoreVector.begin())
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000475 return;
476
477 // We are either at the last parameter, or a gap.
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000478 // Make sure it's not a gap
479 for (; MMI != MME; ++MMI)
480 if (*MMI != nullptr)
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000481 return;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000482
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000483 Context.UsePush = true;
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000484}
485
Hans Wennborg501e7392016-05-05 16:39:31 +0000486void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000487 const CallContext &Context) {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000488 // Ok, we can in fact do the transformation for this call.
489 // Do not remove the FrameSetup instruction, but adjust the parameters.
490 // PEI will end up finalizing the handling of this.
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000491 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
492 MachineBasicBlock &MBB = *(FrameSetup->getParent());
Serge Pavlov49acf9c2017-04-13 14:10:52 +0000493 TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000494
Andrew Kaylore2ea93c2015-09-08 18:18:46 +0000495 DebugLoc DL = FrameSetup->getDebugLoc();
David L Kreitzer0fe46322016-05-02 13:45:25 +0000496 bool Is64Bit = STI->is64Bit();
Zvi Rackover31b101a2017-10-24 12:13:05 +0000497 // Now, iterate through the vector in reverse order, and replace the store to
498 // stack with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000499 // replace uses.
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000500 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000501 MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
502 MachineOperand PushOp = Store->getOperand(X86::AddrNumOperands);
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000503 MachineBasicBlock::iterator Push = nullptr;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000504 unsigned PushOpcode;
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000505 switch (Store->getOpcode()) {
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000506 default:
507 llvm_unreachable("Unexpected Opcode!");
Zvi Rackover31b101a2017-10-24 12:13:05 +0000508 case X86::AND16mi8:
509 case X86::AND32mi8:
510 case X86::AND64mi8:
511 case X86::OR16mi8:
512 case X86::OR32mi8:
513 case X86::OR64mi8:
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000514 case X86::MOV32mi:
David L Kreitzer0fe46322016-05-02 13:45:25 +0000515 case X86::MOV64mi32:
516 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSHi32;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000517 // If the operand is a small (8-bit) immediate, we can use a
518 // PUSH instruction with a shorter encoding.
519 // Note that isImm() may fail even though this is a MOVmi, because
520 // the operand can also be a symbol.
521 if (PushOp.isImm()) {
522 int64_t Val = PushOp.getImm();
523 if (isInt<8>(Val))
David L Kreitzer0fe46322016-05-02 13:45:25 +0000524 PushOpcode = Is64Bit ? X86::PUSH64i8 : X86::PUSH32i8;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000525 }
Diana Picus116bbab2017-01-13 09:58:52 +0000526 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000527 break;
528 case X86::MOV32mr:
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000529 case X86::MOV64mr: {
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000530 unsigned int Reg = PushOp.getReg();
531
David L Kreitzer0fe46322016-05-02 13:45:25 +0000532 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
533 // in preparation for the PUSH64. The upper 32 bits can be undef.
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000534 if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000535 unsigned UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
536 Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
537 BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
538 BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
Diana Picus116bbab2017-01-13 09:58:52 +0000539 .addReg(UndefReg)
540 .add(PushOp)
541 .addImm(X86::sub_32bit);
David L Kreitzer0fe46322016-05-02 13:45:25 +0000542 }
543
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000544 // If PUSHrmm is not slow on this target, try to fold the source of the
545 // push into the instruction.
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000546 bool SlowPUSHrmm = STI->isAtom() || STI->isSLM();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000547
548 // Check that this is legal to fold. Right now, we're extremely
549 // conservative about that.
550 MachineInstr *DefMov = nullptr;
551 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000552 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000553 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000554
555 unsigned NumOps = DefMov->getDesc().getNumOperands();
556 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
557 Push->addOperand(DefMov->getOperand(i));
558
559 DefMov->eraseFromParent();
560 } else {
David L Kreitzer0fe46322016-05-02 13:45:25 +0000561 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000562 Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
David L Kreitzer99775c12016-04-12 21:45:09 +0000563 .addReg(Reg)
564 .getInstr();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000565 }
David L Kreitzerd5cb3412016-04-19 17:43:44 +0000566 break;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000567 }
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000568 }
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000569
Michael Kuperstein73dc8522015-11-03 08:17:25 +0000570 // For debugging, when using SP-based CFA, we need to adjust the CFA
571 // offset after each push.
Michael Kuperstein77ce9d32015-12-06 13:06:20 +0000572 // TODO: This is needed only if we require precise CFA.
Daniel Jasper559aa752017-06-29 13:58:24 +0000573 if (!TFL->hasFP(MF))
574 TFL->BuildCFI(
575 MBB, std::next(Push), DL,
576 MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
577
Zvi Rackoverbf31bf72017-10-24 13:24:26 +0000578 MBB.erase(Store);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000579 }
580
581 // The stack-pointer copy is no longer used in the call sequences.
582 // There should not be any other users, but we can't commit to that, so:
Nico Webereb9488b2016-07-13 21:38:27 +0000583 if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
Michael Kuperstein1921d3d2015-02-11 08:53:55 +0000584 Context.SPCopy->eraseFromParent();
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000585
586 // Once we've done this, we need to make sure PEI doesn't assume a reserved
587 // frame.
588 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
589 FuncInfo->setHasPushSequences(true);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000590}
591
592MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
593 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
594 // Do an extremely restricted form of load folding.
595 // ISel will often create patterns like:
596 // movl 4(%edi), %eax
597 // movl 8(%edi), %ecx
598 // movl 12(%edi), %edx
599 // movl %edx, 8(%esp)
600 // movl %ecx, 4(%esp)
601 // movl %eax, (%esp)
602 // call
603 // Get rid of those with prejudice.
604 if (!TargetRegisterInfo::isVirtualRegister(Reg))
605 return nullptr;
606
607 // Make sure this is the only use of Reg.
608 if (!MRI->hasOneNonDBGUse(Reg))
609 return nullptr;
610
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000611 MachineInstr &DefMI = *MRI->getVRegDef(Reg);
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000612
613 // Make sure the def is a MOV from memory.
David L Kreitzer29711c02016-06-30 21:43:11 +0000614 // If the def is in another block, give up.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000615 if ((DefMI.getOpcode() != X86::MOV32rm &&
616 DefMI.getOpcode() != X86::MOV64rm) ||
617 DefMI.getParent() != FrameSetup->getParent())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000618 return nullptr;
619
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000620 // Make sure we don't have any instructions between DefMI and the
621 // push that make folding the load illegal.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000622 for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +0000623 if (I->isLoadFoldBarrier())
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000624 return nullptr;
625
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000626 return &DefMI;
Michael Kuperstein13fbd452015-02-01 16:56:04 +0000627}
Eugene Zelenkofbd13c52017-02-02 22:55:55 +0000628
629FunctionPass *llvm::createX86CallFrameOptimization() {
630 return new X86CallFrameOptimization();
631}