Some random comment, naming, and format changes.
[oota-llvm.git] / lib / Target / ARM / Thumb1RegisterInfo.cpp
1 //===-- Thumb1RegisterInfo.cpp - Thumb-1 Register 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 Thumb-1 implementation of the TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Thumb1RegisterInfo.h"
16 #include "ARM.h"
17 #include "ARMBaseInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/RegisterScavenging.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Function.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36
37 namespace llvm {
38 extern cl::opt<bool> ReuseFrameIndexVals;
39 }
40
41 using namespace llvm;
42
43 Thumb1RegisterInfo::Thumb1RegisterInfo(const ARMBaseInstrInfo &tii,
44                                        const ARMSubtarget &sti)
45   : ARMBaseRegisterInfo(tii, sti) {
46 }
47
48 const TargetRegisterClass*
49 Thumb1RegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
50                                                                          const {
51   if (ARM::tGPRRegClass.hasSubClassEq(RC))
52     return &ARM::tGPRRegClass;
53   return ARMBaseRegisterInfo::getLargestLegalSuperClass(RC);
54 }
55
56 const TargetRegisterClass *
57 Thumb1RegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
58                                                                          const {
59   return &ARM::tGPRRegClass;
60 }
61
62 /// emitLoadConstPool - Emits a load from constpool to materialize the
63 /// specified immediate.
64 void
65 Thumb1RegisterInfo::emitLoadConstPool(MachineBasicBlock &MBB,
66                                       MachineBasicBlock::iterator &MBBI,
67                                       DebugLoc dl,
68                                       unsigned DestReg, unsigned SubIdx,
69                                       int Val,
70                                       ARMCC::CondCodes Pred, unsigned PredReg,
71                                       unsigned MIFlags) const {
72   MachineFunction &MF = *MBB.getParent();
73   MachineConstantPool *ConstantPool = MF.getConstantPool();
74   const Constant *C = ConstantInt::get(
75           Type::getInt32Ty(MBB.getParent()->getFunction()->getContext()), Val);
76   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
77
78   BuildMI(MBB, MBBI, dl, TII.get(ARM::tLDRpci))
79     .addReg(DestReg, getDefRegState(true), SubIdx)
80     .addConstantPoolIndex(Idx).addImm(Pred).addReg(PredReg)
81     .setMIFlags(MIFlags);
82 }
83
84
85 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
86 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
87 /// in a register using mov / mvn sequences or load the immediate from a
88 /// constpool entry.
89 static
90 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
91                               MachineBasicBlock::iterator &MBBI,
92                               DebugLoc dl,
93                               unsigned DestReg, unsigned BaseReg,
94                               int NumBytes, bool CanChangeCC,
95                               const TargetInstrInfo &TII,
96                               const ARMBaseRegisterInfo& MRI,
97                               unsigned MIFlags = MachineInstr::NoFlags) {
98     MachineFunction &MF = *MBB.getParent();
99     bool isHigh = !isARMLowRegister(DestReg) ||
100                   (BaseReg != 0 && !isARMLowRegister(BaseReg));
101     bool isSub = false;
102     // Subtract doesn't have high register version. Load the negative value
103     // if either base or dest register is a high register. Also, if do not
104     // issue sub as part of the sequence if condition register is to be
105     // preserved.
106     if (NumBytes < 0 && !isHigh && CanChangeCC) {
107       isSub = true;
108       NumBytes = -NumBytes;
109     }
110     unsigned LdReg = DestReg;
111     if (DestReg == ARM::SP) {
112       assert(BaseReg == ARM::SP && "Unexpected!");
113       LdReg = MF.getRegInfo().createVirtualRegister(&ARM::tGPRRegClass);
114     }
115
116     if (NumBytes <= 255 && NumBytes >= 0)
117       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
118         .addImm(NumBytes).setMIFlags(MIFlags);
119     else if (NumBytes < 0 && NumBytes >= -255) {
120       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8), LdReg))
121         .addImm(NumBytes).setMIFlags(MIFlags);
122       AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tRSB), LdReg))
123         .addReg(LdReg, RegState::Kill).setMIFlags(MIFlags);
124     } else
125       MRI.emitLoadConstPool(MBB, MBBI, dl, LdReg, 0, NumBytes,
126                             ARMCC::AL, 0, MIFlags);
127
128     // Emit add / sub.
129     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
130     MachineInstrBuilder MIB =
131       BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
132     if (Opc != ARM::tADDhirr)
133       MIB = AddDefaultT1CC(MIB);
134     if (DestReg == ARM::SP || isSub)
135       MIB.addReg(BaseReg).addReg(LdReg, RegState::Kill);
136     else
137       MIB.addReg(LdReg).addReg(BaseReg, RegState::Kill);
138     AddDefaultPred(MIB);
139 }
140
141 /// calcNumMI - Returns the number of instructions required to materialize
142 /// the specific add / sub r, c instruction.
143 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
144                           unsigned NumBits, unsigned Scale) {
145   unsigned NumMIs = 0;
146   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
147
148   if (Opc == ARM::tADDrSPi) {
149     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
150     Bytes -= ThisVal;
151     NumMIs++;
152     NumBits = 8;
153     Scale = 1;  // Followed by a number of tADDi8.
154     Chunk = ((1 << NumBits) - 1) * Scale;
155   }
156
157   NumMIs += Bytes / Chunk;
158   if ((Bytes % Chunk) != 0)
159     NumMIs++;
160   if (ExtraOpc)
161     NumMIs++;
162   return NumMIs;
163 }
164
165 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
166 /// a destreg = basereg + immediate in Thumb code.
167 void llvm::emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
168                                      MachineBasicBlock::iterator &MBBI,
169                                      DebugLoc dl,
170                                      unsigned DestReg, unsigned BaseReg,
171                                      int NumBytes, const TargetInstrInfo &TII,
172                                      const ARMBaseRegisterInfo& MRI,
173                                      unsigned MIFlags) {
174   bool isSub = NumBytes < 0;
175   unsigned Bytes = (unsigned)NumBytes;
176   if (isSub) Bytes = -NumBytes;
177   bool isMul4 = (Bytes & 3) == 0;
178   bool isTwoAddr = false;
179   bool DstNotEqBase = false;
180   unsigned NumBits = 1;
181   unsigned Scale = 1;
182   int Opc = 0;
183   int ExtraOpc = 0;
184   bool NeedCC = false;
185
186   if (DestReg == BaseReg && BaseReg == ARM::SP) {
187     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
188     NumBits = 7;
189     Scale = 4;
190     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
191     isTwoAddr = true;
192   } else if (!isSub && BaseReg == ARM::SP) {
193     // r1 = add sp, 403
194     // =>
195     // r1 = add sp, 100 * 4
196     // r1 = add r1, 3
197     if (!isMul4) {
198       Bytes &= ~3;
199       ExtraOpc = ARM::tADDi3;
200     }
201     NumBits = 8;
202     Scale = 4;
203     Opc = ARM::tADDrSPi;
204   } else {
205     // sp = sub sp, c
206     // r1 = sub sp, c
207     // r8 = sub sp, c
208     if (DestReg != BaseReg)
209       DstNotEqBase = true;
210     NumBits = 8;
211     if (DestReg == ARM::SP) {
212       Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
213       assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
214       NumBits = 7;
215       Scale = 4;
216     } else {
217       Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
218       NumBits = 8;
219       NeedCC = true;
220     }
221     isTwoAddr = true;
222   }
223
224   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
225   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
226   if (NumMIs > Threshold) {
227     // This will expand into too many instructions. Load the immediate from a
228     // constpool entry.
229     emitThumbRegPlusImmInReg(MBB, MBBI, dl,
230                              DestReg, BaseReg, NumBytes, true,
231                              TII, MRI, MIFlags);
232     return;
233   }
234
235   if (DstNotEqBase) {
236     if (isARMLowRegister(DestReg) && isARMLowRegister(BaseReg)) {
237       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
238       unsigned Chunk = (1 << 3) - 1;
239       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
240       Bytes -= ThisVal;
241       const MCInstrDesc &MCID = TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3);
242       const MachineInstrBuilder MIB =
243         AddDefaultT1CC(BuildMI(MBB, MBBI, dl, MCID, DestReg)
244                          .setMIFlags(MIFlags));
245       AddDefaultPred(MIB.addReg(BaseReg, RegState::Kill).addImm(ThisVal));
246     } else {
247       AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), DestReg)
248         .addReg(BaseReg, RegState::Kill))
249         .setMIFlags(MIFlags);
250     }
251     BaseReg = DestReg;
252   }
253
254   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
255   while (Bytes) {
256     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
257     Bytes -= ThisVal;
258     ThisVal /= Scale;
259     // Build the new tADD / tSUB.
260     if (isTwoAddr) {
261       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
262       if (NeedCC)
263         MIB = AddDefaultT1CC(MIB);
264       MIB.addReg(DestReg).addImm(ThisVal);
265       MIB = AddDefaultPred(MIB);
266       MIB.setMIFlags(MIFlags);
267     } else {
268       bool isKill = BaseReg != ARM::SP;
269       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg);
270       if (NeedCC)
271         MIB = AddDefaultT1CC(MIB);
272       MIB.addReg(BaseReg, getKillRegState(isKill)).addImm(ThisVal);
273       MIB = AddDefaultPred(MIB);
274       MIB.setMIFlags(MIFlags);
275
276       BaseReg = DestReg;
277       if (Opc == ARM::tADDrSPi) {
278         // r4 = add sp, imm
279         // r4 = add r4, imm
280         // ...
281         NumBits = 8;
282         Scale = 1;
283         Chunk = ((1 << NumBits) - 1) * Scale;
284         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
285         NeedCC = isTwoAddr = true;
286       }
287     }
288   }
289
290   if (ExtraOpc) {
291     const MCInstrDesc &MCID = TII.get(ExtraOpc);
292     AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, MCID, DestReg))
293                    .addReg(DestReg, RegState::Kill)
294                    .addImm(((unsigned)NumBytes) & 3)
295                    .setMIFlags(MIFlags));
296   }
297 }
298
299 static void emitSPUpdate(MachineBasicBlock &MBB,
300                          MachineBasicBlock::iterator &MBBI,
301                          const TargetInstrInfo &TII, DebugLoc dl,
302                          const Thumb1RegisterInfo &MRI,
303                          int NumBytes) {
304   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
305                             MRI);
306 }
307
308 void Thumb1RegisterInfo::
309 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
310                               MachineBasicBlock::iterator I) const {
311   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
312
313   if (!TFI->hasReservedCallFrame(MF)) {
314     // If we have alloca, convert as follows:
315     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
316     // ADJCALLSTACKUP   -> add, sp, sp, amount
317     MachineInstr *Old = I;
318     DebugLoc dl = Old->getDebugLoc();
319     unsigned Amount = Old->getOperand(0).getImm();
320     if (Amount != 0) {
321       // We need to keep the stack aligned properly.  To do this, we round the
322       // amount of space needed for the outgoing arguments up to the next
323       // alignment boundary.
324       unsigned Align = TFI->getStackAlignment();
325       Amount = (Amount+Align-1)/Align*Align;
326
327       // Replace the pseudo instruction with a new instruction...
328       unsigned Opc = Old->getOpcode();
329       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
330         emitSPUpdate(MBB, I, TII, dl, *this, -Amount);
331       } else {
332         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
333         emitSPUpdate(MBB, I, TII, dl, *this, Amount);
334       }
335     }
336   }
337   MBB.erase(I);
338 }
339
340 /// emitThumbConstant - Emit a series of instructions to materialize a
341 /// constant.
342 static void emitThumbConstant(MachineBasicBlock &MBB,
343                               MachineBasicBlock::iterator &MBBI,
344                               unsigned DestReg, int Imm,
345                               const TargetInstrInfo &TII,
346                               const Thumb1RegisterInfo& MRI,
347                               DebugLoc dl) {
348   bool isSub = Imm < 0;
349   if (isSub) Imm = -Imm;
350
351   int Chunk = (1 << 8) - 1;
352   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
353   Imm -= ThisVal;
354   AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVi8),
355                                         DestReg))
356                  .addImm(ThisVal));
357   if (Imm > 0)
358     emitThumbRegPlusImmediate(MBB, MBBI, dl, DestReg, DestReg, Imm, TII, MRI);
359   if (isSub) {
360     const MCInstrDesc &MCID = TII.get(ARM::tRSB);
361     AddDefaultPred(AddDefaultT1CC(BuildMI(MBB, MBBI, dl, MCID, DestReg))
362                    .addReg(DestReg, RegState::Kill));
363   }
364 }
365
366 static void removeOperands(MachineInstr &MI, unsigned i) {
367   unsigned Op = i;
368   for (unsigned e = MI.getNumOperands(); i != e; ++i)
369     MI.RemoveOperand(Op);
370 }
371
372 /// convertToNonSPOpcode - Change the opcode to the non-SP version, because
373 /// we're replacing the frame index with a non-SP register.
374 static unsigned convertToNonSPOpcode(unsigned Opcode) {
375   switch (Opcode) {
376   case ARM::tLDRspi:
377     return ARM::tLDRi;
378
379   case ARM::tSTRspi:
380     return ARM::tSTRi;
381   }
382
383   return Opcode;
384 }
385
386 bool Thumb1RegisterInfo::
387 rewriteFrameIndex(MachineBasicBlock::iterator II, unsigned FrameRegIdx,
388                   unsigned FrameReg, int &Offset,
389                   const ARMBaseInstrInfo &TII) const {
390   MachineInstr &MI = *II;
391   MachineBasicBlock &MBB = *MI.getParent();
392   DebugLoc dl = MI.getDebugLoc();
393   MachineInstrBuilder MIB(*MBB.getParent(), &MI);
394   unsigned Opcode = MI.getOpcode();
395   const MCInstrDesc &Desc = MI.getDesc();
396   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
397
398   if (Opcode == ARM::tADDrSPi) {
399     Offset += MI.getOperand(FrameRegIdx+1).getImm();
400
401     // Can't use tADDrSPi if it's based off the frame pointer.
402     unsigned NumBits = 0;
403     unsigned Scale = 1;
404     if (FrameReg != ARM::SP) {
405       Opcode = ARM::tADDi3;
406       NumBits = 3;
407     } else {
408       NumBits = 8;
409       Scale = 4;
410       assert((Offset & 3) == 0 &&
411              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
412     }
413
414     unsigned PredReg;
415     if (Offset == 0 && getInstrPredicate(&MI, PredReg) == ARMCC::AL) {
416       // Turn it into a move.
417       MI.setDesc(TII.get(ARM::tMOVr));
418       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
419       // Remove offset
420       MI.RemoveOperand(FrameRegIdx+1);
421       return true;
422     }
423
424     // Common case: small offset, fits into instruction.
425     unsigned Mask = (1 << NumBits) - 1;
426     if (((Offset / Scale) & ~Mask) == 0) {
427       // Replace the FrameIndex with sp / fp
428       if (Opcode == ARM::tADDi3) {
429         MI.setDesc(TII.get(Opcode));
430         removeOperands(MI, FrameRegIdx);
431         AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg)
432                        .addImm(Offset / Scale));
433       } else {
434         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
435         MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset / Scale);
436       }
437       return true;
438     }
439
440     unsigned DestReg = MI.getOperand(0).getReg();
441     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
442     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
443     // MI would expand into a large number of instructions. Don't try to
444     // simplify the immediate.
445     if (NumMIs > 2) {
446       emitThumbRegPlusImmediate(MBB, II, dl, DestReg, FrameReg, Offset, TII,
447                                 *this);
448       MBB.erase(II);
449       return true;
450     }
451
452     if (Offset > 0) {
453       // Translate r0 = add sp, imm to
454       // r0 = add sp, 255*4
455       // r0 = add r0, (imm - 255*4)
456       if (Opcode == ARM::tADDi3) {
457         MI.setDesc(TII.get(Opcode));
458         removeOperands(MI, FrameRegIdx);
459         AddDefaultPred(AddDefaultT1CC(MIB).addReg(FrameReg).addImm(Mask));
460       } else {
461         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
462         MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Mask);
463       }
464       Offset = (Offset - Mask * Scale);
465       MachineBasicBlock::iterator NII = llvm::next(II);
466       emitThumbRegPlusImmediate(MBB, NII, dl, DestReg, DestReg, Offset, TII,
467                                 *this);
468     } else {
469       // Translate r0 = add sp, -imm to
470       // r0 = -imm (this is then translated into a series of instructons)
471       // r0 = add r0, sp
472       emitThumbConstant(MBB, II, DestReg, Offset, TII, *this, dl);
473
474       MI.setDesc(TII.get(ARM::tADDhirr));
475       MI.getOperand(FrameRegIdx).ChangeToRegister(DestReg, false, false, true);
476       MI.getOperand(FrameRegIdx+1).ChangeToRegister(FrameReg, false);
477     }
478     return true;
479   } else {
480     if (AddrMode != ARMII::AddrModeT1_s)
481       llvm_unreachable("Unsupported addressing mode!");
482
483     unsigned ImmIdx = FrameRegIdx + 1;
484     int InstrOffs = MI.getOperand(ImmIdx).getImm();
485     unsigned NumBits = (FrameReg == ARM::SP) ? 8 : 5;
486     unsigned Scale = 4;
487
488     Offset += InstrOffs * Scale;
489     assert((Offset & (Scale - 1)) == 0 && "Can't encode this offset!");
490
491     // Common case: small offset, fits into instruction.
492     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
493     int ImmedOffset = Offset / Scale;
494     unsigned Mask = (1 << NumBits) - 1;
495
496     if ((unsigned)Offset <= Mask * Scale) {
497       // Replace the FrameIndex with the frame register (e.g., sp).
498       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
499       ImmOp.ChangeToImmediate(ImmedOffset);
500
501       // If we're using a register where sp was stored, convert the instruction
502       // to the non-SP version.
503       unsigned NewOpc = convertToNonSPOpcode(Opcode);
504       if (NewOpc != Opcode && FrameReg != ARM::SP)
505         MI.setDesc(TII.get(NewOpc));
506
507       return true;
508     }
509
510     NumBits = 5;
511     Mask = (1 << NumBits) - 1;
512
513     // If this is a thumb spill / restore, we will be using a constpool load to
514     // materialize the offset.
515     if (Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
516       ImmOp.ChangeToImmediate(0);
517     } else {
518       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
519       ImmedOffset = ImmedOffset & Mask;
520       ImmOp.ChangeToImmediate(ImmedOffset);
521       Offset &= ~(Mask * Scale);
522     }
523   }
524
525   return Offset == 0;
526 }
527
528 void
529 Thumb1RegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
530                                       unsigned BaseReg, int64_t Offset) const {
531   MachineInstr &MI = *I;
532   int Off = Offset; // ARM doesn't need the general 64-bit offsets
533   unsigned i = 0;
534
535   while (!MI.getOperand(i).isFI()) {
536     ++i;
537     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
538   }
539   bool Done = rewriteFrameIndex(MI, i, BaseReg, Off, TII);
540   assert (Done && "Unable to resolve frame index!");
541   (void)Done;
542 }
543
544 /// saveScavengerRegister - Spill the register so it can be used by the
545 /// register scavenger. Return true.
546 bool
547 Thumb1RegisterInfo::saveScavengerRegister(MachineBasicBlock &MBB,
548                                           MachineBasicBlock::iterator I,
549                                           MachineBasicBlock::iterator &UseMI,
550                                           const TargetRegisterClass *RC,
551                                           unsigned Reg) const {
552   // Thumb1 can't use the emergency spill slot on the stack because
553   // ldr/str immediate offsets must be positive, and if we're referencing
554   // off the frame pointer (if, for example, there are alloca() calls in
555   // the function, the offset will be negative. Use R12 instead since that's
556   // a call clobbered register that we know won't be used in Thumb1 mode.
557   DebugLoc DL;
558   AddDefaultPred(BuildMI(MBB, I, DL, TII.get(ARM::tMOVr))
559     .addReg(ARM::R12, RegState::Define)
560     .addReg(Reg, RegState::Kill));
561
562   // The UseMI is where we would like to restore the register. If there's
563   // interference with R12 before then, however, we'll need to restore it
564   // before that instead and adjust the UseMI.
565   bool done = false;
566   for (MachineBasicBlock::iterator II = I; !done && II != UseMI ; ++II) {
567     if (II->isDebugValue())
568       continue;
569     // If this instruction affects R12, adjust our restore point.
570     for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
571       const MachineOperand &MO = II->getOperand(i);
572       if (MO.isRegMask() && MO.clobbersPhysReg(ARM::R12)) {
573         UseMI = II;
574         done = true;
575         break;
576       }
577       if (!MO.isReg() || MO.isUndef() || !MO.getReg() ||
578           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
579         continue;
580       if (MO.getReg() == ARM::R12) {
581         UseMI = II;
582         done = true;
583         break;
584       }
585     }
586   }
587   // Restore the register from R12
588   AddDefaultPred(BuildMI(MBB, UseMI, DL, TII.get(ARM::tMOVr)).
589     addReg(Reg, RegState::Define).addReg(ARM::R12, RegState::Kill));
590
591   return true;
592 }
593
594 void
595 Thumb1RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
596                                         int SPAdj, RegScavenger *RS) const {
597   unsigned VReg = 0;
598   unsigned i = 0;
599   MachineInstr &MI = *II;
600   MachineBasicBlock &MBB = *MI.getParent();
601   MachineFunction &MF = *MBB.getParent();
602   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
603   DebugLoc dl = MI.getDebugLoc();
604   MachineInstrBuilder MIB(*MBB.getParent(), &MI);
605
606   while (!MI.getOperand(i).isFI()) {
607     ++i;
608     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
609   }
610
611   unsigned FrameReg = ARM::SP;
612   int FrameIndex = MI.getOperand(i).getIndex();
613   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
614                MF.getFrameInfo()->getStackSize() + SPAdj;
615
616   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
617     Offset -= AFI->getGPRCalleeSavedArea1Offset();
618   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
619     Offset -= AFI->getGPRCalleeSavedArea2Offset();
620   else if (MF.getFrameInfo()->hasVarSizedObjects()) {
621     assert(SPAdj == 0 && MF.getTarget().getFrameLowering()->hasFP(MF) &&
622            "Unexpected");
623     // There are alloca()'s in this function, must reference off the frame
624     // pointer or base pointer instead.
625     if (!hasBasePointer(MF)) {
626       FrameReg = getFrameRegister(MF);
627       Offset -= AFI->getFramePtrSpillOffset();
628     } else
629       FrameReg = BasePtr;
630   }
631
632   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
633   // call frame setup/destroy instructions have already been eliminated.  That
634   // means the stack pointer cannot be used to access the emergency spill slot
635   // when !hasReservedCallFrame().
636 #ifndef NDEBUG
637   if (RS && FrameReg == ARM::SP && FrameIndex == RS->getScavengingFrameIndex()){
638     assert(MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF) &&
639            "Cannot use SP to access the emergency spill slot in "
640            "functions without a reserved call frame");
641     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
642            "Cannot use SP to access the emergency spill slot in "
643            "functions with variable sized frame objects");
644   }
645 #endif // NDEBUG
646
647   // Special handling of dbg_value instructions.
648   if (MI.isDebugValue()) {
649     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
650     MI.getOperand(i+1).ChangeToImmediate(Offset);
651     return;
652   }
653
654   // Modify MI as necessary to handle as much of 'Offset' as possible
655   assert(AFI->isThumbFunction() &&
656          "This eliminateFrameIndex only supports Thumb1!");
657   if (rewriteFrameIndex(MI, i, FrameReg, Offset, TII))
658     return;
659
660   // If we get here, the immediate doesn't fit into the instruction.  We folded
661   // as much as possible above, handle the rest, providing a register that is
662   // SP+LargeImm.
663   assert(Offset && "This code isn't needed if offset already handled!");
664
665   unsigned Opcode = MI.getOpcode();
666
667   // Remove predicate first.
668   int PIdx = MI.findFirstPredOperandIdx();
669   if (PIdx != -1)
670     removeOperands(MI, PIdx);
671
672   if (MI.mayLoad()) {
673     // Use the destination register to materialize sp + offset.
674     unsigned TmpReg = MI.getOperand(0).getReg();
675     bool UseRR = false;
676     if (Opcode == ARM::tLDRspi) {
677       if (FrameReg == ARM::SP)
678         emitThumbRegPlusImmInReg(MBB, II, dl, TmpReg, FrameReg,
679                                  Offset, false, TII, *this);
680       else {
681         emitLoadConstPool(MBB, II, dl, TmpReg, 0, Offset);
682         UseRR = true;
683       }
684     } else {
685       emitThumbRegPlusImmediate(MBB, II, dl, TmpReg, FrameReg, Offset, TII,
686                                 *this);
687     }
688
689     MI.setDesc(TII.get(UseRR ? ARM::tLDRr : ARM::tLDRi));
690     MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
691     if (UseRR)
692       // Use [reg, reg] addrmode. Replace the immediate operand w/ the frame
693       // register. The offset is already handled in the vreg value.
694       MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
695   } else if (MI.mayStore()) {
696       VReg = MF.getRegInfo().createVirtualRegister(&ARM::tGPRRegClass);
697       bool UseRR = false;
698
699       if (Opcode == ARM::tSTRspi) {
700         if (FrameReg == ARM::SP)
701           emitThumbRegPlusImmInReg(MBB, II, dl, VReg, FrameReg,
702                                    Offset, false, TII, *this);
703         else {
704           emitLoadConstPool(MBB, II, dl, VReg, 0, Offset);
705           UseRR = true;
706         }
707       } else
708         emitThumbRegPlusImmediate(MBB, II, dl, VReg, FrameReg, Offset, TII,
709                                   *this);
710       MI.setDesc(TII.get(UseRR ? ARM::tSTRr : ARM::tSTRi));
711       MI.getOperand(i).ChangeToRegister(VReg, false, false, true);
712       if (UseRR)
713         // Use [reg, reg] addrmode. Replace the immediate operand w/ the frame
714         // register. The offset is already handled in the vreg value.
715         MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
716   } else {
717     llvm_unreachable("Unexpected opcode!");
718   }
719
720   // Add predicate back if it's needed.
721   if (MI.isPredicable())
722     AddDefaultPred(MIB);
723 }