76583f0de888cef8c84d5fab4a45cb15c74ec6b0
[oota-llvm.git] / lib / CodeGen / PrologEpilogInserter.cpp
1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
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 pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
12 // function.
13 //
14 // This pass must be run after register allocation.  After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/ADT/IndexedMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/CodeGen/StackProtector.h"
33 #include "llvm/CodeGen/WinEHFuncInfo.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetFrameLowering.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
46 #include <climits>
47
48 using namespace llvm;
49
50 #define DEBUG_TYPE "pei"
51
52 namespace {
53 class PEI : public MachineFunctionPass {
54 public:
55   static char ID;
56   PEI() : MachineFunctionPass(ID) {
57     initializePEIPass(*PassRegistry::getPassRegistry());
58   }
59
60   void getAnalysisUsage(AnalysisUsage &AU) const override;
61
62   /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
63   /// frame indexes with appropriate references.
64   ///
65   bool runOnMachineFunction(MachineFunction &Fn) override;
66
67 private:
68   RegScavenger *RS;
69
70   // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
71   // stack frame indexes.
72   unsigned MinCSFrameIndex, MaxCSFrameIndex;
73
74   // Save and Restore blocks of the current function.
75   MachineBasicBlock *SaveBlock;
76   SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
77
78   // Flag to control whether to use the register scavenger to resolve
79   // frame index materialization registers. Set according to
80   // TRI->requiresFrameIndexScavenging() for the current function.
81   bool FrameIndexVirtualScavenging;
82
83   void calculateSets(MachineFunction &Fn);
84   void calculateCallsInformation(MachineFunction &Fn);
85   void calculateCalleeSavedRegisters(MachineFunction &Fn);
86   void insertCSRSpillsAndRestores(MachineFunction &Fn);
87   void calculateFrameObjectOffsets(MachineFunction &Fn);
88   void replaceFrameIndices(MachineFunction &Fn);
89   void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
90                            int &SPAdj);
91   void scavengeFrameVirtualRegs(MachineFunction &Fn);
92   void insertPrologEpilogCode(MachineFunction &Fn);
93
94   // Convenience for recognizing return blocks.
95   bool isReturnBlock(MachineBasicBlock *MBB);
96 };
97 } // namespace
98
99 char PEI::ID = 0;
100 char &llvm::PrologEpilogCodeInserterID = PEI::ID;
101
102 static cl::opt<unsigned>
103 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
104               cl::desc("Warn for stack size bigger than the given"
105                        " number"));
106
107 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
108                 "Prologue/Epilogue Insertion", false, false)
109 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
110 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
111 INITIALIZE_PASS_DEPENDENCY(StackProtector)
112 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
113 INITIALIZE_PASS_END(PEI, "prologepilog",
114                     "Prologue/Epilogue Insertion & Frame Finalization",
115                     false, false)
116
117 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
118 STATISTIC(NumBytesStackSpace,
119           "Number of bytes used for stack in all functions");
120
121 void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
122   AU.setPreservesCFG();
123   AU.addPreserved<MachineLoopInfo>();
124   AU.addPreserved<MachineDominatorTree>();
125   AU.addRequired<StackProtector>();
126   AU.addRequired<TargetPassConfig>();
127   MachineFunctionPass::getAnalysisUsage(AU);
128 }
129
130 bool PEI::isReturnBlock(MachineBasicBlock* MBB) {
131   return (MBB && !MBB->empty() && MBB->back().isReturn());
132 }
133
134 /// Compute the set of return blocks
135 void PEI::calculateSets(MachineFunction &Fn) {
136   const MachineFrameInfo *MFI = Fn.getFrameInfo();
137
138   // Even when we do not change any CSR, we still want to insert the
139   // prologue and epilogue of the function.
140   // So set the save points for those.
141
142   // Use the points found by shrink-wrapping, if any.
143   if (MFI->getSavePoint()) {
144     SaveBlock = MFI->getSavePoint();
145     assert(MFI->getRestorePoint() && "Both restore and save must be set");
146     RestoreBlocks.push_back(MFI->getRestorePoint());
147     return;
148   }
149
150   // Save refs to entry and return blocks.
151   SaveBlock = Fn.begin();
152   for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
153        MBB != E; ++MBB)
154     if (isReturnBlock(MBB))
155       RestoreBlocks.push_back(MBB);
156
157   return;
158 }
159
160 /// StackObjSet - A set of stack object indexes
161 typedef SmallSetVector<int, 8> StackObjSet;
162
163 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
164 /// frame indexes with appropriate references.
165 ///
166 bool PEI::runOnMachineFunction(MachineFunction &Fn) {
167   const Function* F = Fn.getFunction();
168   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
169   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
170
171   assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
172
173   RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
174   FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
175
176   // Calculate the MaxCallFrameSize and AdjustsStack variables for the
177   // function's frame information. Also eliminates call frame pseudo
178   // instructions.
179   calculateCallsInformation(Fn);
180
181   // Allow the target machine to make some adjustments to the function
182   // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
183   TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
184
185   // Scan the function for modified callee saved registers and insert spill code
186   // for any callee saved registers that are modified.
187   calculateCalleeSavedRegisters(Fn);
188
189   // Determine placement of CSR spill/restore code:
190   // place all spills in the entry block, all restores in return blocks.
191   calculateSets(Fn);
192
193   // Add the code to save and restore the callee saved registers
194   if (!F->hasFnAttribute(Attribute::Naked))
195     insertCSRSpillsAndRestores(Fn);
196
197   // Allow the target machine to make final modifications to the function
198   // before the frame layout is finalized.
199   TFI->processFunctionBeforeFrameFinalized(Fn, RS);
200
201   // Calculate actual frame offsets for all abstract stack objects...
202   calculateFrameObjectOffsets(Fn);
203
204   // Add prolog and epilog code to the function.  This function is required
205   // to align the stack frame as necessary for any stack variables or
206   // called functions.  Because of this, calculateCalleeSavedRegisters()
207   // must be called before this function in order to set the AdjustsStack
208   // and MaxCallFrameSize variables.
209   if (!F->hasFnAttribute(Attribute::Naked))
210     insertPrologEpilogCode(Fn);
211
212   // Replace all MO_FrameIndex operands with physical register references
213   // and actual offsets.
214   //
215   replaceFrameIndices(Fn);
216
217   // If register scavenging is needed, as we've enabled doing it as a
218   // post-pass, scavenge the virtual registers that frame index elimination
219   // inserted.
220   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
221     scavengeFrameVirtualRegs(Fn);
222
223   // Clear any vregs created by virtual scavenging.
224   Fn.getRegInfo().clearVirtRegs();
225
226   // Warn on stack size when we exceeds the given limit.
227   MachineFrameInfo *MFI = Fn.getFrameInfo();
228   uint64_t StackSize = MFI->getStackSize();
229   if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
230     DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
231     F->getContext().diagnose(DiagStackSize);
232   }
233
234   delete RS;
235   RestoreBlocks.clear();
236   return true;
237 }
238
239 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
240 /// variables for the function's frame information and eliminate call frame
241 /// pseudo instructions.
242 void PEI::calculateCallsInformation(MachineFunction &Fn) {
243   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
244   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
245   MachineFrameInfo *MFI = Fn.getFrameInfo();
246
247   unsigned MaxCallFrameSize = 0;
248   bool AdjustsStack = MFI->adjustsStack();
249
250   // Get the function call frame set-up and tear-down instruction opcode
251   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
252   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
253
254   // Early exit for targets which have no call frame setup/destroy pseudo
255   // instructions.
256   if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
257     return;
258
259   std::vector<MachineBasicBlock::iterator> FrameSDOps;
260   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
261     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
262       if (I->getOpcode() == FrameSetupOpcode ||
263           I->getOpcode() == FrameDestroyOpcode) {
264         assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
265                " instructions should have a single immediate argument!");
266         unsigned Size = I->getOperand(0).getImm();
267         if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
268         AdjustsStack = true;
269         FrameSDOps.push_back(I);
270       } else if (I->isInlineAsm()) {
271         // Some inline asm's need a stack frame, as indicated by operand 1.
272         unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
273         if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
274           AdjustsStack = true;
275       }
276
277   MFI->setAdjustsStack(AdjustsStack);
278   MFI->setMaxCallFrameSize(MaxCallFrameSize);
279
280   for (std::vector<MachineBasicBlock::iterator>::iterator
281          i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
282     MachineBasicBlock::iterator I = *i;
283
284     // If call frames are not being included as part of the stack frame, and
285     // the target doesn't indicate otherwise, remove the call frame pseudos
286     // here. The sub/add sp instruction pairs are still inserted, but we don't
287     // need to track the SP adjustment for frame index elimination.
288     if (TFI->canSimplifyCallFramePseudos(Fn))
289       TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
290   }
291 }
292
293
294 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
295 /// registers.
296 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) {
297   const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
298   const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
299   MachineFrameInfo *MFI = F.getFrameInfo();
300
301   // Get the callee saved register list...
302   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
303
304   // These are used to keep track the callee-save area. Initialize them.
305   MinCSFrameIndex = INT_MAX;
306   MaxCSFrameIndex = 0;
307
308   // Early exit for targets which have no callee saved registers.
309   if (!CSRegs || CSRegs[0] == 0)
310     return;
311
312   // In Naked functions we aren't going to save any registers.
313   if (F.getFunction()->hasFnAttribute(Attribute::Naked))
314     return;
315
316   std::vector<CalleeSavedInfo> CSI;
317   for (unsigned i = 0; CSRegs[i]; ++i) {
318     unsigned Reg = CSRegs[i];
319     // Functions which call __builtin_unwind_init get all their registers saved.
320     if (F.getRegInfo().isPhysRegUsed(Reg) || F.getMMI().callsUnwindInit()) {
321       // If the reg is modified, save it!
322       CSI.push_back(CalleeSavedInfo(Reg));
323     }
324   }
325
326   if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
327     // If target doesn't implement this, use generic code.
328
329     if (CSI.empty())
330       return; // Early exit if no callee saved registers are modified!
331
332     unsigned NumFixedSpillSlots;
333     const TargetFrameLowering::SpillSlot *FixedSpillSlots =
334         TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
335
336     // Now that we know which registers need to be saved and restored, allocate
337     // stack slots for them.
338     for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
339          I != E; ++I) {
340       unsigned Reg = I->getReg();
341       const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
342
343       int FrameIdx;
344       if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
345         I->setFrameIdx(FrameIdx);
346         continue;
347       }
348
349       // Check to see if this physreg must be spilled to a particular stack slot
350       // on this target.
351       const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
352       while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
353              FixedSlot->Reg != Reg)
354         ++FixedSlot;
355
356       if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
357         // Nope, just spill it anywhere convenient.
358         unsigned Align = RC->getAlignment();
359         unsigned StackAlign = TFI->getStackAlignment();
360
361         // We may not be able to satisfy the desired alignment specification of
362         // the TargetRegisterClass if the stack alignment is smaller. Use the
363         // min.
364         Align = std::min(Align, StackAlign);
365         FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
366         if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
367         if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
368       } else {
369         // Spill it to the stack where we must.
370         FrameIdx =
371             MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
372       }
373
374       I->setFrameIdx(FrameIdx);
375     }
376   }
377
378   MFI->setCalleeSavedInfo(CSI);
379 }
380
381 /// Helper function to update the liveness information for the callee-saved
382 /// registers.
383 static void updateLiveness(MachineFunction &MF) {
384   MachineFrameInfo *MFI = MF.getFrameInfo();
385   // Visited will contain all the basic blocks that are in the region
386   // where the callee saved registers are alive:
387   // - Anything that is not Save or Restore -> LiveThrough.
388   // - Save -> LiveIn.
389   // - Restore -> LiveOut.
390   // The live-out is not attached to the block, so no need to keep
391   // Restore in this set.
392   SmallPtrSet<MachineBasicBlock *, 8> Visited;
393   SmallVector<MachineBasicBlock *, 8> WorkList;
394   MachineBasicBlock *Entry = &MF.front();
395   MachineBasicBlock *Save = MFI->getSavePoint();
396
397   if (!Save)
398     Save = Entry;
399
400   if (Entry != Save) {
401     WorkList.push_back(Entry);
402     Visited.insert(Entry);
403   }
404   Visited.insert(Save);
405
406   MachineBasicBlock *Restore = MFI->getRestorePoint();
407   if (Restore)
408     // By construction Restore cannot be visited, otherwise it
409     // means there exists a path to Restore that does not go
410     // through Save.
411     WorkList.push_back(Restore);
412
413   while (!WorkList.empty()) {
414     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
415     // By construction, the region that is after the save point is
416     // dominated by the Save and post-dominated by the Restore.
417     if (CurBB == Save)
418       continue;
419     // Enqueue all the successors not already visited.
420     // Those are by construction either before Save or after Restore.
421     for (MachineBasicBlock *SuccBB : CurBB->successors())
422       if (Visited.insert(SuccBB).second)
423         WorkList.push_back(SuccBB);
424   }
425
426   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
427
428   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
429     for (MachineBasicBlock *MBB : Visited)
430       // Add the callee-saved register as live-in.
431       // It's killed at the spill.
432       MBB->addLiveIn(CSI[i].getReg());
433   }
434 }
435
436 /// insertCSRSpillsAndRestores - Insert spill and restore code for
437 /// callee saved registers used in the function.
438 ///
439 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
440   // Get callee saved register information.
441   MachineFrameInfo *MFI = Fn.getFrameInfo();
442   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
443
444   MFI->setCalleeSavedInfoValid(true);
445
446   // Early exit if no callee saved registers are modified!
447   if (CSI.empty())
448     return;
449
450   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
451   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
452   const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
453   MachineBasicBlock::iterator I;
454
455   // Spill using target interface.
456   I = SaveBlock->begin();
457   if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
458     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
459       // Insert the spill to the stack frame.
460       unsigned Reg = CSI[i].getReg();
461       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
462       TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
463                               RC, TRI);
464     }
465   }
466   // Update the live-in information of all the blocks up to the save point.
467   updateLiveness(Fn);
468
469   // Restore using target interface.
470   for (MachineBasicBlock *MBB : RestoreBlocks) {
471     I = MBB->end();
472
473     // Skip over all terminator instructions, which are part of the return
474     // sequence.
475     MachineBasicBlock::iterator I2 = I;
476     while (I2 != MBB->begin() && (--I2)->isTerminator())
477       I = I2;
478
479     bool AtStart = I == MBB->begin();
480     MachineBasicBlock::iterator BeforeI = I;
481     if (!AtStart)
482       --BeforeI;
483
484     // Restore all registers immediately before the return and any
485     // terminators that precede it.
486     if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
487       for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
488         unsigned Reg = CSI[i].getReg();
489         const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
490         TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
491         assert(I != MBB->begin() &&
492                "loadRegFromStackSlot didn't insert any code!");
493         // Insert in reverse order.  loadRegFromStackSlot can insert
494         // multiple instructions.
495         if (AtStart)
496           I = MBB->begin();
497         else {
498           I = BeforeI;
499           ++I;
500         }
501       }
502     }
503   }
504 }
505
506 /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
507 static inline void
508 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
509                   bool StackGrowsDown, int64_t &Offset,
510                   unsigned &MaxAlign) {
511   // If the stack grows down, add the object size to find the lowest address.
512   if (StackGrowsDown)
513     Offset += MFI->getObjectSize(FrameIdx);
514
515   unsigned Align = MFI->getObjectAlignment(FrameIdx);
516
517   // If the alignment of this object is greater than that of the stack, then
518   // increase the stack alignment to match.
519   MaxAlign = std::max(MaxAlign, Align);
520
521   // Adjust to alignment boundary.
522   Offset = (Offset + Align - 1) / Align * Align;
523
524   if (StackGrowsDown) {
525     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
526     MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
527   } else {
528     DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
529     MFI->setObjectOffset(FrameIdx, Offset);
530     Offset += MFI->getObjectSize(FrameIdx);
531   }
532 }
533
534 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
535 /// those required to be close to the Stack Protector) to stack offsets.
536 static void
537 AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
538                       SmallSet<int, 16> &ProtectedObjs,
539                       MachineFrameInfo *MFI, bool StackGrowsDown,
540                       int64_t &Offset, unsigned &MaxAlign) {
541
542   for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
543         E = UnassignedObjs.end(); I != E; ++I) {
544     int i = *I;
545     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
546     ProtectedObjs.insert(i);
547   }
548 }
549
550 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
551 /// abstract stack objects.
552 ///
553 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
554   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
555   StackProtector *SP = &getAnalysis<StackProtector>();
556
557   bool StackGrowsDown =
558     TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
559
560   // Loop over all of the stack objects, assigning sequential addresses...
561   MachineFrameInfo *MFI = Fn.getFrameInfo();
562
563   // Start at the beginning of the local area.
564   // The Offset is the distance from the stack top in the direction
565   // of stack growth -- so it's always nonnegative.
566   int LocalAreaOffset = TFI.getOffsetOfLocalArea();
567   if (StackGrowsDown)
568     LocalAreaOffset = -LocalAreaOffset;
569   assert(LocalAreaOffset >= 0
570          && "Local area offset should be in direction of stack growth");
571   int64_t Offset = LocalAreaOffset;
572
573   // If there are fixed sized objects that are preallocated in the local area,
574   // non-fixed objects can't be allocated right at the start of local area.
575   // We currently don't support filling in holes in between fixed sized
576   // objects, so we adjust 'Offset' to point to the end of last fixed sized
577   // preallocated object.
578   for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
579     int64_t FixedOff;
580     if (StackGrowsDown) {
581       // The maximum distance from the stack pointer is at lower address of
582       // the object -- which is given by offset. For down growing stack
583       // the offset is negative, so we negate the offset to get the distance.
584       FixedOff = -MFI->getObjectOffset(i);
585     } else {
586       // The maximum distance from the start pointer is at the upper
587       // address of the object.
588       FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
589     }
590     if (FixedOff > Offset) Offset = FixedOff;
591   }
592
593   // First assign frame offsets to stack objects that are used to spill
594   // callee saved registers.
595   if (StackGrowsDown) {
596     for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
597       // If the stack grows down, we need to add the size to find the lowest
598       // address of the object.
599       Offset += MFI->getObjectSize(i);
600
601       unsigned Align = MFI->getObjectAlignment(i);
602       // Adjust to alignment boundary
603       Offset = RoundUpToAlignment(Offset, Align);
604
605       MFI->setObjectOffset(i, -Offset);        // Set the computed offset
606     }
607   } else {
608     int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
609     for (int i = MaxCSFI; i >= MinCSFI ; --i) {
610       unsigned Align = MFI->getObjectAlignment(i);
611       // Adjust to alignment boundary
612       Offset = RoundUpToAlignment(Offset, Align);
613
614       MFI->setObjectOffset(i, Offset);
615       Offset += MFI->getObjectSize(i);
616     }
617   }
618
619   unsigned MaxAlign = MFI->getMaxAlignment();
620
621   // Make sure the special register scavenging spill slot is closest to the
622   // incoming stack pointer if a frame pointer is required and is closer
623   // to the incoming rather than the final stack pointer.
624   const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
625   bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
626                                TFI.isFPCloseToIncomingSP() &&
627                                RegInfo->useFPForScavengingIndex(Fn) &&
628                                !RegInfo->needsStackRealignment(Fn));
629   if (RS && EarlyScavengingSlots) {
630     SmallVector<int, 2> SFIs;
631     RS->getScavengingFrameIndices(SFIs);
632     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
633            IE = SFIs.end(); I != IE; ++I)
634       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
635   }
636
637   // FIXME: Once this is working, then enable flag will change to a target
638   // check for whether the frame is large enough to want to use virtual
639   // frame index registers. Functions which don't want/need this optimization
640   // will continue to use the existing code path.
641   if (MFI->getUseLocalStackAllocationBlock()) {
642     unsigned Align = MFI->getLocalFrameMaxAlign();
643
644     // Adjust to alignment boundary.
645     Offset = RoundUpToAlignment(Offset, Align);
646
647     DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
648
649     // Resolve offsets for objects in the local block.
650     for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
651       std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
652       int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
653       DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
654             FIOffset << "]\n");
655       MFI->setObjectOffset(Entry.first, FIOffset);
656     }
657     // Allocate the local block
658     Offset += MFI->getLocalFrameSize();
659
660     MaxAlign = std::max(Align, MaxAlign);
661   }
662
663   // Make sure that the stack protector comes before the local variables on the
664   // stack.
665   SmallSet<int, 16> ProtectedObjs;
666   if (MFI->getStackProtectorIndex() >= 0) {
667     StackObjSet LargeArrayObjs;
668     StackObjSet SmallArrayObjs;
669     StackObjSet AddrOfObjs;
670
671     AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
672                       Offset, MaxAlign);
673
674     // Assign large stack objects first.
675     for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
676       if (MFI->isObjectPreAllocated(i) &&
677           MFI->getUseLocalStackAllocationBlock())
678         continue;
679       if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
680         continue;
681       if (RS && RS->isScavengingFrameIndex((int)i))
682         continue;
683       if (MFI->isDeadObjectIndex(i))
684         continue;
685       if (MFI->getStackProtectorIndex() == (int)i)
686         continue;
687
688       switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
689       case StackProtector::SSPLK_None:
690         continue;
691       case StackProtector::SSPLK_SmallArray:
692         SmallArrayObjs.insert(i);
693         continue;
694       case StackProtector::SSPLK_AddrOf:
695         AddrOfObjs.insert(i);
696         continue;
697       case StackProtector::SSPLK_LargeArray:
698         LargeArrayObjs.insert(i);
699         continue;
700       }
701       llvm_unreachable("Unexpected SSPLayoutKind.");
702     }
703
704     AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
705                           Offset, MaxAlign);
706     AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
707                           Offset, MaxAlign);
708     AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
709                           Offset, MaxAlign);
710   }
711
712   // Then assign frame offsets to stack objects that are not used to spill
713   // callee saved registers.
714   for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
715     if (MFI->isObjectPreAllocated(i) &&
716         MFI->getUseLocalStackAllocationBlock())
717       continue;
718     if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
719       continue;
720     if (RS && RS->isScavengingFrameIndex((int)i))
721       continue;
722     if (MFI->isDeadObjectIndex(i))
723       continue;
724     if (MFI->getStackProtectorIndex() == (int)i)
725       continue;
726     if (ProtectedObjs.count(i))
727       continue;
728
729     AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
730   }
731
732   // Make sure the special register scavenging spill slot is closest to the
733   // stack pointer.
734   if (RS && !EarlyScavengingSlots) {
735     SmallVector<int, 2> SFIs;
736     RS->getScavengingFrameIndices(SFIs);
737     for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
738            IE = SFIs.end(); I != IE; ++I)
739       AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
740   }
741
742   if (!TFI.targetHandlesStackFrameRounding()) {
743     // If we have reserved argument space for call sites in the function
744     // immediately on entry to the current function, count it as part of the
745     // overall stack size.
746     if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
747       Offset += MFI->getMaxCallFrameSize();
748
749     // Round up the size to a multiple of the alignment.  If the function has
750     // any calls or alloca's, align to the target's StackAlignment value to
751     // ensure that the callee's frame or the alloca data is suitably aligned;
752     // otherwise, for leaf functions, align to the TransientStackAlignment
753     // value.
754     unsigned StackAlign;
755     if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
756         (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
757       StackAlign = TFI.getStackAlignment();
758     else
759       StackAlign = TFI.getTransientStackAlignment();
760
761     // If the frame pointer is eliminated, all frame offsets will be relative to
762     // SP not FP. Align to MaxAlign so this works.
763     StackAlign = std::max(StackAlign, MaxAlign);
764     Offset = RoundUpToAlignment(Offset, StackAlign);
765   }
766
767   // Update frame info to pretend that this is part of the stack...
768   int64_t StackSize = Offset - LocalAreaOffset;
769   MFI->setStackSize(StackSize);
770   NumBytesStackSpace += StackSize;
771 }
772
773 /// insertPrologEpilogCode - Scan the function for modified callee saved
774 /// registers, insert spill code for these callee saved registers, then add
775 /// prolog and epilog code to the function.
776 ///
777 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
778   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
779
780   // Add prologue to the function...
781   TFI.emitPrologue(Fn, *SaveBlock);
782
783   // Add epilogue to restore the callee-save registers in each exiting block.
784   for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
785     TFI.emitEpilogue(Fn, *RestoreBlock);
786
787   // Emit additional code that is required to support segmented stacks, if
788   // we've been asked for it.  This, when linked with a runtime with support
789   // for segmented stacks (libgcc is one), will result in allocating stack
790   // space in small chunks instead of one large contiguous block.
791   if (Fn.shouldSplitStack())
792     TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
793
794   // Emit additional code that is required to explicitly handle the stack in
795   // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
796   // approach is rather similar to that of Segmented Stacks, but it uses a
797   // different conditional check and another BIF for allocating more stack
798   // space.
799   if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
800     TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
801 }
802
803 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
804 /// register references and actual offsets.
805 ///
806 void PEI::replaceFrameIndices(MachineFunction &Fn) {
807   const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
808   if (!TFI.needsFrameIndexResolution(Fn)) return;
809
810   MachineModuleInfo &MMI = Fn.getMMI();
811   const Function *F = Fn.getFunction();
812   const Function *ParentF = MMI.getWinEHParent(F);
813   unsigned FrameReg;
814   if (F == ParentF) {
815     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
816     // FIXME: This should be unconditional but we have bugs in the preparation
817     // pass.
818     if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
819       FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
820           Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
821   } else if (MMI.hasWinEHFuncInfo(F)) {
822     WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
823     auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
824     if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
825       FuncInfo.CatchHandlerParentFrameObjOffset[F] =
826           TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
827   }
828
829   // Store SPAdj at exit of a basic block.
830   SmallVector<int, 8> SPState;
831   SPState.resize(Fn.getNumBlockIDs());
832   SmallPtrSet<MachineBasicBlock*, 8> Reachable;
833
834   // Iterate over the reachable blocks in DFS order.
835   for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
836        DFI != DFE; ++DFI) {
837     int SPAdj = 0;
838     // Check the exit state of the DFS stack predecessor.
839     if (DFI.getPathLength() >= 2) {
840       MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
841       assert(Reachable.count(StackPred) &&
842              "DFS stack predecessor is already visited.\n");
843       SPAdj = SPState[StackPred->getNumber()];
844     }
845     MachineBasicBlock *BB = *DFI;
846     replaceFrameIndices(BB, Fn, SPAdj);
847     SPState[BB->getNumber()] = SPAdj;
848   }
849
850   // Handle the unreachable blocks.
851   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
852     if (Reachable.count(BB))
853       // Already handled in DFS traversal.
854       continue;
855     int SPAdj = 0;
856     replaceFrameIndices(BB, Fn, SPAdj);
857   }
858 }
859
860 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
861                               int &SPAdj) {
862   assert(Fn.getSubtarget().getRegisterInfo() &&
863          "getRegisterInfo() must be implemented!");
864   const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
865   const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
866   const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
867   unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
868   unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
869
870   if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
871
872   bool InsideCallSequence = false;
873
874   for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
875
876     if (I->getOpcode() == FrameSetupOpcode ||
877         I->getOpcode() == FrameDestroyOpcode) {
878       InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
879       SPAdj += TII.getSPAdjust(I);
880
881       MachineBasicBlock::iterator PrevI = BB->end();
882       if (I != BB->begin()) PrevI = std::prev(I);
883       TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
884
885       // Visit the instructions created by eliminateCallFramePseudoInstr().
886       if (PrevI == BB->end())
887         I = BB->begin();     // The replaced instr was the first in the block.
888       else
889         I = std::next(PrevI);
890       continue;
891     }
892
893     MachineInstr *MI = I;
894     bool DoIncr = true;
895     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
896       if (!MI->getOperand(i).isFI())
897         continue;
898
899       // Frame indicies in debug values are encoded in a target independent
900       // way with simply the frame index and offset rather than any
901       // target-specific addressing mode.
902       if (MI->isDebugValue()) {
903         assert(i == 0 && "Frame indicies can only appear as the first "
904                          "operand of a DBG_VALUE machine instruction");
905         unsigned Reg;
906         MachineOperand &Offset = MI->getOperand(1);
907         Offset.setImm(Offset.getImm() +
908                       TFI->getFrameIndexReference(
909                           Fn, MI->getOperand(0).getIndex(), Reg));
910         MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
911         continue;
912       }
913
914       // TODO: This code should be commoned with the code for
915       // PATCHPOINT. There's no good reason for the difference in
916       // implementation other than historical accident.  The only
917       // remaining difference is the unconditional use of the stack
918       // pointer as the base register.
919       if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
920         assert((!MI->isDebugValue() || i == 0) &&
921                "Frame indicies can only appear as the first operand of a "
922                "DBG_VALUE machine instruction");
923         unsigned Reg;
924         MachineOperand &Offset = MI->getOperand(i + 1);
925         const unsigned refOffset =
926           TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
927                                             Reg);
928
929         Offset.setImm(Offset.getImm() + refOffset);
930         MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
931         continue;
932       }
933
934       // Some instructions (e.g. inline asm instructions) can have
935       // multiple frame indices and/or cause eliminateFrameIndex
936       // to insert more than one instruction. We need the register
937       // scavenger to go through all of these instructions so that
938       // it can update its register information. We keep the
939       // iterator at the point before insertion so that we can
940       // revisit them in full.
941       bool AtBeginning = (I == BB->begin());
942       if (!AtBeginning) --I;
943
944       // If this instruction has a FrameIndex operand, we need to
945       // use that target machine register info object to eliminate
946       // it.
947       TRI.eliminateFrameIndex(MI, SPAdj, i,
948                               FrameIndexVirtualScavenging ?  nullptr : RS);
949
950       // Reset the iterator if we were at the beginning of the BB.
951       if (AtBeginning) {
952         I = BB->begin();
953         DoIncr = false;
954       }
955
956       MI = nullptr;
957       break;
958     }
959
960     // If we are looking at a call sequence, we need to keep track of
961     // the SP adjustment made by each instruction in the sequence.
962     // This includes both the frame setup/destroy pseudos (handled above),
963     // as well as other instructions that have side effects w.r.t the SP.
964     // Note that this must come after eliminateFrameIndex, because 
965     // if I itself referred to a frame index, we shouldn't count its own
966     // adjustment.
967     if (MI && InsideCallSequence)
968       SPAdj += TII.getSPAdjust(MI);
969
970     if (DoIncr && I != BB->end()) ++I;
971
972     // Update register states.
973     if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
974   }
975 }
976
977 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
978 /// with physical registers. Use the register scavenger to find an
979 /// appropriate register to use.
980 ///
981 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
982 /// iterate over the vreg use list, which at this point only contains machine
983 /// operands for which eliminateFrameIndex need a new scratch reg.
984 void
985 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
986   // Run through the instructions and find any virtual registers.
987   for (MachineFunction::iterator BB = Fn.begin(),
988        E = Fn.end(); BB != E; ++BB) {
989     RS->enterBasicBlock(BB);
990
991     int SPAdj = 0;
992
993     // The instruction stream may change in the loop, so check BB->end()
994     // directly.
995     for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
996       // We might end up here again with a NULL iterator if we scavenged a
997       // register for which we inserted spill code for definition by what was
998       // originally the first instruction in BB.
999       if (I == MachineBasicBlock::iterator(nullptr))
1000         I = BB->begin();
1001
1002       MachineInstr *MI = I;
1003       MachineBasicBlock::iterator J = std::next(I);
1004       MachineBasicBlock::iterator P =
1005                          I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
1006                                           : std::prev(I);
1007
1008       // RS should process this instruction before we might scavenge at this
1009       // location. This is because we might be replacing a virtual register
1010       // defined by this instruction, and if so, registers killed by this
1011       // instruction are available, and defined registers are not.
1012       RS->forward(I);
1013
1014       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1015         if (MI->getOperand(i).isReg()) {
1016           MachineOperand &MO = MI->getOperand(i);
1017           unsigned Reg = MO.getReg();
1018           if (Reg == 0)
1019             continue;
1020           if (!TargetRegisterInfo::isVirtualRegister(Reg))
1021             continue;
1022
1023           // When we first encounter a new virtual register, it
1024           // must be a definition.
1025           assert(MI->getOperand(i).isDef() &&
1026                  "frame index virtual missing def!");
1027           // Scavenge a new scratch register
1028           const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
1029           unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
1030
1031           ++NumScavengedRegs;
1032
1033           // Replace this reference to the virtual register with the
1034           // scratch register.
1035           assert (ScratchReg && "Missing scratch register!");
1036           MachineRegisterInfo &MRI = Fn.getRegInfo();
1037           Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
1038           
1039           // Make sure MRI now accounts this register as used.
1040           MRI.setPhysRegUsed(ScratchReg);
1041
1042           // Because this instruction was processed by the RS before this
1043           // register was allocated, make sure that the RS now records the
1044           // register as being used.
1045           RS->setRegUsed(ScratchReg);
1046         }
1047       }
1048
1049       // If the scavenger needed to use one of its spill slots, the
1050       // spill code will have been inserted in between I and J. This is a
1051       // problem because we need the spill code before I: Move I to just
1052       // prior to J.
1053       if (I != std::prev(J)) {
1054         BB->splice(J, BB, I);
1055
1056         // Before we move I, we need to prepare the RS to visit I again.
1057         // Specifically, RS will assert if it sees uses of registers that
1058         // it believes are undefined. Because we have already processed
1059         // register kills in I, when it visits I again, it will believe that
1060         // those registers are undefined. To avoid this situation, unprocess
1061         // the instruction I.
1062         assert(RS->getCurrentPosition() == I &&
1063           "The register scavenger has an unexpected position");
1064         I = P;
1065         RS->unprocess(P);
1066       } else
1067         ++I;
1068     }
1069   }
1070 }