ARMCodeEmitter.cpp revision 383e846e3abbfb4e09bd7e020a9d46c424755e34
1//===-- ARM/ARMCodeEmitter.cpp - Convert ARM code to machine code ---------===//
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 pass that transforms the ARM machine instructions into
11// relocatable machine code.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
16#include "ARM.h"
17#include "ARMAddressingModes.h"
18#include "ARMConstantPoolValue.h"
19#include "ARMInstrInfo.h"
20#include "ARMRelocations.h"
21#include "ARMSubtarget.h"
22#include "ARMTargetMachine.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Function.h"
26#include "llvm/PassManager.h"
27#include "llvm/CodeGen/JITCodeEmitter.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineJumpTableInfo.h"
32#include "llvm/CodeGen/MachineModuleInfo.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38#ifndef NDEBUG
39#include <iomanip>
40#endif
41using namespace llvm;
42
43STATISTIC(NumEmitted, "Number of machine instructions emitted");
44
45namespace {
46
47  class ARMCodeEmitter : public MachineFunctionPass {
48    ARMJITInfo                *JTI;
49    const ARMInstrInfo        *II;
50    const TargetData          *TD;
51    const ARMSubtarget        *Subtarget;
52    TargetMachine             &TM;
53    JITCodeEmitter            &MCE;
54    MachineModuleInfo *MMI;
55    const std::vector<MachineConstantPoolEntry> *MCPEs;
56    const std::vector<MachineJumpTableEntry> *MJTEs;
57    bool IsPIC;
58
59    void getAnalysisUsage(AnalysisUsage &AU) const {
60      AU.addRequired<MachineModuleInfo>();
61      MachineFunctionPass::getAnalysisUsage(AU);
62    }
63
64    static char ID;
65  public:
66    ARMCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
67      : MachineFunctionPass(&ID), JTI(0),
68        II((const ARMInstrInfo *)tm.getInstrInfo()),
69        TD(tm.getTargetData()), TM(tm),
70    MCE(mce), MCPEs(0), MJTEs(0),
71    IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
72
73    /// getBinaryCodeForInstr - This function, generated by the
74    /// CodeEmitterGenerator using TableGen, produces the binary encoding for
75    /// machine instructions.
76    unsigned getBinaryCodeForInstr(const MachineInstr &MI);
77
78    bool runOnMachineFunction(MachineFunction &MF);
79
80    virtual const char *getPassName() const {
81      return "ARM Machine Code Emitter";
82    }
83
84    void emitInstruction(const MachineInstr &MI);
85
86  private:
87
88    void emitWordLE(unsigned Binary);
89    void emitDWordLE(uint64_t Binary);
90    void emitConstPoolInstruction(const MachineInstr &MI);
91    void emitMOVi32immInstruction(const MachineInstr &MI);
92    void emitMOVi2piecesInstruction(const MachineInstr &MI);
93    void emitLEApcrelJTInstruction(const MachineInstr &MI);
94    void emitPseudoMoveInstruction(const MachineInstr &MI);
95    void addPCLabel(unsigned LabelID);
96    void emitPseudoInstruction(const MachineInstr &MI);
97    unsigned getMachineSoRegOpValue(const MachineInstr &MI,
98                                    const TargetInstrDesc &TID,
99                                    const MachineOperand &MO,
100                                    unsigned OpIdx);
101
102    unsigned getMachineSoImmOpValue(unsigned SoImm);
103
104    unsigned getAddrModeSBit(const MachineInstr &MI,
105                             const TargetInstrDesc &TID) const;
106
107    void emitDataProcessingInstruction(const MachineInstr &MI,
108                                       unsigned ImplicitRd = 0,
109                                       unsigned ImplicitRn = 0);
110
111    void emitLoadStoreInstruction(const MachineInstr &MI,
112                                  unsigned ImplicitRd = 0,
113                                  unsigned ImplicitRn = 0);
114
115    void emitMiscLoadStoreInstruction(const MachineInstr &MI,
116                                      unsigned ImplicitRn = 0);
117
118    void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
119
120    void emitMulFrmInstruction(const MachineInstr &MI);
121
122    void emitExtendInstruction(const MachineInstr &MI);
123
124    void emitMiscArithInstruction(const MachineInstr &MI);
125
126    void emitBranchInstruction(const MachineInstr &MI);
127
128    void emitInlineJumpTable(unsigned JTIndex);
129
130    void emitMiscBranchInstruction(const MachineInstr &MI);
131
132    void emitVFPArithInstruction(const MachineInstr &MI);
133
134    void emitVFPConversionInstruction(const MachineInstr &MI);
135
136    void emitVFPLoadStoreInstruction(const MachineInstr &MI);
137
138    void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
139
140    void emitMiscInstruction(const MachineInstr &MI);
141
142    void emitNEON1RegModImmInstruction(const MachineInstr &MI);
143    void emitNEON2RegInstruction(const MachineInstr &MI);
144    void emitNEON3RegInstruction(const MachineInstr &MI);
145
146    /// getMachineOpValue - Return binary encoding of operand. If the machine
147    /// operand requires relocation, record the relocation and return zero.
148    unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
149    unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
150      return getMachineOpValue(MI, MI.getOperand(OpIdx));
151    }
152
153    /// getMovi32Value - Return binary encoding of operand for movw/movt. If the
154    /// machine operand requires relocation, record the relocation and return
155    /// zero.
156    unsigned getMovi32Value(const MachineInstr &MI,const MachineOperand &MO,
157                            unsigned Reloc);
158    unsigned getMovi32Value(const MachineInstr &MI, unsigned OpIdx,
159                            unsigned Reloc) {
160      return getMovi32Value(MI, MI.getOperand(OpIdx), Reloc);
161    }
162
163    /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
164    ///
165    unsigned getShiftOp(unsigned Imm) const ;
166
167    /// Routines that handle operands which add machine relocations which are
168    /// fixed up by the relocation stage.
169    void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
170                           bool MayNeedFarStub,  bool Indirect,
171                           intptr_t ACPV = 0);
172    void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
173    void emitConstPoolAddress(unsigned CPI, unsigned Reloc);
174    void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc);
175    void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
176                               intptr_t JTBase = 0);
177  };
178}
179
180char ARMCodeEmitter::ID = 0;
181
182/// createARMJITCodeEmitterPass - Return a pass that emits the collected ARM
183/// code to the specified MCE object.
184FunctionPass *llvm::createARMJITCodeEmitterPass(ARMBaseTargetMachine &TM,
185                                                JITCodeEmitter &JCE) {
186  return new ARMCodeEmitter(TM, JCE);
187}
188
189bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
190  assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
191          MF.getTarget().getRelocationModel() != Reloc::Static) &&
192         "JIT relocation model must be set to static or default!");
193  JTI = ((ARMTargetMachine &)MF.getTarget()).getJITInfo();
194  II = ((const ARMTargetMachine &)MF.getTarget()).getInstrInfo();
195  TD = ((const ARMTargetMachine &)MF.getTarget()).getTargetData();
196  Subtarget = &TM.getSubtarget<ARMSubtarget>();
197  MCPEs = &MF.getConstantPool()->getConstants();
198  MJTEs = 0;
199  if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
200  IsPIC = TM.getRelocationModel() == Reloc::PIC_;
201  JTI->Initialize(MF, IsPIC);
202  MMI = &getAnalysis<MachineModuleInfo>();
203  MCE.setModuleInfo(MMI);
204
205  do {
206    DEBUG(errs() << "JITTing function '"
207          << MF.getFunction()->getName() << "'\n");
208    MCE.startFunction(MF);
209    for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
210         MBB != E; ++MBB) {
211      MCE.StartMachineBasicBlock(MBB);
212      for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
213           I != E; ++I)
214        emitInstruction(*I);
215    }
216  } while (MCE.finishFunction(MF));
217
218  return false;
219}
220
221/// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
222///
223unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
224  switch (ARM_AM::getAM2ShiftOpc(Imm)) {
225  default: llvm_unreachable("Unknown shift opc!");
226  case ARM_AM::asr: return 2;
227  case ARM_AM::lsl: return 0;
228  case ARM_AM::lsr: return 1;
229  case ARM_AM::ror:
230  case ARM_AM::rrx: return 3;
231  }
232  return 0;
233}
234
235/// getMovi32Value - Return binary encoding of operand for movw/movt. If the
236/// machine operand requires relocation, record the relocation and return zero.
237unsigned ARMCodeEmitter::getMovi32Value(const MachineInstr &MI,
238                                        const MachineOperand &MO,
239                                        unsigned Reloc) {
240  assert(((Reloc == ARM::reloc_arm_movt) || (Reloc == ARM::reloc_arm_movw))
241      && "Relocation to this function should be for movt or movw");
242
243  if (MO.isImm())
244    return static_cast<unsigned>(MO.getImm());
245  else if (MO.isGlobal())
246    emitGlobalAddress(MO.getGlobal(), Reloc, true, false);
247  else if (MO.isSymbol())
248    emitExternalSymbolAddress(MO.getSymbolName(), Reloc);
249  else if (MO.isMBB())
250    emitMachineBasicBlock(MO.getMBB(), Reloc);
251  else {
252#ifndef NDEBUG
253    errs() << MO;
254#endif
255    llvm_unreachable("Unsupported operand type for movw/movt");
256  }
257  return 0;
258}
259
260/// getMachineOpValue - Return binary encoding of operand. If the machine
261/// operand requires relocation, record the relocation and return zero.
262unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
263                                           const MachineOperand &MO) {
264  if (MO.isReg())
265    return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
266  else if (MO.isImm())
267    return static_cast<unsigned>(MO.getImm());
268  else if (MO.isGlobal())
269    emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true, false);
270  else if (MO.isSymbol())
271    emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
272  else if (MO.isCPI()) {
273    const TargetInstrDesc &TID = MI.getDesc();
274    // For VFP load, the immediate offset is multiplied by 4.
275    unsigned Reloc =  ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
276      ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
277    emitConstPoolAddress(MO.getIndex(), Reloc);
278  } else if (MO.isJTI())
279    emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
280  else if (MO.isMBB())
281    emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
282  else {
283#ifndef NDEBUG
284    errs() << MO;
285#endif
286    llvm_unreachable(0);
287  }
288  return 0;
289}
290
291/// emitGlobalAddress - Emit the specified address to the code stream.
292///
293void ARMCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
294                                       bool MayNeedFarStub, bool Indirect,
295                                       intptr_t ACPV) {
296  MachineRelocation MR = Indirect
297    ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
298                                           const_cast<GlobalValue *>(GV),
299                                           ACPV, MayNeedFarStub)
300    : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
301                               const_cast<GlobalValue *>(GV), ACPV,
302                               MayNeedFarStub);
303  MCE.addRelocation(MR);
304}
305
306/// emitExternalSymbolAddress - Arrange for the address of an external symbol to
307/// be emitted to the current location in the function, and allow it to be PC
308/// relative.
309void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
310  MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
311                                                 Reloc, ES));
312}
313
314/// emitConstPoolAddress - Arrange for the address of an constant pool
315/// to be emitted to the current location in the function, and allow it to be PC
316/// relative.
317void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) {
318  // Tell JIT emitter we'll resolve the address.
319  MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
320                                                    Reloc, CPI, 0, true));
321}
322
323/// emitJumpTableAddress - Arrange for the address of a jump table to
324/// be emitted to the current location in the function, and allow it to be PC
325/// relative.
326void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) {
327  MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
328                                                    Reloc, JTIndex, 0, true));
329}
330
331/// emitMachineBasicBlock - Emit the specified address basic block.
332void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
333                                           unsigned Reloc, intptr_t JTBase) {
334  MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
335                                             Reloc, BB, JTBase));
336}
337
338void ARMCodeEmitter::emitWordLE(unsigned Binary) {
339  DEBUG(errs() << "  0x";
340        errs().write_hex(Binary) << "\n");
341  MCE.emitWordLE(Binary);
342}
343
344void ARMCodeEmitter::emitDWordLE(uint64_t Binary) {
345  DEBUG(errs() << "  0x";
346        errs().write_hex(Binary) << "\n");
347  MCE.emitDWordLE(Binary);
348}
349
350void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
351  DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI);
352
353  MCE.processDebugLoc(MI.getDebugLoc(), true);
354
355  ++NumEmitted;  // Keep track of the # of mi's emitted
356  switch (MI.getDesc().TSFlags & ARMII::FormMask) {
357  default: {
358    llvm_unreachable("Unhandled instruction encoding format!");
359    break;
360  }
361  case ARMII::Pseudo:
362    emitPseudoInstruction(MI);
363    break;
364  case ARMII::DPFrm:
365  case ARMII::DPSoRegFrm:
366    emitDataProcessingInstruction(MI);
367    break;
368  case ARMII::LdFrm:
369  case ARMII::StFrm:
370    emitLoadStoreInstruction(MI);
371    break;
372  case ARMII::LdMiscFrm:
373  case ARMII::StMiscFrm:
374    emitMiscLoadStoreInstruction(MI);
375    break;
376  case ARMII::LdStMulFrm:
377    emitLoadStoreMultipleInstruction(MI);
378    break;
379  case ARMII::MulFrm:
380    emitMulFrmInstruction(MI);
381    break;
382  case ARMII::ExtFrm:
383    emitExtendInstruction(MI);
384    break;
385  case ARMII::ArithMiscFrm:
386    emitMiscArithInstruction(MI);
387    break;
388  case ARMII::BrFrm:
389    emitBranchInstruction(MI);
390    break;
391  case ARMII::BrMiscFrm:
392    emitMiscBranchInstruction(MI);
393    break;
394  // VFP instructions.
395  case ARMII::VFPUnaryFrm:
396  case ARMII::VFPBinaryFrm:
397    emitVFPArithInstruction(MI);
398    break;
399  case ARMII::VFPConv1Frm:
400  case ARMII::VFPConv2Frm:
401  case ARMII::VFPConv3Frm:
402  case ARMII::VFPConv4Frm:
403  case ARMII::VFPConv5Frm:
404    emitVFPConversionInstruction(MI);
405    break;
406  case ARMII::VFPLdStFrm:
407    emitVFPLoadStoreInstruction(MI);
408    break;
409  case ARMII::VFPLdStMulFrm:
410    emitVFPLoadStoreMultipleInstruction(MI);
411    break;
412  case ARMII::VFPMiscFrm:
413    emitMiscInstruction(MI);
414    break;
415  // NEON instructions.
416  case ARMII::N1RegModImmFrm:
417    emitNEON1RegModImmInstruction(MI);
418    break;
419  case ARMII::N2RegFrm:
420    emitNEON2RegInstruction(MI);
421    break;
422  case ARMII::N3RegFrm:
423    emitNEON3RegInstruction(MI);
424    break;
425  }
426  MCE.processDebugLoc(MI.getDebugLoc(), false);
427}
428
429void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
430  unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
431  unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
432  const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
433
434  // Remember the CONSTPOOL_ENTRY address for later relocation.
435  JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
436
437  // Emit constpool island entry. In most cases, the actual values will be
438  // resolved and relocated after code emission.
439  if (MCPE.isMachineConstantPoolEntry()) {
440    ARMConstantPoolValue *ACPV =
441      static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
442
443    DEBUG(errs() << "  ** ARM constant pool #" << CPI << " @ "
444          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n');
445
446    assert(ACPV->isGlobalValue() && "unsupported constant pool value");
447    const GlobalValue *GV = ACPV->getGV();
448    if (GV) {
449      Reloc::Model RelocM = TM.getRelocationModel();
450      emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
451                        isa<Function>(GV),
452                        Subtarget->GVIsIndirectSymbol(GV, RelocM),
453                        (intptr_t)ACPV);
454     } else  {
455      emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
456    }
457    emitWordLE(0);
458  } else {
459    const Constant *CV = MCPE.Val.ConstVal;
460
461    DEBUG({
462        errs() << "  ** Constant pool #" << CPI << " @ "
463               << (void*)MCE.getCurrentPCValue() << " ";
464        if (const Function *F = dyn_cast<Function>(CV))
465          errs() << F->getName();
466        else
467          errs() << *CV;
468        errs() << '\n';
469      });
470
471    if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
472      emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV), false);
473      emitWordLE(0);
474    } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
475      uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
476      emitWordLE(Val);
477    } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
478      if (CFP->getType()->isFloatTy())
479        emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
480      else if (CFP->getType()->isDoubleTy())
481        emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
482      else {
483        llvm_unreachable("Unable to handle this constantpool entry!");
484      }
485    } else {
486      llvm_unreachable("Unable to handle this constantpool entry!");
487    }
488  }
489}
490
491void ARMCodeEmitter::emitMOVi32immInstruction(const MachineInstr &MI) {
492  const MachineOperand &MO0 = MI.getOperand(0);
493  const MachineOperand &MO1 = MI.getOperand(1);
494
495  // Emit the 'movw' instruction.
496  unsigned Binary = 0x30 << 20;  // mov: Insts{27-20} = 0b00110000
497
498  unsigned Lo16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movw) & 0xFFFF;
499
500  // Set the conditional execution predicate.
501  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
502
503  // Encode Rd.
504  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
505
506  // Encode imm16 as imm4:imm12
507  Binary |= Lo16 & 0xFFF; // Insts{11-0} = imm12
508  Binary |= ((Lo16 >> 12) & 0xF) << 16; // Insts{19-16} = imm4
509  emitWordLE(Binary);
510
511  unsigned Hi16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movt) >> 16;
512  // Emit the 'movt' instruction.
513  Binary = 0x34 << 20; // movt: Insts{27-20} = 0b00110100
514
515  // Set the conditional execution predicate.
516  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
517
518  // Encode Rd.
519  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
520
521  // Encode imm16 as imm4:imm1, same as movw above.
522  Binary |= Hi16 & 0xFFF;
523  Binary |= ((Hi16 >> 12) & 0xF) << 16;
524  emitWordLE(Binary);
525}
526
527void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
528  const MachineOperand &MO0 = MI.getOperand(0);
529  const MachineOperand &MO1 = MI.getOperand(1);
530  assert(MO1.isImm() && ARM_AM::isSOImmTwoPartVal(MO1.getImm()) &&
531                                                  "Not a valid so_imm value!");
532  unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
533  unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
534
535  // Emit the 'mov' instruction.
536  unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
537
538  // Set the conditional execution predicate.
539  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
540
541  // Encode Rd.
542  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
543
544  // Encode so_imm.
545  // Set bit I(25) to identify this is the immediate form of <shifter_op>
546  Binary |= 1 << ARMII::I_BitShift;
547  Binary |= getMachineSoImmOpValue(V1);
548  emitWordLE(Binary);
549
550  // Now the 'orr' instruction.
551  Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
552
553  // Set the conditional execution predicate.
554  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
555
556  // Encode Rd.
557  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
558
559  // Encode Rn.
560  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
561
562  // Encode so_imm.
563  // Set bit I(25) to identify this is the immediate form of <shifter_op>
564  Binary |= 1 << ARMII::I_BitShift;
565  Binary |= getMachineSoImmOpValue(V2);
566  emitWordLE(Binary);
567}
568
569void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
570  // It's basically add r, pc, (LJTI - $+8)
571
572  const TargetInstrDesc &TID = MI.getDesc();
573
574  // Emit the 'add' instruction.
575  unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
576
577  // Set the conditional execution predicate
578  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
579
580  // Encode S bit if MI modifies CPSR.
581  Binary |= getAddrModeSBit(MI, TID);
582
583  // Encode Rd.
584  Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
585
586  // Encode Rn which is PC.
587  Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
588
589  // Encode the displacement.
590  Binary |= 1 << ARMII::I_BitShift;
591  emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
592
593  emitWordLE(Binary);
594}
595
596void ARMCodeEmitter::emitPseudoMoveInstruction(const MachineInstr &MI) {
597  unsigned Opcode = MI.getDesc().Opcode;
598
599  // Part of binary is determined by TableGn.
600  unsigned Binary = getBinaryCodeForInstr(MI);
601
602  // Set the conditional execution predicate
603  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
604
605  // Encode S bit if MI modifies CPSR.
606  if (Opcode == ARM::MOVsrl_flag || Opcode == ARM::MOVsra_flag)
607    Binary |= 1 << ARMII::S_BitShift;
608
609  // Encode register def if there is one.
610  Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
611
612  // Encode the shift operation.
613  switch (Opcode) {
614  default: break;
615  case ARM::MOVrx:
616    // rrx
617    Binary |= 0x6 << 4;
618    break;
619  case ARM::MOVsrl_flag:
620    // lsr #1
621    Binary |= (0x2 << 4) | (1 << 7);
622    break;
623  case ARM::MOVsra_flag:
624    // asr #1
625    Binary |= (0x4 << 4) | (1 << 7);
626    break;
627  }
628
629  // Encode register Rm.
630  Binary |= getMachineOpValue(MI, 1);
631
632  emitWordLE(Binary);
633}
634
635void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
636  DEBUG(errs() << "  ** LPC" << LabelID << " @ "
637        << (void*)MCE.getCurrentPCValue() << '\n');
638  JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
639}
640
641void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
642  unsigned Opcode = MI.getDesc().Opcode;
643  switch (Opcode) {
644  default:
645    llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");
646  case TargetOpcode::INLINEASM: {
647    // We allow inline assembler nodes with empty bodies - they can
648    // implicitly define registers, which is ok for JIT.
649    if (MI.getOperand(0).getSymbolName()[0]) {
650      report_fatal_error("JIT does not support inline asm!");
651    }
652    break;
653  }
654  case TargetOpcode::DBG_LABEL:
655  case TargetOpcode::EH_LABEL:
656    MCE.emitLabel(MI.getOperand(0).getMCSymbol());
657    break;
658  case TargetOpcode::IMPLICIT_DEF:
659  case TargetOpcode::KILL:
660    // Do nothing.
661    break;
662  case ARM::CONSTPOOL_ENTRY:
663    emitConstPoolInstruction(MI);
664    break;
665  case ARM::PICADD: {
666    // Remember of the address of the PC label for relocation later.
667    addPCLabel(MI.getOperand(2).getImm());
668    // PICADD is just an add instruction that implicitly read pc.
669    emitDataProcessingInstruction(MI, 0, ARM::PC);
670    break;
671  }
672  case ARM::PICLDR:
673  case ARM::PICLDRB:
674  case ARM::PICSTR:
675  case ARM::PICSTRB: {
676    // Remember of the address of the PC label for relocation later.
677    addPCLabel(MI.getOperand(2).getImm());
678    // These are just load / store instructions that implicitly read pc.
679    emitLoadStoreInstruction(MI, 0, ARM::PC);
680    break;
681  }
682  case ARM::PICLDRH:
683  case ARM::PICLDRSH:
684  case ARM::PICLDRSB:
685  case ARM::PICSTRH: {
686    // Remember of the address of the PC label for relocation later.
687    addPCLabel(MI.getOperand(2).getImm());
688    // These are just load / store instructions that implicitly read pc.
689    emitMiscLoadStoreInstruction(MI, ARM::PC);
690    break;
691  }
692
693  case ARM::MOVi32imm:
694    emitMOVi32immInstruction(MI);
695    break;
696
697  case ARM::MOVi2pieces:
698    // Two instructions to materialize a constant.
699    emitMOVi2piecesInstruction(MI);
700    break;
701  case ARM::LEApcrelJT:
702    // Materialize jumptable address.
703    emitLEApcrelJTInstruction(MI);
704    break;
705  case ARM::MOVrx:
706  case ARM::MOVsrl_flag:
707  case ARM::MOVsra_flag:
708    emitPseudoMoveInstruction(MI);
709    break;
710  }
711}
712
713unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
714                                                const TargetInstrDesc &TID,
715                                                const MachineOperand &MO,
716                                                unsigned OpIdx) {
717  unsigned Binary = getMachineOpValue(MI, MO);
718
719  const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
720  const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
721  ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
722
723  // Encode the shift opcode.
724  unsigned SBits = 0;
725  unsigned Rs = MO1.getReg();
726  if (Rs) {
727    // Set shift operand (bit[7:4]).
728    // LSL - 0001
729    // LSR - 0011
730    // ASR - 0101
731    // ROR - 0111
732    // RRX - 0110 and bit[11:8] clear.
733    switch (SOpc) {
734    default: llvm_unreachable("Unknown shift opc!");
735    case ARM_AM::lsl: SBits = 0x1; break;
736    case ARM_AM::lsr: SBits = 0x3; break;
737    case ARM_AM::asr: SBits = 0x5; break;
738    case ARM_AM::ror: SBits = 0x7; break;
739    case ARM_AM::rrx: SBits = 0x6; break;
740    }
741  } else {
742    // Set shift operand (bit[6:4]).
743    // LSL - 000
744    // LSR - 010
745    // ASR - 100
746    // ROR - 110
747    switch (SOpc) {
748    default: llvm_unreachable("Unknown shift opc!");
749    case ARM_AM::lsl: SBits = 0x0; break;
750    case ARM_AM::lsr: SBits = 0x2; break;
751    case ARM_AM::asr: SBits = 0x4; break;
752    case ARM_AM::ror: SBits = 0x6; break;
753    }
754  }
755  Binary |= SBits << 4;
756  if (SOpc == ARM_AM::rrx)
757    return Binary;
758
759  // Encode the shift operation Rs or shift_imm (except rrx).
760  if (Rs) {
761    // Encode Rs bit[11:8].
762    assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
763    return Binary |
764      (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
765  }
766
767  // Encode shift_imm bit[11:7].
768  return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
769}
770
771unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
772  int SoImmVal = ARM_AM::getSOImmVal(SoImm);
773  assert(SoImmVal != -1 && "Not a valid so_imm value!");
774
775  // Encode rotate_imm.
776  unsigned Binary = (ARM_AM::getSOImmValRot((unsigned)SoImmVal) >> 1)
777    << ARMII::SoRotImmShift;
778
779  // Encode immed_8.
780  Binary |= ARM_AM::getSOImmValImm((unsigned)SoImmVal);
781  return Binary;
782}
783
784unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
785                                         const TargetInstrDesc &TID) const {
786  for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
787    const MachineOperand &MO = MI.getOperand(i-1);
788    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
789      return 1 << ARMII::S_BitShift;
790  }
791  return 0;
792}
793
794void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
795                                                   unsigned ImplicitRd,
796                                                   unsigned ImplicitRn) {
797  const TargetInstrDesc &TID = MI.getDesc();
798
799  // Part of binary is determined by TableGn.
800  unsigned Binary = getBinaryCodeForInstr(MI);
801
802  // Set the conditional execution predicate
803  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
804
805  // Encode S bit if MI modifies CPSR.
806  Binary |= getAddrModeSBit(MI, TID);
807
808  // Encode register def if there is one.
809  unsigned NumDefs = TID.getNumDefs();
810  unsigned OpIdx = 0;
811  if (NumDefs)
812    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
813  else if (ImplicitRd)
814    // Special handling for implicit use (e.g. PC).
815    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
816               << ARMII::RegRdShift);
817
818  if (TID.Opcode == ARM::MOVi16) {
819      // Get immediate from MI.
820      unsigned Lo16 = getMovi32Value(MI, MI.getOperand(OpIdx),
821                      ARM::reloc_arm_movw);
822      // Encode imm which is the same as in emitMOVi32immInstruction().
823      Binary |= Lo16 & 0xFFF;
824      Binary |= ((Lo16 >> 12) & 0xF) << 16;
825      emitWordLE(Binary);
826      return;
827  } else if(TID.Opcode == ARM::MOVTi16) {
828      unsigned Hi16 = (getMovi32Value(MI, MI.getOperand(OpIdx),
829                       ARM::reloc_arm_movt) >> 16);
830      Binary |= Hi16 & 0xFFF;
831      Binary |= ((Hi16 >> 12) & 0xF) << 16;
832      emitWordLE(Binary);
833      return;
834  } else if ((TID.Opcode == ARM::BFC) || (TID.Opcode == ARM::BFI)) {
835      uint32_t v = ~MI.getOperand(2).getImm();
836      int32_t lsb = CountTrailingZeros_32(v);
837      int32_t msb = (32 - CountLeadingZeros_32(v)) - 1;
838      // Instr{20-16} = msb, Instr{11-7} = lsb
839      Binary |= (msb & 0x1F) << 16;
840      Binary |= (lsb & 0x1F) << 7;
841      emitWordLE(Binary);
842      return;
843  } else if ((TID.Opcode == ARM::UBFX) || (TID.Opcode == ARM::SBFX)) {
844      // Encode Rn in Instr{0-3}
845      Binary |= getMachineOpValue(MI, OpIdx++);
846
847      uint32_t lsb = MI.getOperand(OpIdx++).getImm();
848      uint32_t widthm1 = MI.getOperand(OpIdx++).getImm() - 1;
849
850      // Instr{20-16} = widthm1, Instr{11-7} = lsb
851      Binary |= (widthm1 & 0x1F) << 16;
852      Binary |= (lsb & 0x1F) << 7;
853      emitWordLE(Binary);
854      return;
855  }
856
857  // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
858  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
859    ++OpIdx;
860
861  // Encode first non-shifter register operand if there is one.
862  bool isUnary = TID.TSFlags & ARMII::UnaryDP;
863  if (!isUnary) {
864    if (ImplicitRn)
865      // Special handling for implicit use (e.g. PC).
866      Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
867                 << ARMII::RegRnShift);
868    else {
869      Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
870      ++OpIdx;
871    }
872  }
873
874  // Encode shifter operand.
875  const MachineOperand &MO = MI.getOperand(OpIdx);
876  if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
877    // Encode SoReg.
878    emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
879    return;
880  }
881
882  if (MO.isReg()) {
883    // Encode register Rm.
884    emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
885    return;
886  }
887
888  // Encode so_imm.
889  Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
890
891  emitWordLE(Binary);
892}
893
894void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
895                                              unsigned ImplicitRd,
896                                              unsigned ImplicitRn) {
897  const TargetInstrDesc &TID = MI.getDesc();
898  unsigned Form = TID.TSFlags & ARMII::FormMask;
899  bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
900
901  // Part of binary is determined by TableGn.
902  unsigned Binary = getBinaryCodeForInstr(MI);
903
904  // Set the conditional execution predicate
905  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
906
907  unsigned OpIdx = 0;
908
909  // Operand 0 of a pre- and post-indexed store is the address base
910  // writeback. Skip it.
911  bool Skipped = false;
912  if (IsPrePost && Form == ARMII::StFrm) {
913    ++OpIdx;
914    Skipped = true;
915  }
916
917  // Set first operand
918  if (ImplicitRd)
919    // Special handling for implicit use (e.g. PC).
920    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
921               << ARMII::RegRdShift);
922  else
923    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
924
925  // Set second operand
926  if (ImplicitRn)
927    // Special handling for implicit use (e.g. PC).
928    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
929               << ARMII::RegRnShift);
930  else
931    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
932
933  // If this is a two-address operand, skip it. e.g. LDR_PRE.
934  if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
935    ++OpIdx;
936
937  const MachineOperand &MO2 = MI.getOperand(OpIdx);
938  unsigned AM2Opc = (ImplicitRn == ARM::PC)
939    ? 0 : MI.getOperand(OpIdx+1).getImm();
940
941  // Set bit U(23) according to sign of immed value (positive or negative).
942  Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
943             ARMII::U_BitShift);
944  if (!MO2.getReg()) { // is immediate
945    if (ARM_AM::getAM2Offset(AM2Opc))
946      // Set the value of offset_12 field
947      Binary |= ARM_AM::getAM2Offset(AM2Opc);
948    emitWordLE(Binary);
949    return;
950  }
951
952  // Set bit I(25), because this is not in immediate enconding.
953  Binary |= 1 << ARMII::I_BitShift;
954  assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
955  // Set bit[3:0] to the corresponding Rm register
956  Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
957
958  // If this instr is in scaled register offset/index instruction, set
959  // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
960  if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
961    Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
962    Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
963  }
964
965  emitWordLE(Binary);
966}
967
968void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
969                                                  unsigned ImplicitRn) {
970  const TargetInstrDesc &TID = MI.getDesc();
971  unsigned Form = TID.TSFlags & ARMII::FormMask;
972  bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
973
974  // Part of binary is determined by TableGn.
975  unsigned Binary = getBinaryCodeForInstr(MI);
976
977  // Set the conditional execution predicate
978  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
979
980  unsigned OpIdx = 0;
981
982  // Operand 0 of a pre- and post-indexed store is the address base
983  // writeback. Skip it.
984  bool Skipped = false;
985  if (IsPrePost && Form == ARMII::StMiscFrm) {
986    ++OpIdx;
987    Skipped = true;
988  }
989
990  // Set first operand
991  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
992
993  // Skip LDRD and STRD's second operand.
994  if (TID.Opcode == ARM::LDRD || TID.Opcode == ARM::STRD)
995    ++OpIdx;
996
997  // Set second operand
998  if (ImplicitRn)
999    // Special handling for implicit use (e.g. PC).
1000    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
1001               << ARMII::RegRnShift);
1002  else
1003    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1004
1005  // If this is a two-address operand, skip it. e.g. LDRH_POST.
1006  if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1007    ++OpIdx;
1008
1009  const MachineOperand &MO2 = MI.getOperand(OpIdx);
1010  unsigned AM3Opc = (ImplicitRn == ARM::PC)
1011    ? 0 : MI.getOperand(OpIdx+1).getImm();
1012
1013  // Set bit U(23) according to sign of immed value (positive or negative)
1014  Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
1015             ARMII::U_BitShift);
1016
1017  // If this instr is in register offset/index encoding, set bit[3:0]
1018  // to the corresponding Rm register.
1019  if (MO2.getReg()) {
1020    Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
1021    emitWordLE(Binary);
1022    return;
1023  }
1024
1025  // This instr is in immediate offset/index encoding, set bit 22 to 1.
1026  Binary |= 1 << ARMII::AM3_I_BitShift;
1027  if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
1028    // Set operands
1029    Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
1030    Binary |= (ImmOffs & 0xF);                      // immedL
1031  }
1032
1033  emitWordLE(Binary);
1034}
1035
1036static unsigned getAddrModeUPBits(unsigned Mode) {
1037  unsigned Binary = 0;
1038
1039  // Set addressing mode by modifying bits U(23) and P(24)
1040  // IA - Increment after  - bit U = 1 and bit P = 0
1041  // IB - Increment before - bit U = 1 and bit P = 1
1042  // DA - Decrement after  - bit U = 0 and bit P = 0
1043  // DB - Decrement before - bit U = 0 and bit P = 1
1044  switch (Mode) {
1045  default: llvm_unreachable("Unknown addressing sub-mode!");
1046  case ARM_AM::da:                                     break;
1047  case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
1048  case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
1049  case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
1050  }
1051
1052  return Binary;
1053}
1054
1055void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
1056  const TargetInstrDesc &TID = MI.getDesc();
1057  bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1058
1059  // Part of binary is determined by TableGn.
1060  unsigned Binary = getBinaryCodeForInstr(MI);
1061
1062  // Set the conditional execution predicate
1063  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1064
1065  // Skip operand 0 of an instruction with base register update.
1066  unsigned OpIdx = 0;
1067  if (IsUpdating)
1068    ++OpIdx;
1069
1070  // Set base address operand
1071  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1072
1073  // Set addressing mode by modifying bits U(23) and P(24)
1074  const MachineOperand &MO = MI.getOperand(OpIdx++);
1075  Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
1076
1077  // Set bit W(21)
1078  if (IsUpdating)
1079    Binary |= 0x1 << ARMII::W_BitShift;
1080
1081  // Set registers
1082  for (unsigned i = OpIdx+2, e = MI.getNumOperands(); i != e; ++i) {
1083    const MachineOperand &MO = MI.getOperand(i);
1084    if (!MO.isReg() || MO.isImplicit())
1085      break;
1086    unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
1087    assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
1088           RegNum < 16);
1089    Binary |= 0x1 << RegNum;
1090  }
1091
1092  emitWordLE(Binary);
1093}
1094
1095void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
1096  const TargetInstrDesc &TID = MI.getDesc();
1097
1098  // Part of binary is determined by TableGn.
1099  unsigned Binary = getBinaryCodeForInstr(MI);
1100
1101  // Set the conditional execution predicate
1102  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1103
1104  // Encode S bit if MI modifies CPSR.
1105  Binary |= getAddrModeSBit(MI, TID);
1106
1107  // 32x32->64bit operations have two destination registers. The number
1108  // of register definitions will tell us if that's what we're dealing with.
1109  unsigned OpIdx = 0;
1110  if (TID.getNumDefs() == 2)
1111    Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
1112
1113  // Encode Rd
1114  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
1115
1116  // Encode Rm
1117  Binary |= getMachineOpValue(MI, OpIdx++);
1118
1119  // Encode Rs
1120  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
1121
1122  // Many multiple instructions (e.g. MLA) have three src operands. Encode
1123  // it as Rn (for multiply, that's in the same offset as RdLo.
1124  if (TID.getNumOperands() > OpIdx &&
1125      !TID.OpInfo[OpIdx].isPredicate() &&
1126      !TID.OpInfo[OpIdx].isOptionalDef())
1127    Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1128
1129  emitWordLE(Binary);
1130}
1131
1132void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
1133  const TargetInstrDesc &TID = MI.getDesc();
1134
1135  // Part of binary is determined by TableGn.
1136  unsigned Binary = getBinaryCodeForInstr(MI);
1137
1138  // Set the conditional execution predicate
1139  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1140
1141  unsigned OpIdx = 0;
1142
1143  // Encode Rd
1144  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1145
1146  const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1147  const MachineOperand &MO2 = MI.getOperand(OpIdx);
1148  if (MO2.isReg()) {
1149    // Two register operand form.
1150    // Encode Rn.
1151    Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1152
1153    // Encode Rm.
1154    Binary |= getMachineOpValue(MI, MO2);
1155    ++OpIdx;
1156  } else {
1157    Binary |= getMachineOpValue(MI, MO1);
1158  }
1159
1160  // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1161  if (MI.getOperand(OpIdx).isImm() &&
1162      !TID.OpInfo[OpIdx].isPredicate() &&
1163      !TID.OpInfo[OpIdx].isOptionalDef())
1164    Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1165
1166  emitWordLE(Binary);
1167}
1168
1169void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
1170  const TargetInstrDesc &TID = MI.getDesc();
1171
1172  // Part of binary is determined by TableGn.
1173  unsigned Binary = getBinaryCodeForInstr(MI);
1174
1175  // Set the conditional execution predicate
1176  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1177
1178  unsigned OpIdx = 0;
1179
1180  // Encode Rd
1181  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1182
1183  const MachineOperand &MO = MI.getOperand(OpIdx++);
1184  if (OpIdx == TID.getNumOperands() ||
1185      TID.OpInfo[OpIdx].isPredicate() ||
1186      TID.OpInfo[OpIdx].isOptionalDef()) {
1187    // Encode Rm and it's done.
1188    Binary |= getMachineOpValue(MI, MO);
1189    emitWordLE(Binary);
1190    return;
1191  }
1192
1193  // Encode Rn.
1194  Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1195
1196  // Encode Rm.
1197  Binary |= getMachineOpValue(MI, OpIdx++);
1198
1199  // Encode shift_imm.
1200  unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1201  assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1202  Binary |= ShiftAmt << ARMII::ShiftShift;
1203
1204  emitWordLE(Binary);
1205}
1206
1207void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
1208  const TargetInstrDesc &TID = MI.getDesc();
1209
1210  if (TID.Opcode == ARM::TPsoft) {
1211    llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1212  }
1213
1214  // Part of binary is determined by TableGn.
1215  unsigned Binary = getBinaryCodeForInstr(MI);
1216
1217  // Set the conditional execution predicate
1218  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1219
1220  // Set signed_immed_24 field
1221  Binary |= getMachineOpValue(MI, 0);
1222
1223  emitWordLE(Binary);
1224}
1225
1226void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1227  // Remember the base address of the inline jump table.
1228  uintptr_t JTBase = MCE.getCurrentPCValue();
1229  JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1230  DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1231               << '\n');
1232
1233  // Now emit the jump table entries.
1234  const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1235  for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1236    if (IsPIC)
1237      // DestBB address - JT base.
1238      emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1239    else
1240      // Absolute DestBB address.
1241      emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1242    emitWordLE(0);
1243  }
1244}
1245
1246void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1247  const TargetInstrDesc &TID = MI.getDesc();
1248
1249  // Handle jump tables.
1250  if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1251    // First emit a ldr pc, [] instruction.
1252    emitDataProcessingInstruction(MI, ARM::PC);
1253
1254    // Then emit the inline jump table.
1255    unsigned JTIndex =
1256      (TID.Opcode == ARM::BR_JTr)
1257      ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1258    emitInlineJumpTable(JTIndex);
1259    return;
1260  } else if (TID.Opcode == ARM::BR_JTm) {
1261    // First emit a ldr pc, [] instruction.
1262    emitLoadStoreInstruction(MI, ARM::PC);
1263
1264    // Then emit the inline jump table.
1265    emitInlineJumpTable(MI.getOperand(3).getIndex());
1266    return;
1267  }
1268
1269  // Part of binary is determined by TableGn.
1270  unsigned Binary = getBinaryCodeForInstr(MI);
1271
1272  // Set the conditional execution predicate
1273  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1274
1275  if (TID.Opcode == ARM::BX_RET || TID.Opcode == ARM::MOVPCLR)
1276    // The return register is LR.
1277    Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
1278  else
1279    // otherwise, set the return register
1280    Binary |= getMachineOpValue(MI, 0);
1281
1282  emitWordLE(Binary);
1283}
1284
1285static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1286  unsigned RegD = MI.getOperand(OpIdx).getReg();
1287  unsigned Binary = 0;
1288  bool isSPVFP = false;
1289  RegD = ARMRegisterInfo::getRegisterNumbering(RegD, &isSPVFP);
1290  if (!isSPVFP)
1291    Binary |=   RegD               << ARMII::RegRdShift;
1292  else {
1293    Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1294    Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1295  }
1296  return Binary;
1297}
1298
1299static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1300  unsigned RegN = MI.getOperand(OpIdx).getReg();
1301  unsigned Binary = 0;
1302  bool isSPVFP = false;
1303  RegN = ARMRegisterInfo::getRegisterNumbering(RegN, &isSPVFP);
1304  if (!isSPVFP)
1305    Binary |=   RegN               << ARMII::RegRnShift;
1306  else {
1307    Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1308    Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1309  }
1310  return Binary;
1311}
1312
1313static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1314  unsigned RegM = MI.getOperand(OpIdx).getReg();
1315  unsigned Binary = 0;
1316  bool isSPVFP = false;
1317  RegM = ARMRegisterInfo::getRegisterNumbering(RegM, &isSPVFP);
1318  if (!isSPVFP)
1319    Binary |=   RegM;
1320  else {
1321    Binary |= ((RegM & 0x1E) >> 1);
1322    Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1323  }
1324  return Binary;
1325}
1326
1327void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1328  const TargetInstrDesc &TID = MI.getDesc();
1329
1330  // Part of binary is determined by TableGn.
1331  unsigned Binary = getBinaryCodeForInstr(MI);
1332
1333  // Set the conditional execution predicate
1334  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1335
1336  unsigned OpIdx = 0;
1337  assert((Binary & ARMII::D_BitShift) == 0 &&
1338         (Binary & ARMII::N_BitShift) == 0 &&
1339         (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1340
1341  // Encode Dd / Sd.
1342  Binary |= encodeVFPRd(MI, OpIdx++);
1343
1344  // If this is a two-address operand, skip it, e.g. FMACD.
1345  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1346    ++OpIdx;
1347
1348  // Encode Dn / Sn.
1349  if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1350    Binary |= encodeVFPRn(MI, OpIdx++);
1351
1352  if (OpIdx == TID.getNumOperands() ||
1353      TID.OpInfo[OpIdx].isPredicate() ||
1354      TID.OpInfo[OpIdx].isOptionalDef()) {
1355    // FCMPEZD etc. has only one operand.
1356    emitWordLE(Binary);
1357    return;
1358  }
1359
1360  // Encode Dm / Sm.
1361  Binary |= encodeVFPRm(MI, OpIdx);
1362
1363  emitWordLE(Binary);
1364}
1365
1366void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1367  const TargetInstrDesc &TID = MI.getDesc();
1368  unsigned Form = TID.TSFlags & ARMII::FormMask;
1369
1370  // Part of binary is determined by TableGn.
1371  unsigned Binary = getBinaryCodeForInstr(MI);
1372
1373  // Set the conditional execution predicate
1374  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1375
1376  switch (Form) {
1377  default: break;
1378  case ARMII::VFPConv1Frm:
1379  case ARMII::VFPConv2Frm:
1380  case ARMII::VFPConv3Frm:
1381    // Encode Dd / Sd.
1382    Binary |= encodeVFPRd(MI, 0);
1383    break;
1384  case ARMII::VFPConv4Frm:
1385    // Encode Dn / Sn.
1386    Binary |= encodeVFPRn(MI, 0);
1387    break;
1388  case ARMII::VFPConv5Frm:
1389    // Encode Dm / Sm.
1390    Binary |= encodeVFPRm(MI, 0);
1391    break;
1392  }
1393
1394  switch (Form) {
1395  default: break;
1396  case ARMII::VFPConv1Frm:
1397    // Encode Dm / Sm.
1398    Binary |= encodeVFPRm(MI, 1);
1399    break;
1400  case ARMII::VFPConv2Frm:
1401  case ARMII::VFPConv3Frm:
1402    // Encode Dn / Sn.
1403    Binary |= encodeVFPRn(MI, 1);
1404    break;
1405  case ARMII::VFPConv4Frm:
1406  case ARMII::VFPConv5Frm:
1407    // Encode Dd / Sd.
1408    Binary |= encodeVFPRd(MI, 1);
1409    break;
1410  }
1411
1412  if (Form == ARMII::VFPConv5Frm)
1413    // Encode Dn / Sn.
1414    Binary |= encodeVFPRn(MI, 2);
1415  else if (Form == ARMII::VFPConv3Frm)
1416    // Encode Dm / Sm.
1417    Binary |= encodeVFPRm(MI, 2);
1418
1419  emitWordLE(Binary);
1420}
1421
1422void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1423  // Part of binary is determined by TableGn.
1424  unsigned Binary = getBinaryCodeForInstr(MI);
1425
1426  // Set the conditional execution predicate
1427  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1428
1429  unsigned OpIdx = 0;
1430
1431  // Encode Dd / Sd.
1432  Binary |= encodeVFPRd(MI, OpIdx++);
1433
1434  // Encode address base.
1435  const MachineOperand &Base = MI.getOperand(OpIdx++);
1436  Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1437
1438  // If there is a non-zero immediate offset, encode it.
1439  if (Base.isReg()) {
1440    const MachineOperand &Offset = MI.getOperand(OpIdx);
1441    if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1442      if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1443        Binary |= 1 << ARMII::U_BitShift;
1444      Binary |= ImmOffs;
1445      emitWordLE(Binary);
1446      return;
1447    }
1448  }
1449
1450  // If immediate offset is omitted, default to +0.
1451  Binary |= 1 << ARMII::U_BitShift;
1452
1453  emitWordLE(Binary);
1454}
1455
1456void
1457ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1458  const TargetInstrDesc &TID = MI.getDesc();
1459  bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1460
1461  // Part of binary is determined by TableGn.
1462  unsigned Binary = getBinaryCodeForInstr(MI);
1463
1464  // Set the conditional execution predicate
1465  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1466
1467  // Skip operand 0 of an instruction with base register update.
1468  unsigned OpIdx = 0;
1469  if (IsUpdating)
1470    ++OpIdx;
1471
1472  // Set base address operand
1473  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1474
1475  // Set addressing mode by modifying bits U(23) and P(24)
1476  const MachineOperand &MO = MI.getOperand(OpIdx++);
1477  Binary |= getAddrModeUPBits(ARM_AM::getAM5SubMode(MO.getImm()));
1478
1479  // Set bit W(21)
1480  if (IsUpdating)
1481    Binary |= 0x1 << ARMII::W_BitShift;
1482
1483  // First register is encoded in Dd.
1484  Binary |= encodeVFPRd(MI, OpIdx+2);
1485
1486  // Number of registers are encoded in offset field.
1487  unsigned NumRegs = 1;
1488  for (unsigned i = OpIdx+3, e = MI.getNumOperands(); i != e; ++i) {
1489    const MachineOperand &MO = MI.getOperand(i);
1490    if (!MO.isReg() || MO.isImplicit())
1491      break;
1492    ++NumRegs;
1493  }
1494  // Bit 8 will be set if <list> is consecutive 64-bit registers (e.g., D0)
1495  // Otherwise, it will be 0, in the case of 32-bit registers.
1496  if(Binary & 0x100)
1497    Binary |= NumRegs * 2;
1498  else
1499    Binary |= NumRegs;
1500
1501  emitWordLE(Binary);
1502}
1503
1504void ARMCodeEmitter::emitMiscInstruction(const MachineInstr &MI) {
1505  unsigned Opcode = MI.getDesc().Opcode;
1506  // Part of binary is determined by TableGn.
1507  unsigned Binary = getBinaryCodeForInstr(MI);
1508
1509  // Set the conditional execution predicate
1510  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1511
1512  switch(Opcode) {
1513  default:
1514    llvm_unreachable("ARMCodeEmitter::emitMiscInstruction");
1515
1516  case ARM::FMSTAT:
1517    // No further encoding needed.
1518    break;
1519
1520  case ARM::VMRS:
1521  case ARM::VMSR: {
1522    const MachineOperand &MO0 = MI.getOperand(0);
1523    // Encode Rt.
1524    Binary |= ARMRegisterInfo::getRegisterNumbering(MO0.getReg())
1525                << ARMII::RegRdShift;
1526    break;
1527  }
1528
1529  case ARM::FCONSTD:
1530  case ARM::FCONSTS: {
1531    // Encode Dd / Sd.
1532    Binary |= encodeVFPRd(MI, 0);
1533
1534    // Encode imm., Table A7-18 VFP modified immediate constants
1535    const MachineOperand &MO1 = MI.getOperand(1);
1536    unsigned Imm = static_cast<unsigned>(MO1.getFPImm()->getValueAPF()
1537                      .bitcastToAPInt().getHiBits(32).getLimitedValue());
1538    unsigned ModifiedImm;
1539
1540    if(Opcode == ARM::FCONSTS)
1541      ModifiedImm = (Imm & 0x80000000) >> 24 | // a
1542                    (Imm & 0x03F80000) >> 19;  // bcdefgh
1543    else // Opcode == ARM::FCONSTD
1544      ModifiedImm = (Imm & 0x80000000) >> 24 | // a
1545                    (Imm & 0x007F0000) >> 16;  // bcdefgh
1546
1547    // Insts{19-16} = abcd, Insts{3-0} = efgh
1548    Binary |= ((ModifiedImm & 0xF0) >> 4) << 16;
1549    Binary |= (ModifiedImm & 0xF);
1550    break;
1551  }
1552  }
1553
1554  emitWordLE(Binary);
1555}
1556
1557static unsigned encodeNEONRd(const MachineInstr &MI, unsigned OpIdx) {
1558  unsigned RegD = MI.getOperand(OpIdx).getReg();
1559  unsigned Binary = 0;
1560  RegD = ARMRegisterInfo::getRegisterNumbering(RegD);
1561  Binary |= (RegD & 0xf) << ARMII::RegRdShift;
1562  Binary |= ((RegD >> 4) & 1) << ARMII::D_BitShift;
1563  return Binary;
1564}
1565
1566static unsigned encodeNEONRn(const MachineInstr &MI, unsigned OpIdx) {
1567  unsigned RegN = MI.getOperand(OpIdx).getReg();
1568  unsigned Binary = 0;
1569  RegN = ARMRegisterInfo::getRegisterNumbering(RegN);
1570  Binary |= (RegN & 0xf) << ARMII::RegRnShift;
1571  Binary |= ((RegN >> 4) & 1) << ARMII::N_BitShift;
1572  return Binary;
1573}
1574
1575static unsigned encodeNEONRm(const MachineInstr &MI, unsigned OpIdx) {
1576  unsigned RegM = MI.getOperand(OpIdx).getReg();
1577  unsigned Binary = 0;
1578  RegM = ARMRegisterInfo::getRegisterNumbering(RegM);
1579  Binary |= (RegM & 0xf);
1580  Binary |= ((RegM >> 4) & 1) << ARMII::M_BitShift;
1581  return Binary;
1582}
1583
1584void ARMCodeEmitter::emitNEON1RegModImmInstruction(const MachineInstr &MI) {
1585  unsigned Binary = getBinaryCodeForInstr(MI);
1586  // Destination register is encoded in Dd.
1587  Binary |= encodeNEONRd(MI, 0);
1588  // Immediate fields: Op, Cmode, I, Imm3, Imm4
1589  unsigned Imm = MI.getOperand(1).getImm();
1590  unsigned Op = (Imm >> 12) & 1;
1591  Binary |= (Op << 5);
1592  unsigned Cmode = (Imm >> 8) & 0xf;
1593  Binary |= (Cmode << 8);
1594  unsigned I = (Imm >> 7) & 1;
1595  Binary |= (I << 24);
1596  unsigned Imm3 = (Imm >> 4) & 0x7;
1597  Binary |= (Imm3 << 16);
1598  unsigned Imm4 = Imm & 0xf;
1599  Binary |= Imm4;
1600  emitWordLE(Binary);
1601}
1602
1603void ARMCodeEmitter::emitNEON2RegInstruction(const MachineInstr &MI) {
1604  const TargetInstrDesc &TID = MI.getDesc();
1605  unsigned Binary = getBinaryCodeForInstr(MI);
1606  // Destination register is encoded in Dd; source register in Dm.
1607  unsigned OpIdx = 0;
1608  Binary |= encodeNEONRd(MI, OpIdx++);
1609  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1610    ++OpIdx;
1611  Binary |= encodeNEONRm(MI, OpIdx);
1612  // FIXME: This does not handle VDUPfdf or VDUPfqf.
1613  emitWordLE(Binary);
1614}
1615
1616void ARMCodeEmitter::emitNEON3RegInstruction(const MachineInstr &MI) {
1617  const TargetInstrDesc &TID = MI.getDesc();
1618  unsigned Binary = getBinaryCodeForInstr(MI);
1619  // Destination register is encoded in Dd; source registers in Dn and Dm.
1620  unsigned OpIdx = 0;
1621  Binary |= encodeNEONRd(MI, OpIdx++);
1622  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1623    ++OpIdx;
1624  Binary |= encodeNEONRn(MI, OpIdx++);
1625  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1626    ++OpIdx;
1627  Binary |= encodeNEONRm(MI, OpIdx);
1628  // FIXME: This does not handle VMOVDneon or VMOVQ.
1629  emitWordLE(Binary);
1630}
1631
1632#include "ARMGenCodeEmitter.inc"
1633