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