Refactor code.
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===- ARMBaseInstrInfo.cpp - ARM Instruction 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 Base ARM implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMBaseInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMGenInstrInfo.inc"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 using namespace llvm;
37
38 static cl::opt<bool>
39 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
40                cl::desc("Enable ARM 2-addr to 3-addr conv"));
41
42 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
43   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
44     Subtarget(STI) {
45 }
46
47 MachineInstr *
48 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
49                                         MachineBasicBlock::iterator &MBBI,
50                                         LiveVariables *LV) const {
51   // FIXME: Thumb2 support.
52
53   if (!EnableARM3Addr)
54     return NULL;
55
56   MachineInstr *MI = MBBI;
57   MachineFunction &MF = *MI->getParent()->getParent();
58   unsigned TSFlags = MI->getDesc().TSFlags;
59   bool isPre = false;
60   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
61   default: return NULL;
62   case ARMII::IndexModePre:
63     isPre = true;
64     break;
65   case ARMII::IndexModePost:
66     break;
67   }
68
69   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
70   // operation.
71   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
72   if (MemOpc == 0)
73     return NULL;
74
75   MachineInstr *UpdateMI = NULL;
76   MachineInstr *MemMI = NULL;
77   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
78   const TargetInstrDesc &TID = MI->getDesc();
79   unsigned NumOps = TID.getNumOperands();
80   bool isLoad = !TID.mayStore();
81   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
82   const MachineOperand &Base = MI->getOperand(2);
83   const MachineOperand &Offset = MI->getOperand(NumOps-3);
84   unsigned WBReg = WB.getReg();
85   unsigned BaseReg = Base.getReg();
86   unsigned OffReg = Offset.getReg();
87   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
88   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
89   switch (AddrMode) {
90   default:
91     assert(false && "Unknown indexed op!");
92     return NULL;
93   case ARMII::AddrMode2: {
94     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
95     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
96     if (OffReg == 0) {
97       if (ARM_AM::getSOImmVal(Amt) == -1)
98         // Can't encode it in a so_imm operand. This transformation will
99         // add more than 1 instruction. Abandon!
100         return NULL;
101       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
102                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
103         .addReg(BaseReg).addImm(Amt)
104         .addImm(Pred).addReg(0).addReg(0);
105     } else if (Amt != 0) {
106       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
107       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
108       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
109                          get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
110         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
111         .addImm(Pred).addReg(0).addReg(0);
112     } else
113       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
114                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
115         .addReg(BaseReg).addReg(OffReg)
116         .addImm(Pred).addReg(0).addReg(0);
117     break;
118   }
119   case ARMII::AddrMode3 : {
120     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
121     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
122     if (OffReg == 0)
123       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
124       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
125                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
126         .addReg(BaseReg).addImm(Amt)
127         .addImm(Pred).addReg(0).addReg(0);
128     else
129       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
130                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
131         .addReg(BaseReg).addReg(OffReg)
132         .addImm(Pred).addReg(0).addReg(0);
133     break;
134   }
135   }
136
137   std::vector<MachineInstr*> NewMIs;
138   if (isPre) {
139     if (isLoad)
140       MemMI = BuildMI(MF, MI->getDebugLoc(),
141                       get(MemOpc), MI->getOperand(0).getReg())
142         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
143     else
144       MemMI = BuildMI(MF, MI->getDebugLoc(),
145                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
146         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
147     NewMIs.push_back(MemMI);
148     NewMIs.push_back(UpdateMI);
149   } else {
150     if (isLoad)
151       MemMI = BuildMI(MF, MI->getDebugLoc(),
152                       get(MemOpc), MI->getOperand(0).getReg())
153         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
154     else
155       MemMI = BuildMI(MF, MI->getDebugLoc(),
156                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
157         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
158     if (WB.isDead())
159       UpdateMI->getOperand(0).setIsDead();
160     NewMIs.push_back(UpdateMI);
161     NewMIs.push_back(MemMI);
162   }
163
164   // Transfer LiveVariables states, kill / dead info.
165   if (LV) {
166     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
167       MachineOperand &MO = MI->getOperand(i);
168       if (MO.isReg() && MO.getReg() &&
169           TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
170         unsigned Reg = MO.getReg();
171
172         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
173         if (MO.isDef()) {
174           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
175           if (MO.isDead())
176             LV->addVirtualRegisterDead(Reg, NewMI);
177         }
178         if (MO.isUse() && MO.isKill()) {
179           for (unsigned j = 0; j < 2; ++j) {
180             // Look at the two new MI's in reverse order.
181             MachineInstr *NewMI = NewMIs[j];
182             if (!NewMI->readsRegister(Reg))
183               continue;
184             LV->addVirtualRegisterKilled(Reg, NewMI);
185             if (VI.removeKill(MI))
186               VI.Kills.push_back(NewMI);
187             break;
188           }
189         }
190       }
191     }
192   }
193
194   MFI->insert(MBBI, NewMIs[1]);
195   MFI->insert(MBBI, NewMIs[0]);
196   return NewMIs[0];
197 }
198
199 // Branch analysis.
200 bool
201 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
202                                 MachineBasicBlock *&FBB,
203                                 SmallVectorImpl<MachineOperand> &Cond,
204                                 bool AllowModify) const {
205   // If the block has no terminators, it just falls into the block after it.
206   MachineBasicBlock::iterator I = MBB.end();
207   if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
208     return false;
209
210   // Get the last instruction in the block.
211   MachineInstr *LastInst = I;
212
213   // If there is only one terminator instruction, process it.
214   unsigned LastOpc = LastInst->getOpcode();
215   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
216     if (isUncondBranchOpcode(LastOpc)) {
217       TBB = LastInst->getOperand(0).getMBB();
218       return false;
219     }
220     if (isCondBranchOpcode(LastOpc)) {
221       // Block ends with fall-through condbranch.
222       TBB = LastInst->getOperand(0).getMBB();
223       Cond.push_back(LastInst->getOperand(1));
224       Cond.push_back(LastInst->getOperand(2));
225       return false;
226     }
227     return true;  // Can't handle indirect branch.
228   }
229
230   // Get the instruction before it if it is a terminator.
231   MachineInstr *SecondLastInst = I;
232
233   // If there are three terminators, we don't know what sort of block this is.
234   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
235     return true;
236
237   // If the block ends with a B and a Bcc, handle it.
238   unsigned SecondLastOpc = SecondLastInst->getOpcode();
239   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
240     TBB =  SecondLastInst->getOperand(0).getMBB();
241     Cond.push_back(SecondLastInst->getOperand(1));
242     Cond.push_back(SecondLastInst->getOperand(2));
243     FBB = LastInst->getOperand(0).getMBB();
244     return false;
245   }
246
247   // If the block ends with two unconditional branches, handle it.  The second
248   // one is not executed, so remove it.
249   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
250     TBB = SecondLastInst->getOperand(0).getMBB();
251     I = LastInst;
252     if (AllowModify)
253       I->eraseFromParent();
254     return false;
255   }
256
257   // ...likewise if it ends with a branch table followed by an unconditional
258   // branch. The branch folder can create these, and we must get rid of them for
259   // correctness of Thumb constant islands.
260   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
261        isIndirectBranchOpcode(SecondLastOpc)) &&
262       isUncondBranchOpcode(LastOpc)) {
263     I = LastInst;
264     if (AllowModify)
265       I->eraseFromParent();
266     return true;
267   }
268
269   // Otherwise, can't handle this.
270   return true;
271 }
272
273
274 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
275   MachineBasicBlock::iterator I = MBB.end();
276   if (I == MBB.begin()) return 0;
277   --I;
278   if (!isUncondBranchOpcode(I->getOpcode()) &&
279       !isCondBranchOpcode(I->getOpcode()))
280     return 0;
281
282   // Remove the branch.
283   I->eraseFromParent();
284
285   I = MBB.end();
286
287   if (I == MBB.begin()) return 1;
288   --I;
289   if (!isCondBranchOpcode(I->getOpcode()))
290     return 1;
291
292   // Remove the branch.
293   I->eraseFromParent();
294   return 2;
295 }
296
297 unsigned
298 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
299                                MachineBasicBlock *FBB,
300                              const SmallVectorImpl<MachineOperand> &Cond) const {
301   // FIXME this should probably have a DebugLoc argument
302   DebugLoc dl = DebugLoc::getUnknownLoc();
303
304   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
305   int BOpc   = !AFI->isThumbFunction()
306     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
307   int BccOpc = !AFI->isThumbFunction()
308     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
309
310   // Shouldn't be a fall through.
311   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
312   assert((Cond.size() == 2 || Cond.size() == 0) &&
313          "ARM branch conditions have two components!");
314
315   if (FBB == 0) {
316     if (Cond.empty()) // Unconditional branch?
317       BuildMI(&MBB, dl, get(BOpc)).addMBB(TBB);
318     else
319       BuildMI(&MBB, dl, get(BccOpc)).addMBB(TBB)
320         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
321     return 1;
322   }
323
324   // Two-way conditional branch.
325   BuildMI(&MBB, dl, get(BccOpc)).addMBB(TBB)
326     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
327   BuildMI(&MBB, dl, get(BOpc)).addMBB(FBB);
328   return 2;
329 }
330
331 bool ARMBaseInstrInfo::
332 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
333   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
334   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
335   return false;
336 }
337
338 bool ARMBaseInstrInfo::
339 PredicateInstruction(MachineInstr *MI,
340                      const SmallVectorImpl<MachineOperand> &Pred) const {
341   unsigned Opc = MI->getOpcode();
342   if (isUncondBranchOpcode(Opc)) {
343     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
344     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
345     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
346     return true;
347   }
348
349   int PIdx = MI->findFirstPredOperandIdx();
350   if (PIdx != -1) {
351     MachineOperand &PMO = MI->getOperand(PIdx);
352     PMO.setImm(Pred[0].getImm());
353     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
354     return true;
355   }
356   return false;
357 }
358
359 bool ARMBaseInstrInfo::
360 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
361                   const SmallVectorImpl<MachineOperand> &Pred2) const {
362   if (Pred1.size() > 2 || Pred2.size() > 2)
363     return false;
364
365   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
366   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
367   if (CC1 == CC2)
368     return true;
369
370   switch (CC1) {
371   default:
372     return false;
373   case ARMCC::AL:
374     return true;
375   case ARMCC::HS:
376     return CC2 == ARMCC::HI;
377   case ARMCC::LS:
378     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
379   case ARMCC::GE:
380     return CC2 == ARMCC::GT;
381   case ARMCC::LE:
382     return CC2 == ARMCC::LT;
383   }
384 }
385
386 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
387                                     std::vector<MachineOperand> &Pred) const {
388   // FIXME: This confuses implicit_def with optional CPSR def.
389   const TargetInstrDesc &TID = MI->getDesc();
390   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
391     return false;
392
393   bool Found = false;
394   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
395     const MachineOperand &MO = MI->getOperand(i);
396     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
397       Pred.push_back(MO);
398       Found = true;
399     }
400   }
401
402   return Found;
403 }
404
405
406 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
407 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
408                                 unsigned JTI) DISABLE_INLINE;
409 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
410                                 unsigned JTI) {
411   return JT[JTI].MBBs.size();
412 }
413
414 /// GetInstSize - Return the size of the specified MachineInstr.
415 ///
416 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
417   const MachineBasicBlock &MBB = *MI->getParent();
418   const MachineFunction *MF = MBB.getParent();
419   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
420
421   // Basic size info comes from the TSFlags field.
422   const TargetInstrDesc &TID = MI->getDesc();
423   unsigned TSFlags = TID.TSFlags;
424
425   unsigned Opc = MI->getOpcode();
426   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
427   default: {
428     // If this machine instr is an inline asm, measure it.
429     if (MI->getOpcode() == ARM::INLINEASM)
430       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
431     if (MI->isLabel())
432       return 0;
433     switch (Opc) {
434     default:
435       llvm_unreachable("Unknown or unset size field for instr!");
436     case TargetInstrInfo::IMPLICIT_DEF:
437     case TargetInstrInfo::KILL:
438     case TargetInstrInfo::DBG_LABEL:
439     case TargetInstrInfo::EH_LABEL:
440       return 0;
441     }
442     break;
443   }
444   case ARMII::Size8Bytes: return 8;          // ARM instruction x 2.
445   case ARMII::Size4Bytes: return 4;          // ARM / Thumb2 instruction.
446   case ARMII::Size2Bytes: return 2;          // Thumb1 instruction.
447   case ARMII::SizeSpecial: {
448     switch (Opc) {
449     case ARM::CONSTPOOL_ENTRY:
450       // If this machine instr is a constant pool entry, its size is recorded as
451       // operand #2.
452       return MI->getOperand(2).getImm();
453     case ARM::Int_eh_sjlj_setjmp:
454       return 24;
455     case ARM::t2Int_eh_sjlj_setjmp:
456       return 22;
457     case ARM::BR_JTr:
458     case ARM::BR_JTm:
459     case ARM::BR_JTadd:
460     case ARM::tBR_JTr:
461     case ARM::t2BR_JT:
462     case ARM::t2TBB:
463     case ARM::t2TBH: {
464       // These are jumptable branches, i.e. a branch followed by an inlined
465       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
466       // entry is one byte; TBH two byte each.
467       unsigned EntrySize = (Opc == ARM::t2TBB)
468         ? 1 : ((Opc == ARM::t2TBH) ? 2 : 4);
469       unsigned NumOps = TID.getNumOperands();
470       MachineOperand JTOP =
471         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
472       unsigned JTI = JTOP.getIndex();
473       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
474       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
475       assert(JTI < JT.size());
476       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
477       // 4 aligned. The assembler / linker may add 2 byte padding just before
478       // the JT entries.  The size does not include this padding; the
479       // constant islands pass does separate bookkeeping for it.
480       // FIXME: If we know the size of the function is less than (1 << 16) *2
481       // bytes, we can use 16-bit entries instead. Then there won't be an
482       // alignment issue.
483       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
484       unsigned NumEntries = getNumJTEntries(JT, JTI);
485       if (Opc == ARM::t2TBB && (NumEntries & 1))
486         // Make sure the instruction that follows TBB is 2-byte aligned.
487         // FIXME: Constant island pass should insert an "ALIGN" instruction
488         // instead.
489         ++NumEntries;
490       return NumEntries * EntrySize + InstSize;
491     }
492     default:
493       // Otherwise, pseudo-instruction sizes are zero.
494       return 0;
495     }
496   }
497   }
498   return 0; // Not reached
499 }
500
501 /// Return true if the instruction is a register to register move and
502 /// leave the source and dest operands in the passed parameters.
503 ///
504 bool
505 ARMBaseInstrInfo::isMoveInstr(const MachineInstr &MI,
506                               unsigned &SrcReg, unsigned &DstReg,
507                               unsigned& SrcSubIdx, unsigned& DstSubIdx) const {
508   SrcSubIdx = DstSubIdx = 0; // No sub-registers.
509
510   switch (MI.getOpcode()) {
511   default: break;
512   case ARM::FCPYS:
513   case ARM::FCPYD:
514   case ARM::VMOVD:
515   case ARM::VMOVQ: {
516     SrcReg = MI.getOperand(1).getReg();
517     DstReg = MI.getOperand(0).getReg();
518     return true;
519   }
520   case ARM::MOVr:
521   case ARM::tMOVr:
522   case ARM::tMOVgpr2tgpr:
523   case ARM::tMOVtgpr2gpr:
524   case ARM::tMOVgpr2gpr:
525   case ARM::t2MOVr: {
526     assert(MI.getDesc().getNumOperands() >= 2 &&
527            MI.getOperand(0).isReg() &&
528            MI.getOperand(1).isReg() &&
529            "Invalid ARM MOV instruction");
530     SrcReg = MI.getOperand(1).getReg();
531     DstReg = MI.getOperand(0).getReg();
532     return true;
533   }
534   }
535
536   return false;
537 }
538
539 unsigned
540 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
541                                       int &FrameIndex) const {
542   switch (MI->getOpcode()) {
543   default: break;
544   case ARM::LDR:
545   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
546     if (MI->getOperand(1).isFI() &&
547         MI->getOperand(2).isReg() &&
548         MI->getOperand(3).isImm() &&
549         MI->getOperand(2).getReg() == 0 &&
550         MI->getOperand(3).getImm() == 0) {
551       FrameIndex = MI->getOperand(1).getIndex();
552       return MI->getOperand(0).getReg();
553     }
554     break;
555   case ARM::t2LDRi12:
556   case ARM::tRestore:
557     if (MI->getOperand(1).isFI() &&
558         MI->getOperand(2).isImm() &&
559         MI->getOperand(2).getImm() == 0) {
560       FrameIndex = MI->getOperand(1).getIndex();
561       return MI->getOperand(0).getReg();
562     }
563     break;
564   case ARM::FLDD:
565   case ARM::FLDS:
566     if (MI->getOperand(1).isFI() &&
567         MI->getOperand(2).isImm() &&
568         MI->getOperand(2).getImm() == 0) {
569       FrameIndex = MI->getOperand(1).getIndex();
570       return MI->getOperand(0).getReg();
571     }
572     break;
573   }
574
575   return 0;
576 }
577
578 unsigned
579 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
580                                      int &FrameIndex) const {
581   switch (MI->getOpcode()) {
582   default: break;
583   case ARM::STR:
584   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
585     if (MI->getOperand(1).isFI() &&
586         MI->getOperand(2).isReg() &&
587         MI->getOperand(3).isImm() &&
588         MI->getOperand(2).getReg() == 0 &&
589         MI->getOperand(3).getImm() == 0) {
590       FrameIndex = MI->getOperand(1).getIndex();
591       return MI->getOperand(0).getReg();
592     }
593     break;
594   case ARM::t2STRi12:
595   case ARM::tSpill:
596     if (MI->getOperand(1).isFI() &&
597         MI->getOperand(2).isImm() &&
598         MI->getOperand(2).getImm() == 0) {
599       FrameIndex = MI->getOperand(1).getIndex();
600       return MI->getOperand(0).getReg();
601     }
602     break;
603   case ARM::FSTD:
604   case ARM::FSTS:
605     if (MI->getOperand(1).isFI() &&
606         MI->getOperand(2).isImm() &&
607         MI->getOperand(2).getImm() == 0) {
608       FrameIndex = MI->getOperand(1).getIndex();
609       return MI->getOperand(0).getReg();
610     }
611     break;
612   }
613
614   return 0;
615 }
616
617 bool
618 ARMBaseInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
619                                MachineBasicBlock::iterator I,
620                                unsigned DestReg, unsigned SrcReg,
621                                const TargetRegisterClass *DestRC,
622                                const TargetRegisterClass *SrcRC) const {
623   DebugLoc DL = DebugLoc::getUnknownLoc();
624   if (I != MBB.end()) DL = I->getDebugLoc();
625
626   if (DestRC != SrcRC) {
627     if (DestRC->getSize() != SrcRC->getSize())
628       return false;
629
630     // Allow DPR / DPR_VFP2 / DPR_8 cross-class copies.
631     // Allow QPR / QPR_VFP2 / QPR_8 cross-class copies.
632     if (DestRC->getSize() != 8 && DestRC->getSize() != 16)
633       return false;
634   }
635
636   if (DestRC == ARM::GPRRegisterClass) {
637     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr),
638                                         DestReg).addReg(SrcReg)));
639   } else if (DestRC == ARM::SPRRegisterClass) {
640     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FCPYS), DestReg)
641                    .addReg(SrcReg));
642   } else if (DestRC == ARM::DPRRegisterClass) {
643     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FCPYD), DestReg)
644                    .addReg(SrcReg));
645   } else if (DestRC == ARM::DPR_VFP2RegisterClass ||
646              DestRC == ARM::DPR_8RegisterClass ||
647              SrcRC == ARM::DPR_VFP2RegisterClass ||
648              SrcRC == ARM::DPR_8RegisterClass) {
649     // Always use neon reg-reg move if source or dest is NEON-only regclass.
650     BuildMI(MBB, I, DL, get(ARM::VMOVD), DestReg).addReg(SrcReg);
651   } else if (DestRC == ARM::QPRRegisterClass ||
652              DestRC == ARM::QPR_VFP2RegisterClass ||
653              DestRC == ARM::QPR_8RegisterClass) {
654     BuildMI(MBB, I, DL, get(ARM::VMOVQ), DestReg).addReg(SrcReg);
655   } else {
656     return false;
657   }
658
659   return true;
660 }
661
662 void ARMBaseInstrInfo::
663 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
664                     unsigned SrcReg, bool isKill, int FI,
665                     const TargetRegisterClass *RC) const {
666   DebugLoc DL = DebugLoc::getUnknownLoc();
667   if (I != MBB.end()) DL = I->getDebugLoc();
668   MachineFunction &MF = *MBB.getParent();
669   MachineFrameInfo &MFI = *MF.getFrameInfo();
670
671   MachineMemOperand *MMO =
672     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
673                             MachineMemOperand::MOStore, 0,
674                             MFI.getObjectSize(FI),
675                             MFI.getObjectAlignment(FI));
676
677   if (RC == ARM::GPRRegisterClass) {
678     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STR))
679                    .addReg(SrcReg, getKillRegState(isKill))
680                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
681   } else if (RC == ARM::DPRRegisterClass ||
682              RC == ARM::DPR_VFP2RegisterClass ||
683              RC == ARM::DPR_8RegisterClass) {
684     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FSTD))
685                    .addReg(SrcReg, getKillRegState(isKill))
686                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
687   } else if (RC == ARM::SPRRegisterClass) {
688     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FSTS))
689                    .addReg(SrcReg, getKillRegState(isKill))
690                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
691   } else {
692     assert((RC == ARM::QPRRegisterClass ||
693             RC == ARM::QPR_VFP2RegisterClass) && "Unknown regclass!");
694     // FIXME: Neon instructions should support predicates
695     BuildMI(MBB, I, DL, get(ARM::VSTRQ)).addReg(SrcReg, getKillRegState(isKill))
696       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
697   }
698 }
699
700 void ARMBaseInstrInfo::
701 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
702                      unsigned DestReg, int FI,
703                      const TargetRegisterClass *RC) const {
704   DebugLoc DL = DebugLoc::getUnknownLoc();
705   if (I != MBB.end()) DL = I->getDebugLoc();
706   MachineFunction &MF = *MBB.getParent();
707   MachineFrameInfo &MFI = *MF.getFrameInfo();
708
709   MachineMemOperand *MMO =
710     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FI),
711                             MachineMemOperand::MOLoad, 0,
712                             MFI.getObjectSize(FI),
713                             MFI.getObjectAlignment(FI));
714
715   if (RC == ARM::GPRRegisterClass) {
716     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDR), DestReg)
717                    .addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO));
718   } else if (RC == ARM::DPRRegisterClass ||
719              RC == ARM::DPR_VFP2RegisterClass ||
720              RC == ARM::DPR_8RegisterClass) {
721     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FLDD), DestReg)
722                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
723   } else if (RC == ARM::SPRRegisterClass) {
724     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::FLDS), DestReg)
725                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
726   } else {
727     assert((RC == ARM::QPRRegisterClass ||
728             RC == ARM::QPR_VFP2RegisterClass ||
729             RC == ARM::QPR_8RegisterClass) && "Unknown regclass!");
730     // FIXME: Neon instructions should support predicates
731     BuildMI(MBB, I, DL, get(ARM::VLDRQ), DestReg).addFrameIndex(FI).addImm(0).
732       addMemOperand(MMO);
733   }
734 }
735
736 MachineInstr *ARMBaseInstrInfo::
737 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr *MI,
738                       const SmallVectorImpl<unsigned> &Ops, int FI) const {
739   if (Ops.size() != 1) return NULL;
740
741   unsigned OpNum = Ops[0];
742   unsigned Opc = MI->getOpcode();
743   MachineInstr *NewMI = NULL;
744   if (Opc == ARM::MOVr || Opc == ARM::t2MOVr) {
745     // If it is updating CPSR, then it cannot be folded.
746     if (MI->getOperand(4).getReg() == ARM::CPSR && !MI->getOperand(4).isDead())
747       return NULL;
748     unsigned Pred = MI->getOperand(2).getImm();
749     unsigned PredReg = MI->getOperand(3).getReg();
750     if (OpNum == 0) { // move -> store
751       unsigned SrcReg = MI->getOperand(1).getReg();
752       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
753       bool isKill = MI->getOperand(1).isKill();
754       bool isUndef = MI->getOperand(1).isUndef();
755       if (Opc == ARM::MOVr)
756         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::STR))
757           .addReg(SrcReg,
758                   getKillRegState(isKill) | getUndefRegState(isUndef),
759                   SrcSubReg)
760           .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
761       else // ARM::t2MOVr
762         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2STRi12))
763           .addReg(SrcReg,
764                   getKillRegState(isKill) | getUndefRegState(isUndef),
765                   SrcSubReg)
766           .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
767     } else {          // move -> load
768       unsigned DstReg = MI->getOperand(0).getReg();
769       unsigned DstSubReg = MI->getOperand(0).getSubReg();
770       bool isDead = MI->getOperand(0).isDead();
771       bool isUndef = MI->getOperand(0).isUndef();
772       if (Opc == ARM::MOVr)
773         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::LDR))
774           .addReg(DstReg,
775                   RegState::Define |
776                   getDeadRegState(isDead) |
777                   getUndefRegState(isUndef), DstSubReg)
778           .addFrameIndex(FI).addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
779       else // ARM::t2MOVr
780         NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2LDRi12))
781           .addReg(DstReg,
782                   RegState::Define |
783                   getDeadRegState(isDead) |
784                   getUndefRegState(isUndef), DstSubReg)
785           .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
786     }
787   } else if (Opc == ARM::tMOVgpr2gpr ||
788              Opc == ARM::tMOVtgpr2gpr ||
789              Opc == ARM::tMOVgpr2tgpr) {
790     if (OpNum == 0) { // move -> store
791       unsigned SrcReg = MI->getOperand(1).getReg();
792       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
793       bool isKill = MI->getOperand(1).isKill();
794       bool isUndef = MI->getOperand(1).isUndef();
795       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2STRi12))
796         .addReg(SrcReg,
797                 getKillRegState(isKill) | getUndefRegState(isUndef),
798                 SrcSubReg)
799         .addFrameIndex(FI).addImm(0).addImm(ARMCC::AL).addReg(0);
800     } else {          // move -> load
801       unsigned DstReg = MI->getOperand(0).getReg();
802       unsigned DstSubReg = MI->getOperand(0).getSubReg();
803       bool isDead = MI->getOperand(0).isDead();
804       bool isUndef = MI->getOperand(0).isUndef();
805       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::t2LDRi12))
806         .addReg(DstReg,
807                 RegState::Define |
808                 getDeadRegState(isDead) |
809                 getUndefRegState(isUndef),
810                 DstSubReg)
811         .addFrameIndex(FI).addImm(0).addImm(ARMCC::AL).addReg(0);
812     }
813   } else if (Opc == ARM::FCPYS) {
814     unsigned Pred = MI->getOperand(2).getImm();
815     unsigned PredReg = MI->getOperand(3).getReg();
816     if (OpNum == 0) { // move -> store
817       unsigned SrcReg = MI->getOperand(1).getReg();
818       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
819       bool isKill = MI->getOperand(1).isKill();
820       bool isUndef = MI->getOperand(1).isUndef();
821       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FSTS))
822         .addReg(SrcReg, getKillRegState(isKill) | getUndefRegState(isUndef),
823                 SrcSubReg)
824         .addFrameIndex(FI)
825         .addImm(0).addImm(Pred).addReg(PredReg);
826     } else {          // move -> load
827       unsigned DstReg = MI->getOperand(0).getReg();
828       unsigned DstSubReg = MI->getOperand(0).getSubReg();
829       bool isDead = MI->getOperand(0).isDead();
830       bool isUndef = MI->getOperand(0).isUndef();
831       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FLDS))
832         .addReg(DstReg,
833                 RegState::Define |
834                 getDeadRegState(isDead) |
835                 getUndefRegState(isUndef),
836                 DstSubReg)
837         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
838     }
839   }
840   else if (Opc == ARM::FCPYD) {
841     unsigned Pred = MI->getOperand(2).getImm();
842     unsigned PredReg = MI->getOperand(3).getReg();
843     if (OpNum == 0) { // move -> store
844       unsigned SrcReg = MI->getOperand(1).getReg();
845       unsigned SrcSubReg = MI->getOperand(1).getSubReg();
846       bool isKill = MI->getOperand(1).isKill();
847       bool isUndef = MI->getOperand(1).isUndef();
848       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FSTD))
849         .addReg(SrcReg,
850                 getKillRegState(isKill) | getUndefRegState(isUndef),
851                 SrcSubReg)
852         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
853     } else {          // move -> load
854       unsigned DstReg = MI->getOperand(0).getReg();
855       unsigned DstSubReg = MI->getOperand(0).getSubReg();
856       bool isDead = MI->getOperand(0).isDead();
857       bool isUndef = MI->getOperand(0).isUndef();
858       NewMI = BuildMI(MF, MI->getDebugLoc(), get(ARM::FLDD))
859         .addReg(DstReg,
860                 RegState::Define |
861                 getDeadRegState(isDead) |
862                 getUndefRegState(isUndef),
863                 DstSubReg)
864         .addFrameIndex(FI).addImm(0).addImm(Pred).addReg(PredReg);
865     }
866   }
867
868   return NewMI;
869 }
870
871 MachineInstr*
872 ARMBaseInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
873                                         MachineInstr* MI,
874                                         const SmallVectorImpl<unsigned> &Ops,
875                                         MachineInstr* LoadMI) const {
876   // FIXME
877   return 0;
878 }
879
880 bool
881 ARMBaseInstrInfo::canFoldMemoryOperand(const MachineInstr *MI,
882                                    const SmallVectorImpl<unsigned> &Ops) const {
883   if (Ops.size() != 1) return false;
884
885   unsigned Opc = MI->getOpcode();
886   if (Opc == ARM::MOVr || Opc == ARM::t2MOVr) {
887     // If it is updating CPSR, then it cannot be folded.
888     return MI->getOperand(4).getReg() != ARM::CPSR ||
889       MI->getOperand(4).isDead();
890   } else if (Opc == ARM::tMOVgpr2gpr ||
891              Opc == ARM::tMOVtgpr2gpr ||
892              Opc == ARM::tMOVgpr2tgpr) {
893     return true;
894   } else if (Opc == ARM::FCPYS || Opc == ARM::FCPYD) {
895     return true;
896   } else if (Opc == ARM::VMOVD || Opc == ARM::VMOVQ) {
897     return false; // FIXME
898   }
899
900   return false;
901 }
902
903 void ARMBaseInstrInfo::
904 reMaterialize(MachineBasicBlock &MBB,
905               MachineBasicBlock::iterator I,
906               unsigned DestReg, unsigned SubIdx,
907               const MachineInstr *Orig) const {
908   DebugLoc dl = Orig->getDebugLoc();
909   unsigned Opcode = Orig->getOpcode();
910   switch (Opcode) {
911   default: {
912     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
913     MI->getOperand(0).setReg(DestReg);
914     MBB.insert(I, MI);
915     break;
916   }
917   case ARM::tLDRpci_pic:
918   case ARM::t2LDRpci_pic: {
919     MachineFunction &MF = *MBB.getParent();
920     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
921     MachineConstantPool *MCP = MF.getConstantPool();
922     unsigned CPI = Orig->getOperand(1).getIndex();
923     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
924     assert(MCPE.isMachineConstantPoolEntry() &&
925            "Expecting a machine constantpool entry!");
926     ARMConstantPoolValue *ACPV =
927       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
928     unsigned PCLabelId = AFI->createConstPoolEntryUId();
929     ARMConstantPoolValue *NewCPV = 0;
930     if (ACPV->isGlobalValue())
931       NewCPV = new ARMConstantPoolValue(ACPV->getGV(), PCLabelId,
932                                         ARMCP::CPValue, 4);
933     else if (ACPV->isExtSymbol())
934       NewCPV = new ARMConstantPoolValue(MF.getFunction()->getContext(),
935                                         ACPV->getSymbol(), PCLabelId, 4);
936     else if (ACPV->isBlockAddress())
937       NewCPV = new ARMConstantPoolValue(ACPV->getBlockAddress(), PCLabelId,
938                                         ARMCP::CPBlockAddress, 4);
939     else
940       llvm_unreachable("Unexpected ARM constantpool value type!!");
941     CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
942     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
943                                       DestReg)
944       .addConstantPoolIndex(CPI).addImm(PCLabelId);
945     (*MIB).setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
946     break;
947   }
948   }
949
950   MachineInstr *NewMI = prior(I);
951   NewMI->getOperand(0).setSubReg(SubIdx);
952 }
953
954 bool ARMBaseInstrInfo::isIdentical(const MachineInstr *MI0,
955                                   const MachineInstr *MI1,
956                                   const MachineRegisterInfo *MRI) const {
957   int Opcode = MI0->getOpcode();
958   if (Opcode == ARM::t2LDRpci_pic || Opcode == ARM::tLDRpci_pic) {
959     if (MI1->getOpcode() != Opcode)
960       return false;
961     if (MI0->getNumOperands() != MI1->getNumOperands())
962       return false;
963
964     const MachineOperand &MO0 = MI0->getOperand(1);
965     const MachineOperand &MO1 = MI1->getOperand(1);
966     if (MO0.getOffset() != MO1.getOffset())
967       return false;
968
969     const MachineFunction *MF = MI0->getParent()->getParent();
970     const MachineConstantPool *MCP = MF->getConstantPool();
971     int CPI0 = MO0.getIndex();
972     int CPI1 = MO1.getIndex();
973     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
974     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
975     ARMConstantPoolValue *ACPV0 =
976       static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
977     ARMConstantPoolValue *ACPV1 =
978       static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
979     return ACPV0->hasSameValue(ACPV1);
980   }
981
982   return TargetInstrInfoImpl::isIdentical(MI0, MI1, MRI);
983 }
984
985 /// getInstrPredicate - If instruction is predicated, returns its predicate
986 /// condition, otherwise returns AL. It also returns the condition code
987 /// register by reference.
988 ARMCC::CondCodes
989 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
990   int PIdx = MI->findFirstPredOperandIdx();
991   if (PIdx == -1) {
992     PredReg = 0;
993     return ARMCC::AL;
994   }
995
996   PredReg = MI->getOperand(PIdx+1).getReg();
997   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
998 }
999
1000
1001 int llvm::getMatchingCondBranchOpcode(int Opc) {
1002   if (Opc == ARM::B)
1003     return ARM::Bcc;
1004   else if (Opc == ARM::tB)
1005     return ARM::tBcc;
1006   else if (Opc == ARM::t2B)
1007       return ARM::t2Bcc;
1008
1009   llvm_unreachable("Unknown unconditional branch opcode!");
1010   return 0;
1011 }
1012
1013
1014 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1015                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1016                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1017                                ARMCC::CondCodes Pred, unsigned PredReg,
1018                                const ARMBaseInstrInfo &TII) {
1019   bool isSub = NumBytes < 0;
1020   if (isSub) NumBytes = -NumBytes;
1021
1022   while (NumBytes) {
1023     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1024     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1025     assert(ThisVal && "Didn't extract field correctly");
1026
1027     // We will handle these bits from offset, clear them.
1028     NumBytes &= ~ThisVal;
1029
1030     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1031
1032     // Build the new ADD / SUB.
1033     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1034     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1035       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1036       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
1037     BaseReg = DestReg;
1038   }
1039 }
1040
1041 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1042                                 unsigned FrameReg, int &Offset,
1043                                 const ARMBaseInstrInfo &TII) {
1044   unsigned Opcode = MI.getOpcode();
1045   const TargetInstrDesc &Desc = MI.getDesc();
1046   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1047   bool isSub = false;
1048
1049   // Memory operands in inline assembly always use AddrMode2.
1050   if (Opcode == ARM::INLINEASM)
1051     AddrMode = ARMII::AddrMode2;
1052
1053   if (Opcode == ARM::ADDri) {
1054     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1055     if (Offset == 0) {
1056       // Turn it into a move.
1057       MI.setDesc(TII.get(ARM::MOVr));
1058       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1059       MI.RemoveOperand(FrameRegIdx+1);
1060       Offset = 0;
1061       return true;
1062     } else if (Offset < 0) {
1063       Offset = -Offset;
1064       isSub = true;
1065       MI.setDesc(TII.get(ARM::SUBri));
1066     }
1067
1068     // Common case: small offset, fits into instruction.
1069     if (ARM_AM::getSOImmVal(Offset) != -1) {
1070       // Replace the FrameIndex with sp / fp
1071       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1072       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1073       Offset = 0;
1074       return true;
1075     }
1076
1077     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1078     // as possible.
1079     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1080     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1081
1082     // We will handle these bits from offset, clear them.
1083     Offset &= ~ThisImmVal;
1084
1085     // Get the properly encoded SOImmVal field.
1086     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1087            "Bit extraction didn't work?");
1088     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1089  } else {
1090     unsigned ImmIdx = 0;
1091     int InstrOffs = 0;
1092     unsigned NumBits = 0;
1093     unsigned Scale = 1;
1094     switch (AddrMode) {
1095     case ARMII::AddrMode2: {
1096       ImmIdx = FrameRegIdx+2;
1097       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1098       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1099         InstrOffs *= -1;
1100       NumBits = 12;
1101       break;
1102     }
1103     case ARMII::AddrMode3: {
1104       ImmIdx = FrameRegIdx+2;
1105       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1106       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1107         InstrOffs *= -1;
1108       NumBits = 8;
1109       break;
1110     }
1111     case ARMII::AddrMode4:
1112       // Can't fold any offset even if it's zero.
1113       return false;
1114     case ARMII::AddrMode5: {
1115       ImmIdx = FrameRegIdx+1;
1116       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1117       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1118         InstrOffs *= -1;
1119       NumBits = 8;
1120       Scale = 4;
1121       break;
1122     }
1123     default:
1124       llvm_unreachable("Unsupported addressing mode!");
1125       break;
1126     }
1127
1128     Offset += InstrOffs * Scale;
1129     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1130     if (Offset < 0) {
1131       Offset = -Offset;
1132       isSub = true;
1133     }
1134
1135     // Attempt to fold address comp. if opcode has offset bits
1136     if (NumBits > 0) {
1137       // Common case: small offset, fits into instruction.
1138       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1139       int ImmedOffset = Offset / Scale;
1140       unsigned Mask = (1 << NumBits) - 1;
1141       if ((unsigned)Offset <= Mask * Scale) {
1142         // Replace the FrameIndex with sp
1143         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1144         if (isSub)
1145           ImmedOffset |= 1 << NumBits;
1146         ImmOp.ChangeToImmediate(ImmedOffset);
1147         Offset = 0;
1148         return true;
1149       }
1150
1151       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1152       ImmedOffset = ImmedOffset & Mask;
1153       if (isSub)
1154         ImmedOffset |= 1 << NumBits;
1155       ImmOp.ChangeToImmediate(ImmedOffset);
1156       Offset &= ~(Mask*Scale);
1157     }
1158   }
1159
1160   Offset = (isSub) ? -Offset : Offset;
1161   return Offset == 0;
1162 }