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