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