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