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