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 emitSPUpdate(MachineBasicBlock &MBB,
42                          MachineBasicBlock::iterator &MBBI,
43                          const TargetInstrInfo &TII, const DebugLoc &dl,
44                          const ThumbRegisterInfo &MRI, int NumBytes,
45                          unsigned MIFlags = MachineInstr::NoFlags) {
46   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
47                             MRI, MIFlags);
48 }
49 
50 
51 MachineBasicBlock::iterator Thumb1FrameLowering::
52 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
53                               MachineBasicBlock::iterator I) const {
54   const Thumb1InstrInfo &TII =
55       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
56   const ThumbRegisterInfo *RegInfo =
57       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
58   if (!hasReservedCallFrame(MF)) {
59     // If we have alloca, convert as follows:
60     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
61     // ADJCALLSTACKUP   -> add, sp, sp, amount
62     MachineInstr *Old = I;
63     DebugLoc dl = Old->getDebugLoc();
64     unsigned Amount = Old->getOperand(0).getImm();
65     if (Amount != 0) {
66       // We need to keep the stack aligned properly.  To do this, we round the
67       // amount of space needed for the outgoing arguments up to the next
68       // alignment boundary.
69       unsigned Align = getStackAlignment();
70       Amount = (Amount+Align-1)/Align*Align;
71 
72       // Replace the pseudo instruction with a new instruction...
73       unsigned Opc = Old->getOpcode();
74       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
75         emitSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
76       } else {
77         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
78         emitSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
79       }
80     }
81   }
82   return MBB.erase(I);
83 }
84 
85 void Thumb1FrameLowering::emitPrologue(MachineFunction &MF,
86                                        MachineBasicBlock &MBB) const {
87   MachineBasicBlock::iterator MBBI = MBB.begin();
88   MachineFrameInfo  *MFI = MF.getFrameInfo();
89   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
90   MachineModuleInfo &MMI = MF.getMMI();
91   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
92   const ThumbRegisterInfo *RegInfo =
93       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
94   const Thumb1InstrInfo &TII =
95       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
96 
97   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
98   unsigned NumBytes = MFI->getStackSize();
99   assert(NumBytes >= ArgRegsSaveSize &&
100          "ArgRegsSaveSize is included in NumBytes");
101   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
102 
103   // Debug location must be unknown since the first debug location is used
104   // to determine the end of the prologue.
105   DebugLoc dl;
106 
107   unsigned FramePtr = RegInfo->getFrameRegister(MF);
108   unsigned BasePtr = RegInfo->getBaseRegister();
109   int CFAOffset = 0;
110 
111   // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
112   NumBytes = (NumBytes + 3) & ~3;
113   MFI->setStackSize(NumBytes);
114 
115   // Determine the sizes of each callee-save spill areas and record which frame
116   // belongs to which callee-save spill areas.
117   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
118   int FramePtrSpillFI = 0;
119 
120   if (ArgRegsSaveSize) {
121     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
122                  MachineInstr::FrameSetup);
123     CFAOffset -= ArgRegsSaveSize;
124     unsigned CFIIndex = MMI.addFrameInst(
125         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
126     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
127         .addCFIIndex(CFIIndex)
128         .setMIFlags(MachineInstr::FrameSetup);
129   }
130 
131   if (!AFI->hasStackFrame()) {
132     if (NumBytes - ArgRegsSaveSize != 0) {
133       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -(NumBytes - ArgRegsSaveSize),
134                    MachineInstr::FrameSetup);
135       CFAOffset -= NumBytes - ArgRegsSaveSize;
136       unsigned CFIIndex = MMI.addFrameInst(
137           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
138       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
139           .addCFIIndex(CFIIndex)
140           .setMIFlags(MachineInstr::FrameSetup);
141     }
142     return;
143   }
144 
145   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
146     unsigned Reg = CSI[i].getReg();
147     int FI = CSI[i].getFrameIdx();
148     switch (Reg) {
149     case ARM::R8:
150     case ARM::R9:
151     case ARM::R10:
152     case ARM::R11:
153       if (STI.splitFramePushPop()) {
154         GPRCS2Size += 4;
155         break;
156       }
157       // fallthrough
158     case ARM::R4:
159     case ARM::R5:
160     case ARM::R6:
161     case ARM::R7:
162     case ARM::LR:
163       if (Reg == FramePtr)
164         FramePtrSpillFI = FI;
165       GPRCS1Size += 4;
166       break;
167     default:
168       DPRCSSize += 8;
169     }
170   }
171 
172   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
173     ++MBBI;
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.splitFramePushPop())
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   // Adjust FP so it point to the stack slot that contains the previous FP.
237   if (HasFP) {
238     FramePtrOffsetInBlock +=
239         MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
240     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
241       .addReg(ARM::SP).addImm(FramePtrOffsetInBlock / 4)
242       .setMIFlags(MachineInstr::FrameSetup));
243     if(FramePtrOffsetInBlock) {
244       CFAOffset += FramePtrOffsetInBlock;
245       unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
246           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
247       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
248           .addCFIIndex(CFIIndex)
249           .setMIFlags(MachineInstr::FrameSetup);
250     } else {
251       unsigned CFIIndex =
252           MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
253               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
254       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
255           .addCFIIndex(CFIIndex)
256           .setMIFlags(MachineInstr::FrameSetup);
257     }
258     if (NumBytes > 508)
259       // If offset is > 508 then sp cannot be adjusted in a single instruction,
260       // try restoring from fp instead.
261       AFI->setShouldRestoreSPFromFP(true);
262   }
263 
264   if (NumBytes) {
265     // Insert it after all the callee-save spills.
266     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
267                  MachineInstr::FrameSetup);
268     if (!HasFP) {
269       CFAOffset -= NumBytes;
270       unsigned CFIIndex = MMI.addFrameInst(
271           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
272       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
273           .addCFIIndex(CFIIndex)
274           .setMIFlags(MachineInstr::FrameSetup);
275     }
276   }
277 
278   if (STI.isTargetELF() && HasFP)
279     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
280                              AFI->getFramePtrSpillOffset());
281 
282   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
283   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
284   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
285 
286   // Thumb1 does not currently support dynamic stack realignment.  Report a
287   // fatal error rather then silently generate bad code.
288   if (RegInfo->needsStackRealignment(MF))
289       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
290 
291   // If we need a base pointer, set it up here. It's whatever the value
292   // of the stack pointer is at this point. Any variable size objects
293   // will be allocated after this, so we can still use the base pointer
294   // to reference locals.
295   if (RegInfo->hasBasePointer(MF))
296     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
297                    .addReg(ARM::SP));
298 
299   // If the frame has variable sized objects then the epilogue must restore
300   // the sp from fp. We can assume there's an FP here since hasFP already
301   // checks for hasVarSizedObjects.
302   if (MFI->hasVarSizedObjects())
303     AFI->setShouldRestoreSPFromFP(true);
304 }
305 
306 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
307   if (MI->getOpcode() == ARM::tLDRspi &&
308       MI->getOperand(1).isFI() &&
309       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
310     return true;
311   else if (MI->getOpcode() == ARM::tPOP) {
312     // The first two operands are predicates. The last two are
313     // imp-def and imp-use of SP. Check everything in between.
314     for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
315       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
316         return false;
317     return true;
318   }
319   return false;
320 }
321 
322 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
323                                    MachineBasicBlock &MBB) const {
324   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
325   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
326   MachineFrameInfo *MFI = MF.getFrameInfo();
327   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
328   const ThumbRegisterInfo *RegInfo =
329       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
330   const Thumb1InstrInfo &TII =
331       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
332 
333   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
334   int NumBytes = (int)MFI->getStackSize();
335   assert((unsigned)NumBytes >= ArgRegsSaveSize &&
336          "ArgRegsSaveSize is included in NumBytes");
337   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
338   unsigned FramePtr = RegInfo->getFrameRegister(MF);
339 
340   if (!AFI->hasStackFrame()) {
341     if (NumBytes - ArgRegsSaveSize != 0)
342       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes - ArgRegsSaveSize);
343   } else {
344     // Unwind MBBI to point to first LDR / VLDRD.
345     if (MBBI != MBB.begin()) {
346       do
347         --MBBI;
348       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
349       if (!isCSRestore(MBBI, CSRegs))
350         ++MBBI;
351     }
352 
353     // Move SP to start of FP callee save spill area.
354     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
355                  AFI->getGPRCalleeSavedArea2Size() +
356                  AFI->getDPRCalleeSavedAreaSize() +
357                  ArgRegsSaveSize);
358 
359     if (AFI->shouldRestoreSPFromFP()) {
360       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
361       // Reset SP based on frame pointer only if the stack frame extends beyond
362       // frame pointer stack slot, the target is ELF and the function has FP, or
363       // the target uses var sized objects.
364       if (NumBytes) {
365         assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
366                "No scratch register to restore SP from FP!");
367         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
368                                   TII, *RegInfo);
369         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
370                                ARM::SP)
371           .addReg(ARM::R4));
372       } else
373         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
374                                ARM::SP)
375           .addReg(FramePtr));
376     } else {
377       if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
378           &MBB.front() != MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
379         MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
380         if (!tryFoldSPUpdateIntoPushPop(STI, MF, PMBBI, NumBytes))
381           emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
382       } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
383         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
384     }
385   }
386 
387   if (needPopSpecialFixUp(MF)) {
388     bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
389     (void)Done;
390     assert(Done && "Emission of the special fixup failed!?");
391   }
392 }
393 
394 bool Thumb1FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
395   if (!needPopSpecialFixUp(*MBB.getParent()))
396     return true;
397 
398   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
399   return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
400 }
401 
402 bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
403   ARMFunctionInfo *AFI =
404       const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
405   if (AFI->getArgRegsSaveSize())
406     return true;
407 
408   // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
409   for (const CalleeSavedInfo &CSI : MF.getFrameInfo()->getCalleeSavedInfo())
410     if (CSI.getReg() == ARM::LR)
411       return true;
412 
413   return false;
414 }
415 
416 bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
417                                               bool DoIt) const {
418   MachineFunction &MF = *MBB.getParent();
419   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
420   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
421   const TargetInstrInfo &TII = *STI.getInstrInfo();
422   const ThumbRegisterInfo *RegInfo =
423       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
424 
425   // If MBBI is a return instruction, or is a tPOP followed by a return
426   // instruction in the successor BB, we may be able to directly restore
427   // LR in the PC.
428   // This is only possible with v5T ops (v4T can't change the Thumb bit via
429   // a POP PC instruction), and only if we do not need to emit any SP update.
430   // Otherwise, we need a temporary register to pop the value
431   // and copy that value into LR.
432   auto MBBI = MBB.getFirstTerminator();
433   bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
434   if (CanRestoreDirectly) {
435     if (MBBI != MBB.end() && MBBI->getOpcode() != ARM::tB)
436       CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
437                             MBBI->getOpcode() == ARM::tPOP_RET);
438     else {
439       auto MBBI_prev = MBBI;
440       MBBI_prev--;
441       assert(MBBI_prev->getOpcode() == ARM::tPOP);
442       assert(MBB.succ_size() == 1);
443       if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
444         MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
445       else
446         CanRestoreDirectly = false;
447     }
448   }
449 
450   if (CanRestoreDirectly) {
451     if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
452       return true;
453     MachineInstrBuilder MIB =
454         AddDefaultPred(
455             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET)));
456     // Copy implicit ops and popped registers, if any.
457     for (auto MO: MBBI->operands())
458       if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
459         MIB.addOperand(MO);
460     MIB.addReg(ARM::PC, RegState::Define);
461     // Erase the old instruction (tBX_RET or tPOP).
462     MBB.erase(MBBI);
463     return true;
464   }
465 
466   // Look for a temporary register to use.
467   // First, compute the liveness information.
468   LivePhysRegs UsedRegs(STI.getRegisterInfo());
469   UsedRegs.addLiveOuts(MBB);
470   // The semantic of pristines changed recently and now,
471   // the callee-saved registers that are touched in the function
472   // are not part of the pristines set anymore.
473   // Add those callee-saved now.
474   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
475   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
476   for (unsigned i = 0; CSRegs[i]; ++i)
477     UsedRegs.addReg(CSRegs[i]);
478 
479   DebugLoc dl = DebugLoc();
480   if (MBBI != MBB.end()) {
481     dl = MBBI->getDebugLoc();
482     auto InstUpToMBBI = MBB.end();
483     while (InstUpToMBBI != MBBI)
484       // The pre-decrement is on purpose here.
485       // We want to have the liveness right before MBBI.
486       UsedRegs.stepBackward(*--InstUpToMBBI);
487   }
488 
489   // Look for a register that can be directly use in the POP.
490   unsigned PopReg = 0;
491   // And some temporary register, just in case.
492   unsigned TemporaryReg = 0;
493   BitVector PopFriendly =
494       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
495   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
496   // Rebuild the GPRs from the high registers because they are removed
497   // form the GPR reg class for thumb1.
498   BitVector GPRsNoLRSP =
499       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
500   GPRsNoLRSP |= PopFriendly;
501   GPRsNoLRSP.reset(ARM::LR);
502   GPRsNoLRSP.reset(ARM::SP);
503   GPRsNoLRSP.reset(ARM::PC);
504   for (int Register = GPRsNoLRSP.find_first(); Register != -1;
505        Register = GPRsNoLRSP.find_next(Register)) {
506     if (!UsedRegs.contains(Register)) {
507       // Remember the first pop-friendly register and exit.
508       if (PopFriendly.test(Register)) {
509         PopReg = Register;
510         TemporaryReg = 0;
511         break;
512       }
513       // Otherwise, remember that the register will be available to
514       // save a pop-friendly register.
515       TemporaryReg = Register;
516     }
517   }
518 
519   if (!DoIt && !PopReg && !TemporaryReg)
520     return false;
521 
522   assert((PopReg || TemporaryReg) && "Cannot get LR");
523 
524   if (TemporaryReg) {
525     assert(!PopReg && "Unnecessary MOV is about to be inserted");
526     PopReg = PopFriendly.find_first();
527     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
528                        .addReg(TemporaryReg, RegState::Define)
529                        .addReg(PopReg, RegState::Kill));
530   }
531 
532   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
533     // We couldn't use the direct restoration above, so
534     // perform the opposite conversion: tPOP_RET to tPOP.
535     MachineInstrBuilder MIB =
536         AddDefaultPred(
537             BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP)));
538     bool Popped = false;
539     for (auto MO: MBBI->operands())
540       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
541           MO.getReg() != ARM::PC) {
542         MIB.addOperand(MO);
543         if (!MO.isImplicit())
544           Popped = true;
545       }
546     // Is there anything left to pop?
547     if (!Popped)
548       MBB.erase(MIB.getInstr());
549     // Erase the old instruction.
550     MBB.erase(MBBI);
551     MBBI = AddDefaultPred(BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET)));
552   }
553 
554   assert(PopReg && "Do not know how to get LR");
555   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
556       .addReg(PopReg, RegState::Define);
557 
558   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
559 
560   AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
561                      .addReg(ARM::LR, RegState::Define)
562                      .addReg(PopReg, RegState::Kill));
563 
564   if (TemporaryReg)
565     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
566                        .addReg(PopReg, RegState::Define)
567                        .addReg(TemporaryReg, RegState::Kill));
568 
569   return true;
570 }
571 
572 bool Thumb1FrameLowering::
573 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
574                           MachineBasicBlock::iterator MI,
575                           const std::vector<CalleeSavedInfo> &CSI,
576                           const TargetRegisterInfo *TRI) const {
577   if (CSI.empty())
578     return false;
579 
580   DebugLoc DL;
581   const TargetInstrInfo &TII = *STI.getInstrInfo();
582 
583   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
584   AddDefaultPred(MIB);
585   for (unsigned i = CSI.size(); i != 0; --i) {
586     unsigned Reg = CSI[i-1].getReg();
587     bool isKill = true;
588 
589     // Add the callee-saved register as live-in unless it's LR and
590     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
591     // then it's already added to the function and entry block live-in sets.
592     if (Reg == ARM::LR) {
593       MachineFunction &MF = *MBB.getParent();
594       if (MF.getFrameInfo()->isReturnAddressTaken() &&
595           MF.getRegInfo().isLiveIn(Reg))
596         isKill = false;
597     }
598 
599     if (isKill)
600       MBB.addLiveIn(Reg);
601 
602     MIB.addReg(Reg, getKillRegState(isKill));
603   }
604   MIB.setMIFlags(MachineInstr::FrameSetup);
605   return true;
606 }
607 
608 bool Thumb1FrameLowering::
609 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
610                             MachineBasicBlock::iterator MI,
611                             const std::vector<CalleeSavedInfo> &CSI,
612                             const TargetRegisterInfo *TRI) const {
613   if (CSI.empty())
614     return false;
615 
616   MachineFunction &MF = *MBB.getParent();
617   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
618   const TargetInstrInfo &TII = *STI.getInstrInfo();
619 
620   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
621   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
622   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
623   AddDefaultPred(MIB);
624 
625   bool NeedsPop = false;
626   for (unsigned i = CSI.size(); i != 0; --i) {
627     unsigned Reg = CSI[i-1].getReg();
628     if (Reg == ARM::LR) {
629       if (MBB.succ_empty()) {
630         // Special epilogue for vararg functions. See emitEpilogue
631         if (isVarArg)
632           continue;
633         // ARMv4T requires BX, see emitEpilogue
634         if (!STI.hasV5TOps())
635           continue;
636         Reg = ARM::PC;
637         (*MIB).setDesc(TII.get(ARM::tPOP_RET));
638         if (MI != MBB.end())
639           MIB.copyImplicitOps(*MI);
640         MI = MBB.erase(MI);
641       } else
642         // LR may only be popped into PC, as part of return sequence.
643         // If this isn't the return sequence, we'll need emitPopSpecialFixUp
644         // to restore LR the hard way.
645         continue;
646     }
647     MIB.addReg(Reg, getDefRegState(true));
648     NeedsPop = true;
649   }
650 
651   // It's illegal to emit pop instruction without operands.
652   if (NeedsPop)
653     MBB.insert(MI, &*MIB);
654   else
655     MF.DeleteMachineInstr(MIB);
656 
657   return true;
658 }
659