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