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 // Information we know about a particular call site
56 : Call(nullptr), SPCopy(nullptr), ExpectedDist(0),
57 MovVector(4, nullptr), NoStackParams(false), UsePush(false){}
59 // Actuall call instruction
62 // A copy of the stack pointer
65 // The total displacement of all passed parameters
68 // The sequence of movs used to pass the parameters
69 SmallVector<MachineInstr *, 4> MovVector;
71 // True if this call site has no stack parameters
74 // True of this callsite can use push instructions
78 typedef DenseMap<MachineInstr *, CallContext> ContextMap;
80 bool isLegal(MachineFunction &MF);
82 bool isProfitable(MachineFunction &MF, ContextMap &CallSeqMap);
84 void collectCallInfo(MachineFunction &MF, MachineBasicBlock &MBB,
85 MachineBasicBlock::iterator I, CallContext &Context);
87 bool adjustCallSequence(MachineFunction &MF, MachineBasicBlock::iterator I,
88 const CallContext &Context);
90 MachineInstr *canFoldIntoRegPush(MachineBasicBlock::iterator FrameSetup,
93 enum InstClassification { Convert, Skip, Exit };
95 InstClassification classifyInstruction(MachineBasicBlock &MBB,
96 MachineBasicBlock::iterator MI,
97 const X86RegisterInfo &RegInfo,
98 DenseSet<unsigned int> &UsedRegs);
100 const char *getPassName() const override { return "X86 Optimize Call Frame"; }
102 const TargetInstrInfo *TII;
103 const TargetFrameLowering *TFL;
104 const MachineRegisterInfo *MRI;
108 char X86CallFrameOptimization::ID = 0;
111 FunctionPass *llvm::createX86CallFrameOptimization() {
112 return new X86CallFrameOptimization();
115 // This checks whether the transformation is legal.
116 // Also returns false in cases where it's potentially legal, but
117 // we don't even want to try.
118 bool X86CallFrameOptimization::isLegal(MachineFunction &MF) {
119 if (NoX86CFOpt.getValue())
122 // We currently only support call sequences where *all* parameters.
123 // are passed on the stack.
124 // No point in running this in 64-bit mode, since some arguments are
125 // passed in-register in all common calling conventions, so the pattern
126 // we're looking for will never match.
127 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
131 // You would expect straight-line code between call-frame setup and
132 // call-frame destroy. You would be wrong. There are circumstances (e.g.
133 // CMOV_GR8 expansion of a select that feeds a function call!) where we can
134 // end up with the setup and the destroy in different basic blocks.
135 // This is bad, and breaks SP adjustment.
136 // So, check that all of the frames in the function are closed inside
137 // the same block, and, for good measure, that there are no nested frames.
138 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
139 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
140 for (MachineBasicBlock &BB : MF) {
141 bool InsideFrameSequence = false;
142 for (MachineInstr &MI : BB) {
143 if (MI.getOpcode() == FrameSetupOpcode) {
144 if (InsideFrameSequence)
146 InsideFrameSequence = true;
147 } else if (MI.getOpcode() == FrameDestroyOpcode) {
148 if (!InsideFrameSequence)
150 InsideFrameSequence = false;
154 if (InsideFrameSequence)
161 // Check whether this trasnformation is profitable for a particular
162 // function - in terms of code size.
163 bool X86CallFrameOptimization::isProfitable(MachineFunction &MF,
164 ContextMap &CallSeqMap) {
165 // This transformation is always a win when we do not expect to have
166 // a reserved call frame. Under other circumstances, it may be either
167 // a win or a loss, and requires a heuristic.
168 bool CannotReserveFrame = MF.getFrameInfo()->hasVarSizedObjects();
169 if (CannotReserveFrame)
172 // Don't do this when not optimizing for size.
173 if (!MF.getFunction()->optForSize())
176 unsigned StackAlign = TFL->getStackAlignment();
178 int64_t Advantage = 0;
179 for (auto CC : CallSeqMap) {
180 // Call sites where no parameters are passed on the stack
181 // do not affect the cost, since there needs to be no
183 if (CC.second.NoStackParams)
186 if (!CC.second.UsePush) {
187 // If we don't use pushes for a particular call site,
188 // we pay for not having a reserved call frame with an
189 // additional sub/add esp pair. The cost is ~3 bytes per instruction,
190 // depending on the size of the constant.
191 // TODO: Callee-pop functions should have a smaller penalty, because
192 // an add is needed even with a reserved call frame.
195 // We can use pushes. First, account for the fixed costs.
196 // We'll need a add after the call.
198 // If we have to realign the stack, we'll also need and sub before
199 if (CC.second.ExpectedDist % StackAlign)
201 // Now, for each push, we save ~3 bytes. For small constants, we actually,
202 // save more (up to 5 bytes), but 3 should be a good approximation.
203 Advantage += (CC.second.ExpectedDist / 4) * 3;
207 return (Advantage >= 0);
210 bool X86CallFrameOptimization::runOnMachineFunction(MachineFunction &MF) {
211 TII = MF.getSubtarget().getInstrInfo();
212 TFL = MF.getSubtarget().getFrameLowering();
213 MRI = &MF.getRegInfo();
218 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
220 bool Changed = false;
222 ContextMap CallSeqMap;
224 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
225 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
226 if (I->getOpcode() == FrameSetupOpcode) {
227 CallContext &Context = CallSeqMap[I];
228 collectCallInfo(MF, *BB, I, Context);
231 if (!isProfitable(MF, CallSeqMap))
234 for (auto CC : CallSeqMap)
235 if (CC.second.UsePush)
236 Changed |= adjustCallSequence(MF, CC.first, CC.second);
241 X86CallFrameOptimization::InstClassification
242 X86CallFrameOptimization::classifyInstruction(
243 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
244 const X86RegisterInfo &RegInfo, DenseSet<unsigned int> &UsedRegs) {
248 // The instructions we actually care about are movs onto the stack
249 int Opcode = MI->getOpcode();
250 if (Opcode == X86::MOV32mi || Opcode == X86::MOV32mr)
253 // Not all calling conventions have only stack MOVs between the stack
254 // adjust and the call.
256 // We want to tolerate other instructions, to cover more cases.
258 // a) PCrel calls, where we expect an additional COPY of the basereg.
259 // b) Passing frame-index addresses.
260 // c) Calling conventions that have inreg parameters. These generate
261 // both copies and movs into registers.
262 // To avoid creating lots of special cases, allow any instruction
263 // that does not write into memory, does not def or use the stack
264 // pointer, and does not def any register that was used by a preceding
266 // (Reading from memory is allowed, even if referenced through a
267 // frame index, since these will get adjusted properly in PEI)
269 // The reason for the last condition is that the pushes can't replace
270 // the movs in place, because the order must be reversed.
271 // So if we have a MOV32mr that uses EDX, then an instruction that defs
272 // EDX, and then the call, after the transformation the push will use
273 // the modified version of EDX, and not the original one.
274 // Since we are still in SSA form at this point, we only need to
275 // make sure we don't clobber any *physical* registers that were
276 // used by an earlier mov that will become a push.
278 if (MI->isCall() || MI->mayStore())
281 for (const MachineOperand &MO : MI->operands()) {
284 unsigned int Reg = MO.getReg();
285 if (!RegInfo.isPhysicalRegister(Reg))
287 if (RegInfo.regsOverlap(Reg, RegInfo.getStackRegister()))
290 for (unsigned int U : UsedRegs)
291 if (RegInfo.regsOverlap(Reg, U))
299 void X86CallFrameOptimization::collectCallInfo(MachineFunction &MF,
300 MachineBasicBlock &MBB,
301 MachineBasicBlock::iterator I,
302 CallContext &Context) {
303 // Check that this particular call sequence is amenable to the
305 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
306 MF.getSubtarget().getRegisterInfo());
307 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
309 // We expect to enter this at the beginning of a call sequence
310 assert(I->getOpcode() == TII->getCallFrameSetupOpcode());
311 MachineBasicBlock::iterator FrameSetup = I++;
313 // How much do we adjust the stack? This puts an upper bound on
314 // the number of parameters actually passed on it.
315 unsigned int MaxAdjust = FrameSetup->getOperand(0).getImm() / 4;
317 // A zero adjustment means no stack parameters
319 Context.NoStackParams = true;
323 // For globals in PIC mode, we can have some LEAs here.
324 // Ignore them, they don't bother us.
325 // TODO: Extend this to something that covers more cases.
326 while (I->getOpcode() == X86::LEA32r)
329 // We expect a copy instruction here.
330 // TODO: The copy instruction is a lowering artifact.
331 // We should also support a copy-less version, where the stack
332 // pointer is used directly.
333 if (!I->isCopy() || !I->getOperand(0).isReg())
335 Context.SPCopy = I++;
337 unsigned StackPtr = Context.SPCopy->getOperand(0).getReg();
339 // Scan the call setup sequence for the pattern we're looking for.
340 // We only handle a simple case - a sequence of MOV32mi or MOV32mr
341 // instructions, that push a sequence of 32-bit values onto the stack, with
342 // no gaps between them.
344 Context.MovVector.resize(MaxAdjust, nullptr);
346 InstClassification Classification;
347 DenseSet<unsigned int> UsedRegs;
349 while ((Classification = classifyInstruction(MBB, I, RegInfo, UsedRegs)) !=
351 if (Classification == Skip) {
356 // We know the instruction is a MOV32mi/MOV32mr.
357 // We only want movs of the form:
358 // movl imm/r32, k(%esp)
359 // If we run into something else, bail.
360 // Note that AddrBaseReg may, counter to its name, not be a register,
361 // but rather a frame index.
362 // TODO: Support the fi case. This should probably work now that we
363 // have the infrastructure to track the stack pointer within a call
365 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
366 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
367 !I->getOperand(X86::AddrScaleAmt).isImm() ||
368 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
369 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
370 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
371 !I->getOperand(X86::AddrDisp).isImm())
374 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
375 assert(StackDisp >= 0 &&
376 "Negative stack displacement when passing parameters");
378 // We really don't want to consider the unaligned case.
383 assert((size_t)StackDisp < Context.MovVector.size() &&
384 "Function call has more parameters than the stack is adjusted for.");
386 // If the same stack slot is being filled twice, something's fishy.
387 if (Context.MovVector[StackDisp] != nullptr)
389 Context.MovVector[StackDisp] = I;
391 for (const MachineOperand &MO : I->uses()) {
394 unsigned int Reg = MO.getReg();
395 if (RegInfo.isPhysicalRegister(Reg))
396 UsedRegs.insert(Reg);
402 // We now expect the end of the sequence. If we stopped early,
403 // or reached the end of the block without finding a call, bail.
404 if (I == MBB.end() || !I->isCall())
408 if ((++I)->getOpcode() != FrameDestroyOpcode)
411 // Now, go through the vector, and see that we don't have any gaps,
412 // but only a series of 32-bit MOVs.
413 auto MMI = Context.MovVector.begin(), MME = Context.MovVector.end();
414 for (; MMI != MME; ++MMI, Context.ExpectedDist += 4)
418 // If the call had no parameters, do nothing
419 if (MMI == Context.MovVector.begin())
422 // We are either at the last parameter, or a gap.
423 // Make sure it's not a gap
424 for (; MMI != MME; ++MMI)
428 Context.UsePush = true;
432 bool X86CallFrameOptimization::adjustCallSequence(MachineFunction &MF,
433 MachineBasicBlock::iterator I,
434 const CallContext &Context) {
435 // Ok, we can in fact do the transformation for this call.
436 // Do not remove the FrameSetup instruction, but adjust the parameters.
437 // PEI will end up finalizing the handling of this.
438 MachineBasicBlock::iterator FrameSetup = I;
439 MachineBasicBlock &MBB = *(I->getParent());
440 FrameSetup->getOperand(1).setImm(Context.ExpectedDist);
442 DebugLoc DL = I->getDebugLoc();
443 // Now, iterate through the vector in reverse order, and replace the movs
444 // with pushes. MOVmi/MOVmr doesn't have any defs, so no need to
446 for (int Idx = (Context.ExpectedDist / 4) - 1; Idx >= 0; --Idx) {
447 MachineBasicBlock::iterator MOV = *Context.MovVector[Idx];
448 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
449 if (MOV->getOpcode() == X86::MOV32mi) {
450 unsigned PushOpcode = X86::PUSHi32;
451 // If the operand is a small (8-bit) immediate, we can use a
452 // PUSH instruction with a shorter encoding.
453 // Note that isImm() may fail even though this is a MOVmi, because
454 // the operand can also be a symbol.
455 if (PushOp.isImm()) {
456 int64_t Val = PushOp.getImm();
458 PushOpcode = X86::PUSH32i8;
460 BuildMI(MBB, Context.Call, DL, TII->get(PushOpcode)).addOperand(PushOp);
462 unsigned int Reg = PushOp.getReg();
464 // If PUSHrmm is not slow on this target, try to fold the source of the
465 // push into the instruction.
466 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
467 bool SlowPUSHrmm = ST.isAtom() || ST.isSLM();
469 // Check that this is legal to fold. Right now, we're extremely
470 // conservative about that.
471 MachineInstr *DefMov = nullptr;
472 if (!SlowPUSHrmm && (DefMov = canFoldIntoRegPush(FrameSetup, Reg))) {
474 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32rmm));
476 unsigned NumOps = DefMov->getDesc().getNumOperands();
477 for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
478 Push->addOperand(DefMov->getOperand(i));
480 DefMov->eraseFromParent();
482 BuildMI(MBB, Context.Call, DL, TII->get(X86::PUSH32r))
491 // The stack-pointer copy is no longer used in the call sequences.
492 // There should not be any other users, but we can't commit to that, so:
493 if (MRI->use_empty(Context.SPCopy->getOperand(0).getReg()))
494 Context.SPCopy->eraseFromParent();
496 // Once we've done this, we need to make sure PEI doesn't assume a reserved
498 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
499 FuncInfo->setHasPushSequences(true);
504 MachineInstr *X86CallFrameOptimization::canFoldIntoRegPush(
505 MachineBasicBlock::iterator FrameSetup, unsigned Reg) {
506 // Do an extremely restricted form of load folding.
507 // ISel will often create patterns like:
508 // movl 4(%edi), %eax
509 // movl 8(%edi), %ecx
510 // movl 12(%edi), %edx
511 // movl %edx, 8(%esp)
512 // movl %ecx, 4(%esp)
515 // Get rid of those with prejudice.
516 if (!TargetRegisterInfo::isVirtualRegister(Reg))
519 // Make sure this is the only use of Reg.
520 if (!MRI->hasOneNonDBGUse(Reg))
523 MachineBasicBlock::iterator DefMI = MRI->getVRegDef(Reg);
525 // Make sure the def is a MOV from memory.
526 // If the def is an another block, give up.
527 if (DefMI->getOpcode() != X86::MOV32rm ||
528 DefMI->getParent() != FrameSetup->getParent())
531 // Now, make sure everything else up until the ADJCALLSTACK is a sequence
532 // of MOVs. To be less conservative would require duplicating a lot of the
533 // logic from PeepholeOptimizer.
534 // FIXME: A possibly better approach would be to teach the PeepholeOptimizer
535 // to be smarter about folding into pushes.
536 for (auto I = DefMI; I != FrameSetup; ++I)
537 if (I->getOpcode() != X86::MOV32rm)