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