1//===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a pass that optimizes call sequences on x86.
10// Currently, it converts movs of function parameters onto the stack into
11// pushes. This is beneficial for two main reasons:
12// 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
13// 2) It is possible to push memory arguments directly. So, if the
14// the transformation is performed pre-reg-alloc, it can help relieve
15// register pressure.
16//
17//===----------------------------------------------------------------------===//
18
19#include "MCTargetDesc/X86BaseInfo.h"
20#include "X86.h"
21#include "X86FrameLowering.h"
22#include "X86InstrInfo.h"
23#include "X86MachineFunctionInfo.h"
24#include "X86RegisterInfo.h"
25#include "X86Subtarget.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstr.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/TargetInstrInfo.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Function.h"
41#include "llvm/MC/MCDwarf.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MathExtras.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <iterator>
49
50using namespace llvm;
51
52#define DEBUG_TYPE "x86-cf-opt"
53
54static cl::opt<bool>
55 NoX86CFOpt("no-x86-call-frame-opt",
56 cl::desc("Avoid optimizing x86 call frames for size"),
57 cl::init(Val: false), cl::Hidden);
58
59namespace {
60
61class X86CallFrameOptimizationImpl {
62public:
63 bool runOnMachineFunction(MachineFunction &MF);
64
65private:
66 // Information we know about a particular call site
67 struct CallContext {
68 CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
69
70 // Iterator referring to the frame setup instruction
71 MachineBasicBlock::iterator FrameSetup;
72
73 // Actual call instruction
74 MachineInstr *Call = nullptr;
75
76 // A copy of the stack pointer
77 MachineInstr *SPCopy = nullptr;
78
79 // The total displacement of all passed parameters
80 int64_t ExpectedDist = 0;
81
82 // The sequence of storing instructions used to pass the parameters
83 SmallVector<MachineInstr *, 4> ArgStoreVector;
84
85 // True if this call site has no stack parameters
86 bool NoStackParams = false;
87
88 // True if this call site can use push instructions
89 bool UsePush = false;
90 };
91
92 typedef SmallVector<CallContext, 8> ContextVector;
93
94 bool isLegal(MachineFunction &MF);
95
96 bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
97
98 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
99 MachineBasicBlock::iterator I, CallContext &Context);
100
101 void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
102
103 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
104 Register Reg);
105
106 enum InstClassification { Convert, Skip, Exit };
107
108 InstClassification classifyInstruction(MachineBasicBlock &MBB,
109 MachineBasicBlock::iterator MI,
110 const X86RegisterInfo &RegInfo,
111 const DenseSet<MCRegister> &UsedRegs);
112
113 const X86InstrInfo *TII = nullptr;
114 const X86FrameLowering *TFL = nullptr;
115 const X86Subtarget *STI = nullptr;
116 MachineRegisterInfo *MRI = nullptr;
117 unsigned SlotSize = 0;
118 unsigned Log2SlotSize = 0;
119};
120
121class X86CallFrameOptimizationLegacy : public MachineFunctionPass {
122public:
123 X86CallFrameOptimizationLegacy() : MachineFunctionPass(ID) {}
124
125 bool runOnMachineFunction(MachineFunction &MF) override;
126
127 static char ID;
128
129private:
130 StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
131};
132
133} // end anonymous namespace
134char X86CallFrameOptimizationLegacy::ID = 0;
135INITIALIZE_PASS(X86CallFrameOptimizationLegacy, DEBUG_TYPE,
136 "X86 Call Frame Optimization", false, false)
137
138// This checks whether the transformation is legal.
139// Also returns false in cases where it's potentially legal, but
140// we don't even want to try.
141bool X86CallFrameOptimizationImpl::isLegal(MachineFunction &MF) {
142 if (NoX86CFOpt.getValue())
143 return false;
144
145 // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
146 // in the compact unwind encoding that Darwin uses. So, bail if there
147 // is a danger of that being generated.
148 if (STI->isTargetDarwin() &&
149 (!MF.getLandingPads().empty() ||
150 (MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
151 return false;
152
153 // It is not valid to change the stack pointer outside the prolog/epilog
154 // on 64-bit Windows.
155 if (STI->isTargetWin64())
156 return false;
157
158 // You would expect straight-line code between call-frame setup and
159 // call-frame destroy. You would be wrong. There are circumstances (e.g.
160 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
161 // end up with the setup and the destroy in different basic blocks.
162 // This is bad, and breaks SP adjustment.
163 // So, check that all of the frames in the function are closed inside
164 // the same block, and, for good measure, that there are no nested frames.
165 //
166 // If any call allocates more argument stack memory than the stack
167 // probe size, don't do this optimization. Otherwise, this pass
168 // would need to synthesize additional stack probe calls to allocate
169 // memory for arguments.
170 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
171 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
172 bool EmitStackProbeCall = STI->getTargetLowering()->hasStackProbeSymbol(MF);
173 unsigned StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
174 for (MachineBasicBlock &BB : MF) {
175 bool InsideFrameSequence = false;
176 for (MachineInstr &MI : BB) {
177 if (MI.getOpcode() == FrameSetupOpcode) {
178 if (TII->getFrameSize(I: MI) >= StackProbeSize && EmitStackProbeCall)
179 return false;
180 if (InsideFrameSequence)
181 return false;
182 InsideFrameSequence = true;
183 } else if (MI.getOpcode() == FrameDestroyOpcode) {
184 if (!InsideFrameSequence)
185 return false;
186 InsideFrameSequence = false;
187 }
188 }
189
190 if (InsideFrameSequence)
191 return false;
192 }
193
194 return true;
195}
196
197// Check whether this transformation is profitable for a particular
198// function - in terms of code size.
199bool X86CallFrameOptimizationImpl::isProfitable(MachineFunction &MF,
200 ContextVector &CallSeqVector) {
201 // This transformation is always a win when we do not expect to have
202 // a reserved call frame. Under other circumstances, it may be either
203 // a win or a loss, and requires a heuristic.
204 bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
205 if (CannotReserveFrame)
206 return true;
207
208 Align StackAlign = TFL->getStackAlign();
209
210 int64_t Advantage = 0;
211 for (const auto &CC : CallSeqVector) {
212 // Call sites where no parameters are passed on the stack
213 // do not affect the cost, since there needs to be no
214 // stack adjustment.
215 if (CC.NoStackParams)
216 continue;
217
218 if (!CC.UsePush) {
219 // If we don't use pushes for a particular call site,
220 // we pay for not having a reserved call frame with an
221 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
222 // depending on the size of the constant.
223 // TODO: Callee-pop functions should have a smaller penalty, because
224 // an add is needed even with a reserved call frame.
225 Advantage -= 6;
226 } else {
227 // We can use pushes. First, account for the fixed costs.
228 // We'll need a add after the call.
229 Advantage -= 3;
230 // If we have to realign the stack, we'll also need a sub before
231 if (!isAligned(Lhs: StackAlign, SizeInBytes: CC.ExpectedDist))
232 Advantage -= 3;
233 // Now, for each push, we save ~3 bytes. For small constants, we actually,
234 // save more (up to 5 bytes), but 3 should be a good approximation.
235 Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
236 }
237 }
238
239 return Advantage >= 0;
240}
241
242bool X86CallFrameOptimizationImpl::runOnMachineFunction(MachineFunction &MF) {
243 STI = &MF.getSubtarget<X86Subtarget>();
244 TII = STI->getInstrInfo();
245 TFL = STI->getFrameLowering();
246 MRI = &MF.getRegInfo();
247
248 const X86RegisterInfo &RegInfo = *STI->getRegisterInfo();
249 SlotSize = RegInfo.getSlotSize();
250 assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
251 Log2SlotSize = Log2_32(Value: SlotSize);
252
253 if (!isLegal(MF))
254 return false;
255
256 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
257
258 bool Changed = false;
259
260 ContextVector CallSeqVector;
261
262 for (auto &MBB : MF)
263 for (auto &MI : MBB)
264 if (MI.getOpcode() == FrameSetupOpcode) {
265 CallContext Context;
266 collectCallInfo(MF, MBB, I: MI, Context);
267 CallSeqVector.push_back(Elt: Context);
268 }
269
270 if (!isProfitable(MF, CallSeqVector))
271 return false;
272
273 for (const auto &CC : CallSeqVector) {
274 if (CC.UsePush) {
275 adjustCallSequence(MF, Context: CC);
276 Changed = true;
277 }
278 }
279
280 return Changed;
281}
282
283X86CallFrameOptimizationImpl::InstClassification
284X86CallFrameOptimizationImpl::classifyInstruction(
285 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
286 const X86RegisterInfo &RegInfo, const DenseSet<MCRegister> &UsedRegs) {
287 if (MI == MBB.end())
288 return Exit;
289
290 // The instructions we actually care about are movs onto the stack or special
291 // cases of constant-stores to stack
292 switch (MI->getOpcode()) {
293 case X86::AND16mi:
294 case X86::AND32mi:
295 case X86::AND64mi32: {
296 const MachineOperand &ImmOp = MI->getOperand(i: X86::AddrNumOperands);
297 return ImmOp.getImm() == 0 ? Convert : Exit;
298 }
299 case X86::OR16mi:
300 case X86::OR32mi:
301 case X86::OR64mi32: {
302 const MachineOperand &ImmOp = MI->getOperand(i: X86::AddrNumOperands);
303 return ImmOp.getImm() == -1 ? Convert : Exit;
304 }
305 case X86::MOV32mi:
306 case X86::MOV32mr:
307 case X86::MOV64mi32:
308 case X86::MOV64mr:
309 return Convert;
310 }
311
312 // Not all calling conventions have only stack MOVs between the stack
313 // adjust and the call.
314
315 // We want to tolerate other instructions, to cover more cases.
316 // In particular:
317 // a) PCrel calls, where we expect an additional COPY of the basereg.
318 // b) Passing frame-index addresses.
319 // c) Calling conventions that have inreg parameters. These generate
320 // both copies and movs into registers.
321 // To avoid creating lots of special cases, allow any instruction
322 // that does not write into memory, does not def or use the stack
323 // pointer, and does not def any register that was used by a preceding
324 // push.
325 // (Reading from memory is allowed, even if referenced through a
326 // frame index, since these will get adjusted properly in PEI)
327
328 // The reason for the last condition is that the pushes can't replace
329 // the movs in place, because the order must be reversed.
330 // So if we have a MOV32mr that uses EDX, then an instruction that defs
331 // EDX, and then the call, after the transformation the push will use
332 // the modified version of EDX, and not the original one.
333 // Since we are still in SSA form at this point, we only need to
334 // make sure we don't clobber any *physical* registers that were
335 // used by an earlier mov that will become a push.
336
337 if (MI->isCall() || MI->mayStore())
338 return Exit;
339
340 for (const MachineOperand &MO : MI->operands()) {
341 if (!MO.isReg())
342 continue;
343 Register Reg = MO.getReg();
344 if (!Reg.isPhysical())
345 continue;
346 if (RegInfo.regsOverlap(RegA: Reg, RegB: RegInfo.getStackRegister()))
347 return Exit;
348 if (MO.isDef()) {
349 for (MCRegister U : UsedRegs)
350 if (RegInfo.regsOverlap(RegA: Reg, RegB: U))
351 return Exit;
352 }
353 }
354
355 return Skip;
356}
357
358void X86CallFrameOptimizationImpl::collectCallInfo(
359 MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
360 CallContext &Context) {
361 // Check that this particular call sequence is amenable to the
362 // transformation.
363 const X86RegisterInfo &RegInfo = *STI->getRegisterInfo();
364
365 // We expect to enter this at the beginning of a call sequence
366 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
367 MachineBasicBlock::iterator FrameSetup = I++;
368 Context.FrameSetup = FrameSetup;
369
370 // How much do we adjust the stack? This puts an upper bound on
371 // the number of parameters actually passed on it.
372 unsigned int MaxAdjust = TII->getFrameSize(I: *FrameSetup) >> Log2SlotSize;
373
374 // A zero adjustment means no stack parameters
375 if (!MaxAdjust) {
376 Context.NoStackParams = true;
377 return;
378 }
379
380 // Skip over DEBUG_VALUE.
381 // For globals in PIC mode, we can have some LEAs here. Skip them as well.
382 // TODO: Extend this to something that covers more cases.
383 while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
384 ++I;
385
386 Register StackPtr = RegInfo.getStackRegister();
387 auto StackPtrCopyInst = MBB.end();
388 // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
389 // register. If it's there, use that virtual register as stack pointer
390 // instead. Also, we need to locate this instruction so that we can later
391 // safely ignore it while doing the conservative processing of the call chain.
392 // The COPY can be located anywhere between the call-frame setup
393 // instruction and its first use. We use the call instruction as a boundary
394 // because it is usually cheaper to check if an instruction is a call than
395 // checking if an instruction uses a register.
396 for (auto J = I; !J->isCall(); ++J)
397 if (J->isCopy() && J->getOperand(i: 0).isReg() && J->getOperand(i: 1).isReg() &&
398 J->getOperand(i: 1).getReg() == StackPtr) {
399 StackPtrCopyInst = J;
400 Context.SPCopy = &*J++;
401 StackPtr = Context.SPCopy->getOperand(i: 0).getReg();
402 break;
403 }
404
405 // Scan the call setup sequence for the pattern we're looking for.
406 // We only handle a simple case - a sequence of store instructions that
407 // push a sequence of stack-slot-aligned values onto the stack, with
408 // no gaps between them.
409 if (MaxAdjust > 4)
410 Context.ArgStoreVector.resize(N: MaxAdjust, NV: nullptr);
411
412 DenseSet<MCRegister> UsedRegs;
413
414 for (InstClassification Classification = Skip; Classification != Exit; ++I) {
415 // If this is the COPY of the stack pointer, it's ok to ignore.
416 if (I == StackPtrCopyInst)
417 continue;
418 Classification = classifyInstruction(MBB, MI: I, RegInfo, UsedRegs);
419 if (Classification != Convert)
420 continue;
421 // We know the instruction has a supported store opcode.
422 // We only want movs of the form:
423 // mov imm/reg, k(%StackPtr)
424 // If we run into something else, bail.
425 // Note that AddrBaseReg may, counter to its name, not be a register,
426 // but rather a frame index.
427 // TODO: Support the fi case. This should probably work now that we
428 // have the infrastructure to track the stack pointer within a call
429 // sequence.
430 if (!I->getOperand(i: X86::AddrBaseReg).isReg() ||
431 (I->getOperand(i: X86::AddrBaseReg).getReg() != StackPtr) ||
432 !I->getOperand(i: X86::AddrScaleAmt).isImm() ||
433 (I->getOperand(i: X86::AddrScaleAmt).getImm() != 1) ||
434 (I->getOperand(i: X86::AddrIndexReg).getReg() != X86::NoRegister) ||
435 (I->getOperand(i: X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
436 !I->getOperand(i: X86::AddrDisp).isImm())
437 return;
438
439 int64_t StackDisp = I->getOperand(i: X86::AddrDisp).getImm();
440 assert(StackDisp >= 0 &&
441 "Negative stack displacement when passing parameters");
442
443 // We really don't want to consider the unaligned case.
444 if (StackDisp & (SlotSize - 1))
445 return;
446 StackDisp >>= Log2SlotSize;
447
448 assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
449 "Function call has more parameters than the stack is adjusted for.");
450
451 // If the same stack slot is being filled twice, something's fishy.
452 if (Context.ArgStoreVector[StackDisp] != nullptr)
453 return;
454 Context.ArgStoreVector[StackDisp] = &*I;
455
456 for (const MachineOperand &MO : I->uses()) {
457 if (!MO.isReg())
458 continue;
459 Register Reg = MO.getReg();
460 if (Reg.isPhysical())
461 UsedRegs.insert(V: Reg.asMCReg());
462 }
463 }
464
465 --I;
466
467 // We now expect the end of the sequence. If we stopped early,
468 // or reached the end of the block without finding a call, bail.
469 if (I == MBB.end() || !I->isCall())
470 return;
471
472 Context.Call = &*I;
473 if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
474 return;
475
476 // Now, go through the vector, and see that we don't have any gaps,
477 // but only a series of storing instructions.
478 auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
479 for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
480 if (*MMI == nullptr)
481 break;
482
483 // If the call had no parameters, do nothing
484 if (MMI == Context.ArgStoreVector.begin())
485 return;
486
487 // We are either at the last parameter, or a gap.
488 // Make sure it's not a gap
489 for (; MMI != MME; ++MMI)
490 if (*MMI != nullptr)
491 return;
492
493 Context.UsePush = true;
494}
495
496void X86CallFrameOptimizationImpl::adjustCallSequence(
497 MachineFunction &MF, const CallContext &Context) {
498 // Ok, we can in fact do the transformation for this call.
499 // Do not remove the FrameSetup instruction, but adjust the parameters.
500 // PEI will end up finalizing the handling of this.
501 MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
502 MachineBasicBlock &MBB = *(FrameSetup->getParent());
503 TII->setFrameAdjustment(I&: *FrameSetup, V: Context.ExpectedDist);
504
505 const DebugLoc &DL = FrameSetup->getDebugLoc();
506 bool Is64Bit = STI->is64Bit();
507 // Now, iterate through the vector in reverse order, and replace the store to
508 // stack with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
509 // replace uses.
510 for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
511 MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
512 const MachineOperand &PushOp = Store->getOperand(i: X86::AddrNumOperands);
513 MachineBasicBlock::iterator Push = nullptr;
514 unsigned PushOpcode;
515 switch (Store->getOpcode()) {
516 default:
517 llvm_unreachable("Unexpected Opcode!");
518 case X86::AND16mi:
519 case X86::AND32mi:
520 case X86::AND64mi32:
521 case X86::OR16mi:
522 case X86::OR32mi:
523 case X86::OR64mi32:
524 case X86::MOV32mi:
525 case X86::MOV64mi32:
526 PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSH32i;
527 Push = BuildMI(BB&: MBB, I: Context.Call, MIMD: DL, MCID: TII->get(Opcode: PushOpcode)).add(MO: PushOp);
528 Push->cloneMemRefs(MF, MI: *Store);
529 break;
530 case X86::MOV32mr:
531 case X86::MOV64mr: {
532 Register Reg = PushOp.getReg();
533
534 // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
535 // in preparation for the PUSH64. The upper 32 bits can be undef.
536 if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
537 Register UndefReg = MRI->createVirtualRegister(RegClass: &X86::GR64RegClass);
538 Reg = MRI->createVirtualRegister(RegClass: &X86::GR64RegClass);
539 BuildMI(BB&: MBB, I: Context.Call, MIMD: DL, MCID: TII->get(Opcode: X86::IMPLICIT_DEF), DestReg: UndefReg);
540 BuildMI(BB&: MBB, I: Context.Call, MIMD: DL, MCID: TII->get(Opcode: X86::INSERT_SUBREG), DestReg: Reg)
541 .addReg(RegNo: UndefReg)
542 .add(MO: PushOp)
543 .addImm(Val: X86::sub_32bit);
544 }
545
546 // If PUSHrmm is not slow on this target, try to fold the source of the
547 // push into the instruction.
548 bool SlowPUSHrmm = STI->slowTwoMemOps();
549
550 // Check that this is legal to fold. Right now, we're extremely
551 // conservative about that.
552 MachineInstr *DefMov = nullptr;
553 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
554 PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
555 Push = BuildMI(BB&: MBB, I: Context.Call, MIMD: DL, MCID: TII->get(Opcode: PushOpcode));
556
557 unsigned NumOps = DefMov->getDesc().getNumOperands();
558 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
559 Push->addOperand(Op: DefMov->getOperand(i));
560 Push->cloneMergedMemRefs(MF, MIs: {DefMov, &*Store});
561 DefMov->eraseFromParent();
562 } else {
563 PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
564 Push = BuildMI(BB&: MBB, I: Context.Call, MIMD: DL, MCID: TII->get(Opcode: PushOpcode))
565 .addReg(RegNo: Reg)
566 .getInstr();
567 Push->cloneMemRefs(MF, MI: *Store);
568 }
569 break;
570 }
571 }
572
573 // For debugging, when using SP-based CFA, we need to adjust the CFA
574 // offset after each push.
575 // TODO: This is needed only if we require precise CFA.
576 if (!TFL->hasFP(MF))
577 TFL->BuildCFI(
578 MBB, MBBI: std::next(x: Push), DL,
579 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: SlotSize));
580
581 MBB.erase(I: Store);
582 }
583
584 // The stack-pointer copy is no longer used in the call sequences.
585 // There should not be any other users, but we can't commit to that, so:
586 if (Context.SPCopy && MRI->use_empty(RegNo: Context.SPCopy->getOperand(i: 0).getReg()))
587 Context.SPCopy->eraseFromParent();
588
589 // Once we've done this, we need to make sure PEI doesn't assume a reserved
590 // frame.
591 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
592 FuncInfo->setHasPushSequences(true);
593}
594
595MachineInstr *X86CallFrameOptimizationImpl::canFoldIntoRegPush(
596 MachineBasicBlock::iterator FrameSetup, Register Reg) {
597 // Do an extremely restricted form of load folding.
598 // ISel will often create patterns like:
599 // movl 4(%edi), %eax
600 // movl 8(%edi), %ecx
601 // movl 12(%edi), %edx
602 // movl %edx, 8(%esp)
603 // movl %ecx, 4(%esp)
604 // movl %eax, (%esp)
605 // call
606 // Get rid of those with prejudice.
607 if (!Reg.isVirtual())
608 return nullptr;
609
610 // Make sure this is the only use of Reg.
611 if (!MRI->hasOneNonDBGUse(RegNo: Reg))
612 return nullptr;
613
614 MachineInstr &DefMI = *MRI->getVRegDef(Reg);
615
616 // Make sure the def is a MOV from memory.
617 // If the def is in another block, give up.
618 if ((DefMI.getOpcode() != X86::MOV32rm &&
619 DefMI.getOpcode() != X86::MOV64rm) ||
620 DefMI.getParent() != FrameSetup->getParent())
621 return nullptr;
622
623 // Make sure we don't have any instructions between DefMI and the
624 // push that make folding the load illegal.
625 for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
626 if (I->isLoadFoldBarrier())
627 return nullptr;
628
629 return &DefMI;
630}
631
632FunctionPass *llvm::createX86CallFrameOptimizationLegacyPass() {
633 return new X86CallFrameOptimizationLegacy();
634}
635
636bool X86CallFrameOptimizationLegacy::runOnMachineFunction(MachineFunction &MF) {
637 if (skipFunction(F: MF.getFunction()))
638 return false;
639 X86CallFrameOptimizationImpl Impl;
640 return Impl.runOnMachineFunction(MF);
641}
642
643PreservedAnalyses
644X86CallFrameOptimizationPass::run(MachineFunction &MF,
645 MachineFunctionAnalysisManager &MFAM) {
646 X86CallFrameOptimizationImpl Impl;
647 bool Changed = Impl.runOnMachineFunction(MF);
648 return Changed ? getMachineFunctionPassPreservedAnalyses()
649 : PreservedAnalyses::all();
650}
651