OSDN Git Service

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