1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass is responsible for finalizing the functions frame layout, saving
11 // callee saved registers, and for emitting prolog & epilog code for the
14 // This pass must be run after register allocation. After this pass is
15 // executed, it is illegal to construct MO_FrameIndex operands.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
30 struct PEI : public MachineFunctionPass {
31 const char *getPassName() const {
32 return "Prolog/Epilog Insertion & Frame Finalization";
35 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
36 /// frame indexes with appropriate references.
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.
43 saveCallerSavedRegisters(Fn);
45 // Allow the target machine to make final modifications to the function
46 // before the frame layout is finalized.
47 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
49 // Calculate actual frame offsets for all of the abstract stack objects...
50 calculateFrameObjectOffsets(Fn);
52 // Add prolog and epilog code to the function.
53 insertPrologEpilogCode(Fn);
55 // Replace all MO_FrameIndex operands with physical register references
56 // and actual offsets.
58 replaceFrameIndices(Fn);
63 void saveCallerSavedRegisters(MachineFunction &Fn);
64 void calculateFrameObjectOffsets(MachineFunction &Fn);
65 void replaceFrameIndices(MachineFunction &Fn);
66 void insertPrologEpilogCode(MachineFunction &Fn);
71 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
72 /// prolog and epilog code, and eliminates abstract frame references.
74 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
77 /// saveCallerSavedRegisters - Scan the function for modified caller saved
78 /// registers and insert spill code for any caller saved registers that are
79 /// modified. Also calculate the MaxCallFrameSize and HasCalls variables for
80 /// the function's frame information and eliminates call frame pseudo
83 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
84 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
85 const TargetFrameInfo &FrameInfo = Fn.getTarget().getFrameInfo();
87 // Get the callee saved register list...
88 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
90 // Get the function call frame set-up and tear-down instruction opcode
91 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
92 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
94 // Early exit for targets which have no callee saved registers and no call
95 // frame setup/destroy pseudo instructions.
96 if ((CSRegs == 0 || CSRegs[0] == 0) &&
97 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
100 // This bitset contains an entry for each physical register for the target...
101 std::vector<bool> ModifiedRegs(RegInfo->getNumRegs());
102 unsigned MaxCallFrameSize = 0;
103 bool HasCalls = false;
105 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
106 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
107 if (I->getOpcode() == FrameSetupOpcode ||
108 I->getOpcode() == FrameDestroyOpcode) {
109 assert(I->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
110 " instructions should have a single immediate argument!");
111 unsigned Size = I->getOperand(0).getImmedValue();
112 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
114 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++);
116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
117 MachineOperand &MO = I->getOperand(i);
118 if (MO.isRegister() && MO.isDef()) {
119 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
120 "Register allocation must be performed!");
121 ModifiedRegs[MO.getReg()] = true; // Register is modified
127 MachineFrameInfo *FFI = Fn.getFrameInfo();
128 FFI->setHasCalls(HasCalls);
129 FFI->setMaxCallFrameSize(MaxCallFrameSize);
131 // Now figure out which *callee saved* registers are modified by the current
132 // function, thus needing to be saved and restored in the prolog/epilog.
134 std::vector<unsigned> RegsToSave;
135 for (unsigned i = 0; CSRegs[i]; ++i) {
136 unsigned Reg = CSRegs[i];
137 if (ModifiedRegs[Reg]) {
138 RegsToSave.push_back(Reg); // If modified register...
140 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
141 *AliasSet; ++AliasSet) { // Check alias registers too...
142 if (ModifiedRegs[*AliasSet]) {
143 RegsToSave.push_back(Reg);
150 if (RegsToSave.empty())
151 return; // Early exit if no caller saved registers are modified!
153 // Now that we know which registers need to be saved and restored, allocate
154 // stack slots for them.
155 std::vector<int> StackSlots;
156 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
157 int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
158 StackSlots.push_back(FrameIdx);
161 // Now that we have a stack slot for each register to be saved, insert spill
162 // code into the entry block...
163 MachineBasicBlock *MBB = Fn.begin();
164 MachineBasicBlock::iterator I = MBB->begin();
165 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
166 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
168 // Insert the spill to the stack frame...
169 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
172 // Add code to restore the callee-save registers in each exiting block.
173 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
174 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
175 // If last instruction is a return instruction, add an epilogue
176 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) {
180 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
181 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
182 RegInfo->loadRegFromStackSlot(*MBB, I, RegsToSave[i],StackSlots[i], RC);
183 --I; // Insert in reverse order
190 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
191 /// abstract stack objects...
193 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
194 const TargetFrameInfo &TFI = Fn.getTarget().getFrameInfo();
196 bool StackGrowsDown =
197 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown;
198 assert(StackGrowsDown && "Only tested on stack down growing targets!");
200 // Loop over all of the stack objects, assigning sequential addresses...
201 MachineFrameInfo *FFI = Fn.getFrameInfo();
203 unsigned StackAlignment = TFI.getStackAlignment();
205 // Start at the beginning of the local area.
206 int Offset = TFI.getOffsetOfLocalArea();
208 // Check to see if there are any fixed sized objects that are preallocated in
209 // the local area. We currently don't support filling in holes in between
210 // fixed sized objects, so we just skip to the end of the last fixed sized
211 // preallocated object.
212 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
213 int FixedOff = -FFI->getObjectOffset(i);
214 if (FixedOff > Offset) Offset = FixedOff;
217 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
218 Offset += FFI->getObjectSize(i); // Allocate Size bytes...
220 unsigned Align = FFI->getObjectAlignment(i);
221 assert(Align <= StackAlignment && "Cannot align stack object to higher "
222 "alignment boundary than the stack itself!");
223 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
225 FFI->setObjectOffset(i, -Offset); // Set the computed offset
228 // Align the final stack pointer offset, but only if there are calls in the
229 // function. This ensures that any calls to subroutines have their stack
230 // frames suitable aligned.
232 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
234 // Set the final value of the stack pointer...
235 FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
239 /// insertPrologEpilogCode - Scan the function for modified caller saved
240 /// registers, insert spill code for these caller saved registers, then add
241 /// prolog and epilog code to the function.
243 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
244 // Add prologue to the function...
245 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
247 // Add epilogue to restore the callee-save registers in each exiting block
248 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
249 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
250 // If last instruction is a return instruction, add an epilogue
251 if (!I->empty() && TII.isReturn(I->back().getOpcode()))
252 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
257 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
258 /// register references and actual offsets.
260 void PEI::replaceFrameIndices(MachineFunction &Fn) {
261 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
263 const TargetMachine &TM = Fn.getTarget();
264 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
265 const MRegisterInfo &MRI = *TM.getRegisterInfo();
267 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
268 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
269 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
270 if (I->getOperand(i).isFrameIndex()) {
271 // If this instruction has a FrameIndex operand, we need to use that
272 // target machine register info object to eliminate it.
273 MRI.eliminateFrameIndex(Fn, I);