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