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