OSDN Git Service

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