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