Rename MRegisterInfo to TargetRegisterInfo.
[oota-llvm.git] / lib / Target / ARM / ARMInstrInfo.cpp
1 //===- ARMInstrInfo.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 ARM implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMGenInstrInfo.inc"
18 #include "ARMMachineFunctionInfo.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 using namespace llvm;
27
28 static cl::opt<bool> EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
29                                   cl::desc("Enable ARM 2-addr to 3-addr conv"));
30
31 static inline
32 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
33   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
34 }
35
36 static inline
37 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
38   return MIB.addReg(0);
39 }
40
41 ARMInstrInfo::ARMInstrInfo(const ARMSubtarget &STI)
42   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
43     RI(*this, STI) {
44 }
45
46 const TargetRegisterClass *ARMInstrInfo::getPointerRegClass() const {
47   return &ARM::GPRRegClass;
48 }
49
50 /// Return true if the instruction is a register to register move and
51 /// leave the source and dest operands in the passed parameters.
52 ///
53 bool ARMInstrInfo::isMoveInstr(const MachineInstr &MI,
54                                unsigned &SrcReg, unsigned &DstReg) const {
55   unsigned oc = MI.getOpcode();
56   switch (oc) {
57   default:
58     return false;
59   case ARM::FCPYS:
60   case ARM::FCPYD:
61     SrcReg = MI.getOperand(1).getReg();
62     DstReg = MI.getOperand(0).getReg();
63     return true;
64   case ARM::MOVr:
65   case ARM::tMOVr:
66     assert(MI.getDesc().getNumOperands() >= 2 &&
67            MI.getOperand(0).isRegister() &&
68            MI.getOperand(1).isRegister() &&
69            "Invalid ARM MOV instruction");
70     SrcReg = MI.getOperand(1).getReg();
71     DstReg = MI.getOperand(0).getReg();
72     return true;
73   }
74 }
75
76 unsigned ARMInstrInfo::isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
77   switch (MI->getOpcode()) {
78   default: break;
79   case ARM::LDR:
80     if (MI->getOperand(1).isFrameIndex() &&
81         MI->getOperand(2).isRegister() &&
82         MI->getOperand(3).isImmediate() && 
83         MI->getOperand(2).getReg() == 0 &&
84         MI->getOperand(3).getImm() == 0) {
85       FrameIndex = MI->getOperand(1).getIndex();
86       return MI->getOperand(0).getReg();
87     }
88     break;
89   case ARM::FLDD:
90   case ARM::FLDS:
91     if (MI->getOperand(1).isFrameIndex() &&
92         MI->getOperand(2).isImmediate() && 
93         MI->getOperand(2).getImm() == 0) {
94       FrameIndex = MI->getOperand(1).getIndex();
95       return MI->getOperand(0).getReg();
96     }
97     break;
98   case ARM::tRestore:
99     if (MI->getOperand(1).isFrameIndex() &&
100         MI->getOperand(2).isImmediate() && 
101         MI->getOperand(2).getImm() == 0) {
102       FrameIndex = MI->getOperand(1).getIndex();
103       return MI->getOperand(0).getReg();
104     }
105     break;
106   }
107   return 0;
108 }
109
110 unsigned ARMInstrInfo::isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
111   switch (MI->getOpcode()) {
112   default: break;
113   case ARM::STR:
114     if (MI->getOperand(1).isFrameIndex() &&
115         MI->getOperand(2).isRegister() &&
116         MI->getOperand(3).isImmediate() && 
117         MI->getOperand(2).getReg() == 0 &&
118         MI->getOperand(3).getImm() == 0) {
119       FrameIndex = MI->getOperand(1).getIndex();
120       return MI->getOperand(0).getReg();
121     }
122     break;
123   case ARM::FSTD:
124   case ARM::FSTS:
125     if (MI->getOperand(1).isFrameIndex() &&
126         MI->getOperand(2).isImmediate() && 
127         MI->getOperand(2).getImm() == 0) {
128       FrameIndex = MI->getOperand(1).getIndex();
129       return MI->getOperand(0).getReg();
130     }
131     break;
132   case ARM::tSpill:
133     if (MI->getOperand(1).isFrameIndex() &&
134         MI->getOperand(2).isImmediate() && 
135         MI->getOperand(2).getImm() == 0) {
136       FrameIndex = MI->getOperand(1).getIndex();
137       return MI->getOperand(0).getReg();
138     }
139     break;
140   }
141   return 0;
142 }
143
144 static unsigned getUnindexedOpcode(unsigned Opc) {
145   switch (Opc) {
146   default: break;
147   case ARM::LDR_PRE:
148   case ARM::LDR_POST:
149     return ARM::LDR;
150   case ARM::LDRH_PRE:
151   case ARM::LDRH_POST:
152     return ARM::LDRH;
153   case ARM::LDRB_PRE:
154   case ARM::LDRB_POST:
155     return ARM::LDRB;
156   case ARM::LDRSH_PRE:
157   case ARM::LDRSH_POST:
158     return ARM::LDRSH;
159   case ARM::LDRSB_PRE:
160   case ARM::LDRSB_POST:
161     return ARM::LDRSB;
162   case ARM::STR_PRE:
163   case ARM::STR_POST:
164     return ARM::STR;
165   case ARM::STRH_PRE:
166   case ARM::STRH_POST:
167     return ARM::STRH;
168   case ARM::STRB_PRE:
169   case ARM::STRB_POST:
170     return ARM::STRB;
171   }
172   return 0;
173 }
174
175 MachineInstr *
176 ARMInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
177                                     MachineBasicBlock::iterator &MBBI,
178                                     LiveVariables &LV) const {
179   if (!EnableARM3Addr)
180     return NULL;
181
182   MachineInstr *MI = MBBI;
183   unsigned TSFlags = MI->getDesc().TSFlags;
184   bool isPre = false;
185   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
186   default: return NULL;
187   case ARMII::IndexModePre:
188     isPre = true;
189     break;
190   case ARMII::IndexModePost:
191     break;
192   }
193
194   // Try spliting an indexed load / store to a un-indexed one plus an add/sub
195   // operation.
196   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
197   if (MemOpc == 0)
198     return NULL;
199
200   MachineInstr *UpdateMI = NULL;
201   MachineInstr *MemMI = NULL;
202   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
203   const TargetInstrDesc &TID = MI->getDesc();
204   unsigned NumOps = TID.getNumOperands();
205   bool isLoad = !TID.mayStore();
206   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
207   const MachineOperand &Base = MI->getOperand(2);
208   const MachineOperand &Offset = MI->getOperand(NumOps-3);
209   unsigned WBReg = WB.getReg();
210   unsigned BaseReg = Base.getReg();
211   unsigned OffReg = Offset.getReg();
212   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
213   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
214   switch (AddrMode) {
215   default:
216     assert(false && "Unknown indexed op!");
217     return NULL;
218   case ARMII::AddrMode2: {
219     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
220     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
221     if (OffReg == 0) {
222       int SOImmVal = ARM_AM::getSOImmVal(Amt);
223       if (SOImmVal == -1)
224         // Can't encode it in a so_imm operand. This transformation will
225         // add more than 1 instruction. Abandon!
226         return NULL;
227       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
228         .addReg(BaseReg).addImm(SOImmVal)
229         .addImm(Pred).addReg(0).addReg(0);
230     } else if (Amt != 0) {
231       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
232       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
233       UpdateMI = BuildMI(get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
234         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
235         .addImm(Pred).addReg(0).addReg(0);
236     } else 
237       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
238         .addReg(BaseReg).addReg(OffReg)
239         .addImm(Pred).addReg(0).addReg(0);
240     break;
241   }
242   case ARMII::AddrMode3 : {
243     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
244     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
245     if (OffReg == 0)
246       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
247       UpdateMI = BuildMI(get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
248         .addReg(BaseReg).addImm(Amt)
249         .addImm(Pred).addReg(0).addReg(0);
250     else
251       UpdateMI = BuildMI(get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
252         .addReg(BaseReg).addReg(OffReg)
253         .addImm(Pred).addReg(0).addReg(0);
254     break;
255   }
256   }
257
258   std::vector<MachineInstr*> NewMIs;
259   if (isPre) {
260     if (isLoad)
261       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
262         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
263     else
264       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
265         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
266     NewMIs.push_back(MemMI);
267     NewMIs.push_back(UpdateMI);
268   } else {
269     if (isLoad)
270       MemMI = BuildMI(get(MemOpc), MI->getOperand(0).getReg())
271         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
272     else
273       MemMI = BuildMI(get(MemOpc)).addReg(MI->getOperand(1).getReg())
274         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
275     if (WB.isDead())
276       UpdateMI->getOperand(0).setIsDead();
277     NewMIs.push_back(UpdateMI);
278     NewMIs.push_back(MemMI);
279   }
280   
281   // Transfer LiveVariables states, kill / dead info.
282   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
283     MachineOperand &MO = MI->getOperand(i);
284     if (MO.isRegister() && MO.getReg() &&
285         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
286       unsigned Reg = MO.getReg();
287       LiveVariables::VarInfo &VI = LV.getVarInfo(Reg);
288       if (MO.isDef()) {
289         MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
290         if (MO.isDead())
291           LV.addVirtualRegisterDead(Reg, NewMI);
292       }
293       if (MO.isUse() && MO.isKill()) {
294         for (unsigned j = 0; j < 2; ++j) {
295           // Look at the two new MI's in reverse order.
296           MachineInstr *NewMI = NewMIs[j];
297           int NIdx = NewMI->findRegisterUseOperandIdx(Reg);
298           if (NIdx == -1)
299             continue;
300           LV.addVirtualRegisterKilled(Reg, NewMI);
301           if (VI.removeKill(MI))
302             VI.Kills.push_back(NewMI);
303           break;
304         }
305       }
306     }
307   }
308
309   MFI->insert(MBBI, NewMIs[1]);
310   MFI->insert(MBBI, NewMIs[0]);
311   return NewMIs[0];
312 }
313
314 // Branch analysis.
315 bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
316                                  MachineBasicBlock *&FBB,
317                                  std::vector<MachineOperand> &Cond) const {
318   // If the block has no terminators, it just falls into the block after it.
319   MachineBasicBlock::iterator I = MBB.end();
320   if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
321     return false;
322   
323   // Get the last instruction in the block.
324   MachineInstr *LastInst = I;
325   
326   // If there is only one terminator instruction, process it.
327   unsigned LastOpc = LastInst->getOpcode();
328   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
329     if (LastOpc == ARM::B || LastOpc == ARM::tB) {
330       TBB = LastInst->getOperand(0).getMBB();
331       return false;
332     }
333     if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
334       // Block ends with fall-through condbranch.
335       TBB = LastInst->getOperand(0).getMBB();
336       Cond.push_back(LastInst->getOperand(1));
337       Cond.push_back(LastInst->getOperand(2));
338       return false;
339     }
340     return true;  // Can't handle indirect branch.
341   }
342   
343   // Get the instruction before it if it is a terminator.
344   MachineInstr *SecondLastInst = I;
345   
346   // If there are three terminators, we don't know what sort of block this is.
347   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
348     return true;
349   
350   // If the block ends with ARM::B/ARM::tB and a ARM::Bcc/ARM::tBcc, handle it.
351   unsigned SecondLastOpc = SecondLastInst->getOpcode();
352   if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
353       (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
354     TBB =  SecondLastInst->getOperand(0).getMBB();
355     Cond.push_back(SecondLastInst->getOperand(1));
356     Cond.push_back(SecondLastInst->getOperand(2));
357     FBB = LastInst->getOperand(0).getMBB();
358     return false;
359   }
360   
361   // If the block ends with two unconditional branches, handle it.  The second 
362   // one is not executed, so remove it.
363   if ((SecondLastOpc == ARM::B || SecondLastOpc==ARM::tB) &&
364       (LastOpc == ARM::B || LastOpc == ARM::tB)) {
365     TBB = SecondLastInst->getOperand(0).getMBB();
366     I = LastInst;
367     I->eraseFromParent();
368     return false;
369   }
370
371   // Likewise if it ends with a branch table followed by an unconditional branch.
372   // The branch folder can create these, and we must get rid of them for
373   // correctness of Thumb constant islands.
374   if ((SecondLastOpc == ARM::BR_JTr || SecondLastOpc==ARM::BR_JTm ||
375        SecondLastOpc == ARM::BR_JTadd || SecondLastOpc==ARM::tBR_JTr) &&
376       (LastOpc == ARM::B || LastOpc == ARM::tB)) {
377     I = LastInst;
378     I->eraseFromParent();
379     return true;
380   } 
381
382   // Otherwise, can't handle this.
383   return true;
384 }
385
386
387 unsigned ARMInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
388   MachineFunction &MF = *MBB.getParent();
389   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
390   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
391   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
392
393   MachineBasicBlock::iterator I = MBB.end();
394   if (I == MBB.begin()) return 0;
395   --I;
396   if (I->getOpcode() != BOpc && I->getOpcode() != BccOpc)
397     return 0;
398   
399   // Remove the branch.
400   I->eraseFromParent();
401   
402   I = MBB.end();
403   
404   if (I == MBB.begin()) return 1;
405   --I;
406   if (I->getOpcode() != BccOpc)
407     return 1;
408   
409   // Remove the branch.
410   I->eraseFromParent();
411   return 2;
412 }
413
414 unsigned ARMInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
415                                 MachineBasicBlock *FBB,
416                                 const std::vector<MachineOperand> &Cond) const {
417   MachineFunction &MF = *MBB.getParent();
418   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
419   int BOpc   = AFI->isThumbFunction() ? ARM::tB : ARM::B;
420   int BccOpc = AFI->isThumbFunction() ? ARM::tBcc : ARM::Bcc;
421
422   // Shouldn't be a fall through.
423   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
424   assert((Cond.size() == 2 || Cond.size() == 0) &&
425          "ARM branch conditions have two components!");
426   
427   if (FBB == 0) {
428     if (Cond.empty()) // Unconditional branch?
429       BuildMI(&MBB, get(BOpc)).addMBB(TBB);
430     else
431       BuildMI(&MBB, get(BccOpc)).addMBB(TBB)
432         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
433     return 1;
434   }
435   
436   // Two-way conditional branch.
437   BuildMI(&MBB, get(BccOpc)).addMBB(TBB)
438     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
439   BuildMI(&MBB, get(BOpc)).addMBB(FBB);
440   return 2;
441 }
442
443 void ARMInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
444                                    MachineBasicBlock::iterator I,
445                                    unsigned DestReg, unsigned SrcReg,
446                                    const TargetRegisterClass *DestRC,
447                                    const TargetRegisterClass *SrcRC) const {
448   if (DestRC != SrcRC) {
449     cerr << "Not yet supported!";
450     abort();
451   }
452
453   if (DestRC == ARM::GPRRegisterClass) {
454     MachineFunction &MF = *MBB.getParent();
455     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
456     if (AFI->isThumbFunction())
457       BuildMI(MBB, I, get(ARM::tMOVr), DestReg).addReg(SrcReg);
458     else
459       AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, get(ARM::MOVr), DestReg)
460                                   .addReg(SrcReg)));
461   } else if (DestRC == ARM::SPRRegisterClass)
462     AddDefaultPred(BuildMI(MBB, I, get(ARM::FCPYS), DestReg)
463                    .addReg(SrcReg));
464   else if (DestRC == ARM::DPRRegisterClass)
465     AddDefaultPred(BuildMI(MBB, I, get(ARM::FCPYD), DestReg)
466                    .addReg(SrcReg));
467   else
468     abort();
469 }
470
471 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
472                                                      MachineOperand &MO) {
473   if (MO.isRegister())
474     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
475   else if (MO.isImmediate())
476     MIB = MIB.addImm(MO.getImm());
477   else if (MO.isFrameIndex())
478     MIB = MIB.addFrameIndex(MO.getIndex());
479   else
480     assert(0 && "Unknown operand for ARMInstrAddOperand!");
481
482   return MIB;
483 }
484
485 void ARMInstrInfo::
486 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
487                     unsigned SrcReg, bool isKill, int FI,
488                     const TargetRegisterClass *RC) const {
489   if (RC == ARM::GPRRegisterClass) {
490     MachineFunction &MF = *MBB.getParent();
491     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
492     if (AFI->isThumbFunction())
493       BuildMI(MBB, I, get(ARM::tSpill)).addReg(SrcReg, false, false, isKill)
494         .addFrameIndex(FI).addImm(0);
495     else
496       AddDefaultPred(BuildMI(MBB, I, get(ARM::STR))
497                      .addReg(SrcReg, false, false, isKill)
498                      .addFrameIndex(FI).addReg(0).addImm(0));
499   } else if (RC == ARM::DPRRegisterClass) {
500     AddDefaultPred(BuildMI(MBB, I, get(ARM::FSTD))
501                    .addReg(SrcReg, false, false, isKill)
502                    .addFrameIndex(FI).addImm(0));
503   } else {
504     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
505     AddDefaultPred(BuildMI(MBB, I, get(ARM::FSTS))
506                    .addReg(SrcReg, false, false, isKill)
507                    .addFrameIndex(FI).addImm(0));
508   }
509 }
510
511 void ARMInstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
512                                      bool isKill,
513                                      SmallVectorImpl<MachineOperand> &Addr,
514                                      const TargetRegisterClass *RC,
515                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
516   unsigned Opc = 0;
517   if (RC == ARM::GPRRegisterClass) {
518     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
519     if (AFI->isThumbFunction()) {
520       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
521       MachineInstrBuilder MIB = 
522         BuildMI(get(Opc)).addReg(SrcReg, false, false, isKill);
523       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
524         MIB = ARMInstrAddOperand(MIB, Addr[i]);
525       NewMIs.push_back(MIB);
526       return;
527     }
528     Opc = ARM::STR;
529   } else if (RC == ARM::DPRRegisterClass) {
530     Opc = ARM::FSTD;
531   } else {
532     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
533     Opc = ARM::FSTS;
534   }
535
536   MachineInstrBuilder MIB = 
537     BuildMI(get(Opc)).addReg(SrcReg, false, false, isKill);
538   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
539     MIB = ARMInstrAddOperand(MIB, Addr[i]);
540   AddDefaultPred(MIB);
541   NewMIs.push_back(MIB);
542   return;
543 }
544
545 void ARMInstrInfo::
546 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
547                      unsigned DestReg, int FI,
548                      const TargetRegisterClass *RC) const {
549   if (RC == ARM::GPRRegisterClass) {
550     MachineFunction &MF = *MBB.getParent();
551     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
552     if (AFI->isThumbFunction())
553       BuildMI(MBB, I, get(ARM::tRestore), DestReg)
554         .addFrameIndex(FI).addImm(0);
555     else
556       AddDefaultPred(BuildMI(MBB, I, get(ARM::LDR), DestReg)
557                      .addFrameIndex(FI).addReg(0).addImm(0));
558   } else if (RC == ARM::DPRRegisterClass) {
559     AddDefaultPred(BuildMI(MBB, I, get(ARM::FLDD), DestReg)
560                    .addFrameIndex(FI).addImm(0));
561   } else {
562     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
563     AddDefaultPred(BuildMI(MBB, I, get(ARM::FLDS), DestReg)
564                    .addFrameIndex(FI).addImm(0));
565   }
566 }
567
568 void ARMInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
569                                       SmallVectorImpl<MachineOperand> &Addr,
570                                       const TargetRegisterClass *RC,
571                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
572   unsigned Opc = 0;
573   if (RC == ARM::GPRRegisterClass) {
574     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
575     if (AFI->isThumbFunction()) {
576       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
577       MachineInstrBuilder MIB = BuildMI(get(Opc), DestReg);
578       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
579         MIB = ARMInstrAddOperand(MIB, Addr[i]);
580       NewMIs.push_back(MIB);
581       return;
582     }
583     Opc = ARM::LDR;
584   } else if (RC == ARM::DPRRegisterClass) {
585     Opc = ARM::FLDD;
586   } else {
587     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
588     Opc = ARM::FLDS;
589   }
590
591   MachineInstrBuilder MIB =  BuildMI(get(Opc), DestReg);
592   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
593     MIB = ARMInstrAddOperand(MIB, Addr[i]);
594   AddDefaultPred(MIB);
595   NewMIs.push_back(MIB);
596   return;
597 }
598
599 bool ARMInstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
600                                                 MachineBasicBlock::iterator MI,
601                                 const std::vector<CalleeSavedInfo> &CSI) const {
602   MachineFunction &MF = *MBB.getParent();
603   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
604   if (!AFI->isThumbFunction() || CSI.empty())
605     return false;
606
607   MachineInstrBuilder MIB = BuildMI(MBB, MI, get(ARM::tPUSH));
608   for (unsigned i = CSI.size(); i != 0; --i) {
609     unsigned Reg = CSI[i-1].getReg();
610     // Add the callee-saved register as live-in. It's killed at the spill.
611     MBB.addLiveIn(Reg);
612     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
613   }
614   return true;
615 }
616
617 bool ARMInstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
618                                                  MachineBasicBlock::iterator MI,
619                                 const std::vector<CalleeSavedInfo> &CSI) const {
620   MachineFunction &MF = *MBB.getParent();
621   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
622   if (!AFI->isThumbFunction() || CSI.empty())
623     return false;
624
625   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
626   MachineInstr *PopMI = new MachineInstr(get(ARM::tPOP));
627   MBB.insert(MI, PopMI);
628   for (unsigned i = CSI.size(); i != 0; --i) {
629     unsigned Reg = CSI[i-1].getReg();
630     if (Reg == ARM::LR) {
631       // Special epilogue for vararg functions. See emitEpilogue
632       if (isVarArg)
633         continue;
634       Reg = ARM::PC;
635       PopMI->setDesc(get(ARM::tPOP_RET));
636       MBB.erase(MI);
637     }
638     PopMI->addOperand(MachineOperand::CreateReg(Reg, true));
639   }
640   return true;
641 }
642
643 MachineInstr *ARMInstrInfo::foldMemoryOperand(MachineFunction &MF,
644                                               MachineInstr *MI,
645                                               SmallVectorImpl<unsigned> &Ops,
646                                               int FI) const {
647   if (Ops.size() != 1) return NULL;
648
649   unsigned OpNum = Ops[0];
650   unsigned Opc = MI->getOpcode();
651   MachineInstr *NewMI = NULL;
652   switch (Opc) {
653   default: break;
654   case ARM::MOVr: {
655     if (MI->getOperand(4).getReg() == ARM::CPSR)
656       // If it is updating CPSR, then it cannot be foled.
657       break;
658     unsigned Pred = MI->getOperand(2).getImm();
659     unsigned PredReg = MI->getOperand(3).getReg();
660     if (OpNum == 0) { // move -> store
661       unsigned SrcReg = MI->getOperand(1).getReg();
662       NewMI = BuildMI(get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
663         .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
664     } else {          // move -> load
665       unsigned DstReg = MI->getOperand(0).getReg();
666       NewMI = BuildMI(get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
667         .addImm(0).addImm(Pred).addReg(PredReg);
668     }
669     break;
670   }
671   case ARM::tMOVr: {
672     if (OpNum == 0) { // move -> store
673       unsigned SrcReg = MI->getOperand(1).getReg();
674       if (RI.isPhysicalRegister(SrcReg) && !RI.isLowRegister(SrcReg))
675         // tSpill cannot take a high register operand.
676         break;
677       NewMI = BuildMI(get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
678         .addImm(0);
679     } else {          // move -> load
680       unsigned DstReg = MI->getOperand(0).getReg();
681       if (RI.isPhysicalRegister(DstReg) && !RI.isLowRegister(DstReg))
682         // tRestore cannot target a high register operand.
683         break;
684       NewMI = BuildMI(get(ARM::tRestore), DstReg).addFrameIndex(FI)
685         .addImm(0);
686     }
687     break;
688   }
689   case ARM::FCPYS: {
690     unsigned Pred = MI->getOperand(2).getImm();
691     unsigned PredReg = MI->getOperand(3).getReg();
692     if (OpNum == 0) { // move -> store
693       unsigned SrcReg = MI->getOperand(1).getReg();
694       NewMI = BuildMI(get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
695         .addImm(0).addImm(Pred).addReg(PredReg);
696     } else {          // move -> load
697       unsigned DstReg = MI->getOperand(0).getReg();
698       NewMI = BuildMI(get(ARM::FLDS), DstReg).addFrameIndex(FI)
699         .addImm(0).addImm(Pred).addReg(PredReg);
700     }
701     break;
702   }
703   case ARM::FCPYD: {
704     unsigned Pred = MI->getOperand(2).getImm();
705     unsigned PredReg = MI->getOperand(3).getReg();
706     if (OpNum == 0) { // move -> store
707       unsigned SrcReg = MI->getOperand(1).getReg();
708       NewMI = BuildMI(get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
709         .addImm(0).addImm(Pred).addReg(PredReg);
710     } else {          // move -> load
711       unsigned DstReg = MI->getOperand(0).getReg();
712       NewMI = BuildMI(get(ARM::FLDD), DstReg).addFrameIndex(FI)
713         .addImm(0).addImm(Pred).addReg(PredReg);
714     }
715     break;
716   }
717   }
718
719   if (NewMI)
720     NewMI->copyKillDeadInfo(MI);
721   return NewMI;
722 }
723
724 bool ARMInstrInfo::canFoldMemoryOperand(MachineInstr *MI,
725                                         SmallVectorImpl<unsigned> &Ops) const {
726   if (Ops.size() != 1) return false;
727
728   unsigned OpNum = Ops[0];
729   unsigned Opc = MI->getOpcode();
730   switch (Opc) {
731   default: break;
732   case ARM::MOVr:
733     // If it is updating CPSR, then it cannot be foled.
734     return MI->getOperand(4).getReg() != ARM::CPSR;
735   case ARM::tMOVr: {
736     if (OpNum == 0) { // move -> store
737       unsigned SrcReg = MI->getOperand(1).getReg();
738       if (RI.isPhysicalRegister(SrcReg) && !RI.isLowRegister(SrcReg))
739         // tSpill cannot take a high register operand.
740         return false;
741     } else {          // move -> load
742       unsigned DstReg = MI->getOperand(0).getReg();
743       if (RI.isPhysicalRegister(DstReg) && !RI.isLowRegister(DstReg))
744         // tRestore cannot target a high register operand.
745         return false;
746     }
747     return true;
748   }
749   case ARM::FCPYS:
750   case ARM::FCPYD:
751     return true;
752   }
753
754   return false;
755 }
756
757 bool ARMInstrInfo::BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
758   if (MBB.empty()) return false;
759   
760   switch (MBB.back().getOpcode()) {
761   case ARM::BX_RET:   // Return.
762   case ARM::LDM_RET:
763   case ARM::tBX_RET:
764   case ARM::tBX_RET_vararg:
765   case ARM::tPOP_RET:
766   case ARM::B:
767   case ARM::tB:       // Uncond branch.
768   case ARM::tBR_JTr:
769   case ARM::BR_JTr:   // Jumptable branch.
770   case ARM::BR_JTm:   // Jumptable branch through mem.
771   case ARM::BR_JTadd: // Jumptable branch add to pc.
772     return true;
773   default: return false;
774   }
775 }
776
777 bool ARMInstrInfo::
778 ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
779   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
780   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
781   return false;
782 }
783
784 bool ARMInstrInfo::isPredicated(const MachineInstr *MI) const {
785   int PIdx = MI->findFirstPredOperandIdx();
786   return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
787 }
788
789 bool ARMInstrInfo::PredicateInstruction(MachineInstr *MI,
790                                 const std::vector<MachineOperand> &Pred) const {
791   unsigned Opc = MI->getOpcode();
792   if (Opc == ARM::B || Opc == ARM::tB) {
793     MI->setDesc(get(Opc == ARM::B ? ARM::Bcc : ARM::tBcc));
794     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
795     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
796     return true;
797   }
798
799   int PIdx = MI->findFirstPredOperandIdx();
800   if (PIdx != -1) {
801     MachineOperand &PMO = MI->getOperand(PIdx);
802     PMO.setImm(Pred[0].getImm());
803     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
804     return true;
805   }
806   return false;
807 }
808
809 bool
810 ARMInstrInfo::SubsumesPredicate(const std::vector<MachineOperand> &Pred1,
811                                 const std::vector<MachineOperand> &Pred2) const{
812   if (Pred1.size() > 2 || Pred2.size() > 2)
813     return false;
814
815   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
816   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
817   if (CC1 == CC2)
818     return true;
819
820   switch (CC1) {
821   default:
822     return false;
823   case ARMCC::AL:
824     return true;
825   case ARMCC::HS:
826     return CC2 == ARMCC::HI;
827   case ARMCC::LS:
828     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
829   case ARMCC::GE:
830     return CC2 == ARMCC::GT;
831   case ARMCC::LE:
832     return CC2 == ARMCC::LT;
833   }
834 }
835
836 bool ARMInstrInfo::DefinesPredicate(MachineInstr *MI,
837                                     std::vector<MachineOperand> &Pred) const {
838   const TargetInstrDesc &TID = MI->getDesc();
839   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
840     return false;
841
842   bool Found = false;
843   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
844     const MachineOperand &MO = MI->getOperand(i);
845     if (MO.isRegister() && MO.getReg() == ARM::CPSR) {
846       Pred.push_back(MO);
847       Found = true;
848     }
849   }
850
851   return Found;
852 }
853
854
855 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
856 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
857                                 unsigned JTI) DISABLE_INLINE;
858 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
859                                 unsigned JTI) {
860   return JT[JTI].MBBs.size();
861 }
862
863 /// GetInstSize - Return the size of the specified MachineInstr.
864 ///
865 unsigned ARM::GetInstSize(MachineInstr *MI) {
866   MachineBasicBlock &MBB = *MI->getParent();
867   const MachineFunction *MF = MBB.getParent();
868   const TargetAsmInfo *TAI = MF->getTarget().getTargetAsmInfo();
869
870   // Basic size info comes from the TSFlags field.
871   const TargetInstrDesc &TID = MI->getDesc();
872   unsigned TSFlags = TID.TSFlags;
873   
874   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
875   default:
876     // If this machine instr is an inline asm, measure it.
877     if (MI->getOpcode() == ARM::INLINEASM)
878       return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
879     if (MI->getOpcode() == ARM::LABEL)
880       return 0;
881     assert(0 && "Unknown or unset size field for instr!");
882     break;
883   case ARMII::Size8Bytes: return 8;          // Arm instruction x 2.
884   case ARMII::Size4Bytes: return 4;          // Arm instruction.
885   case ARMII::Size2Bytes: return 2;          // Thumb instruction.
886   case ARMII::SizeSpecial: {
887     switch (MI->getOpcode()) {
888     case ARM::CONSTPOOL_ENTRY:
889       // If this machine instr is a constant pool entry, its size is recorded as
890       // operand #2.
891       return MI->getOperand(2).getImm();
892     case ARM::BR_JTr:
893     case ARM::BR_JTm:
894     case ARM::BR_JTadd:
895     case ARM::tBR_JTr: {
896       // These are jumptable branches, i.e. a branch followed by an inlined
897       // jumptable. The size is 4 + 4 * number of entries.
898       unsigned NumOps = TID.getNumOperands();
899       MachineOperand JTOP =
900         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
901       unsigned JTI = JTOP.getIndex();
902       MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
903       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
904       assert(JTI < JT.size());
905       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
906       // 4 aligned. The assembler / linker may add 2 byte padding just before
907       // the JT entries.  The size does not include this padding; the
908       // constant islands pass does separate bookkeeping for it.
909       // FIXME: If we know the size of the function is less than (1 << 16) *2
910       // bytes, we can use 16-bit entries instead. Then there won't be an
911       // alignment issue.
912       return getNumJTEntries(JT, JTI) * 4 + 
913              (MI->getOpcode()==ARM::tBR_JTr ? 2 : 4);
914     }
915     default:
916       // Otherwise, pseudo-instruction sizes are zero.
917       return 0;
918     }
919   }
920   }
921 }
922
923 /// GetFunctionSize - Returns the size of the specified MachineFunction.
924 ///
925 unsigned ARM::GetFunctionSize(MachineFunction &MF) {
926   unsigned FnSize = 0;
927   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
928        MBBI != E; ++MBBI) {
929     MachineBasicBlock &MBB = *MBBI;
930     for (MachineBasicBlock::iterator I = MBB.begin(),E = MBB.end(); I != E; ++I)
931       FnSize += ARM::GetInstSize(I);
932   }
933   return FnSize;
934 }