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