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 "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMSubtarget.h"
19 #include "Thumb1InstrInfo.h"
20 #include "ThumbRegisterInfo.h"
21 #include "Utils/ARMBaseInfo.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/CodeGen/LivePhysRegs.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCDwarf.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOpcodes.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <bitset>
45 #include <cassert>
46 #include <iterator>
47 #include <vector>
48 
49 using namespace llvm;
50 
51 Thumb1FrameLowering::Thumb1FrameLowering(const ARMSubtarget &sti)
52     : ARMFrameLowering(sti) {}
53 
54 bool Thumb1FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const{
55   const MachineFrameInfo &MFI = MF.getFrameInfo();
56   unsigned CFSize = MFI.getMaxCallFrameSize();
57   // It's not always a good idea to include the call frame as part of the
58   // stack frame. ARM (especially Thumb) has small immediate offset to
59   // address the stack frame. So a large call frame can cause poor codegen
60   // and may even makes it impossible to scavenge a register.
61   if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
62     return false;
63 
64   return !MFI.hasVarSizedObjects();
65 }
66 
67 static void emitSPUpdate(MachineBasicBlock &MBB,
68                          MachineBasicBlock::iterator &MBBI,
69                          const TargetInstrInfo &TII, const DebugLoc &dl,
70                          const ThumbRegisterInfo &MRI, int NumBytes,
71                          unsigned MIFlags = MachineInstr::NoFlags) {
72   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
73                             MRI, MIFlags);
74 }
75 
76 MachineBasicBlock::iterator Thumb1FrameLowering::
77 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
78                               MachineBasicBlock::iterator I) const {
79   const Thumb1InstrInfo &TII =
80       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
81   const ThumbRegisterInfo *RegInfo =
82       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
83   if (!hasReservedCallFrame(MF)) {
84     // If we have alloca, convert as follows:
85     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
86     // ADJCALLSTACKUP   -> add, sp, sp, amount
87     MachineInstr &Old = *I;
88     DebugLoc dl = Old.getDebugLoc();
89     unsigned Amount = TII.getFrameSize(Old);
90     if (Amount != 0) {
91       // We need to keep the stack aligned properly.  To do this, we round the
92       // amount of space needed for the outgoing arguments up to the next
93       // alignment boundary.
94       Amount = alignTo(Amount, getStackAlignment());
95 
96       // Replace the pseudo instruction with a new instruction...
97       unsigned Opc = Old.getOpcode();
98       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
99         emitSPUpdate(MBB, I, TII, dl, *RegInfo, -Amount);
100       } else {
101         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
102         emitSPUpdate(MBB, I, TII, dl, *RegInfo, Amount);
103       }
104     }
105   }
106   return MBB.erase(I);
107 }
108 
109 void Thumb1FrameLowering::emitPrologue(MachineFunction &MF,
110                                        MachineBasicBlock &MBB) const {
111   MachineBasicBlock::iterator MBBI = MBB.begin();
112   MachineFrameInfo &MFI = MF.getFrameInfo();
113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
114   MachineModuleInfo &MMI = MF.getMMI();
115   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
116   const ThumbRegisterInfo *RegInfo =
117       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
118   const Thumb1InstrInfo &TII =
119       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
120 
121   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
122   unsigned NumBytes = MFI.getStackSize();
123   assert(NumBytes >= ArgRegsSaveSize &&
124          "ArgRegsSaveSize is included in NumBytes");
125   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
126 
127   // Debug location must be unknown since the first debug location is used
128   // to determine the end of the prologue.
129   DebugLoc dl;
130 
131   unsigned FramePtr = RegInfo->getFrameRegister(MF);
132   unsigned BasePtr = RegInfo->getBaseRegister();
133   int CFAOffset = 0;
134 
135   // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
136   NumBytes = (NumBytes + 3) & ~3;
137   MFI.setStackSize(NumBytes);
138 
139   // Determine the sizes of each callee-save spill areas and record which frame
140   // belongs to which callee-save spill areas.
141   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
142   int FramePtrSpillFI = 0;
143 
144   if (ArgRegsSaveSize) {
145     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -ArgRegsSaveSize,
146                  MachineInstr::FrameSetup);
147     CFAOffset -= ArgRegsSaveSize;
148     unsigned CFIIndex = MF.addFrameInst(
149         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
150     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
151         .addCFIIndex(CFIIndex)
152         .setMIFlags(MachineInstr::FrameSetup);
153   }
154 
155   if (!AFI->hasStackFrame()) {
156     if (NumBytes - ArgRegsSaveSize != 0) {
157       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -(NumBytes - ArgRegsSaveSize),
158                    MachineInstr::FrameSetup);
159       CFAOffset -= NumBytes - ArgRegsSaveSize;
160       unsigned CFIIndex = MF.addFrameInst(
161           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
162       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
163           .addCFIIndex(CFIIndex)
164           .setMIFlags(MachineInstr::FrameSetup);
165     }
166     return;
167   }
168 
169   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
170     unsigned Reg = CSI[i].getReg();
171     int FI = CSI[i].getFrameIdx();
172     switch (Reg) {
173     case ARM::R8:
174     case ARM::R9:
175     case ARM::R10:
176     case ARM::R11:
177       if (STI.splitFramePushPop(MF)) {
178         GPRCS2Size += 4;
179         break;
180       }
181       LLVM_FALLTHROUGH;
182     case ARM::R4:
183     case ARM::R5:
184     case ARM::R6:
185     case ARM::R7:
186     case ARM::LR:
187       if (Reg == FramePtr)
188         FramePtrSpillFI = FI;
189       GPRCS1Size += 4;
190       break;
191     default:
192       DPRCSSize += 8;
193     }
194   }
195 
196   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
197     ++MBBI;
198   }
199 
200   // Determine starting offsets of spill areas.
201   unsigned DPRCSOffset  = NumBytes - ArgRegsSaveSize - (GPRCS1Size + GPRCS2Size + DPRCSSize);
202   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
203   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
204   bool HasFP = hasFP(MF);
205   if (HasFP)
206     AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
207                                 NumBytes);
208   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
209   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
210   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
211   NumBytes = DPRCSOffset;
212 
213   int FramePtrOffsetInBlock = 0;
214   unsigned adjustedGPRCS1Size = GPRCS1Size;
215   if (GPRCS1Size > 0 && GPRCS2Size == 0 &&
216       tryFoldSPUpdateIntoPushPop(STI, MF, &*std::prev(MBBI), NumBytes)) {
217     FramePtrOffsetInBlock = NumBytes;
218     adjustedGPRCS1Size += NumBytes;
219     NumBytes = 0;
220   }
221 
222   if (adjustedGPRCS1Size) {
223     CFAOffset -= adjustedGPRCS1Size;
224     unsigned CFIIndex = MF.addFrameInst(
225         MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
226     BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
227         .addCFIIndex(CFIIndex)
228         .setMIFlags(MachineInstr::FrameSetup);
229   }
230   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
231          E = CSI.end(); I != E; ++I) {
232     unsigned Reg = I->getReg();
233     int FI = I->getFrameIdx();
234     switch (Reg) {
235     case ARM::R8:
236     case ARM::R9:
237     case ARM::R10:
238     case ARM::R11:
239     case ARM::R12:
240       if (STI.splitFramePushPop(MF))
241         break;
242       LLVM_FALLTHROUGH;
243     case ARM::R0:
244     case ARM::R1:
245     case ARM::R2:
246     case ARM::R3:
247     case ARM::R4:
248     case ARM::R5:
249     case ARM::R6:
250     case ARM::R7:
251     case ARM::LR:
252       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
253           nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
254       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
255           .addCFIIndex(CFIIndex)
256           .setMIFlags(MachineInstr::FrameSetup);
257       break;
258     }
259   }
260 
261   // Adjust FP so it point to the stack slot that contains the previous FP.
262   if (HasFP) {
263     FramePtrOffsetInBlock +=
264         MFI.getObjectOffset(FramePtrSpillFI) + GPRCS1Size + ArgRegsSaveSize;
265     BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
266         .addReg(ARM::SP)
267         .addImm(FramePtrOffsetInBlock / 4)
268         .setMIFlags(MachineInstr::FrameSetup)
269         .add(predOps(ARMCC::AL));
270     if(FramePtrOffsetInBlock) {
271       CFAOffset += FramePtrOffsetInBlock;
272       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
273           nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
274       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
275           .addCFIIndex(CFIIndex)
276           .setMIFlags(MachineInstr::FrameSetup);
277     } else {
278       unsigned CFIIndex =
279           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
280               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
281       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
282           .addCFIIndex(CFIIndex)
283           .setMIFlags(MachineInstr::FrameSetup);
284     }
285     if (NumBytes > 508)
286       // If offset is > 508 then sp cannot be adjusted in a single instruction,
287       // try restoring from fp instead.
288       AFI->setShouldRestoreSPFromFP(true);
289   }
290 
291   // Skip past the spilling of r8-r11, which could consist of multiple tPUSH
292   // and tMOVr instructions. We don't need to add any call frame information
293   // in-between these instructions, because they do not modify the high
294   // registers.
295   while (true) {
296     MachineBasicBlock::iterator OldMBBI = MBBI;
297     // Skip a run of tMOVr instructions
298     while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tMOVr)
299       MBBI++;
300     if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
301       MBBI++;
302     } else {
303       // We have reached an instruction which is not a push, so the previous
304       // run of tMOVr instructions (which may have been empty) was not part of
305       // the prologue. Reset MBBI back to the last PUSH of the prologue.
306       MBBI = OldMBBI;
307       break;
308     }
309   }
310 
311   // Emit call frame information for the callee-saved high registers.
312   for (auto &I : CSI) {
313     unsigned Reg = I.getReg();
314     int FI = I.getFrameIdx();
315     switch (Reg) {
316     case ARM::R8:
317     case ARM::R9:
318     case ARM::R10:
319     case ARM::R11:
320     case ARM::R12: {
321       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
322           nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
323       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
324           .addCFIIndex(CFIIndex)
325           .setMIFlags(MachineInstr::FrameSetup);
326       break;
327     }
328     default:
329       break;
330     }
331   }
332 
333   if (NumBytes) {
334     // Insert it after all the callee-save spills.
335     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
336                  MachineInstr::FrameSetup);
337     if (!HasFP) {
338       CFAOffset -= NumBytes;
339       unsigned CFIIndex = MF.addFrameInst(
340           MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
341       BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
342           .addCFIIndex(CFIIndex)
343           .setMIFlags(MachineInstr::FrameSetup);
344     }
345   }
346 
347   if (STI.isTargetELF() && HasFP)
348     MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
349                             AFI->getFramePtrSpillOffset());
350 
351   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
352   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
353   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
354 
355   // Thumb1 does not currently support dynamic stack realignment.  Report a
356   // fatal error rather then silently generate bad code.
357   if (RegInfo->needsStackRealignment(MF))
358       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
359 
360   // If we need a base pointer, set it up here. It's whatever the value
361   // of the stack pointer is at this point. Any variable size objects
362   // will be allocated after this, so we can still use the base pointer
363   // to reference locals.
364   if (RegInfo->hasBasePointer(MF))
365     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
366         .addReg(ARM::SP)
367         .add(predOps(ARMCC::AL));
368 
369   // If the frame has variable sized objects then the epilogue must restore
370   // the sp from fp. We can assume there's an FP here since hasFP already
371   // checks for hasVarSizedObjects.
372   if (MFI.hasVarSizedObjects())
373     AFI->setShouldRestoreSPFromFP(true);
374 
375   // In some cases, virtual registers have been introduced, e.g. by uses of
376   // emitThumbRegPlusImmInReg.
377   MF.getProperties().reset(MachineFunctionProperties::Property::NoVRegs);
378 }
379 
380 static bool isCSRestore(MachineInstr &MI, const MCPhysReg *CSRegs) {
381   if (MI.getOpcode() == ARM::tLDRspi && MI.getOperand(1).isFI() &&
382       isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs))
383     return true;
384   else if (MI.getOpcode() == ARM::tPOP) {
385     return true;
386   } else if (MI.getOpcode() == ARM::tMOVr) {
387     unsigned Dst = MI.getOperand(0).getReg();
388     unsigned Src = MI.getOperand(1).getReg();
389     return ((ARM::tGPRRegClass.contains(Src) || Src == ARM::LR) &&
390             ARM::hGPRRegClass.contains(Dst));
391   }
392   return false;
393 }
394 
395 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
396                                    MachineBasicBlock &MBB) const {
397   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
398   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
399   MachineFrameInfo &MFI = MF.getFrameInfo();
400   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
401   const ThumbRegisterInfo *RegInfo =
402       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
403   const Thumb1InstrInfo &TII =
404       *static_cast<const Thumb1InstrInfo *>(STI.getInstrInfo());
405 
406   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
407   int NumBytes = (int)MFI.getStackSize();
408   assert((unsigned)NumBytes >= ArgRegsSaveSize &&
409          "ArgRegsSaveSize is included in NumBytes");
410   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
411   unsigned FramePtr = RegInfo->getFrameRegister(MF);
412 
413   if (!AFI->hasStackFrame()) {
414     if (NumBytes - ArgRegsSaveSize != 0)
415       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes - ArgRegsSaveSize);
416   } else {
417     // Unwind MBBI to point to first LDR / VLDRD.
418     if (MBBI != MBB.begin()) {
419       do
420         --MBBI;
421       while (MBBI != MBB.begin() && isCSRestore(*MBBI, CSRegs));
422       if (!isCSRestore(*MBBI, CSRegs))
423         ++MBBI;
424     }
425 
426     // Move SP to start of FP callee save spill area.
427     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
428                  AFI->getGPRCalleeSavedArea2Size() +
429                  AFI->getDPRCalleeSavedAreaSize() +
430                  ArgRegsSaveSize);
431 
432     if (AFI->shouldRestoreSPFromFP()) {
433       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
434       // Reset SP based on frame pointer only if the stack frame extends beyond
435       // frame pointer stack slot, the target is ELF and the function has FP, or
436       // the target uses var sized objects.
437       if (NumBytes) {
438         assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
439                "No scratch register to restore SP from FP!");
440         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
441                                   TII, *RegInfo);
442         BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
443             .addReg(ARM::R4)
444             .add(predOps(ARMCC::AL));
445       } else
446         BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
447             .addReg(FramePtr)
448             .add(predOps(ARMCC::AL));
449     } else {
450       if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tBX_RET &&
451           &MBB.front() != &*MBBI && std::prev(MBBI)->getOpcode() == ARM::tPOP) {
452         MachineBasicBlock::iterator PMBBI = std::prev(MBBI);
453         if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*PMBBI, NumBytes))
454           emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
455       } else if (!tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
456         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
457     }
458   }
459 
460   if (needPopSpecialFixUp(MF)) {
461     bool Done = emitPopSpecialFixUp(MBB, /* DoIt */ true);
462     (void)Done;
463     assert(Done && "Emission of the special fixup failed!?");
464   }
465 }
466 
467 bool Thumb1FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
468   if (!needPopSpecialFixUp(*MBB.getParent()))
469     return true;
470 
471   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
472   return emitPopSpecialFixUp(*TmpMBB, /* DoIt */ false);
473 }
474 
475 bool Thumb1FrameLowering::needPopSpecialFixUp(const MachineFunction &MF) const {
476   ARMFunctionInfo *AFI =
477       const_cast<MachineFunction *>(&MF)->getInfo<ARMFunctionInfo>();
478   if (AFI->getArgRegsSaveSize())
479     return true;
480 
481   // LR cannot be encoded with Thumb1, i.e., it requires a special fix-up.
482   for (const CalleeSavedInfo &CSI : MF.getFrameInfo().getCalleeSavedInfo())
483     if (CSI.getReg() == ARM::LR)
484       return true;
485 
486   return false;
487 }
488 
489 bool Thumb1FrameLowering::emitPopSpecialFixUp(MachineBasicBlock &MBB,
490                                               bool DoIt) const {
491   MachineFunction &MF = *MBB.getParent();
492   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
493   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
494   const TargetInstrInfo &TII = *STI.getInstrInfo();
495   const ThumbRegisterInfo *RegInfo =
496       static_cast<const ThumbRegisterInfo *>(STI.getRegisterInfo());
497 
498   // If MBBI is a return instruction, or is a tPOP followed by a return
499   // instruction in the successor BB, we may be able to directly restore
500   // LR in the PC.
501   // This is only possible with v5T ops (v4T can't change the Thumb bit via
502   // a POP PC instruction), and only if we do not need to emit any SP update.
503   // Otherwise, we need a temporary register to pop the value
504   // and copy that value into LR.
505   auto MBBI = MBB.getFirstTerminator();
506   bool CanRestoreDirectly = STI.hasV5TOps() && !ArgRegsSaveSize;
507   if (CanRestoreDirectly) {
508     if (MBBI != MBB.end() && MBBI->getOpcode() != ARM::tB)
509       CanRestoreDirectly = (MBBI->getOpcode() == ARM::tBX_RET ||
510                             MBBI->getOpcode() == ARM::tPOP_RET);
511     else {
512       auto MBBI_prev = MBBI;
513       MBBI_prev--;
514       assert(MBBI_prev->getOpcode() == ARM::tPOP);
515       assert(MBB.succ_size() == 1);
516       if ((*MBB.succ_begin())->begin()->getOpcode() == ARM::tBX_RET)
517         MBBI = MBBI_prev; // Replace the final tPOP with a tPOP_RET.
518       else
519         CanRestoreDirectly = false;
520     }
521   }
522 
523   if (CanRestoreDirectly) {
524     if (!DoIt || MBBI->getOpcode() == ARM::tPOP_RET)
525       return true;
526     MachineInstrBuilder MIB =
527         BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP_RET))
528             .add(predOps(ARMCC::AL));
529     // Copy implicit ops and popped registers, if any.
530     for (auto MO: MBBI->operands())
531       if (MO.isReg() && (MO.isImplicit() || MO.isDef()))
532         MIB.add(MO);
533     MIB.addReg(ARM::PC, RegState::Define);
534     // Erase the old instruction (tBX_RET or tPOP).
535     MBB.erase(MBBI);
536     return true;
537   }
538 
539   // Look for a temporary register to use.
540   // First, compute the liveness information.
541   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
542   LivePhysRegs UsedRegs(TRI);
543   UsedRegs.addLiveOuts(MBB);
544   // The semantic of pristines changed recently and now,
545   // the callee-saved registers that are touched in the function
546   // are not part of the pristines set anymore.
547   // Add those callee-saved now.
548   const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
549   for (unsigned i = 0; CSRegs[i]; ++i)
550     UsedRegs.addReg(CSRegs[i]);
551 
552   DebugLoc dl = DebugLoc();
553   if (MBBI != MBB.end()) {
554     dl = MBBI->getDebugLoc();
555     auto InstUpToMBBI = MBB.end();
556     while (InstUpToMBBI != MBBI)
557       // The pre-decrement is on purpose here.
558       // We want to have the liveness right before MBBI.
559       UsedRegs.stepBackward(*--InstUpToMBBI);
560   }
561 
562   // Look for a register that can be directly use in the POP.
563   unsigned PopReg = 0;
564   // And some temporary register, just in case.
565   unsigned TemporaryReg = 0;
566   BitVector PopFriendly =
567       TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::tGPRRegClassID));
568   assert(PopFriendly.any() && "No allocatable pop-friendly register?!");
569   // Rebuild the GPRs from the high registers because they are removed
570   // form the GPR reg class for thumb1.
571   BitVector GPRsNoLRSP =
572       TRI.getAllocatableSet(MF, TRI.getRegClass(ARM::hGPRRegClassID));
573   GPRsNoLRSP |= PopFriendly;
574   GPRsNoLRSP.reset(ARM::LR);
575   GPRsNoLRSP.reset(ARM::SP);
576   GPRsNoLRSP.reset(ARM::PC);
577   for (unsigned Register : GPRsNoLRSP.set_bits()) {
578     if (!UsedRegs.contains(Register)) {
579       // Remember the first pop-friendly register and exit.
580       if (PopFriendly.test(Register)) {
581         PopReg = Register;
582         TemporaryReg = 0;
583         break;
584       }
585       // Otherwise, remember that the register will be available to
586       // save a pop-friendly register.
587       TemporaryReg = Register;
588     }
589   }
590 
591   if (!DoIt && !PopReg && !TemporaryReg)
592     return false;
593 
594   assert((PopReg || TemporaryReg) && "Cannot get LR");
595 
596   if (TemporaryReg) {
597     assert(!PopReg && "Unnecessary MOV is about to be inserted");
598     PopReg = PopFriendly.find_first();
599     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
600         .addReg(TemporaryReg, RegState::Define)
601         .addReg(PopReg, RegState::Kill)
602         .add(predOps(ARMCC::AL));
603   }
604 
605   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPOP_RET) {
606     // We couldn't use the direct restoration above, so
607     // perform the opposite conversion: tPOP_RET to tPOP.
608     MachineInstrBuilder MIB =
609         BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII.get(ARM::tPOP))
610             .add(predOps(ARMCC::AL));
611     bool Popped = false;
612     for (auto MO: MBBI->operands())
613       if (MO.isReg() && (MO.isImplicit() || MO.isDef()) &&
614           MO.getReg() != ARM::PC) {
615         MIB.add(MO);
616         if (!MO.isImplicit())
617           Popped = true;
618       }
619     // Is there anything left to pop?
620     if (!Popped)
621       MBB.erase(MIB.getInstr());
622     // Erase the old instruction.
623     MBB.erase(MBBI);
624     MBBI = BuildMI(MBB, MBB.end(), dl, TII.get(ARM::tBX_RET))
625                .add(predOps(ARMCC::AL));
626   }
627 
628   assert(PopReg && "Do not know how to get LR");
629   BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP))
630       .add(predOps(ARMCC::AL))
631       .addReg(PopReg, RegState::Define);
632 
633   emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, ArgRegsSaveSize);
634 
635   BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
636       .addReg(ARM::LR, RegState::Define)
637       .addReg(PopReg, RegState::Kill)
638       .add(predOps(ARMCC::AL));
639 
640   if (TemporaryReg)
641     BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr))
642         .addReg(PopReg, RegState::Define)
643         .addReg(TemporaryReg, RegState::Kill)
644         .add(predOps(ARMCC::AL));
645 
646   return true;
647 }
648 
649 using ARMRegSet = std::bitset<ARM::NUM_TARGET_REGS>;
650 
651 // Return the first iteraror after CurrentReg which is present in EnabledRegs,
652 // or OrderEnd if no further registers are in that set. This does not advance
653 // the iterator fiorst, so returns CurrentReg if it is in EnabledRegs.
654 static const unsigned *findNextOrderedReg(const unsigned *CurrentReg,
655                                           const ARMRegSet &EnabledRegs,
656                                           const unsigned *OrderEnd) {
657   while (CurrentReg != OrderEnd && !EnabledRegs[*CurrentReg])
658     ++CurrentReg;
659   return CurrentReg;
660 }
661 
662 bool Thumb1FrameLowering::
663 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
664                           MachineBasicBlock::iterator MI,
665                           const std::vector<CalleeSavedInfo> &CSI,
666                           const TargetRegisterInfo *TRI) const {
667   if (CSI.empty())
668     return false;
669 
670   DebugLoc DL;
671   const TargetInstrInfo &TII = *STI.getInstrInfo();
672   MachineFunction &MF = *MBB.getParent();
673   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
674       MF.getSubtarget().getRegisterInfo());
675 
676   ARMRegSet LoRegsToSave; // r0-r7, lr
677   ARMRegSet HiRegsToSave; // r8-r11
678   ARMRegSet CopyRegs;     // Registers which can be used after pushing
679                           // LoRegs for saving HiRegs.
680 
681   for (unsigned i = CSI.size(); i != 0; --i) {
682     unsigned Reg = CSI[i-1].getReg();
683 
684     if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
685       LoRegsToSave[Reg] = true;
686     } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
687       HiRegsToSave[Reg] = true;
688     } else {
689       llvm_unreachable("callee-saved register of unexpected class");
690     }
691 
692     if ((ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) &&
693         !MF.getRegInfo().isLiveIn(Reg) &&
694         !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
695       CopyRegs[Reg] = true;
696   }
697 
698   // Unused argument registers can be used for the high register saving.
699   for (unsigned ArgReg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3})
700     if (!MF.getRegInfo().isLiveIn(ArgReg))
701       CopyRegs[ArgReg] = true;
702 
703   // Push the low registers and lr
704   const MachineRegisterInfo &MRI = MF.getRegInfo();
705   if (!LoRegsToSave.none()) {
706     MachineInstrBuilder MIB =
707         BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
708     for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6, ARM::R7, ARM::LR}) {
709       if (LoRegsToSave[Reg]) {
710         bool isKill = !MRI.isLiveIn(Reg);
711         if (isKill && !MRI.isReserved(Reg))
712           MBB.addLiveIn(Reg);
713 
714         MIB.addReg(Reg, getKillRegState(isKill));
715       }
716     }
717     MIB.setMIFlags(MachineInstr::FrameSetup);
718   }
719 
720   // Push the high registers. There are no store instructions that can access
721   // these registers directly, so we have to move them to low registers, and
722   // push them. This might take multiple pushes, as it is possible for there to
723   // be fewer low registers available than high registers which need saving.
724 
725   // These are in reverse order so that in the case where we need to use
726   // multiple PUSH instructions, the order of the registers on the stack still
727   // matches the unwind info. They need to be swicthed back to ascending order
728   // before adding to the PUSH instruction.
729   static const unsigned AllCopyRegs[] = {ARM::LR, ARM::R7, ARM::R6,
730                                          ARM::R5, ARM::R4, ARM::R3,
731                                          ARM::R2, ARM::R1, ARM::R0};
732   static const unsigned AllHighRegs[] = {ARM::R11, ARM::R10, ARM::R9, ARM::R8};
733 
734   const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
735   const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
736 
737   // Find the first register to save.
738   const unsigned *HiRegToSave = findNextOrderedReg(
739       std::begin(AllHighRegs), HiRegsToSave, AllHighRegsEnd);
740 
741   while (HiRegToSave != AllHighRegsEnd) {
742     // Find the first low register to use.
743     const unsigned *CopyReg =
744         findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
745 
746     // Create the PUSH, but don't insert it yet (the MOVs need to come first).
747     MachineInstrBuilder PushMIB =
748         BuildMI(MF, DL, TII.get(ARM::tPUSH)).add(predOps(ARMCC::AL));
749 
750     SmallVector<unsigned, 4> RegsToPush;
751     while (HiRegToSave != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
752       if (HiRegsToSave[*HiRegToSave]) {
753         bool isKill = !MRI.isLiveIn(*HiRegToSave);
754         if (isKill && !MRI.isReserved(*HiRegToSave))
755           MBB.addLiveIn(*HiRegToSave);
756 
757         // Emit a MOV from the high reg to the low reg.
758         BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
759             .addReg(*CopyReg, RegState::Define)
760             .addReg(*HiRegToSave, getKillRegState(isKill))
761             .add(predOps(ARMCC::AL));
762 
763         // Record the register that must be added to the PUSH.
764         RegsToPush.push_back(*CopyReg);
765 
766         CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
767         HiRegToSave =
768             findNextOrderedReg(++HiRegToSave, HiRegsToSave, AllHighRegsEnd);
769       }
770     }
771 
772     // Add the low registers to the PUSH, in ascending order.
773     for (unsigned Reg : llvm::reverse(RegsToPush))
774       PushMIB.addReg(Reg, RegState::Kill);
775 
776     // Insert the PUSH instruction after the MOVs.
777     MBB.insert(MI, PushMIB);
778   }
779 
780   return true;
781 }
782 
783 bool Thumb1FrameLowering::
784 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
785                             MachineBasicBlock::iterator MI,
786                             std::vector<CalleeSavedInfo> &CSI,
787                             const TargetRegisterInfo *TRI) const {
788   if (CSI.empty())
789     return false;
790 
791   MachineFunction &MF = *MBB.getParent();
792   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
793   const TargetInstrInfo &TII = *STI.getInstrInfo();
794   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
795       MF.getSubtarget().getRegisterInfo());
796 
797   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
798   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
799 
800   ARMRegSet LoRegsToRestore;
801   ARMRegSet HiRegsToRestore;
802   // Low registers (r0-r7) which can be used to restore the high registers.
803   ARMRegSet CopyRegs;
804 
805   for (CalleeSavedInfo I : CSI) {
806     unsigned Reg = I.getReg();
807 
808     if (ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR) {
809       LoRegsToRestore[Reg] = true;
810     } else if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::LR) {
811       HiRegsToRestore[Reg] = true;
812     } else {
813       llvm_unreachable("callee-saved register of unexpected class");
814     }
815 
816     // If this is a low register not used as the frame pointer, we may want to
817     // use it for restoring the high registers.
818     if ((ARM::tGPRRegClass.contains(Reg)) &&
819         !(hasFP(MF) && Reg == RegInfo->getFrameRegister(MF)))
820       CopyRegs[Reg] = true;
821   }
822 
823   // If this is a return block, we may be able to use some unused return value
824   // registers for restoring the high regs.
825   auto Terminator = MBB.getFirstTerminator();
826   if (Terminator != MBB.end() && Terminator->getOpcode() == ARM::tBX_RET) {
827     CopyRegs[ARM::R0] = true;
828     CopyRegs[ARM::R1] = true;
829     CopyRegs[ARM::R2] = true;
830     CopyRegs[ARM::R3] = true;
831     for (auto Op : Terminator->implicit_operands()) {
832       if (Op.isReg())
833         CopyRegs[Op.getReg()] = false;
834     }
835   }
836 
837   static const unsigned AllCopyRegs[] = {ARM::R0, ARM::R1, ARM::R2, ARM::R3,
838                                          ARM::R4, ARM::R5, ARM::R6, ARM::R7};
839   static const unsigned AllHighRegs[] = {ARM::R8, ARM::R9, ARM::R10, ARM::R11};
840 
841   const unsigned *AllCopyRegsEnd = std::end(AllCopyRegs);
842   const unsigned *AllHighRegsEnd = std::end(AllHighRegs);
843 
844   // Find the first register to restore.
845   auto HiRegToRestore = findNextOrderedReg(std::begin(AllHighRegs),
846                                            HiRegsToRestore, AllHighRegsEnd);
847 
848   while (HiRegToRestore != AllHighRegsEnd) {
849     assert(!CopyRegs.none());
850     // Find the first low register to use.
851     auto CopyReg =
852         findNextOrderedReg(std::begin(AllCopyRegs), CopyRegs, AllCopyRegsEnd);
853 
854     // Create the POP instruction.
855     MachineInstrBuilder PopMIB =
856         BuildMI(MBB, MI, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
857 
858     while (HiRegToRestore != AllHighRegsEnd && CopyReg != AllCopyRegsEnd) {
859       // Add the low register to the POP.
860       PopMIB.addReg(*CopyReg, RegState::Define);
861 
862       // Create the MOV from low to high register.
863       BuildMI(MBB, MI, DL, TII.get(ARM::tMOVr))
864           .addReg(*HiRegToRestore, RegState::Define)
865           .addReg(*CopyReg, RegState::Kill)
866           .add(predOps(ARMCC::AL));
867 
868       CopyReg = findNextOrderedReg(++CopyReg, CopyRegs, AllCopyRegsEnd);
869       HiRegToRestore =
870           findNextOrderedReg(++HiRegToRestore, HiRegsToRestore, AllHighRegsEnd);
871     }
872   }
873 
874   MachineInstrBuilder MIB =
875       BuildMI(MF, DL, TII.get(ARM::tPOP)).add(predOps(ARMCC::AL));
876 
877   bool NeedsPop = false;
878   for (unsigned i = CSI.size(); i != 0; --i) {
879     CalleeSavedInfo &Info = CSI[i-1];
880     unsigned Reg = Info.getReg();
881 
882     // High registers (excluding lr) have already been dealt with
883     if (!(ARM::tGPRRegClass.contains(Reg) || Reg == ARM::LR))
884       continue;
885 
886     if (Reg == ARM::LR) {
887       Info.setRestored(false);
888       if (MBB.succ_empty()) {
889         // Special epilogue for vararg functions. See emitEpilogue
890         if (isVarArg)
891           continue;
892         // ARMv4T requires BX, see emitEpilogue
893         if (!STI.hasV5TOps())
894           continue;
895         // Tailcall optimization failed; change TCRETURN to a tBL
896         if (MI->getOpcode() == ARM::TCRETURNdi ||
897             MI->getOpcode() == ARM::TCRETURNri) {
898           unsigned Opcode = MI->getOpcode() == ARM::TCRETURNdi
899                             ? ARM::tBL : ARM::tBLXr;
900           MachineInstrBuilder BL = BuildMI(MF, DL, TII.get(Opcode));
901           BL.add(predOps(ARMCC::AL));
902           BL.add(MI->getOperand(0));
903           MBB.insert(MI, &*BL);
904         }
905         Reg = ARM::PC;
906         (*MIB).setDesc(TII.get(ARM::tPOP_RET));
907         if (MI != MBB.end())
908           MIB.copyImplicitOps(*MI);
909         MI = MBB.erase(MI);
910       } else
911         // LR may only be popped into PC, as part of return sequence.
912         // If this isn't the return sequence, we'll need emitPopSpecialFixUp
913         // to restore LR the hard way.
914         continue;
915     }
916     MIB.addReg(Reg, getDefRegState(true));
917     NeedsPop = true;
918   }
919 
920   // It's illegal to emit pop instruction without operands.
921   if (NeedsPop)
922     MBB.insert(MI, &*MIB);
923   else
924     MF.DeleteMachineInstr(MIB);
925 
926   return true;
927 }
928