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