blob: d9443c83e7550fe9ee15828dc7bde53de5408ef4 [file] [log] [blame]
Chris Lattner58b33282002-12-28 20:43:30 +00001//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner58b33282002-12-28 20:43:30 +00009//
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
Chris Lattnerf00a3f92003-01-13 00:23:41 +000019#include "llvm/CodeGen/Passes.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner58b33282002-12-28 20:43:30 +000021#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnereb24db92002-12-28 21:08:26 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner58b33282002-12-28 20:43:30 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/MRegisterInfo.h"
Chris Lattner8bd66e62002-12-28 21:00:25 +000025#include "llvm/Target/TargetFrameInfo.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000026#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner05d83502004-02-15 00:14:20 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner58b33282002-12-28 20:43:30 +000029namespace {
Chris Lattnerf00a3f92003-01-13 00:23:41 +000030 struct PEI : public MachineFunctionPass {
31 const char *getPassName() const {
32 return "Prolog/Epilog Insertion & Frame Finalization";
Chris Lattner58b33282002-12-28 20:43:30 +000033 }
34
35 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
36 /// frame indexes with appropriate references.
37 ///
38 bool runOnMachineFunction(MachineFunction &Fn) {
39 // Scan the function for modified caller saved registers and insert spill
40 // code for any caller saved registers that are modified. Also calculate
41 // the MaxCallFrameSize and HasCalls variables for the function's frame
42 // information and eliminates call frame pseudo instructions.
Chris Lattnerc330b682004-08-12 19:01:14 +000043 calculateCallerSavedRegisters(Fn);
44
45 // Add the code to save and restore the caller saved registers
Chris Lattner58b33282002-12-28 20:43:30 +000046 saveCallerSavedRegisters(Fn);
47
48 // Allow the target machine to make final modifications to the function
49 // before the frame layout is finalized.
50 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
51
52 // Calculate actual frame offsets for all of the abstract stack objects...
53 calculateFrameObjectOffsets(Fn);
54
Chris Lattnerc330b682004-08-12 19:01:14 +000055 // Add prolog and epilog code to the function. This function is required
56 // to align the stack frame as necessary for any stack variables or
57 // called functions. Because of this, calculateCallerSavedRegisters
58 // must be called before this function in order to set the HasCalls
59 // and MaxCallFrameSize variables.
Chris Lattner4ac7d732003-01-15 22:52:34 +000060 insertPrologEpilogCode(Fn);
61
Chris Lattner58b33282002-12-28 20:43:30 +000062 // Replace all MO_FrameIndex operands with physical register references
63 // and actual offsets.
64 //
65 replaceFrameIndices(Fn);
Chris Lattnerc330b682004-08-12 19:01:14 +000066
67 RegsToSave.clear();
68 StackSlots.clear();
Chris Lattner58b33282002-12-28 20:43:30 +000069 return true;
70 }
71
72 private:
Chris Lattnerc330b682004-08-12 19:01:14 +000073 std::vector<unsigned> RegsToSave;
74 std::vector<int> StackSlots;
75
76 void calculateCallerSavedRegisters(MachineFunction &Fn);
Chris Lattner58b33282002-12-28 20:43:30 +000077 void saveCallerSavedRegisters(MachineFunction &Fn);
78 void calculateFrameObjectOffsets(MachineFunction &Fn);
79 void replaceFrameIndices(MachineFunction &Fn);
80 void insertPrologEpilogCode(MachineFunction &Fn);
81 };
82}
83
Brian Gaeked0fde302003-11-11 22:41:34 +000084
Chris Lattner58b33282002-12-28 20:43:30 +000085/// createPrologEpilogCodeInserter - This function returns a pass that inserts
86/// prolog and epilog code, and eliminates abstract frame references.
87///
Chris Lattner05d83502004-02-15 00:14:20 +000088FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
Chris Lattner58b33282002-12-28 20:43:30 +000089
90
Chris Lattnerc330b682004-08-12 19:01:14 +000091/// calculateCallerSavedRegisters - Scan the function for modified caller saved
92/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for
Chris Lattner58b33282002-12-28 20:43:30 +000093/// the function's frame information and eliminates call frame pseudo
94/// instructions.
95///
Chris Lattnerc330b682004-08-12 19:01:14 +000096void PEI::calculateCallerSavedRegisters(MachineFunction &Fn) {
Chris Lattner58b33282002-12-28 20:43:30 +000097 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
Chris Lattnerc330b682004-08-12 19:01:14 +000098 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo();
Chris Lattner58b33282002-12-28 20:43:30 +000099
100 // Get the callee saved register list...
101 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
102
103 // Get the function call frame set-up and tear-down instruction opcode
104 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
105 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
106
107 // Early exit for targets which have no callee saved registers and no call
108 // frame setup/destroy pseudo instructions.
109 if ((CSRegs == 0 || CSRegs[0] == 0) &&
110 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
111 return;
112
113 // This bitset contains an entry for each physical register for the target...
Alkis Evlogimenos859a18b2004-02-15 21:37:17 +0000114 std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
Chris Lattner58b33282002-12-28 20:43:30 +0000115 unsigned MaxCallFrameSize = 0;
116 bool HasCalls = false;
117
118 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
119 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000120 if (I->getOpcode() == FrameSetupOpcode ||
Chris Lattnerd555da52004-08-07 07:07:57 +0000121 I->getOpcode() == FrameDestroyOpcode) {
122 assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
123 " instructions should have a single immediate argument!");
124 unsigned Size = I->getOperand(0).getImmedValue();
125 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
126 HasCalls = true;
127 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
Chris Lattner58b33282002-12-28 20:43:30 +0000128 } else {
Chris Lattnerd555da52004-08-07 07:07:57 +0000129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
130 MachineOperand &MO = I->getOperand(i);
131 if (MO.isRegister() && MO.isDef()) {
Chris Lattner1cbe4d02004-02-10 21:12:22 +0000132 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
133 "Register allocation must be performed!");
Chris Lattnerd555da52004-08-07 07:07:57 +0000134 ModifiedRegs[MO.getReg()] = true; // Register is modified
Chris Lattner1cbe4d02004-02-10 21:12:22 +0000135 }
136 }
Chris Lattnerd555da52004-08-07 07:07:57 +0000137 ++I;
Chris Lattner58b33282002-12-28 20:43:30 +0000138 }
139
Chris Lattnereb24db92002-12-28 21:08:26 +0000140 MachineFrameInfo *FFI = Fn.getFrameInfo();
Chris Lattner58b33282002-12-28 20:43:30 +0000141 FFI->setHasCalls(HasCalls);
142 FFI->setMaxCallFrameSize(MaxCallFrameSize);
143
144 // Now figure out which *callee saved* registers are modified by the current
145 // function, thus needing to be saved and restored in the prolog/epilog.
146 //
Chris Lattner58b33282002-12-28 20:43:30 +0000147 for (unsigned i = 0; CSRegs[i]; ++i) {
148 unsigned Reg = CSRegs[i];
149 if (ModifiedRegs[Reg]) {
150 RegsToSave.push_back(Reg); // If modified register...
Alkis Evlogimenos73ff5122003-10-08 05:20:08 +0000151 } else {
152 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
153 *AliasSet; ++AliasSet) { // Check alias registers too...
Chris Lattnerecf8afd2004-08-07 07:18:41 +0000154 if (ModifiedRegs[*AliasSet]) {
Chris Lattnerd555da52004-08-07 07:07:57 +0000155 RegsToSave.push_back(Reg);
156 break;
Chris Lattnerecf8afd2004-08-07 07:18:41 +0000157 }
Alkis Evlogimenos73ff5122003-10-08 05:20:08 +0000158 }
159 }
Chris Lattner58b33282002-12-28 20:43:30 +0000160 }
161
162 if (RegsToSave.empty())
163 return; // Early exit if no caller saved registers are modified!
164
Chris Lattnerc330b682004-08-12 19:01:14 +0000165 unsigned NumFixedSpillSlots;
Alkis Evlogimenos8c9b4de2004-08-15 09:18:55 +0000166 const std::pair<unsigned,int> *FixedSpillSlots =
Chris Lattnerc330b682004-08-12 19:01:14 +0000167 TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots);
168
Chris Lattner58b33282002-12-28 20:43:30 +0000169 // Now that we know which registers need to be saved and restored, allocate
170 // stack slots for them.
Chris Lattner58b33282002-12-28 20:43:30 +0000171 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
Chris Lattnerc330b682004-08-12 19:01:14 +0000172 unsigned Reg = RegsToSave[i];
173 int FrameIdx;
174 const TargetRegisterClass *RC = RegInfo->getRegClass(Reg);
175
176 // Check to see if this physreg must be spilled to a particular stack slot
177 // on this target.
Alkis Evlogimenos8c9b4de2004-08-15 09:18:55 +0000178 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots;
Chris Lattnerc330b682004-08-12 19:01:14 +0000179 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
180 FixedSlot->first != Reg)
181 ++FixedSlot;
182
183 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) {
184 // Nope, just spill it anywhere convenient.
185 FrameIdx = FFI->CreateStackObject(RC);
186 } else {
187 // Spill it to the stack where we must.
188 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second);
189 }
Chris Lattner58b33282002-12-28 20:43:30 +0000190 StackSlots.push_back(FrameIdx);
191 }
Chris Lattnerc330b682004-08-12 19:01:14 +0000192}
193
194/// saveCallerSavedRegisters - Insert spill code for any caller saved registers
195/// that are modified in the function.
196///
197void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
198 // Early exit if no caller saved registers are modified!
199 if (RegsToSave.empty())
200 return;
201
202 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
Chris Lattner58b33282002-12-28 20:43:30 +0000203
204 // Now that we have a stack slot for each register to be saved, insert spill
205 // code into the entry block...
206 MachineBasicBlock *MBB = Fn.begin();
207 MachineBasicBlock::iterator I = MBB->begin();
208 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
Chris Lattner57f1b672004-08-15 21:56:44 +0000209 // Insert the spill to the stack frame.
210 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i]);
Chris Lattner58b33282002-12-28 20:43:30 +0000211 }
212
213 // Add code to restore the callee-save registers in each exiting block.
Chris Lattner9bcdcd12004-06-02 05:57:12 +0000214 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
Chris Lattner58b33282002-12-28 20:43:30 +0000215 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
216 // If last instruction is a return instruction, add an epilogue
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000217 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
218 MBB = FI;
219 I = MBB->end(); --I;
Chris Lattner58b33282002-12-28 20:43:30 +0000220
221 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
Chris Lattner57f1b672004-08-15 21:56:44 +0000222 RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i]);
Chris Lattnerecf8afd2004-08-07 07:18:41 +0000223 --I; // Insert in reverse order
Chris Lattner58b33282002-12-28 20:43:30 +0000224 }
225 }
226 }
227}
228
229
230/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
231/// abstract stack objects...
232///
233void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
Chris Lattner9bcdcd12004-06-02 05:57:12 +0000234 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo();
Chris Lattner58b33282002-12-28 20:43:30 +0000235
236 bool StackGrowsDown =
237 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
Chris Lattner58b33282002-12-28 20:43:30 +0000238
239 // Loop over all of the stack objects, assigning sequential addresses...
Chris Lattnereb24db92002-12-28 21:08:26 +0000240 MachineFrameInfo *FFI = Fn.getFrameInfo();
Chris Lattner58b33282002-12-28 20:43:30 +0000241
Chris Lattnerf85249c2003-01-16 02:24:20 +0000242 unsigned StackAlignment = TFI.getStackAlignment();
Chris Lattner78d6db52003-01-16 02:22:08 +0000243
Chris Lattner05d83502004-02-15 00:14:20 +0000244 // Start at the beginning of the local area.
Chris Lattner577aec12004-06-10 06:23:35 +0000245 // The Offset is the distance from the stack top in the direction
246 // of stack growth -- so it's always positive.
Chris Lattner4ac7d732003-01-15 22:52:34 +0000247 int Offset = TFI.getOffsetOfLocalArea();
Chris Lattner577aec12004-06-10 06:23:35 +0000248 if (StackGrowsDown)
Chris Lattner7f7bbc22004-06-11 06:37:11 +0000249 Offset = -Offset;
Chris Lattner577aec12004-06-10 06:23:35 +0000250 assert(Offset >= 0
251 && "Local area offset should be in direction of stack growth");
Chris Lattner05d83502004-02-15 00:14:20 +0000252
Chris Lattner577aec12004-06-10 06:23:35 +0000253 // If there are fixed sized objects that are preallocated in the local area,
254 // non-fixed objects can't be allocated right at the start of local area.
255 // We currently don't support filling in holes in between fixed sized objects,
256 // so we adjust 'Offset' to point to the end of last fixed sized
Chris Lattner05d83502004-02-15 00:14:20 +0000257 // preallocated object.
258 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
Chris Lattner577aec12004-06-10 06:23:35 +0000259 int FixedOff;
260 if (StackGrowsDown) {
261 // The maximum distance from the stack pointer is at lower address of
262 // the object -- which is given by offset. For down growing stack
263 // the offset is negative, so we negate the offset to get the distance.
264 FixedOff = -FFI->getObjectOffset(i);
265 } else {
266 // The maximum distance from the start pointer is at the upper
267 // address of the object.
268 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i);
269 }
270 if (FixedOff > Offset) Offset = FixedOff;
Chris Lattner05d83502004-02-15 00:14:20 +0000271 }
272
Chris Lattner58b33282002-12-28 20:43:30 +0000273 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
Chris Lattner577aec12004-06-10 06:23:35 +0000274 // If stack grows down, we need to add size of find the lowest
275 // address of the object.
276 if (StackGrowsDown)
277 Offset += FFI->getObjectSize(i);
Chris Lattner58b33282002-12-28 20:43:30 +0000278
279 unsigned Align = FFI->getObjectAlignment(i);
Chris Lattnerf85249c2003-01-16 02:24:20 +0000280 assert(Align <= StackAlignment && "Cannot align stack object to higher "
Chris Lattner78d6db52003-01-16 02:22:08 +0000281 "alignment boundary than the stack itself!");
Chris Lattner58b33282002-12-28 20:43:30 +0000282 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
283
Chris Lattner577aec12004-06-10 06:23:35 +0000284 if (StackGrowsDown) {
285 FFI->setObjectOffset(i, -Offset); // Set the computed offset
286 } else {
287 FFI->setObjectOffset(i, Offset);
288 Offset += FFI->getObjectSize(i);
289 }
Chris Lattner58b33282002-12-28 20:43:30 +0000290 }
291
Chris Lattner93799292004-02-14 20:10:59 +0000292 // Align the final stack pointer offset, but only if there are calls in the
293 // function. This ensures that any calls to subroutines have their stack
294 // frames suitable aligned.
295 if (FFI->hasCalls())
296 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
Chris Lattner58b33282002-12-28 20:43:30 +0000297
298 // Set the final value of the stack pointer...
Chris Lattner7f7bbc22004-06-11 06:37:11 +0000299 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea());
Chris Lattner4ac7d732003-01-15 22:52:34 +0000300}
301
302
303/// insertPrologEpilogCode - Scan the function for modified caller saved
304/// registers, insert spill code for these caller saved registers, then add
305/// prolog and epilog code to the function.
306///
307void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
308 // Add prologue to the function...
309 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
310
311 // Add epilogue to restore the callee-save registers in each exiting block
Chris Lattner9bcdcd12004-06-02 05:57:12 +0000312 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
Chris Lattner4ac7d732003-01-15 22:52:34 +0000313 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
314 // If last instruction is a return instruction, add an epilogue
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000315 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
Chris Lattner4ac7d732003-01-15 22:52:34 +0000316 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
317 }
Chris Lattner58b33282002-12-28 20:43:30 +0000318}
319
320
321/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
322/// register references and actual offsets.
323///
324void PEI::replaceFrameIndices(MachineFunction &Fn) {
325 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
326
327 const TargetMachine &TM = Fn.getTarget();
328 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
329 const MRegisterInfo &MRI = *TM.getRegisterInfo();
330
331 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
332 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000333 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattnerecf8afd2004-08-07 07:18:41 +0000334 if (I->getOperand(i).isFrameIndex()) {
335 // If this instruction has a FrameIndex operand, we need to use that
336 // target machine register info object to eliminate it.
Nate Begeman5de0f7a2004-08-14 22:00:10 +0000337 MRI.eliminateFrameIndex(I);
Chris Lattnerecf8afd2004-08-07 07:18:41 +0000338 break;
339 }
Chris Lattner58b33282002-12-28 20:43:30 +0000340}