[ARM] Refactor the prologue/epilogue emission to be more robust.
[oota-llvm.git] / lib / Target / ARM / Thumb1FrameLowering.cpp
1 //===-- Thumb1FrameLowering.cpp - Thumb1 Frame Information ----------------===//
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 file contains the Thumb1 implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Thumb1FrameLowering.h"
15 #include "ARMMachineFunctionInfo.h"
16 #include "llvm/CodeGen/LivePhysRegs.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22
23 using namespace llvm;
24
25 Thumb1FrameLowering::Thumb1FrameLowering(const ARMSubtarget &sti)
26     : ARMFrameLowering(sti) {}
27
28 bool Thumb1FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const{
29   const MachineFrameInfo *FFI = MF.getFrameInfo();
30   unsigned CFSize = FFI->getMaxCallFrameSize();
31   // It's not always a good idea to include the call frame as part of the
32   // stack frame. ARM (especially Thumb) has small immediate offset to
33   // address the stack frame. So a large call frame can cause poor codegen
34   // and may even makes it impossible to scavenge a register.
35   if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
36     return false;
37
38   return !MF.getFrameInfo()->hasVarSizedObjects();
39 }
40
41 static void
42 emitSPUpdate(MachineBasicBlock &MBB,
43              MachineBasicBlock::iterator &MBBI,
44              const TargetInstrInfo &TII, DebugLoc dl,
45              const ThumbRegisterInfo &MRI,
46              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags)  {
47   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
48                             MRI, MIFlags);
49 }
50
51
52 void Thumb1FrameLowering::
53 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
54                               MachineBasicBlock::iterator I) const {
55   const Thumb1InstrInfo &TII =
56       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
57   const ThumbRegisterInfo *RegInfo =
58       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
59   if (!hasReservedCallFrame(MF)) {
60     // If we have alloca, convert as follows:
61     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
62     // ADJCALLSTACKUP   -> add, sp, sp, amount
63     MachineInstr *Old = I;
64     DebugLoc dl = Old->getDebugLoc();
65     unsigned Amount = Old->getOperand(0).getImm();
66     if (Amount != 0) {
67       // We need to keep the stack aligned properly.  To do this, we round the
68       // amount of space needed for the outgoing arguments up to the next
69       // alignment boundary.
70       unsigned Align = getStackAlignment();
71       Amount = (Amount+Align-1)/Align*Align;
72
73       // Replace the pseudo instruction with a new instruction...
74       unsigned Opc = Old->getOpcode();
75       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
76         emitSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
77       } else {
78         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
79         emitSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
80       }
81     }
82   }
83   MBB.erase(I);
84 }
85
86 void Thumb1FrameLowering::emitPrologue(MachineFunction &MF,
87                                        MachineBasicBlock &MBB) const {
88   assert(&MBB == &MF.front() && "Shrink-wrapping not yet implemented");
89   MachineBasicBlock::iterator MBBI = MBB.begin();
90   MachineFrameInfo  *MFI = MF.getFrameInfo();
91   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
92   MachineModuleInfo &MMI = MF.getMMI();
93   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
94   const ThumbRegisterInfo *RegInfo =
95       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
96   const Thumb1InstrInfo &TII =
97       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
98
99   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
100   unsigned NumBytes = MFI->getStackSize();
101   assert(NumBytes >= ArgRegsSaveSize &&
102          "ArgRegsSaveSize is included in NumBytes");
103   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
104   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
105   unsigned FramePtr = RegInfo->getFrameRegister(MF);
106   unsigned BasePtr = RegInfo->getBaseRegister();
107   int CFAOffset = 0;
108
109   // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
110   NumBytes = (NumBytes + 3) & ~3;
111   MFI->setStackSize(NumBytes);
112
113   // Determine the sizes of each callee-save spill areas and record which frame
114   // belongs to which callee-save spill areas.
115   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
116   int FramePtrSpillFI = 0;
117
118   if (ArgRegsSaveSize) {
119     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
120                  MachineInstr::FrameSetup);
121     CFAOffset -= ArgRegsSaveSize;
122     unsigned CFIIndex = MMI.addFrameInst(
123         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
124     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
125         .addCFIIndex(CFIIndex)
126         .setMIFlags(MachineInstr::FrameSetup);
127   }
128
129   if (!AFI->hasStackFrame()) {
130     if (NumBytes - ArgRegsSaveSize != 0) {
131       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -(NumBytes - ArgRegsSaveSize),
132                    MachineInstr::FrameSetup);
133       CFAOffset -= NumBytes - ArgRegsSaveSize;
134       unsigned CFIIndex = MMI.addFrameInst(
135           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
136       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
137           .addCFIIndex(CFIIndex)
138           .setMIFlags(MachineInstr::FrameSetup);
139     }
140     return;
141   }
142
143   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
144     unsigned Reg = CSI[i].getReg();
145     int FI = CSI[i].getFrameIdx();
146     switch (Reg) {
147     case ARM::R8:
148     case ARM::R9:
149     case ARM::R10:
150     case ARM::R11:
151       if (STI.isTargetMachO()) {
152         GPRCS2Size += 4;
153         break;
154       }
155       // fallthrough
156     case ARM::R4:
157     case ARM::R5:
158     case ARM::R6:
159     case ARM::R7:
160     case ARM::LR:
161       if (Reg == FramePtr)
162         FramePtrSpillFI = FI;
163       GPRCS1Size += 4;
164       break;
165     default:
166       DPRCSSize += 8;
167     }
168   }
169
170   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
171     ++MBBI;
172     if (MBBI != MBB.end())
173       dl = MBBI->getDebugLoc();
174   }
175
176   // Determine starting offsets of spill areas.
177   unsigned DPRCSOffset  = NumBytes - ArgRegsSaveSize - (GPRCS1Size + GPRCS2Size + DPRCSSize);
178   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
179   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
180   bool HasFP = hasFP(MF);
181   if (HasFP)
182     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
183                                 NumBytes);
184   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
185   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
186   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
187   NumBytes = DPRCSOffset;
188
189   int FramePtrOffsetInBlock = 0;
190   unsigned adjustedGPRCS1Size = GPRCS1Size;
191   if (tryFoldSPUpdateIntoPushPop(STI, MF, std::prev(MBBI), NumBytes)) {
192     FramePtrOffsetInBlock = NumBytes;
193     adjustedGPRCS1Size += NumBytes;
194     NumBytes = 0;
195   }
196
197   if (adjustedGPRCS1Size) {
198     CFAOffset -= adjustedGPRCS1Size;
199     unsigned CFIIndex = MMI.addFrameInst(
200         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
201     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
202         .addCFIIndex(CFIIndex)
203         .setMIFlags(MachineInstr::FrameSetup);
204   }
205   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
206          E = CSI.end(); I != E; ++I) {
207     unsigned Reg = I->getReg();
208     int FI = I->getFrameIdx();
209     switch (Reg) {
210     case ARM::R8:
211     case ARM::R9:
212     case ARM::R10:
213     case ARM::R11:
214     case ARM::R12:
215       if (STI.isTargetMachO())
216         break;
217       // fallthough
218     case ARM::R0:
219     case ARM::R1:
220     case ARM::R2:
221     case ARM::R3:
222     case ARM::R4:
223     case ARM::R5:
224     case ARM::R6:
225     case ARM::R7:
226     case ARM::LR:
227       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
228           nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
229       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
230           .addCFIIndex(CFIIndex)
231           .setMIFlags(MachineInstr::FrameSetup);
232       break;
233     }
234   }
235
236
237   // Adjust FP so it point to the stack slot that contains the previous FP.
238   if (HasFP) {
239     FramePtrOffsetInBlock += MFI->getObjectOffset(FramePtrSpillFI)
240                                      + GPRCS1Size + ArgRegsSaveSize;
241     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
242       .addReg(ARM::SP).addImm(FramePtrOffsetInBlock / 4)
243       .setMIFlags(MachineInstr::FrameSetup));
244     if(FramePtrOffsetInBlock) {
245       CFAOffset += FramePtrOffsetInBlock;
246       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
247           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
248       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
249           .addCFIIndex(CFIIndex)
250           .setMIFlags(MachineInstr::FrameSetup);
251     } else {
252       unsigned CFIIndex =
253           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
254               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
255       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
256           .addCFIIndex(CFIIndex)
257           .setMIFlags(MachineInstr::FrameSetup);
258     }
259     if (NumBytes > 508)
260       // If offset is > 508 then sp cannot be adjusted in a single instruction,
261       // try restoring from fp instead.
262       AFI->setShouldRestoreSPFromFP(true);
263   }
264
265   if (NumBytes) {
266     // Insert it after all the callee-save spills.
267     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
268                  MachineInstr::FrameSetup);
269     if (!HasFP) {
270       CFAOffset -= NumBytes;
271       unsigned CFIIndex = MMI.addFrameInst(
272           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
273       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
274           .addCFIIndex(CFIIndex)
275           .setMIFlags(MachineInstr::FrameSetup);
276     }
277   }
278
279   if (STI.isTargetELF() && HasFP)
280     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
281                              AFI->getFramePtrSpillOffset());
282
283   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
284   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
285   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
286
287   // Thumb1 does not currently support dynamic stack realignment.  Report a
288   // fatal error rather then silently generate bad code.
289   if (RegInfo->needsStackRealignment(MF))
290       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
291
292   // If we need a base pointer, set it up here. It's whatever the value
293   // of the stack pointer is at this point. Any variable size objects
294   // will be allocated after this, so we can still use the base pointer
295   // to reference locals.
296   if (RegInfo->hasBasePointer(MF))
297     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
298                    .addReg(ARM::SP));
299
300   // If the frame has variable sized objects then the epilogue must restore
301   // the sp from fp. We can assume there's an FP here since hasFP already
302   // checks for hasVarSizedObjects.
303   if (MFI->hasVarSizedObjects())
304     AFI->setShouldRestoreSPFromFP(true);
305 }
306
307 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
308   if (MI->getOpcode() == ARM::tLDRspi &&
309       MI->getOperand(1).isFI() &&
310       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
311     return true;
312   else if (MI->getOpcode() == ARM::tPOP) {
313     // The first two operands are predicates. The last two are
314     // imp-def and imp-use of SP. Check everything in between.
315     for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
316       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
317         return false;
318     return true;
319   }
320   return false;
321 }
322
323 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
324                                    MachineBasicBlock &MBB) const {
325   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
326   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
327   MachineFrameInfo *MFI = MF.getFrameInfo();
328   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
329   const ThumbRegisterInfo *RegInfo =
330       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
331   const Thumb1InstrInfo &TII =
332       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
333
334   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
335   int NumBytes = (int)MFI->getStackSize();
336   assert((unsigned)NumBytes >= ArgRegsSaveSize &&
337          "ArgRegsSaveSize is included in NumBytes");
338   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
339   unsigned FramePtr = RegInfo->getFrameRegister(MF);
340
341   if (!AFI->hasStackFrame()) {
342     if (NumBytes - ArgRegsSaveSize != 0)
343       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes - ArgRegsSaveSize);
344   } else {
345     // Unwind MBBI to point to first LDR / VLDRD.
346     if (MBBI != MBB.begin()) {
347       do
348         --MBBI;
349       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
350       if (!isCSRestore(MBBI, CSRegs))
351         ++MBBI;
352     }
353
354     // Move SP to start of FP callee save spill area.
355     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
356                  AFI->getGPRCalleeSavedArea2Size() +
357                  AFI->getDPRCalleeSavedAreaSize() +
358                  ArgRegsSaveSize);
359
360     if (AFI->shouldRestoreSPFromFP()) {
361       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
362       // Reset SP based on frame pointer only if the stack frame extends beyond
363       // frame pointer stack slot, the target is ELF and the function has FP, or
364       // the target uses var sized objects.
365       if (NumBytes) {
366         assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
367                "No scratch register to restore SP from FP!");
368         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
369                                   TII, *RegInfo);
370         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
371                                ARM::SP)
372           .addReg(ARM::R4));
373       } else
374         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
375                                ARM::SP)
376           .addReg(FramePtr));
377     } else {
378       if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
379           &MBB.front() != MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
380         MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
381         if (!tryFoldSPUpdateIntoPushPop(STI, MF, PMBBI, NumBytes))
382           emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
383       } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
384         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
385     }
386   }
387
388   bool IsV4PopReturn = false;
389   for (const CalleeSavedInfo &CSI : MFI->getCalleeSavedInfo())
390     if (CSI.getReg() == ARM::LR)
391       IsV4PopReturn = true;
392   IsV4PopReturn &= STI.hasV4TOps() && !STI.hasV5TOps();
393
394   // Unlike T2 and ARM mode, the T1 pop instruction cannot restore
395   // to LR, and we can't pop the value directly to the PC since
396   // we need to update the SP after popping the value. So instead
397   // we have to emit:
398   //   POP {r3}
399   //   ADD sp, #offset
400   //   BX r3
401   // If this would clobber a return value, then generate this sequence instead:
402   //   MOV ip, r3
403   //   POP {r3}
404   //   ADD sp, #offset
405   //   MOV lr, r3
406   //   MOV r3, ip
407   //   BX lr
408   if (ArgRegsSaveSize || IsV4PopReturn) {
409     // If MBBI is a return instruction, we may be able to directly restore
410     // LR in the PC.
411     // This is possible if we do not need to emit any SP update.
412     // Otherwise, we need a temporary register to pop the value
413     // and copy that value into LR.
414     MBBI = MBB.getFirstTerminator();
415     if (!ArgRegsSaveSize && MBBI != MBB.end() &&
416         MBBI->getOpcode() == ARM::tBX_RET) {
417       MachineInstrBuilder MIB =
418           AddDefaultPred(
419               BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET)))
420               .addReg(ARM::PC, RegState::Define);
421       MIB.copyImplicitOps(&*MBBI);
422       // erase the old tBX_RET instruction
423       MBB.erase(MBBI);
424       return;
425     }
426
427     // Look for a temporary register to use.
428     // First, compute the liveness information.
429     LivePhysRegs UsedRegs(STI.getRegisterInfo());
430     UsedRegs.addLiveOuts(&MBB, /*AddPristines*/ true);
431     // The semantic of pristines changed recently and now,
432     // the callee-saved registers that are touched in the function
433     // are not part of the pristines set anymore.
434     // Add those callee-saved now.
435     const TargetRegisterInfo *TRI = STI.getRegisterInfo();
436     const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
437     for (unsigned i = 0; CSRegs[i]; ++i)
438       UsedRegs.addReg(CSRegs[i]);
439
440     DebugLoc dl = DebugLoc();
441     if (MBBI != MBB.end()) {
442       dl = MBBI->getDebugLoc();
443       auto InstUpToMBBI = MBB.end();
444       // The post-decrement is on purpose here.
445       // We want to have the liveness right before MBBI.
446       while (InstUpToMBBI-- != MBBI)
447         UsedRegs.stepBackward(*InstUpToMBBI);
448     }
449
450     // Look for a register that can be directly use in the POP.
451     unsigned PopReg = 0;
452     // And some temporary register, just in case.
453     unsigned TemporaryReg = 0;
454     BitVector PopFriendly =
455         TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
456     assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
457     // Rebuild the GPRs from the high registers because they are removed
458     // form the GPR reg class for thumb1.
459     BitVector GPRsNoLRSP =
460         TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
461     GPRsNoLRSP |= PopFriendly;
462     GPRsNoLRSP.reset(ARM::LR);
463     GPRsNoLRSP.reset(ARM::SP);
464     GPRsNoLRSP.reset(ARM::PC);
465     for (int Register = GPRsNoLRSP.find_first(); Register != -1;
466          Register = GPRsNoLRSP.find_next(Register)) {
467       if (!UsedRegs.contains(Register)) {
468         // Remember the first pop-friendly register and exit.
469         if (PopFriendly.test(Register)) {
470           PopReg = Register;
471           TemporaryReg = 0;
472           break;
473         }
474         // Otherwise, remember that the register will be available to
475         // save a pop-friendly register.
476         TemporaryReg = Register;
477       }
478     }
479
480     assert((PopReg || TemporaryReg) && "Cannot get LR");
481
482     if (TemporaryReg) {
483       assert(!PopReg && "Unnecessary MOV is about to be inserted");
484       PopReg = PopFriendly.find_first();
485       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
486                          .addReg(TemporaryReg, RegState::Define)
487                          .addReg(PopReg, RegState::Kill));
488     }
489
490     assert(PopReg && "Do not know how to get LR");
491     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
492         .addReg(PopReg, RegState::Define);
493
494     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
495
496     if (!TemporaryReg && MBBI != MBB.end() &&
497         MBBI->getOpcode() == ARM::tBX_RET) {
498       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX))
499                                     .addReg(PopReg, RegState::Kill);
500       AddDefaultPred(MIB);
501       MIB.copyImplicitOps(&*MBBI);
502       // erase the old tBX_RET instruction
503       MBB.erase(MBBI);
504       return;
505     }
506
507     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
508                        .addReg(ARM::LR, RegState::Define)
509                        .addReg(PopReg, RegState::Kill));
510
511     if (TemporaryReg) {
512       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
513                          .addReg(PopReg, RegState::Define)
514                          .addReg(TemporaryReg, RegState::Kill));
515     }
516   }
517 }
518
519 bool Thumb1FrameLowering::
520 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
521                           MachineBasicBlock::iterator MI,
522                           const std::vector<CalleeSavedInfo> &CSI,
523                           const TargetRegisterInfo *TRI) const {
524   if (CSI.empty())
525     return false;
526
527   DebugLoc DL;
528   const TargetInstrInfo &TII = *STI.getInstrInfo();
529
530   if (MI != MBB.end()) DL = MI->getDebugLoc();
531
532   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
533   AddDefaultPred(MIB);
534   for (unsigned i = CSI.size(); i != 0; --i) {
535     unsigned Reg = CSI[i-1].getReg();
536     bool isKill = true;
537
538     // Add the callee-saved register as live-in unless it's LR and
539     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
540     // then it's already added to the function and entry block live-in sets.
541     if (Reg == ARM::LR) {
542       MachineFunction &MF = *MBB.getParent();
543       if (MF.getFrameInfo()->isReturnAddressTaken() &&
544           MF.getRegInfo().isLiveIn(Reg))
545         isKill = false;
546     }
547
548     if (isKill)
549       MBB.addLiveIn(Reg);
550
551     MIB.addReg(Reg, getKillRegState(isKill));
552   }
553   MIB.setMIFlags(MachineInstr::FrameSetup);
554   return true;
555 }
556
557 bool Thumb1FrameLowering::
558 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
559                             MachineBasicBlock::iterator MI,
560                             const std::vector<CalleeSavedInfo> &CSI,
561                             const TargetRegisterInfo *TRI) const {
562   if (CSI.empty())
563     return false;
564
565   MachineFunction &MF = *MBB.getParent();
566   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
567   const TargetInstrInfo &TII = *STI.getInstrInfo();
568
569   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
570   DebugLoc DL = MI->getDebugLoc();
571   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
572   AddDefaultPred(MIB);
573
574   bool NumRegs = false;
575   for (unsigned i = CSI.size(); i != 0; --i) {
576     unsigned Reg = CSI[i-1].getReg();
577     if (Reg == ARM::LR && MBB.succ_empty()) {
578       // Special epilogue for vararg functions. See emitEpilogue
579       if (isVarArg)
580         continue;
581       // ARMv4T requires BX, see emitEpilogue
582       if (STI.hasV4TOps() && !STI.hasV5TOps())
583         continue;
584       Reg = ARM::PC;
585       (*MIB).setDesc(TII.get(ARM::tPOP_RET));
586       if (MI != MBB.end())
587         MIB.copyImplicitOps(&*MI);
588       MI = MBB.erase(MI);
589     }
590     MIB.addReg(Reg, getDefRegState(true));
591     NumRegs = true;
592   }
593
594   // It's illegal to emit pop instruction without operands.
595   if (NumRegs)
596     MBB.insert(MI, &*MIB);
597   else
598     MF.DeleteMachineInstr(MIB);
599
600   return true;
601 }