OSDN Git Service

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