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