1 //===----- X86CallFrameOptimization.cpp - Optimize x86 call sequences -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pass that optimizes call sequences on x86.
11 // Currently, it converts movs of function parameters onto the stack into
12 // pushes. This is beneficial for two main reasons:
13 // 1) The push instruction encoding is much smaller than an esp-relative mov
14 // 2) It is possible to push memory arguments directly. So, if the
15 // the transformation is preformed pre-reg-alloc, it can help relieve
18 //===----------------------------------------------------------------------===//
23 #include "X86InstrInfo.h"
24 #include "X86Subtarget.h"
25 #include "X86MachineFunctionInfo.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
38 #define DEBUG_TYPE "x86-cf-opt"
41 NoX86CFOpt("no-x86-call-frame-opt",
42 cl::desc("Avoid optimizing x86 call frames for size"),
43 cl::init(false), cl::Hidden);
46 class X86CallFrameOptimization : public MachineFunctionPass {
48 X86CallFrameOptimization() : MachineFunctionPass(ID) {}
50 bool runOnMachineFunction(MachineFunction &MF) override;
53 bool shouldPerformTransformation(MachineFunction &MF);
55 // Information we know about a particular call site
58 : Call(nullptr), SPCopy(nullptr), ExpectedDist(0),
59 MovVector(4, nullptr), UsePush(false){};
61 // Actuall call instruction
64 // A copy of the stack pointer
67 // The total displacement of all passed parameters
70 // The sequence of movs used to pass the parameters
71 SmallVector<MachineInstr *, 4> MovVector;
73 // Whether this site should use push instructions
77 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
78 MachineBasicBlock::iterator I, CallContext &Context);
80 bool adjustCallSequence(MachineFunction &MF, MachineBasicBlock::iterator I,
81 const CallContext &Context);
83 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
86 const char *getPassName() const override { return "X86 Optimize Call Frame"; }
88 const TargetInstrInfo *TII;
89 const TargetFrameLowering *TFL;
90 const MachineRegisterInfo *MRI;
94 char X86CallFrameOptimization::ID = 0;
97 FunctionPass *llvm::createX86CallFrameOptimization() {
98 return new X86CallFrameOptimization();
101 // This checks whether the transformation is legal and profitable
102 bool X86CallFrameOptimization::shouldPerformTransformation(
103 MachineFunction &MF) {
104 if (NoX86CFOpt.getValue())
107 // We currently only support call sequences where *all* parameters.
108 // are passed on the stack.
109 // No point in running this in 64-bit mode, since some arguments are
110 // passed in-register in all common calling conventions, so the pattern
111 // we're looking for will never match.
112 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
116 // You would expect straight-line code between call-frame setup and
117 // call-frame destroy. You would be wrong. There are circumstances (e.g.
118 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
119 // end up with the setup and the destroy in different basic blocks.
120 // This is bad, and breaks SP adjustment.
121 // So, check that all of the frames in the function are closed inside
122 // the same block, and, for good measure, that there are no nested frames.
123 int FrameSetupOpcode = TII->getCallFrameSetupOpcode();
124 int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
125 for (MachineBasicBlock &BB : MF) {
126 bool InsideFrameSequence = false;
127 for (MachineInstr &MI : BB) {
128 if (MI.getOpcode() == FrameSetupOpcode) {
129 if (InsideFrameSequence)
131 InsideFrameSequence = true;
132 } else if (MI.getOpcode() == FrameDestroyOpcode) {
133 if (!InsideFrameSequence)
135 InsideFrameSequence = false;
139 if (InsideFrameSequence)
143 // Now that we know the transformation is legal, check if it is
145 // TODO: Add a heuristic that actually looks at the function,
146 // and enable this for more cases.
148 // This transformation is always a win when we expected to have
149 // a reserved call frame. Under other circumstances, it may be either
150 // a win or a loss, and requires a heuristic.
151 // For now, enable it only for the relatively clear win cases.
152 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
153 if (CannotReserveFrame)
156 // For now, don't even try to evaluate the profitability when
157 // not optimizing for size.
158 AttributeSet FnAttrs = MF.getFunction()->getAttributes();
160 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
161 Attribute::OptimizeForSize) ||
162 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
167 // Stack re-alignment can make this unprofitable even in terms of size.
168 // As mentioned above, a better heuristic is needed. For now, don't do this
169 // when the required alignment is above 8. (4 would be the safe choice, but
170 // some experimentation showed 8 is generally good).
171 if (TFL->getStackAlignment() > 8)
177 bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
178 TII = MF.getSubtarget().getInstrInfo();
179 TFL = MF.getSubtarget().getFrameLowering();
180 MRI = &MF.getRegInfo();
182 if (!shouldPerformTransformation(MF))
185 int FrameSetupOpcode = TII->getCallFrameSetupOpcode();
187 bool Changed = false;
189 DenseMap<MachineInstr *, CallContext> CallSeqMap;
191 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
192 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
193 if (I->getOpcode() == FrameSetupOpcode) {
194 CallContext &Context = CallSeqMap[I];
195 collectCallInfo(MF, *BB, I, Context);
198 for (auto CC : CallSeqMap)
199 if (CC.second.UsePush)
200 Changed |= adjustCallSequence(MF, CC.first, CC.second);
205 void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
206 MachineBasicBlock &MBB,
207 MachineBasicBlock::iterator I,
208 CallContext &Context) {
209 // Check that this particular call sequence is amenable to the
211 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
212 MF.getSubtarget().getRegisterInfo());
213 unsigned StackPtr = RegInfo.getStackRegister();
214 int FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
216 // We expect to enter this at the beginning of a call sequence
217 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
218 MachineBasicBlock::iterator FrameSetup = I++;
220 // For globals in PIC mode, we can have some LEAs here.
221 // Ignore them, they don't bother us.
222 // TODO: Extend this to something that covers more cases.
223 while (I->getOpcode() == X86::LEA32r)
226 // We expect a copy instruction here.
227 // TODO: The copy instruction is a lowering artifact.
228 // We should also support a copy-less version, where the stack
229 // pointer is used directly.
230 if (!I->isCopy() || !I->getOperand(0).isReg())
232 Context.SPCopy = I++;
233 StackPtr = Context.SPCopy->getOperand(0).getReg();
235 // Scan the call setup sequence for the pattern we're looking for.
236 // We only handle a simple case - a sequence of MOV32mi or MOV32mr
237 // instructions, that push a sequence of 32-bit values onto the stack, with
238 // no gaps between them.
239 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4;
241 Context.MovVector.resize(MaxAdjust, nullptr);
244 int Opcode = I->getOpcode();
245 if (Opcode != X86::MOV32mi && Opcode != X86::MOV32mr)
248 // We only want movs of the form:
249 // movl imm/r32, k(%esp)
250 // If we run into something else, bail.
251 // Note that AddrBaseReg may, counter to its name, not be a register,
252 // but rather a frame index.
253 // TODO: Support the fi case. This should probably work now that we
254 // have the infrastructure to track the stack pointer within a call
256 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
257 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
258 !I->getOperand(X86::AddrScaleAmt).isImm() ||
259 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
260 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
261 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
262 !I->getOperand(X86::AddrDisp).isImm())
265 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
266 assert(StackDisp >= 0 &&
267 "Negative stack displacement when passing parameters");
269 // We really don't want to consider the unaligned case.
274 assert((size_t)StackDisp < Context.MovVector.size() &&
275 "Function call has more parameters than the stack is adjusted for.");
277 // If the same stack slot is being filled twice, something's fishy.
278 if (Context.MovVector[StackDisp] != nullptr)
280 Context.MovVector[StackDisp] = I;
283 } while (I != MBB.end());
285 // We now expect the end of the sequence - a call and a stack adjust.
289 // For PCrel calls, we expect an additional COPY of the basereg.
290 // If we find one, skip it.
292 if (I->getOperand(1).getReg() ==
293 MF.getInfo<X86MachineFunctionInfo>()->getGlobalBaseReg())
303 if ((++I)->getOpcode() != FrameDestroyOpcode)
306 // Now, go through the vector, and see that we don't have any gaps,
307 // but only a series of 32-bit MOVs.
308 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
309 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4)
313 // If the call had no parameters, do nothing
314 if (MMI == Context.MovVector.begin())
317 // We are either at the last parameter, or a gap.
318 // Make sure it's not a gap
319 for (; MMI != MME; ++MMI)
323 Context.UsePush = true;
327 bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
328 MachineBasicBlock::iterator I,
329 const CallContext &Context) {
330 // Ok, we can in fact do the transformation for this call.
331 // Do not remove the FrameSetup instruction, but adjust the parameters.
332 // PEI will end up finalizing the handling of this.
333 MachineBasicBlock::iterator FrameSetup = I;
334 MachineBasicBlock &MBB = *(I->getParent());
335 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
337 DebugLoc DL = I->getDebugLoc();
338 // Now, iterate through the vector in reverse order, and replace the movs
339 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
341 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) {
342 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
343 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
344 if (MOV->getOpcode() == X86::MOV32mi) {
345 unsigned PushOpcode = X86::PUSHi32;
346 // If the operand is a small (8-bit) immediate, we can use a
347 // PUSH instruction with a shorter encoding.
348 // Note that isImm() may fail even though this is a MOVmi, because
349 // the operand can also be a symbol.
350 if (PushOp.isImm()) {
351 int64_t Val = PushOp.getImm();
353 PushOpcode = X86::PUSH32i8;
355 BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).addOperand(PushOp);
357 unsigned int Reg = PushOp.getReg();
359 // If PUSHrmm is not slow on this target, try to fold the source of the
360 // push into the instruction.
361 const X86Subtarget &ST = MF.getTarget().getSubtarget<X86Subtarget>();
362 bool SlowPUSHrmm = ST.isAtom() || ST.isSLM();
364 // Check that this is legal to fold. Right now, we're extremely
365 // conservative about that.
366 MachineInstr *DefMov = nullptr;
367 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
369 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm));
371 unsigned NumOps = DefMov->getDesc().getNumOperands();
372 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
373 Push->addOperand(DefMov->getOperand(i));
375 DefMov->eraseFromParent();
377 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r))
386 // The stack-pointer copy is no longer used in the call sequences.
387 // There should not be any other users, but we can't commit to that, so:
388 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
389 Context.SPCopy->eraseFromParent();
391 // Once we've done this, we need to make sure PEI doesn't assume a reserved
393 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
394 FuncInfo->setHasPushSequences(true);
399 MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
400 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
401 // Do an extremely restricted form of load folding.
402 // ISel will often create patterns like:
403 // movl 4(%edi), %eax
404 // movl 8(%edi), %ecx
405 // movl 12(%edi), %edx
406 // movl %edx, 8(%esp)
407 // movl %ecx, 4(%esp)
410 // Get rid of those with prejudice.
411 if (!TargetRegisterInfo::isVirtualRegister(Reg))
414 // Make sure this is the only use of Reg.
415 if (!MRI->hasOneNonDBGUse(Reg))
418 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
420 // Make sure the def is a MOV from memory.
421 // If the def is an another block, give up.
422 if (DefMI->getOpcode() != X86::MOV32rm ||
423 DefMI->getParent() != FrameSetup->getParent())
426 // Be careful with movs that load from a stack slot, since it may get
427 // resolved incorrectly.
428 // TODO: Again, we already have the infrastructure, so this should work.
429 if (!DefMI->getOperand(1).isReg())
432 // Now, make sure everything else up until the ADJCALLSTACK is a sequence
433 // of MOVs. To be less conservative would require duplicating a lot of the
434 // logic from PeepholeOptimizer.
435 // FIXME: A possibly better approach would be to teach the PeepholeOptimizer
436 // to be smarter about folding into pushes.
437 for (auto I = DefMI; I != FrameSetup; ++I)
438 if (I->getOpcode() != X86::MOV32rm)