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