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 &MFI = MF.getFrameInfo();
30   unsigned CFSize = MFI.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 !MFI.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 = MF.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 = MF.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(MF)) {
154         GPRCS2Size += 4;
155         break;
156       }
157       LLVM_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 (GPRCS1Size > 0 && GPRCS2Size == 0 &&
192       tryFoldSPUpdateIntoPushPop(STI, MF, &*std::prev(MBBI), NumBytes)) {
193     FramePtrOffsetInBlock = NumBytes;
194     adjustedGPRCS1Size += NumBytes;
195     NumBytes = 0;
196   }
197 
198   if (adjustedGPRCS1Size) {
199     CFAOffset -= adjustedGPRCS1Size;
200     unsigned CFIIndex = MF.addFrameInst(
201         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
202     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
203         .addCFIIndex(CFIIndex)
204         .setMIFlags(MachineInstr::FrameSetup);
205   }
206   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
207          E = CSI.end(); I != E; ++I) {
208     unsigned Reg = I->getReg();
209     int FI = I->getFrameIdx();
210     switch (Reg) {
211     case ARM::R8:
212     case ARM::R9:
213     case ARM::R10:
214     case ARM::R11:
215     case ARM::R12:
216       if (STI.splitFramePushPop(MF))
217         break;
218       // fallthough
219     case ARM::R0:
220     case ARM::R1:
221     case ARM::R2:
222     case ARM::R3:
223     case ARM::R4:
224     case ARM::R5:
225     case ARM::R6:
226     case ARM::R7:
227     case ARM::LR:
228       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
229           nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
230       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
231           .addCFIIndex(CFIIndex)
232           .setMIFlags(MachineInstr::FrameSetup);
233       break;
234     }
235   }
236 
237   // Adjust FP so it point to the stack slot that contains the previous FP.
238   if (HasFP) {
239     FramePtrOffsetInBlock +=
240         MFI.getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
241     BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
242         .addReg(ARM::SP)
243         .addImm(FramePtrOffsetInBlock / 4)
244         .setMIFlags(MachineInstr::FrameSetup)
245         .add(predOps(ARMCC::AL));
246     if(FramePtrOffsetInBlock) {
247       CFAOffset += FramePtrOffsetInBlock;
248       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
249           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
250       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
251           .addCFIIndex(CFIIndex)
252           .setMIFlags(MachineInstr::FrameSetup);
253     } else {
254       unsigned CFIIndex =
255           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
256               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
257       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
258           .addCFIIndex(CFIIndex)
259           .setMIFlags(MachineInstr::FrameSetup);
260     }
261     if (NumBytes > 508)
262       // If offset is > 508 then sp cannot be adjusted in a single instruction,
263       // try restoring from fp instead.
264       AFI->setShouldRestoreSPFromFP(true);
265   }
266 
267   // Skip past the spilling of r8-r11, which could consist of multiple tPUSH
268   // and tMOVr instructions. We don't need to add any call frame information
269   // in-between these instructions, because they do not modify the high
270   // registers.
271   while (true) {
272     MachineBasicBlock::iterator OldMBBI = MBBI;
273     // Skip a run of tMOVr instructions
274     while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tMOVr)
275       MBBI++;
276     if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
277       MBBI++;
278     } else {
279       // We have reached an instruction which is not a push, so the previous
280       // run of tMOVr instructions (which may have been empty) was not part of
281       // the prologue. Reset MBBI back to the last PUSH of the prologue.
282       MBBI = OldMBBI;
283       break;
284     }
285   }
286 
287   // Emit call frame information for the callee-saved high registers.
288   for (auto &I : CSI) {
289     unsigned Reg = I.getReg();
290     int FI = I.getFrameIdx();
291     switch (Reg) {
292     case ARM::R8:
293     case ARM::R9:
294     case ARM::R10:
295     case ARM::R11:
296     case ARM::R12: {
297       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
298           nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
299       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
300           .addCFIIndex(CFIIndex)
301           .setMIFlags(MachineInstr::FrameSetup);
302       break;
303     }
304     default:
305       break;
306     }
307   }
308 
309   if (NumBytes) {
310     // Insert it after all the callee-save spills.
311     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
312                  MachineInstr::FrameSetup);
313     if (!HasFP) {
314       CFAOffset -= NumBytes;
315       unsigned CFIIndex = MF.addFrameInst(
316           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
317       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
318           .addCFIIndex(CFIIndex)
319           .setMIFlags(MachineInstr::FrameSetup);
320     }
321   }
322 
323   if (STI.isTargetELF() && HasFP)
324     MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
325                             AFI->getFramePtrSpillOffset());
326 
327   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
328   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
329   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
330 
331   // Thumb1 does not currently support dynamic stack realignment.  Report a
332   // fatal error rather then silently generate bad code.
333   if (RegInfo->needsStackRealignment(MF))
334       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
335 
336   // If we need a base pointer, set it up here. It's whatever the value
337   // of the stack pointer is at this point. Any variable size objects
338   // will be allocated after this, so we can still use the base pointer
339   // to reference locals.
340   if (RegInfo->hasBasePointer(MF))
341     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
342         .addReg(ARM::SP)
343         .add(predOps(ARMCC::AL));
344 
345   // If the frame has variable sized objects then the epilogue must restore
346   // the sp from fp. We can assume there's an FP here since hasFP already
347   // checks for hasVarSizedObjects.
348   if (MFI.hasVarSizedObjects())
349     AFI->setShouldRestoreSPFromFP(true);
350 }
351 
352 static bool isCSRestore(MachineInstr &MI, const MCPhysReg *CSRegs) {
353   if (MI.getOpcode() == ARM::tLDRspi && MI.getOperand(1).isFI() &&
354       isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs))
355     return true;
356   else if (MI.getOpcode() == ARM::tPOP) {
357     return true;
358   } else if (MI.getOpcode() == ARM::tMOVr) {
359     unsigned Dst = MI.getOperand(0).getReg();
360     unsigned Src = MI.getOperand(1).getReg();
361     return ((ARM::tGPRRegClass.contains(Src) || Src == ARM::LR) &&
362             ARM::hGPRRegClass.contains(Dst));
363   }
364   return false;
365 }
366 
367 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
368                                    MachineBasicBlock &MBB) const {
369   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
370   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
371   MachineFrameInfo &MFI = MF.getFrameInfo();
372   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
373   const ThumbRegisterInfo *RegInfo =
374       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
375   const Thumb1InstrInfo &TII =
376       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
377 
378   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
379   int NumBytes = (int)MFI.getStackSize();
380   assert((unsigned)NumBytes >= ArgRegsSaveSize &&
381          "ArgRegsSaveSize is included in NumBytes");
382   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
383   unsigned FramePtr = RegInfo->getFrameRegister(MF);
384 
385   if (!AFI->hasStackFrame()) {
386     if (NumBytes - ArgRegsSaveSize != 0)
387       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes - ArgRegsSaveSize);
388   } else {
389     // Unwind MBBI to point to first LDR / VLDRD.
390     if (MBBI != MBB.begin()) {
391       do
392         --MBBI;
393       while (MBBI != MBB.begin() && isCSRestore(*MBBI, CSRegs));
394       if (!isCSRestore(*MBBI, CSRegs))
395         ++MBBI;
396     }
397 
398     // Move SP to start of FP callee save spill area.
399     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
400                  AFI->getGPRCalleeSavedArea2Size() +
401                  AFI->getDPRCalleeSavedAreaSize() +
402                  ArgRegsSaveSize);
403 
404     if (AFI->shouldRestoreSPFromFP()) {
405       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
406       // Reset SP based on frame pointer only if the stack frame extends beyond
407       // frame pointer stack slot, the target is ELF and the function has FP, or
408       // the target uses var sized objects.
409       if (NumBytes) {
410         assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
411                "No scratch register to restore SP from FP!");
412         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
413                                   TII, *RegInfo);
414         BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
415             .addReg(ARM::R4)
416             .add(predOps(ARMCC::AL));
417       } else
418         BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
419             .addReg(FramePtr)
420             .add(predOps(ARMCC::AL));
421     } else {
422       if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
423           &MBB.front() != &*MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
424         MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
425         if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*PMBBI, NumBytes))
426           emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
427       } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
428         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
429     }
430   }
431 
432   if (needPopSpecialFixUp(MF)) {
433     bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
434     (void)Done;
435     assert(Done && "Emission of the special fixup failed!?");
436   }
437 }
438 
439 bool Thumb1FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
440   if (!needPopSpecialFixUp(*MBB.getParent()))
441     return true;
442 
443   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
444   return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
445 }
446 
447 bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
448   ARMFunctionInfo *AFI =
449       const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
450   if (AFI->getArgRegsSaveSize())
451     return true;
452 
453   // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
454   for (const CalleeSavedInfo &CSI : MF.getFrameInfo().getCalleeSavedInfo())
455     if (CSI.getReg() == ARM::LR)
456       return true;
457 
458   return false;
459 }
460 
461 bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
462                                               bool DoIt) const {
463   MachineFunction &MF = *MBB.getParent();
464   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
465   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
466   const TargetInstrInfo &TII = *STI.getInstrInfo();
467   const ThumbRegisterInfo *RegInfo =
468       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
469 
470   // If MBBI is a return instruction, or is a tPOP followed by a return
471   // instruction in the successor BB, we may be able to directly restore
472   // LR in the PC.
473   // This is only possible with v5T ops (v4T can't change the Thumb bit via
474   // a POP PC instruction), and only if we do not need to emit any SP update.
475   // Otherwise, we need a temporary register to pop the value
476   // and copy that value into LR.
477   auto MBBI = MBB.getFirstTerminator();
478   bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
479   if (CanRestoreDirectly) {
480     if (MBBI != MBB.end() && MBBI->getOpcode() != ARM::tB)
481       CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
482                             MBBI->getOpcode() == ARM::tPOP_RET);
483     else {
484       auto MBBI_prev = MBBI;
485       MBBI_prev--;
486       assert(MBBI_prev->getOpcode() == ARM::tPOP);
487       assert(MBB.succ_size() == 1);
488       if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
489         MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
490       else
491         CanRestoreDirectly = false;
492     }
493   }
494 
495   if (CanRestoreDirectly) {
496     if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
497       return true;
498     MachineInstrBuilder MIB =
499         BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET))
500             .add(predOps(ARMCC::AL));
501     // Copy implicit ops and popped registers, if any.
502     for (auto MO: MBBI->operands())
503       if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
504         MIB.add(MO);
505     MIB.addReg(ARM::PC, RegState::Define);
506     // Erase the old instruction (tBX_RET or tPOP).
507     MBB.erase(MBBI);
508     return true;
509   }
510 
511   // Look for a temporary register to use.
512   // First, compute the liveness information.
513   LivePhysRegs UsedRegs(STI.getRegisterInfo());
514   UsedRegs.addLiveOuts(MBB);
515   // The semantic of pristines changed recently and now,
516   // the callee-saved registers that are touched in the function
517   // are not part of the pristines set anymore.
518   // Add those callee-saved now.
519   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
520   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
521   for (unsigned i = 0; CSRegs[i]; ++i)
522     UsedRegs.addReg(CSRegs[i]);
523 
524   DebugLoc dl = DebugLoc();
525   if (MBBI != MBB.end()) {
526     dl = MBBI->getDebugLoc();
527     auto InstUpToMBBI = MBB.end();
528     while (InstUpToMBBI != MBBI)
529       // The pre-decrement is on purpose here.
530       // We want to have the liveness right before MBBI.
531       UsedRegs.stepBackward(*--InstUpToMBBI);
532   }
533 
534   // Look for a register that can be directly use in the POP.
535   unsigned PopReg = 0;
536   // And some temporary register, just in case.
537   unsigned TemporaryReg = 0;
538   BitVector PopFriendly =
539       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::tGPRRegClassID));
540   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
541   // Rebuild the GPRs from the high registers because they are removed
542   // form the GPR reg class for thumb1.
543   BitVector GPRsNoLRSP =
544       TRI->getAllocatableSet(MF, TRI->getRegClass(ARM::hGPRRegClassID));
545   GPRsNoLRSP |= PopFriendly;
546   GPRsNoLRSP.reset(ARM::LR);
547   GPRsNoLRSP.reset(ARM::SP);
548   GPRsNoLRSP.reset(ARM::PC);
549   for (int Register = GPRsNoLRSP.find_first(); Register != -1;
550        Register = GPRsNoLRSP.find_next(Register)) {
551     if (!UsedRegs.contains(Register)) {
552       // Remember the first pop-friendly register and exit.
553       if (PopFriendly.test(Register)) {
554         PopReg = Register;
555         TemporaryReg = 0;
556         break;
557       }
558       // Otherwise, remember that the register will be available to
559       // save a pop-friendly register.
560       TemporaryReg = Register;
561     }
562   }
563 
564   if (!DoIt && !PopReg && !TemporaryReg)
565     return false;
566 
567   assert((PopReg || TemporaryReg) && "Cannot get LR");
568 
569   if (TemporaryReg) {
570     assert(!PopReg && "Unnecessary MOV is about to be inserted");
571     PopReg = PopFriendly.find_first();
572     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
573         .addReg(TemporaryReg, RegState::Define)
574         .addReg(PopReg, RegState::Kill)
575         .add(predOps(ARMCC::AL));
576   }
577 
578   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
579     // We couldn't use the direct restoration above, so
580     // perform the opposite conversion: tPOP_RET to tPOP.
581     MachineInstrBuilder MIB =
582         BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP))
583             .add(predOps(ARMCC::AL));
584     bool Popped = false;
585     for (auto MO: MBBI->operands())
586       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
587           MO.getReg() != ARM::PC) {
588         MIB.add(MO);
589         if (!MO.isImplicit())
590           Popped = true;
591       }
592     // Is there anything left to pop?
593     if (!Popped)
594       MBB.erase(MIB.getInstr());
595     // Erase the old instruction.
596     MBB.erase(MBBI);
597     MBBI = BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET))
598                .add(predOps(ARMCC::AL));
599   }
600 
601   assert(PopReg && "Do not know how to get LR");
602   BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP))
603       .add(predOps(ARMCC::AL))
604       .addReg(PopReg, RegState::Define);
605 
606   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
607 
608   BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
609       .addReg(ARM::LR, RegState::Define)
610       .addReg(PopReg, RegState::Kill)
611       .add(predOps(ARMCC::AL));
612 
613   if (TemporaryReg)
614     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
615         .addReg(PopReg, RegState::Define)
616         .addReg(TemporaryReg, RegState::Kill)
617         .add(predOps(ARMCC::AL));
618 
619   return true;
620 }
621 
622 // Return the first iteraror after CurrentReg which is present in EnabledRegs,
623 // or OrderEnd if no further registers are in that set. This does not advance
624 // the iterator fiorst, so returns CurrentReg if it is in EnabledRegs.
625 template <unsigned SetSize>
626 static const unsigned *
627 findNextOrderedReg(const unsigned *CurrentReg,
628                    SmallSet<unsigned, SetSize> &EnabledRegs,
629                    const unsigned *OrderEnd) {
630   while (CurrentReg != OrderEnd && !EnabledRegs.count(*CurrentReg))
631     ++CurrentReg;
632   return CurrentReg;
633 }
634 
635 bool Thumb1FrameLowering::
636 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
637                           MachineBasicBlock::iterator MI,
638                           const std::vector<CalleeSavedInfo> &CSI,
639                           const TargetRegisterInfo *TRI) const {
640   if (CSI.empty())
641     return false;
642 
643   DebugLoc DL;
644   const TargetInstrInfo &TII = *STI.getInstrInfo();
645   MachineFunction &MF = *MBB.getParent();
646   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
647       MF.getSubtarget().getRegisterInfo());
648 
649   SmallSet<unsigned, 9> LoRegsToSave; // r0-r7, lr
650   SmallSet<unsigned, 4> HiRegsToSave; // r8-r11
651   SmallSet<unsigned, 9> CopyRegs; // Registers which can be used after pushing
652                            // LoRegs for saving HiRegs.
653 
654   for (unsigned i = CSI.size(); i != 0; --i) {
655     unsigned Reg = CSI[i-1].getReg();
656 
657     if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
658       LoRegsToSave.insert(Reg);
659     } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
660       HiRegsToSave.insert(Reg);
661     } else {
662       llvm_unreachable("callee-saved register of unexpected class");
663     }
664 
665     if ((ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) &&
666         !MF.getRegInfo().isLiveIn(Reg) &&
667         !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
668       CopyRegs.insert(Reg);
669   }
670 
671   // Unused argument registers can be used for the high register saving.
672   for (unsigned ArgReg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3})
673     if (!MF.getRegInfo().isLiveIn(ArgReg))
674       CopyRegs.insert(ArgReg);
675 
676   // Push the low registers and lr
677   if (!LoRegsToSave.empty()) {
678     MachineInstrBuilder MIB =
679         BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
680     for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6, ARM::R7, ARM::LR}) {
681       if (LoRegsToSave.count(Reg)) {
682         bool isKill = !MF.getRegInfo().isLiveIn(Reg);
683         if (isKill)
684           MBB.addLiveIn(Reg);
685 
686         MIB.addReg(Reg, getKillRegState(isKill));
687       }
688     }
689     MIB.setMIFlags(MachineInstr::FrameSetup);
690   }
691 
692   // Push the high registers. There are no store instructions that can access
693   // these registers directly, so we have to move them to low registers, and
694   // push them. This might take multiple pushes, as it is possible for there to
695   // be fewer low registers available than high registers which need saving.
696 
697   // These are in reverse order so that in the case where we need to use
698   // multiple PUSH instructions, the order of the registers on the stack still
699   // matches the unwind info. They need to be swicthed back to ascending order
700   // before adding to the PUSH instruction.
701   static const unsigned AllCopyRegs[] = {ARM::LR, ARM::R7, ARM::R6,
702                                          ARM::R5, ARM::R4, ARM::R3,
703                                          ARM::R2, ARM::R1, ARM::R0};
704   static const unsigned AllHighRegs[] = {ARM::R11, ARM::R10, ARM::R9, ARM::R8};
705 
706   const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
707   const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
708 
709   // Find the first register to save.
710   const unsigned *HiRegToSave = findNextOrderedReg(
711       std::begin(AllHighRegs), HiRegsToSave, AllHighRegsEnd);
712 
713   while (HiRegToSave != AllHighRegsEnd) {
714     // Find the first low register to use.
715     const unsigned *CopyReg =
716         findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
717 
718     // Create the PUSH, but don't insert it yet (the MOVs need to come first).
719     MachineInstrBuilder PushMIB =
720         BuildMI(MF, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
721 
722     SmallVector<unsigned, 4> RegsToPush;
723     while (HiRegToSave != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
724       if (HiRegsToSave.count(*HiRegToSave)) {
725         bool isKill = !MF.getRegInfo().isLiveIn(*HiRegToSave);
726         if (isKill)
727           MBB.addLiveIn(*HiRegToSave);
728 
729         // Emit a MOV from the high reg to the low reg.
730         BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
731             .addReg(*CopyReg, RegState::Define)
732             .addReg(*HiRegToSave, getKillRegState(isKill))
733             .add(predOps(ARMCC::AL));
734 
735         // Record the register that must be added to the PUSH.
736         RegsToPush.push_back(*CopyReg);
737 
738         CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
739         HiRegToSave =
740             findNextOrderedReg(++HiRegToSave, HiRegsToSave, AllHighRegsEnd);
741       }
742     }
743 
744     // Add the low registers to the PUSH, in ascending order.
745     for (unsigned Reg : reverse(RegsToPush))
746       PushMIB.addReg(Reg, RegState::Kill);
747 
748     // Insert the PUSH instruction after the MOVs.
749     MBB.insert(MI, PushMIB);
750   }
751 
752   return true;
753 }
754 
755 bool Thumb1FrameLowering::
756 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
757                             MachineBasicBlock::iterator MI,
758                             const std::vector<CalleeSavedInfo> &CSI,
759                             const TargetRegisterInfo *TRI) const {
760   if (CSI.empty())
761     return false;
762 
763   MachineFunction &MF = *MBB.getParent();
764   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
765   const TargetInstrInfo &TII = *STI.getInstrInfo();
766   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
767       MF.getSubtarget().getRegisterInfo());
768 
769   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
770   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
771 
772   SmallSet<unsigned, 9> LoRegsToRestore;
773   SmallSet<unsigned, 4> HiRegsToRestore;
774   // Low registers (r0-r7) which can be used to restore the high registers.
775   SmallSet<unsigned, 9> CopyRegs;
776 
777   for (CalleeSavedInfo I : CSI) {
778     unsigned Reg = I.getReg();
779 
780     if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
781       LoRegsToRestore.insert(Reg);
782     } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
783       HiRegsToRestore.insert(Reg);
784     } else {
785       llvm_unreachable("callee-saved register of unexpected class");
786     }
787 
788     // If this is a low register not used as the frame pointer, we may want to
789     // use it for restoring the high registers.
790     if ((ARM::tGPRRegClass.contains(Reg)) &&
791         !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
792       CopyRegs.insert(Reg);
793   }
794 
795   // If this is a return block, we may be able to use some unused return value
796   // registers for restoring the high regs.
797   auto Terminator = MBB.getFirstTerminator();
798   if (Terminator != MBB.end() && Terminator->getOpcode() == ARM::tBX_RET) {
799     CopyRegs.insert(ARM::R0);
800     CopyRegs.insert(ARM::R1);
801     CopyRegs.insert(ARM::R2);
802     CopyRegs.insert(ARM::R3);
803     for (auto Op : Terminator->implicit_operands()) {
804       if (Op.isReg())
805         CopyRegs.erase(Op.getReg());
806     }
807   }
808 
809   static const unsigned AllCopyRegs[] = {ARM::R0, ARM::R1, ARM::R2, ARM::R3,
810                                          ARM::R4, ARM::R5, ARM::R6, ARM::R7};
811   static const unsigned AllHighRegs[] = {ARM::R8, ARM::R9, ARM::R10, ARM::R11};
812 
813   const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
814   const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
815 
816   // Find the first register to restore.
817   auto HiRegToRestore = findNextOrderedReg(std::begin(AllHighRegs),
818                                            HiRegsToRestore, AllHighRegsEnd);
819 
820   while (HiRegToRestore != AllHighRegsEnd) {
821     assert(!CopyRegs.empty());
822     // Find the first low register to use.
823     auto CopyReg =
824         findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
825 
826     // Create the POP instruction.
827     MachineInstrBuilder PopMIB =
828         BuildMI(MBB, MI, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
829 
830     while (HiRegToRestore != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
831       // Add the low register to the POP.
832       PopMIB.addReg(*CopyReg, RegState::Define);
833 
834       // Create the MOV from low to high register.
835       BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
836           .addReg(*HiRegToRestore, RegState::Define)
837           .addReg(*CopyReg, RegState::Kill)
838           .add(predOps(ARMCC::AL));
839 
840       CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
841       HiRegToRestore =
842           findNextOrderedReg(++HiRegToRestore, HiRegsToRestore, AllHighRegsEnd);
843     }
844   }
845 
846   MachineInstrBuilder MIB =
847       BuildMI(MF, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
848 
849   bool NeedsPop = false;
850   for (unsigned i = CSI.size(); i != 0; --i) {
851     unsigned Reg = CSI[i-1].getReg();
852 
853     // High registers (excluding lr) have already been dealt with
854     if (!(ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR))
855       continue;
856 
857     if (Reg == ARM::LR) {
858       if (MBB.succ_empty()) {
859         // Special epilogue for vararg functions. See emitEpilogue
860         if (isVarArg)
861           continue;
862         // ARMv4T requires BX, see emitEpilogue
863         if (!STI.hasV5TOps())
864           continue;
865         Reg = ARM::PC;
866         (*MIB).setDesc(TII.get(ARM::tPOP_RET));
867         if (MI != MBB.end())
868           MIB.copyImplicitOps(*MI);
869         MI = MBB.erase(MI);
870       } else
871         // LR may only be popped into PC, as part of return sequence.
872         // If this isn't the return sequence, we'll need emitPopSpecialFixUp
873         // to restore LR the hard way.
874         continue;
875     }
876     MIB.addReg(Reg, getDefRegState(true));
877     NeedsPop = true;
878   }
879 
880   // It's illegal to emit pop instruction without operands.
881   if (NeedsPop)
882     MBB.insert(MI, &*MIB);
883   else
884     MF.DeleteMachineInstr(MIB);
885 
886   return true;
887 }
888