PrologEpilogInserter.cpp revision 57a2306074989dfd6e1c0d9ddd2b5084f664e2a9
1//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===// 2// 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//===----------------------------------------------------------------------===// 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/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" 27#include "llvm/Support/Compiler.h" 28#include <climits> 29using namespace llvm; 30 31namespace { 32 struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass { 33 const char *getPassName() const { 34 return "Prolog/Epilog Insertion & Frame Finalization"; 35 } 36 37 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 38 /// frame indexes with appropriate references. 39 /// 40 bool runOnMachineFunction(MachineFunction &Fn) { 41 // Get MachineDebugInfo so that we can track the construction of the 42 // frame. 43 if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) { 44 Fn.getFrameInfo()->setMachineDebugInfo(DI); 45 } 46 47 // Allow the target machine to make some adjustments to the function 48 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters. 49 Fn.getTarget().getRegisterInfo() 50 ->processFunctionBeforeCalleeSavedScan(Fn); 51 52 // Scan the function for modified callee saved registers and insert spill 53 // code for any callee saved registers that are modified. Also calculate 54 // the MaxCallFrameSize and HasCalls variables for the function's frame 55 // information and eliminates call frame pseudo instructions. 56 calculateCalleeSavedRegisters(Fn); 57 58 // Add the code to save and restore the callee saved registers 59 saveCalleeSavedRegisters(Fn); 60 61 // Allow the target machine to make final modifications to the function 62 // before the frame layout is finalized. 63 Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn); 64 65 // Calculate actual frame offsets for all of the abstract stack objects... 66 calculateFrameObjectOffsets(Fn); 67 68 // Add prolog and epilog code to the function. This function is required 69 // to align the stack frame as necessary for any stack variables or 70 // called functions. Because of this, calculateCalleeSavedRegisters 71 // must be called before this function in order to set the HasCalls 72 // and MaxCallFrameSize variables. 73 insertPrologEpilogCode(Fn); 74 75 // Replace all MO_FrameIndex operands with physical register references 76 // and actual offsets. 77 // 78 replaceFrameIndices(Fn); 79 80 return true; 81 } 82 83 private: 84 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved 85 // stack frame indexes. 86 unsigned MinCSFrameIndex, MaxCSFrameIndex; 87 88 void calculateCalleeSavedRegisters(MachineFunction &Fn); 89 void saveCalleeSavedRegisters(MachineFunction &Fn); 90 void calculateFrameObjectOffsets(MachineFunction &Fn); 91 void replaceFrameIndices(MachineFunction &Fn); 92 void insertPrologEpilogCode(MachineFunction &Fn); 93 }; 94} 95 96 97/// createPrologEpilogCodeInserter - This function returns a pass that inserts 98/// prolog and epilog code, and eliminates abstract frame references. 99/// 100FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); } 101 102 103/// calculateCalleeSavedRegisters - Scan the function for modified callee saved 104/// registers. Also calculate the MaxCallFrameSize and HasCalls variables for 105/// the function's frame information and eliminates call frame pseudo 106/// instructions. 107/// 108void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) { 109 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 110 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); 111 112 // Get the callee saved register list... 113 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(); 114 115 // Get the function call frame set-up and tear-down instruction opcode 116 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode(); 117 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode(); 118 119 // These are used to keep track the callee-save area. Initialize them. 120 MinCSFrameIndex = INT_MAX; 121 MaxCSFrameIndex = 0; 122 123 // Early exit for targets which have no callee saved registers and no call 124 // frame setup/destroy pseudo instructions. 125 if ((CSRegs == 0 || CSRegs[0] == 0) && 126 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) 127 return; 128 129 unsigned MaxCallFrameSize = 0; 130 bool HasCalls = false; 131 132 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 133 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) 134 if (I->getOpcode() == FrameSetupOpcode || 135 I->getOpcode() == FrameDestroyOpcode) { 136 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" 137 " instructions should have a single immediate argument!"); 138 unsigned Size = I->getOperand(0).getImmedValue(); 139 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 140 HasCalls = true; 141 RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++); 142 } else { 143 ++I; 144 } 145 146 MachineFrameInfo *FFI = Fn.getFrameInfo(); 147 FFI->setHasCalls(HasCalls); 148 FFI->setMaxCallFrameSize(MaxCallFrameSize); 149 150 // Now figure out which *callee saved* registers are modified by the current 151 // function, thus needing to be saved and restored in the prolog/epilog. 152 // 153 const bool *PhysRegsUsed = Fn.getUsedPhysregs(); 154 const TargetRegisterClass* const *CSRegClasses = 155 RegInfo->getCalleeSavedRegClasses(); 156 std::vector<CalleeSavedInfo> CSI; 157 for (unsigned i = 0; CSRegs[i]; ++i) { 158 unsigned Reg = CSRegs[i]; 159 if (PhysRegsUsed[Reg]) { 160 // If the reg is modified, save it! 161 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); 162 } else { 163 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg); 164 *AliasSet; ++AliasSet) { // Check alias registers too. 165 if (PhysRegsUsed[*AliasSet]) { 166 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); 167 break; 168 } 169 } 170 } 171 } 172 173 if (CSI.empty()) 174 return; // Early exit if no callee saved registers are modified! 175 176 unsigned NumFixedSpillSlots; 177 const std::pair<unsigned,int> *FixedSpillSlots = 178 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 179 180 // Now that we know which registers need to be saved and restored, allocate 181 // stack slots for them. 182 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 183 unsigned Reg = CSI[i].getReg(); 184 const TargetRegisterClass *RC = CSI[i].getRegClass(); 185 186 // Check to see if this physreg must be spilled to a particular stack slot 187 // on this target. 188 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots; 189 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && 190 FixedSlot->first != Reg) 191 ++FixedSlot; 192 193 int FrameIdx; 194 if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) { 195 // Nope, just spill it anywhere convenient. 196 unsigned Align = RC->getAlignment(); 197 unsigned StackAlign = TFI->getStackAlignment(); 198 // We may not be able to sastify the desired alignment specification of 199 // the TargetRegisterClass if the stack alignment is smaller. Use the min. 200 Align = std::min(Align, StackAlign); 201 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align); 202 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 203 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 204 } else { 205 // Spill it to the stack where we must. 206 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second); 207 } 208 CSI[i].setFrameIdx(FrameIdx); 209 } 210 211 FFI->setCalleeSavedInfo(CSI); 212} 213 214/// saveCalleeSavedRegisters - Insert spill code for any callee saved registers 215/// that are modified in the function. 216/// 217void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) { 218 // Get callee saved register information. 219 MachineFrameInfo *FFI = Fn.getFrameInfo(); 220 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo(); 221 222 // Early exit if no callee saved registers are modified! 223 if (CSI.empty()) 224 return; 225 226 const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 227 228 // Now that we have a stack slot for each register to be saved, insert spill 229 // code into the entry block. 230 MachineBasicBlock *MBB = Fn.begin(); 231 MachineBasicBlock::iterator I = MBB->begin(); 232 if (!RegInfo->spillCalleeSavedRegisters(*MBB, I, CSI)) { 233 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 234 // Insert the spill to the stack frame. 235 RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), 236 CSI[i].getFrameIdx(), 237 CSI[i].getRegClass()); 238 } 239 } 240 241 // Add code to restore the callee-save registers in each exiting block. 242 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 243 for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) 244 // If last instruction is a return instruction, add an epilogue. 245 if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) { 246 MBB = FI; 247 I = MBB->end(); --I; 248 249 // Skip over all terminator instructions, which are part of the return 250 // sequence. 251 MachineBasicBlock::iterator I2 = I; 252 while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode())) 253 I = I2; 254 255 bool AtStart = I == MBB->begin(); 256 MachineBasicBlock::iterator BeforeI = I; 257 if (!AtStart) 258 --BeforeI; 259 260 // Restore all registers immediately before the return and any terminators 261 // that preceed it. 262 if (!RegInfo->restoreCalleeSavedRegisters(*MBB, I, CSI)) { 263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 264 RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(), 265 CSI[i].getFrameIdx(), 266 CSI[i].getRegClass()); 267 assert(I != MBB->begin() && 268 "loadRegFromStackSlot didn't insert any code!"); 269 // Insert in reverse order. loadRegFromStackSlot can insert multiple 270 // instructions. 271 if (AtStart) 272 I = MBB->begin(); 273 else { 274 I = BeforeI; 275 ++I; 276 } 277 } 278 } 279 } 280} 281 282 283/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 284/// abstract stack objects. 285/// 286void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 287 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); 288 289 bool StackGrowsDown = 290 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; 291 292 // Loop over all of the stack objects, assigning sequential addresses... 293 MachineFrameInfo *FFI = Fn.getFrameInfo(); 294 295 unsigned StackAlignment = TFI.getStackAlignment(); 296 unsigned MaxAlign = 0; 297 298 // Start at the beginning of the local area. 299 // The Offset is the distance from the stack top in the direction 300 // of stack growth -- so it's always positive. 301 int Offset = TFI.getOffsetOfLocalArea(); 302 if (StackGrowsDown) 303 Offset = -Offset; 304 assert(Offset >= 0 305 && "Local area offset should be in direction of stack growth"); 306 307 // If there are fixed sized objects that are preallocated in the local area, 308 // non-fixed objects can't be allocated right at the start of local area. 309 // We currently don't support filling in holes in between fixed sized objects, 310 // so we adjust 'Offset' to point to the end of last fixed sized 311 // preallocated object. 312 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) { 313 int FixedOff; 314 if (StackGrowsDown) { 315 // The maximum distance from the stack pointer is at lower address of 316 // the object -- which is given by offset. For down growing stack 317 // the offset is negative, so we negate the offset to get the distance. 318 FixedOff = -FFI->getObjectOffset(i); 319 } else { 320 // The maximum distance from the start pointer is at the upper 321 // address of the object. 322 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i); 323 } 324 if (FixedOff > Offset) Offset = FixedOff; 325 } 326 327 // First assign frame offsets to stack objects that are used to spill 328 // callee saved registers. 329 if (StackGrowsDown) { 330 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { 331 if (i < MinCSFrameIndex || i > MaxCSFrameIndex) 332 continue; 333 334 // If stack grows down, we need to add size of find the lowest 335 // address of the object. 336 Offset += FFI->getObjectSize(i); 337 338 unsigned Align = FFI->getObjectAlignment(i); 339 // If the alignment of this object is greater than that of the stack, then 340 // increase the stack alignment to match. 341 MaxAlign = std::max(MaxAlign, Align); 342 // Adjust to alignment boundary 343 Offset = (Offset+Align-1)/Align*Align; 344 345 FFI->setObjectOffset(i, -Offset); // Set the computed offset 346 } 347 } else { 348 for (int i = FFI->getObjectIndexEnd()-1; i >= 0; --i) { 349 if ((unsigned)i < MinCSFrameIndex || (unsigned)i > MaxCSFrameIndex) 350 continue; 351 352 unsigned Align = FFI->getObjectAlignment(i); 353 // If the alignment of this object is greater than that of the stack, then 354 // increase the stack alignment to match. 355 MaxAlign = std::max(MaxAlign, Align); 356 // Adjust to alignment boundary 357 Offset = (Offset+Align-1)/Align*Align; 358 359 FFI->setObjectOffset(i, Offset); 360 Offset += FFI->getObjectSize(i); 361 } 362 } 363 364 // Then assign frame offsets to stack objects that are not used to spill 365 // callee saved registers. 366 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { 367 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 368 continue; 369 370 // If stack grows down, we need to add size of find the lowest 371 // address of the object. 372 if (StackGrowsDown) 373 Offset += FFI->getObjectSize(i); 374 375 unsigned Align = FFI->getObjectAlignment(i); 376 // If the alignment of this object is greater than that of the stack, then 377 // increase the stack alignment to match. 378 MaxAlign = std::max(MaxAlign, Align); 379 // Adjust to alignment boundary 380 Offset = (Offset+Align-1)/Align*Align; 381 382 if (StackGrowsDown) { 383 FFI->setObjectOffset(i, -Offset); // Set the computed offset 384 } else { 385 FFI->setObjectOffset(i, Offset); 386 Offset += FFI->getObjectSize(i); 387 } 388 } 389 390 // Set the final value of the stack pointer... 391 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea()); 392 393 // Remember the required stack alignment in case targets need it to perform 394 // dynamic stack alignment. 395 assert(FFI->getMaxAlignment() == MaxAlign && 396 "Stack alignment calculation broken!"); 397} 398 399 400/// insertPrologEpilogCode - Scan the function for modified callee saved 401/// registers, insert spill code for these callee saved registers, then add 402/// prolog and epilog code to the function. 403/// 404void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 405 // Add prologue to the function... 406 Fn.getTarget().getRegisterInfo()->emitPrologue(Fn); 407 408 // Add epilogue to restore the callee-save registers in each exiting block 409 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 410 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 411 // If last instruction is a return instruction, add an epilogue 412 if (!I->empty() && TII.isReturn(I->back().getOpcode())) 413 Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I); 414 } 415} 416 417 418/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 419/// register references and actual offsets. 420/// 421void PEI::replaceFrameIndices(MachineFunction &Fn) { 422 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? 423 424 const TargetMachine &TM = Fn.getTarget(); 425 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); 426 const MRegisterInfo &MRI = *TM.getRegisterInfo(); 427 428 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 429 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 430 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 431 if (I->getOperand(i).isFrameIndex()) { 432 // If this instruction has a FrameIndex operand, we need to use that 433 // target machine register info object to eliminate it. 434 MRI.eliminateFrameIndex(I); 435 break; 436 } 437} 438