xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/X86/X86CallFrameOptimization.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines a pass that optimizes call sequences on x86.
100b57cec5SDimitry Andric // Currently, it converts movs of function parameters onto the stack into
110b57cec5SDimitry Andric // pushes. This is beneficial for two main reasons:
120b57cec5SDimitry Andric // 1) The push instruction encoding is much smaller than a stack-ptr-based mov.
130b57cec5SDimitry Andric // 2) It is possible to push memory arguments directly. So, if the
140b57cec5SDimitry Andric //    the transformation is performed pre-reg-alloc, it can help relieve
150b57cec5SDimitry Andric //    register pressure.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #include "MCTargetDesc/X86BaseInfo.h"
205ffd83dbSDimitry Andric #include "X86.h"
210b57cec5SDimitry Andric #include "X86FrameLowering.h"
220b57cec5SDimitry Andric #include "X86InstrInfo.h"
230b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h"
240b57cec5SDimitry Andric #include "X86RegisterInfo.h"
250b57cec5SDimitry Andric #include "X86Subtarget.h"
260b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
270b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
280b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
400b57cec5SDimitry Andric #include "llvm/IR/Function.h"
410b57cec5SDimitry Andric #include "llvm/MC/MCDwarf.h"
420b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
430b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
440b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
450b57cec5SDimitry Andric #include <cassert>
460b57cec5SDimitry Andric #include <cstddef>
470b57cec5SDimitry Andric #include <cstdint>
480b57cec5SDimitry Andric #include <iterator>
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric using namespace llvm;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric #define DEBUG_TYPE "x86-cf-opt"
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric static cl::opt<bool>
550b57cec5SDimitry Andric     NoX86CFOpt("no-x86-call-frame-opt",
560b57cec5SDimitry Andric                cl::desc("Avoid optimizing x86 call frames for size"),
570b57cec5SDimitry Andric                cl::init(false), cl::Hidden);
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric namespace {
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric class X86CallFrameOptimization : public MachineFunctionPass {
620b57cec5SDimitry Andric public:
X86CallFrameOptimization()630b57cec5SDimitry Andric   X86CallFrameOptimization() : MachineFunctionPass(ID) { }
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric   static char ID;
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric private:
700b57cec5SDimitry Andric   // Information we know about a particular call site
710b57cec5SDimitry Andric   struct CallContext {
CallContext__anondb24db010111::X86CallFrameOptimization::CallContext720b57cec5SDimitry Andric     CallContext() : FrameSetup(nullptr), ArgStoreVector(4, nullptr) {}
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric     // Iterator referring to the frame setup instruction
750b57cec5SDimitry Andric     MachineBasicBlock::iterator FrameSetup;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric     // Actual call instruction
780b57cec5SDimitry Andric     MachineInstr *Call = nullptr;
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric     // A copy of the stack pointer
810b57cec5SDimitry Andric     MachineInstr *SPCopy = nullptr;
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric     // The total displacement of all passed parameters
840b57cec5SDimitry Andric     int64_t ExpectedDist = 0;
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric     // The sequence of storing instructions used to pass the parameters
870b57cec5SDimitry Andric     SmallVector<MachineInstr *, 4> ArgStoreVector;
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric     // True if this call site has no stack parameters
900b57cec5SDimitry Andric     bool NoStackParams = false;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric     // True if this call site can use push instructions
930b57cec5SDimitry Andric     bool UsePush = false;
940b57cec5SDimitry Andric   };
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   typedef SmallVector<CallContext, 8> ContextVector;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   bool isLegal(MachineFunction &MF);
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   bool isProfitable(MachineFunction &MF, ContextVector &CallSeqMap);
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
1030b57cec5SDimitry Andric                        MachineBasicBlock::iterator I, CallContext &Context);
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   void adjustCallSequence(MachineFunction &MF, const CallContext &Context);
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
108e8d8bef9SDimitry Andric                                    Register Reg);
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   enum InstClassification { Convert, Skip, Exit };
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   InstClassification classifyInstruction(MachineBasicBlock &MBB,
1130b57cec5SDimitry Andric                                          MachineBasicBlock::iterator MI,
1140b57cec5SDimitry Andric                                          const X86RegisterInfo &RegInfo,
1150b57cec5SDimitry Andric                                          DenseSet<unsigned int> &UsedRegs);
1160b57cec5SDimitry Andric 
getPassName() const1170b57cec5SDimitry Andric   StringRef getPassName() const override { return "X86 Optimize Call Frame"; }
1180b57cec5SDimitry Andric 
119480093f4SDimitry Andric   const X86InstrInfo *TII = nullptr;
120480093f4SDimitry Andric   const X86FrameLowering *TFL = nullptr;
121480093f4SDimitry Andric   const X86Subtarget *STI = nullptr;
122480093f4SDimitry Andric   MachineRegisterInfo *MRI = nullptr;
123480093f4SDimitry Andric   unsigned SlotSize = 0;
124480093f4SDimitry Andric   unsigned Log2SlotSize = 0;
1250b57cec5SDimitry Andric };
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric } // end anonymous namespace
1280b57cec5SDimitry Andric char X86CallFrameOptimization::ID = 0;
1290b57cec5SDimitry Andric INITIALIZE_PASS(X86CallFrameOptimization, DEBUG_TYPE,
1300b57cec5SDimitry Andric                 "X86 Call Frame Optimization", false, false)
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric // This checks whether the transformation is legal.
1330b57cec5SDimitry Andric // Also returns false in cases where it's potentially legal, but
1340b57cec5SDimitry Andric // we don't even want to try.
isLegal(MachineFunction & MF)1350b57cec5SDimitry Andric bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
1360b57cec5SDimitry Andric   if (NoX86CFOpt.getValue())
1370b57cec5SDimitry Andric     return false;
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // We can't encode multiple DW_CFA_GNU_args_size or DW_CFA_def_cfa_offset
1400b57cec5SDimitry Andric   // in the compact unwind encoding that Darwin uses. So, bail if there
1410b57cec5SDimitry Andric   // is a danger of that being generated.
1420b57cec5SDimitry Andric   if (STI->isTargetDarwin() &&
1430b57cec5SDimitry Andric       (!MF.getLandingPads().empty() ||
1440b57cec5SDimitry Andric        (MF.getFunction().needsUnwindTableEntry() && !TFL->hasFP(MF))))
1450b57cec5SDimitry Andric     return false;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   // It is not valid to change the stack pointer outside the prolog/epilog
1480b57cec5SDimitry Andric   // on 64-bit Windows.
1490b57cec5SDimitry Andric   if (STI->isTargetWin64())
1500b57cec5SDimitry Andric     return false;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   // You would expect straight-line code between call-frame setup and
1530b57cec5SDimitry Andric   // call-frame destroy. You would be wrong. There are circumstances (e.g.
1540b57cec5SDimitry Andric   // CMOV_GR8 expansion of a select that feeds a function call!) where we can
1550b57cec5SDimitry Andric   // end up with the setup and the destroy in different basic blocks.
1560b57cec5SDimitry Andric   // This is bad, and breaks SP adjustment.
1570b57cec5SDimitry Andric   // So, check that all of the frames in the function are closed inside
1580b57cec5SDimitry Andric   // the same block, and, for good measure, that there are no nested frames.
1598bcb0991SDimitry Andric   //
1608bcb0991SDimitry Andric   // If any call allocates more argument stack memory than the stack
1618bcb0991SDimitry Andric   // probe size, don't do this optimization. Otherwise, this pass
1628bcb0991SDimitry Andric   // would need to synthesize additional stack probe calls to allocate
1638bcb0991SDimitry Andric   // memory for arguments.
1640b57cec5SDimitry Andric   unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
1650b57cec5SDimitry Andric   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1665ffd83dbSDimitry Andric   bool EmitStackProbeCall = STI->getTargetLowering()->hasStackProbeSymbol(MF);
1678bcb0991SDimitry Andric   unsigned StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
1680b57cec5SDimitry Andric   for (MachineBasicBlock &BB : MF) {
1690b57cec5SDimitry Andric     bool InsideFrameSequence = false;
1700b57cec5SDimitry Andric     for (MachineInstr &MI : BB) {
1710b57cec5SDimitry Andric       if (MI.getOpcode() == FrameSetupOpcode) {
1725ffd83dbSDimitry Andric         if (TII->getFrameSize(MI) >= StackProbeSize && EmitStackProbeCall)
1738bcb0991SDimitry Andric           return false;
1740b57cec5SDimitry Andric         if (InsideFrameSequence)
1750b57cec5SDimitry Andric           return false;
1760b57cec5SDimitry Andric         InsideFrameSequence = true;
1770b57cec5SDimitry Andric       } else if (MI.getOpcode() == FrameDestroyOpcode) {
1780b57cec5SDimitry Andric         if (!InsideFrameSequence)
1790b57cec5SDimitry Andric           return false;
1800b57cec5SDimitry Andric         InsideFrameSequence = false;
1810b57cec5SDimitry Andric       }
1820b57cec5SDimitry Andric     }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric     if (InsideFrameSequence)
1850b57cec5SDimitry Andric       return false;
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   return true;
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric // Check whether this transformation is profitable for a particular
1920b57cec5SDimitry Andric // function - in terms of code size.
isProfitable(MachineFunction & MF,ContextVector & CallSeqVector)1930b57cec5SDimitry Andric bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
1940b57cec5SDimitry Andric                                             ContextVector &CallSeqVector) {
1950b57cec5SDimitry Andric   // This transformation is always a win when we do not expect to have
1960b57cec5SDimitry Andric   // a reserved call frame. Under other circumstances, it may be either
1970b57cec5SDimitry Andric   // a win or a loss, and requires a heuristic.
1980b57cec5SDimitry Andric   bool CannotReserveFrame = MF.getFrameInfo().hasVarSizedObjects();
1990b57cec5SDimitry Andric   if (CannotReserveFrame)
2000b57cec5SDimitry Andric     return true;
2010b57cec5SDimitry Andric 
2025ffd83dbSDimitry Andric   Align StackAlign = TFL->getStackAlign();
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   int64_t Advantage = 0;
205e8d8bef9SDimitry Andric   for (const auto &CC : CallSeqVector) {
2060b57cec5SDimitry Andric     // Call sites where no parameters are passed on the stack
2070b57cec5SDimitry Andric     // do not affect the cost, since there needs to be no
2080b57cec5SDimitry Andric     // stack adjustment.
2090b57cec5SDimitry Andric     if (CC.NoStackParams)
2100b57cec5SDimitry Andric       continue;
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric     if (!CC.UsePush) {
2130b57cec5SDimitry Andric       // If we don't use pushes for a particular call site,
2140b57cec5SDimitry Andric       // we pay for not having a reserved call frame with an
2150b57cec5SDimitry Andric       // additional sub/add esp pair. The cost is ~3 bytes per instruction,
2160b57cec5SDimitry Andric       // depending on the size of the constant.
2170b57cec5SDimitry Andric       // TODO: Callee-pop functions should have a smaller penalty, because
2180b57cec5SDimitry Andric       // an add is needed even with a reserved call frame.
2190b57cec5SDimitry Andric       Advantage -= 6;
2200b57cec5SDimitry Andric     } else {
2210b57cec5SDimitry Andric       // We can use pushes. First, account for the fixed costs.
2220b57cec5SDimitry Andric       // We'll need a add after the call.
2230b57cec5SDimitry Andric       Advantage -= 3;
2240b57cec5SDimitry Andric       // If we have to realign the stack, we'll also need a sub before
2255ffd83dbSDimitry Andric       if (!isAligned(StackAlign, CC.ExpectedDist))
2260b57cec5SDimitry Andric         Advantage -= 3;
2270b57cec5SDimitry Andric       // Now, for each push, we save ~3 bytes. For small constants, we actually,
2280b57cec5SDimitry Andric       // save more (up to 5 bytes), but 3 should be a good approximation.
2290b57cec5SDimitry Andric       Advantage += (CC.ExpectedDist >> Log2SlotSize) * 3;
2300b57cec5SDimitry Andric     }
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   return Advantage >= 0;
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)2360b57cec5SDimitry Andric bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
2370b57cec5SDimitry Andric   STI = &MF.getSubtarget<X86Subtarget>();
2380b57cec5SDimitry Andric   TII = STI->getInstrInfo();
2390b57cec5SDimitry Andric   TFL = STI->getFrameLowering();
2400b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   const X86RegisterInfo &RegInfo =
2430b57cec5SDimitry Andric       *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
2440b57cec5SDimitry Andric   SlotSize = RegInfo.getSlotSize();
2450b57cec5SDimitry Andric   assert(isPowerOf2_32(SlotSize) && "Expect power of 2 stack slot size");
2460b57cec5SDimitry Andric   Log2SlotSize = Log2_32(SlotSize);
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()) || !isLegal(MF))
2490b57cec5SDimitry Andric     return false;
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   bool Changed = false;
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   ContextVector CallSeqVector;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   for (auto &MBB : MF)
2580b57cec5SDimitry Andric     for (auto &MI : MBB)
2590b57cec5SDimitry Andric       if (MI.getOpcode() == FrameSetupOpcode) {
2600b57cec5SDimitry Andric         CallContext Context;
2610b57cec5SDimitry Andric         collectCallInfo(MF, MBB, MI, Context);
2620b57cec5SDimitry Andric         CallSeqVector.push_back(Context);
2630b57cec5SDimitry Andric       }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   if (!isProfitable(MF, CallSeqVector))
2660b57cec5SDimitry Andric     return false;
2670b57cec5SDimitry Andric 
268e8d8bef9SDimitry Andric   for (const auto &CC : CallSeqVector) {
2690b57cec5SDimitry Andric     if (CC.UsePush) {
2700b57cec5SDimitry Andric       adjustCallSequence(MF, CC);
2710b57cec5SDimitry Andric       Changed = true;
2720b57cec5SDimitry Andric     }
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   return Changed;
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric X86CallFrameOptimization::InstClassification
classifyInstruction(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,const X86RegisterInfo & RegInfo,DenseSet<unsigned int> & UsedRegs)2790b57cec5SDimitry Andric X86CallFrameOptimization::classifyInstruction(
2800b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2810b57cec5SDimitry Andric     const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
2820b57cec5SDimitry Andric   if (MI == MBB.end())
2830b57cec5SDimitry Andric     return Exit;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   // The instructions we actually care about are movs onto the stack or special
2860b57cec5SDimitry Andric   // cases of constant-stores to stack
2870b57cec5SDimitry Andric   switch (MI->getOpcode()) {
288*06c3fb27SDimitry Andric     case X86::AND16mi:
289*06c3fb27SDimitry Andric     case X86::AND32mi:
290*06c3fb27SDimitry Andric     case X86::AND64mi32: {
291e8d8bef9SDimitry Andric       const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
2920b57cec5SDimitry Andric       return ImmOp.getImm() == 0 ? Convert : Exit;
2930b57cec5SDimitry Andric     }
294*06c3fb27SDimitry Andric     case X86::OR16mi:
295*06c3fb27SDimitry Andric     case X86::OR32mi:
296*06c3fb27SDimitry Andric     case X86::OR64mi32: {
297e8d8bef9SDimitry Andric       const MachineOperand &ImmOp = MI->getOperand(X86::AddrNumOperands);
2980b57cec5SDimitry Andric       return ImmOp.getImm() == -1 ? Convert : Exit;
2990b57cec5SDimitry Andric     }
3000b57cec5SDimitry Andric     case X86::MOV32mi:
3010b57cec5SDimitry Andric     case X86::MOV32mr:
3020b57cec5SDimitry Andric     case X86::MOV64mi32:
3030b57cec5SDimitry Andric     case X86::MOV64mr:
3040b57cec5SDimitry Andric       return Convert;
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   // Not all calling conventions have only stack MOVs between the stack
3080b57cec5SDimitry Andric   // adjust and the call.
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   // We want to tolerate other instructions, to cover more cases.
3110b57cec5SDimitry Andric   // In particular:
3120b57cec5SDimitry Andric   // a) PCrel calls, where we expect an additional COPY of the basereg.
3130b57cec5SDimitry Andric   // b) Passing frame-index addresses.
3140b57cec5SDimitry Andric   // c) Calling conventions that have inreg parameters. These generate
3150b57cec5SDimitry Andric   //    both copies and movs into registers.
3160b57cec5SDimitry Andric   // To avoid creating lots of special cases, allow any instruction
3170b57cec5SDimitry Andric   // that does not write into memory, does not def or use the stack
3180b57cec5SDimitry Andric   // pointer, and does not def any register that was used by a preceding
3190b57cec5SDimitry Andric   // push.
3200b57cec5SDimitry Andric   // (Reading from memory is allowed, even if referenced through a
3210b57cec5SDimitry Andric   // frame index, since these will get adjusted properly in PEI)
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   // The reason for the last condition is that the pushes can't replace
3240b57cec5SDimitry Andric   // the movs in place, because the order must be reversed.
3250b57cec5SDimitry Andric   // So if we have a MOV32mr that uses EDX, then an instruction that defs
3260b57cec5SDimitry Andric   // EDX, and then the call, after the transformation the push will use
3270b57cec5SDimitry Andric   // the modified version of EDX, and not the original one.
3280b57cec5SDimitry Andric   // Since we are still in SSA form at this point, we only need to
3290b57cec5SDimitry Andric   // make sure we don't clobber any *physical* registers that were
3300b57cec5SDimitry Andric   // used by an earlier mov that will become a push.
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   if (MI->isCall() || MI->mayStore())
3330b57cec5SDimitry Andric     return Exit;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
3360b57cec5SDimitry Andric     if (!MO.isReg())
3370b57cec5SDimitry Andric       continue;
3388bcb0991SDimitry Andric     Register Reg = MO.getReg();
339e8d8bef9SDimitry Andric     if (!Reg.isPhysical())
3400b57cec5SDimitry Andric       continue;
3410b57cec5SDimitry Andric     if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
3420b57cec5SDimitry Andric       return Exit;
3430b57cec5SDimitry Andric     if (MO.isDef()) {
3440b57cec5SDimitry Andric       for (unsigned int U : UsedRegs)
3450b57cec5SDimitry Andric         if (RegInfo.regsOverlap(Reg, U))
3460b57cec5SDimitry Andric           return Exit;
3470b57cec5SDimitry Andric     }
3480b57cec5SDimitry Andric   }
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   return Skip;
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric 
collectCallInfo(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I,CallContext & Context)3530b57cec5SDimitry Andric void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
3540b57cec5SDimitry Andric                                                MachineBasicBlock &MBB,
3550b57cec5SDimitry Andric                                                MachineBasicBlock::iterator I,
3560b57cec5SDimitry Andric                                                CallContext &Context) {
3570b57cec5SDimitry Andric   // Check that this particular call sequence is amenable to the
3580b57cec5SDimitry Andric   // transformation.
3590b57cec5SDimitry Andric   const X86RegisterInfo &RegInfo =
3600b57cec5SDimitry Andric       *static_cast<const X86RegisterInfo *>(STI->getRegisterInfo());
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // We expect to enter this at the beginning of a call sequence
3630b57cec5SDimitry Andric   assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
3640b57cec5SDimitry Andric   MachineBasicBlock::iterator FrameSetup = I++;
3650b57cec5SDimitry Andric   Context.FrameSetup = FrameSetup;
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // How much do we adjust the stack? This puts an upper bound on
3680b57cec5SDimitry Andric   // the number of parameters actually passed on it.
3690b57cec5SDimitry Andric   unsigned int MaxAdjust = TII->getFrameSize(*FrameSetup) >> Log2SlotSize;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // A zero adjustment means no stack parameters
3720b57cec5SDimitry Andric   if (!MaxAdjust) {
3730b57cec5SDimitry Andric     Context.NoStackParams = true;
3740b57cec5SDimitry Andric     return;
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   // Skip over DEBUG_VALUE.
3780b57cec5SDimitry Andric   // For globals in PIC mode, we can have some LEAs here. Skip them as well.
3790b57cec5SDimitry Andric   // TODO: Extend this to something that covers more cases.
3800b57cec5SDimitry Andric   while (I->getOpcode() == X86::LEA32r || I->isDebugInstr())
3810b57cec5SDimitry Andric     ++I;
3820b57cec5SDimitry Andric 
3838bcb0991SDimitry Andric   Register StackPtr = RegInfo.getStackRegister();
3840b57cec5SDimitry Andric   auto StackPtrCopyInst = MBB.end();
3850b57cec5SDimitry Andric   // SelectionDAG (but not FastISel) inserts a copy of ESP into a virtual
3860b57cec5SDimitry Andric   // register.  If it's there, use that virtual register as stack pointer
3870b57cec5SDimitry Andric   // instead. Also, we need to locate this instruction so that we can later
3880b57cec5SDimitry Andric   // safely ignore it while doing the conservative processing of the call chain.
3890b57cec5SDimitry Andric   // The COPY can be located anywhere between the call-frame setup
3900b57cec5SDimitry Andric   // instruction and its first use. We use the call instruction as a boundary
3910b57cec5SDimitry Andric   // because it is usually cheaper to check if an instruction is a call than
3920b57cec5SDimitry Andric   // checking if an instruction uses a register.
3930b57cec5SDimitry Andric   for (auto J = I; !J->isCall(); ++J)
3940b57cec5SDimitry Andric     if (J->isCopy() && J->getOperand(0).isReg() && J->getOperand(1).isReg() &&
3950b57cec5SDimitry Andric         J->getOperand(1).getReg() == StackPtr) {
3960b57cec5SDimitry Andric       StackPtrCopyInst = J;
3970b57cec5SDimitry Andric       Context.SPCopy = &*J++;
3980b57cec5SDimitry Andric       StackPtr = Context.SPCopy->getOperand(0).getReg();
3990b57cec5SDimitry Andric       break;
4000b57cec5SDimitry Andric     }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // Scan the call setup sequence for the pattern we're looking for.
4030b57cec5SDimitry Andric   // We only handle a simple case - a sequence of store instructions that
4040b57cec5SDimitry Andric   // push a sequence of stack-slot-aligned values onto the stack, with
4050b57cec5SDimitry Andric   // no gaps between them.
4060b57cec5SDimitry Andric   if (MaxAdjust > 4)
4070b57cec5SDimitry Andric     Context.ArgStoreVector.resize(MaxAdjust, nullptr);
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   DenseSet<unsigned int> UsedRegs;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   for (InstClassification Classification = Skip; Classification != Exit; ++I) {
4120b57cec5SDimitry Andric     // If this is the COPY of the stack pointer, it's ok to ignore.
4130b57cec5SDimitry Andric     if (I == StackPtrCopyInst)
4140b57cec5SDimitry Andric       continue;
4150b57cec5SDimitry Andric     Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs);
4160b57cec5SDimitry Andric     if (Classification != Convert)
4170b57cec5SDimitry Andric       continue;
4180b57cec5SDimitry Andric     // We know the instruction has a supported store opcode.
4190b57cec5SDimitry Andric     // We only want movs of the form:
4200b57cec5SDimitry Andric     // mov imm/reg, k(%StackPtr)
4210b57cec5SDimitry Andric     // If we run into something else, bail.
4220b57cec5SDimitry Andric     // Note that AddrBaseReg may, counter to its name, not be a register,
4230b57cec5SDimitry Andric     // but rather a frame index.
4240b57cec5SDimitry Andric     // TODO: Support the fi case. This should probably work now that we
4250b57cec5SDimitry Andric     // have the infrastructure to track the stack pointer within a call
4260b57cec5SDimitry Andric     // sequence.
4270b57cec5SDimitry Andric     if (!I->getOperand(X86::AddrBaseReg).isReg() ||
4280b57cec5SDimitry Andric         (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
4290b57cec5SDimitry Andric         !I->getOperand(X86::AddrScaleAmt).isImm() ||
4300b57cec5SDimitry Andric         (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
4310b57cec5SDimitry Andric         (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
4320b57cec5SDimitry Andric         (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
4330b57cec5SDimitry Andric         !I->getOperand(X86::AddrDisp).isImm())
4340b57cec5SDimitry Andric       return;
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric     int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
4370b57cec5SDimitry Andric     assert(StackDisp >= 0 &&
4380b57cec5SDimitry Andric            "Negative stack displacement when passing parameters");
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     // We really don't want to consider the unaligned case.
4410b57cec5SDimitry Andric     if (StackDisp & (SlotSize - 1))
4420b57cec5SDimitry Andric       return;
4430b57cec5SDimitry Andric     StackDisp >>= Log2SlotSize;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     assert((size_t)StackDisp < Context.ArgStoreVector.size() &&
4460b57cec5SDimitry Andric            "Function call has more parameters than the stack is adjusted for.");
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric     // If the same stack slot is being filled twice, something's fishy.
4490b57cec5SDimitry Andric     if (Context.ArgStoreVector[StackDisp] != nullptr)
4500b57cec5SDimitry Andric       return;
4510b57cec5SDimitry Andric     Context.ArgStoreVector[StackDisp] = &*I;
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric     for (const MachineOperand &MO : I->uses()) {
4540b57cec5SDimitry Andric       if (!MO.isReg())
4550b57cec5SDimitry Andric         continue;
4568bcb0991SDimitry Andric       Register Reg = MO.getReg();
457e8d8bef9SDimitry Andric       if (Reg.isPhysical())
4580b57cec5SDimitry Andric         UsedRegs.insert(Reg);
4590b57cec5SDimitry Andric     }
4600b57cec5SDimitry Andric   }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   --I;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // We now expect the end of the sequence. If we stopped early,
4650b57cec5SDimitry Andric   // or reached the end of the block without finding a call, bail.
4660b57cec5SDimitry Andric   if (I == MBB.end() || !I->isCall())
4670b57cec5SDimitry Andric     return;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   Context.Call = &*I;
4700b57cec5SDimitry Andric   if ((++I)->getOpcode() != TII->getCallFrameDestroyOpcode())
4710b57cec5SDimitry Andric     return;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // Now, go through the vector, and see that we don't have any gaps,
4740b57cec5SDimitry Andric   // but only a series of storing instructions.
4750b57cec5SDimitry Andric   auto MMI = Context.ArgStoreVector.begin(), MME = Context.ArgStoreVector.end();
4760b57cec5SDimitry Andric   for (; MMI != MME; ++MMI, Context.ExpectedDist += SlotSize)
4770b57cec5SDimitry Andric     if (*MMI == nullptr)
4780b57cec5SDimitry Andric       break;
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // If the call had no parameters, do nothing
4810b57cec5SDimitry Andric   if (MMI == Context.ArgStoreVector.begin())
4820b57cec5SDimitry Andric     return;
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   // We are either at the last parameter, or a gap.
4850b57cec5SDimitry Andric   // Make sure it's not a gap
4860b57cec5SDimitry Andric   for (; MMI != MME; ++MMI)
4870b57cec5SDimitry Andric     if (*MMI != nullptr)
4880b57cec5SDimitry Andric       return;
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   Context.UsePush = true;
4910b57cec5SDimitry Andric }
4920b57cec5SDimitry Andric 
adjustCallSequence(MachineFunction & MF,const CallContext & Context)4930b57cec5SDimitry Andric void X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
4940b57cec5SDimitry Andric                                                   const CallContext &Context) {
4950b57cec5SDimitry Andric   // Ok, we can in fact do the transformation for this call.
4960b57cec5SDimitry Andric   // Do not remove the FrameSetup instruction, but adjust the parameters.
4970b57cec5SDimitry Andric   // PEI will end up finalizing the handling of this.
4980b57cec5SDimitry Andric   MachineBasicBlock::iterator FrameSetup = Context.FrameSetup;
4990b57cec5SDimitry Andric   MachineBasicBlock &MBB = *(FrameSetup->getParent());
5000b57cec5SDimitry Andric   TII->setFrameAdjustment(*FrameSetup, Context.ExpectedDist);
5010b57cec5SDimitry Andric 
502fe6060f1SDimitry Andric   const DebugLoc &DL = FrameSetup->getDebugLoc();
5030b57cec5SDimitry Andric   bool Is64Bit = STI->is64Bit();
5040b57cec5SDimitry Andric   // Now, iterate through the vector in reverse order, and replace the store to
5050b57cec5SDimitry Andric   // stack with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
5060b57cec5SDimitry Andric   // replace uses.
5070b57cec5SDimitry Andric   for (int Idx = (Context.ExpectedDist >> Log2SlotSize) - 1; Idx >= 0; --Idx) {
5080b57cec5SDimitry Andric     MachineBasicBlock::iterator Store = *Context.ArgStoreVector[Idx];
509e8d8bef9SDimitry Andric     const MachineOperand &PushOp = Store->getOperand(X86::AddrNumOperands);
5100b57cec5SDimitry Andric     MachineBasicBlock::iterator Push = nullptr;
5110b57cec5SDimitry Andric     unsigned PushOpcode;
5120b57cec5SDimitry Andric     switch (Store->getOpcode()) {
5130b57cec5SDimitry Andric     default:
5140b57cec5SDimitry Andric       llvm_unreachable("Unexpected Opcode!");
515*06c3fb27SDimitry Andric     case X86::AND16mi:
516*06c3fb27SDimitry Andric     case X86::AND32mi:
517*06c3fb27SDimitry Andric     case X86::AND64mi32:
518*06c3fb27SDimitry Andric     case X86::OR16mi:
519*06c3fb27SDimitry Andric     case X86::OR32mi:
520*06c3fb27SDimitry Andric     case X86::OR64mi32:
5210b57cec5SDimitry Andric     case X86::MOV32mi:
5220b57cec5SDimitry Andric     case X86::MOV64mi32:
523*06c3fb27SDimitry Andric       PushOpcode = Is64Bit ? X86::PUSH64i32 : X86::PUSH32i;
5240b57cec5SDimitry Andric       Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).add(PushOp);
5255ffd83dbSDimitry Andric       Push->cloneMemRefs(MF, *Store);
5260b57cec5SDimitry Andric       break;
5270b57cec5SDimitry Andric     case X86::MOV32mr:
5280b57cec5SDimitry Andric     case X86::MOV64mr: {
5298bcb0991SDimitry Andric       Register Reg = PushOp.getReg();
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric       // If storing a 32-bit vreg on 64-bit targets, extend to a 64-bit vreg
5320b57cec5SDimitry Andric       // in preparation for the PUSH64. The upper 32 bits can be undef.
5330b57cec5SDimitry Andric       if (Is64Bit && Store->getOpcode() == X86::MOV32mr) {
5348bcb0991SDimitry Andric         Register UndefReg = MRI->createVirtualRegister(&X86::GR64RegClass);
5350b57cec5SDimitry Andric         Reg = MRI->createVirtualRegister(&X86::GR64RegClass);
5360b57cec5SDimitry Andric         BuildMI(MBB, Context.Call, DL, TII->get(X86::IMPLICIT_DEF), UndefReg);
5370b57cec5SDimitry Andric         BuildMI(MBB, Context.Call, DL, TII->get(X86::INSERT_SUBREG), Reg)
5380b57cec5SDimitry Andric             .addReg(UndefReg)
5390b57cec5SDimitry Andric             .add(PushOp)
5400b57cec5SDimitry Andric             .addImm(X86::sub_32bit);
5410b57cec5SDimitry Andric       }
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric       // If PUSHrmm is not slow on this target, try to fold the source of the
5440b57cec5SDimitry Andric       // push into the instruction.
5455ffd83dbSDimitry Andric       bool SlowPUSHrmm = STI->slowTwoMemOps();
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric       // Check that this is legal to fold. Right now, we're extremely
5480b57cec5SDimitry Andric       // conservative about that.
5490b57cec5SDimitry Andric       MachineInstr *DefMov = nullptr;
5500b57cec5SDimitry Andric       if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
5510b57cec5SDimitry Andric         PushOpcode = Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm;
5520b57cec5SDimitry Andric         Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode));
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric         unsigned NumOps = DefMov->getDesc().getNumOperands();
5550b57cec5SDimitry Andric         for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
5560b57cec5SDimitry Andric           Push->addOperand(DefMov->getOperand(i));
557e8d8bef9SDimitry Andric         Push->cloneMergedMemRefs(MF, {DefMov, &*Store});
5580b57cec5SDimitry Andric         DefMov->eraseFromParent();
5590b57cec5SDimitry Andric       } else {
5600b57cec5SDimitry Andric         PushOpcode = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
5610b57cec5SDimitry Andric         Push = BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode))
5620b57cec5SDimitry Andric                    .addReg(Reg)
5630b57cec5SDimitry Andric                    .getInstr();
5645ffd83dbSDimitry Andric         Push->cloneMemRefs(MF, *Store);
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric       break;
5670b57cec5SDimitry Andric     }
5680b57cec5SDimitry Andric     }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric     // For debugging, when using SP-based CFA, we need to adjust the CFA
5710b57cec5SDimitry Andric     // offset after each push.
5720b57cec5SDimitry Andric     // TODO: This is needed only if we require precise CFA.
5730b57cec5SDimitry Andric     if (!TFL->hasFP(MF))
5740b57cec5SDimitry Andric       TFL->BuildCFI(
5750b57cec5SDimitry Andric           MBB, std::next(Push), DL,
5760b57cec5SDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, SlotSize));
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric     MBB.erase(Store);
5790b57cec5SDimitry Andric   }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric   // The stack-pointer copy is no longer used in the call sequences.
5820b57cec5SDimitry Andric   // There should not be any other users, but we can't commit to that, so:
5830b57cec5SDimitry Andric   if (Context.SPCopy && MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
5840b57cec5SDimitry Andric     Context.SPCopy->eraseFromParent();
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   // Once we've done this, we need to make sure PEI doesn't assume a reserved
5870b57cec5SDimitry Andric   // frame.
5880b57cec5SDimitry Andric   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
5890b57cec5SDimitry Andric   FuncInfo->setHasPushSequences(true);
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric 
canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,Register Reg)5920b57cec5SDimitry Andric MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
593e8d8bef9SDimitry Andric     MachineBasicBlock::iterator FrameSetup, Register Reg) {
5940b57cec5SDimitry Andric   // Do an extremely restricted form of load folding.
5950b57cec5SDimitry Andric   // ISel will often create patterns like:
5960b57cec5SDimitry Andric   // movl    4(%edi), %eax
5970b57cec5SDimitry Andric   // movl    8(%edi), %ecx
5980b57cec5SDimitry Andric   // movl    12(%edi), %edx
5990b57cec5SDimitry Andric   // movl    %edx, 8(%esp)
6000b57cec5SDimitry Andric   // movl    %ecx, 4(%esp)
6010b57cec5SDimitry Andric   // movl    %eax, (%esp)
6020b57cec5SDimitry Andric   // call
6030b57cec5SDimitry Andric   // Get rid of those with prejudice.
604e8d8bef9SDimitry Andric   if (!Reg.isVirtual())
6050b57cec5SDimitry Andric     return nullptr;
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   // Make sure this is the only use of Reg.
6080b57cec5SDimitry Andric   if (!MRI->hasOneNonDBGUse(Reg))
6090b57cec5SDimitry Andric     return nullptr;
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   MachineInstr &DefMI = *MRI->getVRegDef(Reg);
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   // Make sure the def is a MOV from memory.
6140b57cec5SDimitry Andric   // If the def is in another block, give up.
6150b57cec5SDimitry Andric   if ((DefMI.getOpcode() != X86::MOV32rm &&
6160b57cec5SDimitry Andric        DefMI.getOpcode() != X86::MOV64rm) ||
6170b57cec5SDimitry Andric       DefMI.getParent() != FrameSetup->getParent())
6180b57cec5SDimitry Andric     return nullptr;
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   // Make sure we don't have any instructions between DefMI and the
6210b57cec5SDimitry Andric   // push that make folding the load illegal.
6220b57cec5SDimitry Andric   for (MachineBasicBlock::iterator I = DefMI; I != FrameSetup; ++I)
6230b57cec5SDimitry Andric     if (I->isLoadFoldBarrier())
6240b57cec5SDimitry Andric       return nullptr;
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   return &DefMI;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
createX86CallFrameOptimization()6290b57cec5SDimitry Andric FunctionPass *llvm::createX86CallFrameOptimization() {
6300b57cec5SDimitry Andric   return new X86CallFrameOptimization();
6310b57cec5SDimitry Andric }
632