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