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