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"
31 struct PEI : public MachineFunctionPass {
32 const char *getPassName() const {
33 return "Prolog/Epilog Insertion & Frame Finalization";
36 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
37 /// frame indexes with appropriate references.
39 bool runOnMachineFunction(MachineFunction &Fn) {
40 // Scan the function for modified caller saved registers and insert spill
41 // code for any caller saved registers that are modified. Also calculate
42 // the MaxCallFrameSize and HasCalls variables for the function's frame
43 // information and eliminates call frame pseudo instructions.
44 saveCallerSavedRegisters(Fn);
46 // Allow the target machine to make final modifications to the function
47 // before the frame layout is finalized.
48 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn);
50 // Calculate actual frame offsets for all of the abstract stack objects...
51 calculateFrameObjectOffsets(Fn);
53 // Add prolog and epilog code to the function.
54 insertPrologEpilogCode(Fn);
56 // Replace all MO_FrameIndex operands with physical register references
57 // and actual offsets.
59 replaceFrameIndices(Fn);
64 void saveCallerSavedRegisters(MachineFunction &Fn);
65 void calculateFrameObjectOffsets(MachineFunction &Fn);
66 void replaceFrameIndices(MachineFunction &Fn);
67 void insertPrologEpilogCode(MachineFunction &Fn);
72 /// createPrologEpilogCodeInserter - This function returns a pass that inserts
73 /// prolog and epilog code, and eliminates abstract frame references.
75 FunctionPass *createPrologEpilogCodeInserter() { return new PEI(); }
78 /// saveCallerSavedRegisters - Scan the function for modified caller saved
79 /// registers and insert spill code for any caller saved registers that are
80 /// modified. Also calculate the MaxCallFrameSize and HasCalls variables for
81 /// the function's frame information and eliminates call frame pseudo
84 void PEI::saveCallerSavedRegisters(MachineFunction &Fn) {
85 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
86 const TargetFrameInfo &FrameInfo = Fn.getTarget().getFrameInfo();
88 // Get the callee saved register list...
89 const unsigned *CSRegs = RegInfo->getCalleeSaveRegs();
91 // Get the function call frame set-up and tear-down instruction opcode
92 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode();
93 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode();
95 // Early exit for targets which have no callee saved registers and no call
96 // frame setup/destroy pseudo instructions.
97 if ((CSRegs == 0 || CSRegs[0] == 0) &&
98 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
101 // This bitset contains an entry for each physical register for the target...
102 std::vector<bool> ModifiedRegs(MRegisterInfo::FirstVirtualRegister);
103 unsigned MaxCallFrameSize = 0;
104 bool HasCalls = false;
106 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
107 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); )
108 if ((*I)->getOpcode() == FrameSetupOpcode ||
109 (*I)->getOpcode() == FrameDestroyOpcode) {
110 assert((*I)->getNumOperands() == 1 && "Call Frame Setup/Destroy Pseudo"
111 " instructions should have a single immediate argument!");
112 unsigned Size = (*I)->getOperand(0).getImmedValue();
113 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
115 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I);
117 for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i) {
118 MachineOperand &MO = (*I)->getOperand(i);
119 if (MO.isRegister() && MO.isDef()) {
120 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
121 "Register allocation must be performed!");
122 ModifiedRegs[MO.getReg()] = true; // Register is modified
128 MachineFrameInfo *FFI = Fn.getFrameInfo();
129 FFI->setHasCalls(HasCalls);
130 FFI->setMaxCallFrameSize(MaxCallFrameSize);
132 // Now figure out which *callee saved* registers are modified by the current
133 // function, thus needing to be saved and restored in the prolog/epilog.
135 std::vector<unsigned> RegsToSave;
136 for (unsigned i = 0; CSRegs[i]; ++i) {
137 unsigned Reg = CSRegs[i];
138 if (ModifiedRegs[Reg]) {
139 RegsToSave.push_back(Reg); // If modified register...
141 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg);
142 *AliasSet; ++AliasSet) { // Check alias registers too...
143 if (ModifiedRegs[*AliasSet]) {
144 RegsToSave.push_back(Reg);
151 if (RegsToSave.empty())
152 return; // Early exit if no caller saved registers are modified!
154 // Now that we know which registers need to be saved and restored, allocate
155 // stack slots for them.
156 std::vector<int> StackSlots;
157 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
158 int FrameIdx = FFI->CreateStackObject(RegInfo->getRegClass(RegsToSave[i]));
159 StackSlots.push_back(FrameIdx);
162 // Now that we have a stack slot for each register to be saved, insert spill
163 // code into the entry block...
164 MachineBasicBlock *MBB = Fn.begin();
165 MachineBasicBlock::iterator I = MBB->begin();
166 for (unsigned i = 0, e = RegsToSave.size(); i != e; ++i) {
167 const TargetRegisterClass *RC = RegInfo->getRegClass(RegsToSave[i]);
169 // Insert the spill to the stack frame...
170 RegInfo->storeRegToStackSlot(*MBB, I, RegsToSave[i], StackSlots[i], RC);
173 // Add code to restore the callee-save registers in each exiting block.
174 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
175 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) {
176 // If last instruction is a return instruction, add an epilogue
177 if (!FI->empty() && TII.isReturn(FI->back()->getOpcode())) {
178 MBB = FI; I = MBB->end()-1;
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();
207 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
208 Offset += FFI->getObjectSize(i); // Allocate Size bytes...
210 unsigned Align = FFI->getObjectAlignment(i);
211 assert(Align <= StackAlignment && "Cannot align stack object to higher "
212 "alignment boundary than the stack itself!");
213 Offset = (Offset+Align-1)/Align*Align; // Adjust to Alignment boundary...
215 FFI->setObjectOffset(i, -Offset); // Set the computed offset
218 // Align the final stack pointer offset...
219 Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment;
221 // Set the final value of the stack pointer...
222 FFI->setStackSize(Offset-TFI.getOffsetOfLocalArea());
226 /// insertPrologEpilogCode - Scan the function for modified caller saved
227 /// registers, insert spill code for these caller saved registers, then add
228 /// prolog and epilog code to the function.
230 void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
231 // Add prologue to the function...
232 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn);
234 // Add epilogue to restore the callee-save registers in each exiting block
235 const TargetInstrInfo &TII = Fn.getTarget().getInstrInfo();
236 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
237 // If last instruction is a return instruction, add an epilogue
238 if (!I->empty() && TII.isReturn(I->back()->getOpcode()))
239 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I);
244 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
245 /// register references and actual offsets.
247 void PEI::replaceFrameIndices(MachineFunction &Fn) {
248 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
250 const TargetMachine &TM = Fn.getTarget();
251 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
252 const MRegisterInfo &MRI = *TM.getRegisterInfo();
254 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
255 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
256 for (unsigned i = 0, e = (*I)->getNumOperands(); i != e; ++i)
257 if ((*I)->getOperand(i).isFrameIndex()) {
258 // If this instruction has a FrameIndex operand, we need to use that
259 // target machine register info object to eliminate it.
260 MRI.eliminateFrameIndex(Fn, I);
265 } // End llvm namespace