Don't forget to emit stubs for function GV's emitted in CONSTPOOL_ENTRY's.
[oota-llvm.git] / lib / Target / ARM / ARMCodeEmitter.cpp
1 //===-- ARM/ARMCodeEmitter.cpp - Convert ARM code to machine code ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the ARM machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "ARM.h"
17 #include "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/MachineCodeEmitter.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/Passes.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #ifndef NDEBUG
37 #include <iomanip>
38 #endif
39 using namespace llvm;
40
41 STATISTIC(NumEmitted, "Number of machine instructions emitted");
42
43 namespace {
44   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
45     ARMJITInfo                *JTI;
46     const ARMInstrInfo        *II;
47     const TargetData          *TD;
48     TargetMachine             &TM;
49     MachineCodeEmitter        &MCE;
50     const std::vector<MachineConstantPoolEntry> *MCPEs;
51     const std::vector<MachineJumpTableEntry> *MJTEs;
52     bool IsPIC;
53
54   public:
55     static char ID;
56     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
57       : MachineFunctionPass(&ID), JTI(0), II(0), TD(0), TM(tm),
58       MCE(mce), MCPEs(0), MJTEs(0),
59       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
60     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
61             const ARMInstrInfo &ii, const TargetData &td)
62       : MachineFunctionPass(&ID), JTI(0), II(&ii), TD(&td), TM(tm),
63       MCE(mce), MCPEs(0), MJTEs(0),
64       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
65
66     bool runOnMachineFunction(MachineFunction &MF);
67
68     virtual const char *getPassName() const {
69       return "ARM Machine Code Emitter";
70     }
71
72     void emitInstruction(const MachineInstr &MI);
73
74   private:
75
76     void emitWordLE(unsigned Binary);
77
78     void emitDWordLE(uint64_t Binary);
79
80     void emitConstPoolInstruction(const MachineInstr &MI);
81
82     void emitMOVi2piecesInstruction(const MachineInstr &MI);
83
84     void emitLEApcrelJTInstruction(const MachineInstr &MI);
85
86     void addPCLabel(unsigned LabelID);
87
88     void emitPseudoInstruction(const MachineInstr &MI);
89
90     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
91                                     const TargetInstrDesc &TID,
92                                     const MachineOperand &MO,
93                                     unsigned OpIdx);
94
95     unsigned getMachineSoImmOpValue(unsigned SoImm);
96
97     unsigned getAddrModeSBit(const MachineInstr &MI,
98                              const TargetInstrDesc &TID) const;
99
100     void emitDataProcessingInstruction(const MachineInstr &MI,
101                                        unsigned ImplicitRd = 0,
102                                        unsigned ImplicitRn = 0);
103
104     void emitLoadStoreInstruction(const MachineInstr &MI,
105                                   unsigned ImplicitRd = 0,
106                                   unsigned ImplicitRn = 0);
107
108     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
109                                       unsigned ImplicitRn = 0);
110
111     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
112
113     void emitMulFrmInstruction(const MachineInstr &MI);
114
115     void emitExtendInstruction(const MachineInstr &MI);
116
117     void emitMiscArithInstruction(const MachineInstr &MI);
118
119     void emitBranchInstruction(const MachineInstr &MI);
120
121     void emitInlineJumpTable(unsigned JTIndex);
122
123     void emitMiscBranchInstruction(const MachineInstr &MI);
124
125     void emitVFPArithInstruction(const MachineInstr &MI);
126
127     void emitVFPConversionInstruction(const MachineInstr &MI);
128
129     void emitVFPLoadStoreInstruction(const MachineInstr &MI);
130
131     void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
132
133     void emitMiscInstruction(const MachineInstr &MI);
134
135     /// getBinaryCodeForInstr - This function, generated by the
136     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
137     /// machine instructions.
138     ///
139     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
140
141     /// getMachineOpValue - Return binary encoding of operand. If the machine
142     /// operand requires relocation, record the relocation and return zero.
143     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
144     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
145       return getMachineOpValue(MI, MI.getOperand(OpIdx));
146     }
147
148     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
149     ///
150     unsigned getShiftOp(unsigned Imm) const ;
151
152     /// Routines that handle operands which add machine relocations which are
153     /// fixed up by the relocation stage.
154     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
155                            bool NeedStub, intptr_t ACPV = 0);
156     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
157     void emitConstPoolAddress(unsigned CPI, unsigned Reloc);
158     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc);
159     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
160                                intptr_t JTBase = 0);
161   };
162   char ARMCodeEmitter::ID = 0;
163 }
164
165 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
166 /// to the specified MCE object.
167 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
168                                              MachineCodeEmitter &MCE) {
169   return new ARMCodeEmitter(TM, MCE);
170 }
171
172 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
173   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
174           MF.getTarget().getRelocationModel() != Reloc::Static) &&
175          "JIT relocation model must be set to static or default!");
176   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
177   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
178   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
179   MCPEs = &MF.getConstantPool()->getConstants();
180   MJTEs = &MF.getJumpTableInfo()->getJumpTables();
181   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
182   JTI->Initialize(MF, IsPIC);
183
184   do {
185     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
186     MCE.startFunction(MF);
187     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
188          MBB != E; ++MBB) {
189       MCE.StartMachineBasicBlock(MBB);
190       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
191            I != E; ++I)
192         emitInstruction(*I);
193     }
194   } while (MCE.finishFunction(MF));
195
196   return false;
197 }
198
199 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
200 ///
201 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
202   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
203   default: assert(0 && "Unknown shift opc!");
204   case ARM_AM::asr: return 2;
205   case ARM_AM::lsl: return 0;
206   case ARM_AM::lsr: return 1;
207   case ARM_AM::ror:
208   case ARM_AM::rrx: return 3;
209   }
210   return 0;
211 }
212
213 /// getMachineOpValue - Return binary encoding of operand. If the machine
214 /// operand requires relocation, record the relocation and return zero.
215 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
216                                            const MachineOperand &MO) {
217   if (MO.isReg())
218     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
219   else if (MO.isImm())
220     return static_cast<unsigned>(MO.getImm());
221   else if (MO.isGlobal())
222     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true);
223   else if (MO.isSymbol())
224     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
225   else if (MO.isCPI()) {
226     const TargetInstrDesc &TID = MI.getDesc();
227     // For VFP load, the immediate offset is multiplied by 4.
228     unsigned Reloc =  ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
229       ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
230     emitConstPoolAddress(MO.getIndex(), Reloc);
231   } else if (MO.isJTI())
232     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
233   else if (MO.isMBB())
234     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
235   else {
236     cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
237     abort();
238   }
239   return 0;
240 }
241
242 /// emitGlobalAddress - Emit the specified address to the code stream.
243 ///
244 void ARMCodeEmitter::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
245                                        bool NeedStub, intptr_t ACPV) {
246   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
247                                              Reloc, GV, ACPV, NeedStub));
248 }
249
250 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
251 /// be emitted to the current location in the function, and allow it to be PC
252 /// relative.
253 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
254   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
255                                                  Reloc, ES));
256 }
257
258 /// emitConstPoolAddress - Arrange for the address of an constant pool
259 /// to be emitted to the current location in the function, and allow it to be PC
260 /// relative.
261 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) {
262   // Tell JIT emitter we'll resolve the address.
263   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
264                                                     Reloc, CPI, 0, true));
265 }
266
267 /// emitJumpTableAddress - Arrange for the address of a jump table to
268 /// be emitted to the current location in the function, and allow it to be PC
269 /// relative.
270 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) {
271   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
272                                                     Reloc, JTIndex, 0, true));
273 }
274
275 /// emitMachineBasicBlock - Emit the specified address basic block.
276 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
277                                            unsigned Reloc, intptr_t JTBase) {
278   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
279                                              Reloc, BB, JTBase));
280 }
281
282 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
283 #ifndef NDEBUG
284   DOUT << "  0x" << std::hex << std::setw(8) << std::setfill('0')
285        << Binary << std::dec << "\n";
286 #endif
287   MCE.emitWordLE(Binary);
288 }
289
290 void ARMCodeEmitter::emitDWordLE(uint64_t Binary) {
291 #ifndef NDEBUG
292   DOUT << "  0x" << std::hex << std::setw(8) << std::setfill('0')
293        << (unsigned)Binary << std::dec << "\n";
294   DOUT << "  0x" << std::hex << std::setw(8) << std::setfill('0')
295        << (unsigned)(Binary >> 32) << std::dec << "\n";
296 #endif
297   MCE.emitDWordLE(Binary);
298 }
299
300 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
301   DOUT << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI;
302
303   NumEmitted++;  // Keep track of the # of mi's emitted
304   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
305   default:
306     assert(0 && "Unhandled instruction encoding format!");
307     break;
308   case ARMII::Pseudo:
309     emitPseudoInstruction(MI);
310     break;
311   case ARMII::DPFrm:
312   case ARMII::DPSoRegFrm:
313     emitDataProcessingInstruction(MI);
314     break;
315   case ARMII::LdFrm:
316   case ARMII::StFrm:
317     emitLoadStoreInstruction(MI);
318     break;
319   case ARMII::LdMiscFrm:
320   case ARMII::StMiscFrm:
321     emitMiscLoadStoreInstruction(MI);
322     break;
323   case ARMII::LdStMulFrm:
324     emitLoadStoreMultipleInstruction(MI);
325     break;
326   case ARMII::MulFrm:
327     emitMulFrmInstruction(MI);
328     break;
329   case ARMII::ExtFrm:
330     emitExtendInstruction(MI);
331     break;
332   case ARMII::ArithMiscFrm:
333     emitMiscArithInstruction(MI);
334     break;
335   case ARMII::BrFrm:
336     emitBranchInstruction(MI);
337     break;
338   case ARMII::BrMiscFrm:
339     emitMiscBranchInstruction(MI);
340     break;
341   // VFP instructions.
342   case ARMII::VFPUnaryFrm:
343   case ARMII::VFPBinaryFrm:
344     emitVFPArithInstruction(MI);
345     break;
346   case ARMII::VFPConv1Frm:
347   case ARMII::VFPConv2Frm:
348   case ARMII::VFPConv3Frm:
349   case ARMII::VFPConv4Frm:
350   case ARMII::VFPConv5Frm:
351     emitVFPConversionInstruction(MI);
352     break;
353   case ARMII::VFPLdStFrm:
354     emitVFPLoadStoreInstruction(MI);
355     break;
356   case ARMII::VFPLdStMulFrm:
357     emitVFPLoadStoreMultipleInstruction(MI);
358     break;
359   case ARMII::VFPMiscFrm:
360     emitMiscInstruction(MI);
361     break;
362   }
363 }
364
365 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
366   unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
367   unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
368   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
369   
370   // Remember the CONSTPOOL_ENTRY address for later relocation.
371   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
372
373   // Emit constpool island entry. In most cases, the actual values will be
374   // resolved and relocated after code emission.
375   if (MCPE.isMachineConstantPoolEntry()) {
376     ARMConstantPoolValue *ACPV =
377       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
378
379     DOUT << "  ** ARM constant pool #" << CPI << " @ "
380          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n';
381
382     GlobalValue *GV = ACPV->getGV();
383     if (GV) {
384       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
385       if (ACPV->isNonLazyPointer())
386         MCE.addRelocation(MachineRelocation::getIndirectSymbol(
387                   MCE.getCurrentPCOffset(), ARM::reloc_arm_machine_cp_entry, GV,
388                   (intptr_t)ACPV, false));
389       else 
390         emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
391                           ACPV->isStub() || isa<Function>(GV), (intptr_t)ACPV);
392      } else  {
393       assert(!ACPV->isNonLazyPointer() && "Don't know how to deal this yet!");
394       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
395     }
396     emitWordLE(0);
397   } else {
398     Constant *CV = MCPE.Val.ConstVal;
399
400 #ifndef NDEBUG
401     DOUT << "  ** Constant pool #" << CPI << " @ "
402          << (void*)MCE.getCurrentPCValue() << " ";
403     if (const Function *F = dyn_cast<Function>(CV))
404       DOUT << F->getName();
405     else
406       DOUT << *CV;
407     DOUT << '\n';
408 #endif
409
410     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
411       emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV));
412       emitWordLE(0);
413     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
414       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
415       emitWordLE(Val);
416     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
417       if (CFP->getType() == Type::FloatTy)
418         emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
419       else if (CFP->getType() == Type::DoubleTy)
420         emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
421       else {
422         assert(0 && "Unable to handle this constantpool entry!");
423         abort();
424       }
425     } else {
426       assert(0 && "Unable to handle this constantpool entry!");
427       abort();
428     }
429   }
430 }
431
432 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
433   const MachineOperand &MO0 = MI.getOperand(0);
434   const MachineOperand &MO1 = MI.getOperand(1);
435   assert(MO1.isImm() && "Not a valid so_imm value!");
436   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
437   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
438
439   // Emit the 'mov' instruction.
440   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
441
442   // Set the conditional execution predicate.
443   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
444
445   // Encode Rd.
446   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
447
448   // Encode so_imm.
449   // Set bit I(25) to identify this is the immediate form of <shifter_op>
450   Binary |= 1 << ARMII::I_BitShift;
451   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V1));
452   emitWordLE(Binary);
453
454   // Now the 'orr' instruction.
455   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
456
457   // Set the conditional execution predicate.
458   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
459
460   // Encode Rd.
461   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
462
463   // Encode Rn.
464   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
465
466   // Encode so_imm.
467   // Set bit I(25) to identify this is the immediate form of <shifter_op>
468   Binary |= 1 << ARMII::I_BitShift;
469   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V2));
470   emitWordLE(Binary);
471 }
472
473 void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
474   // It's basically add r, pc, (LJTI - $+8)
475   
476   const TargetInstrDesc &TID = MI.getDesc();
477
478   // Emit the 'add' instruction.
479   unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
480
481   // Set the conditional execution predicate
482   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
483
484   // Encode S bit if MI modifies CPSR.
485   Binary |= getAddrModeSBit(MI, TID);
486
487   // Encode Rd.
488   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
489
490   // Encode Rn which is PC.
491   Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
492
493   // Encode the displacement.
494   // Set bit I(25) to identify this is the immediate form of <shifter_op>.
495   Binary |= 1 << ARMII::I_BitShift;
496   emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
497
498   emitWordLE(Binary);
499 }
500
501 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
502   DOUT << "  ** LPC" << LabelID << " @ "
503        << (void*)MCE.getCurrentPCValue() << '\n';
504   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
505 }
506
507 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
508   unsigned Opcode = MI.getDesc().Opcode;
509   switch (Opcode) {
510   default:
511     abort(); // FIXME:
512   case ARM::CONSTPOOL_ENTRY:
513     emitConstPoolInstruction(MI);
514     break;
515   case ARM::PICADD: {
516     // Remember of the address of the PC label for relocation later.
517     addPCLabel(MI.getOperand(2).getImm());
518     // PICADD is just an add instruction that implicitly read pc.
519     emitDataProcessingInstruction(MI, 0, ARM::PC);
520     break;
521   }
522   case ARM::PICLDR:
523   case ARM::PICLDRB:
524   case ARM::PICSTR:
525   case ARM::PICSTRB: {
526     // Remember of the address of the PC label for relocation later.
527     addPCLabel(MI.getOperand(2).getImm());
528     // These are just load / store instructions that implicitly read pc.
529     emitLoadStoreInstruction(MI, 0, ARM::PC);
530     break;
531   }
532   case ARM::PICLDRH:
533   case ARM::PICLDRSH:
534   case ARM::PICLDRSB:
535   case ARM::PICSTRH: {
536     // Remember of the address of the PC label for relocation later.
537     addPCLabel(MI.getOperand(2).getImm());
538     // These are just load / store instructions that implicitly read pc.
539     emitMiscLoadStoreInstruction(MI, ARM::PC);
540     break;
541   }
542   case ARM::MOVi2pieces:
543     // Two instructions to materialize a constant.
544     emitMOVi2piecesInstruction(MI);
545     break;
546   case ARM::LEApcrelJT:
547     // Materialize jumptable address.
548     emitLEApcrelJTInstruction(MI);
549     break;
550   }
551 }
552
553
554 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
555                                                 const TargetInstrDesc &TID,
556                                                 const MachineOperand &MO,
557                                                 unsigned OpIdx) {
558   unsigned Binary = getMachineOpValue(MI, MO);
559
560   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
561   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
562   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
563
564   // Encode the shift opcode.
565   unsigned SBits = 0;
566   unsigned Rs = MO1.getReg();
567   if (Rs) {
568     // Set shift operand (bit[7:4]).
569     // LSL - 0001
570     // LSR - 0011
571     // ASR - 0101
572     // ROR - 0111
573     // RRX - 0110 and bit[11:8] clear.
574     switch (SOpc) {
575     default: assert(0 && "Unknown shift opc!");
576     case ARM_AM::lsl: SBits = 0x1; break;
577     case ARM_AM::lsr: SBits = 0x3; break;
578     case ARM_AM::asr: SBits = 0x5; break;
579     case ARM_AM::ror: SBits = 0x7; break;
580     case ARM_AM::rrx: SBits = 0x6; break;
581     }
582   } else {
583     // Set shift operand (bit[6:4]).
584     // LSL - 000
585     // LSR - 010
586     // ASR - 100
587     // ROR - 110
588     switch (SOpc) {
589     default: assert(0 && "Unknown shift opc!");
590     case ARM_AM::lsl: SBits = 0x0; break;
591     case ARM_AM::lsr: SBits = 0x2; break;
592     case ARM_AM::asr: SBits = 0x4; break;
593     case ARM_AM::ror: SBits = 0x6; break;
594     }
595   }
596   Binary |= SBits << 4;
597   if (SOpc == ARM_AM::rrx)
598     return Binary;
599
600   // Encode the shift operation Rs or shift_imm (except rrx).
601   if (Rs) {
602     // Encode Rs bit[11:8].
603     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
604     return Binary |
605       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
606   }
607
608   // Encode shift_imm bit[11:7].
609   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
610 }
611
612 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
613   // Encode rotate_imm.
614   unsigned Binary = (ARM_AM::getSOImmValRot(SoImm) >> 1)
615     << ARMII::SoRotImmShift;
616
617   // Encode immed_8.
618   Binary |= ARM_AM::getSOImmValImm(SoImm);
619   return Binary;
620 }
621
622 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
623                                          const TargetInstrDesc &TID) const {
624   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
625     const MachineOperand &MO = MI.getOperand(i-1);
626     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
627       return 1 << ARMII::S_BitShift;
628   }
629   return 0;
630 }
631
632 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
633                                                    unsigned ImplicitRd,
634                                                    unsigned ImplicitRn) {
635   const TargetInstrDesc &TID = MI.getDesc();
636
637   // Part of binary is determined by TableGn.
638   unsigned Binary = getBinaryCodeForInstr(MI);
639
640   // Set the conditional execution predicate
641   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
642
643   // Encode S bit if MI modifies CPSR.
644   Binary |= getAddrModeSBit(MI, TID);
645
646   // Encode register def if there is one.
647   unsigned NumDefs = TID.getNumDefs();
648   unsigned OpIdx = 0;
649   if (NumDefs)
650     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
651   else if (ImplicitRd)
652     // Special handling for implicit use (e.g. PC).
653     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
654                << ARMII::RegRdShift);
655
656   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
657   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
658     ++OpIdx;
659
660   // Encode first non-shifter register operand if there is one.
661   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
662   if (!isUnary) {
663     if (ImplicitRn)
664       // Special handling for implicit use (e.g. PC).
665       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
666                  << ARMII::RegRnShift);
667     else {
668       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
669       ++OpIdx;
670     }
671   }
672
673   // Encode shifter operand.
674   const MachineOperand &MO = MI.getOperand(OpIdx);
675   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
676     // Encode SoReg.
677     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
678     return;
679   }
680
681   if (MO.isReg()) {
682     // Encode register Rm.
683     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
684     return;
685   }
686
687   // Encode so_imm.
688   // Set bit I(25) to identify this is the immediate form of <shifter_op>.
689   Binary |= 1 << ARMII::I_BitShift;
690   Binary |= getMachineSoImmOpValue(MO.getImm());
691
692   emitWordLE(Binary);
693 }
694
695 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
696                                               unsigned ImplicitRd,
697                                               unsigned ImplicitRn) {
698   const TargetInstrDesc &TID = MI.getDesc();
699   unsigned Form = TID.TSFlags & ARMII::FormMask;
700   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
701
702   // Part of binary is determined by TableGn.
703   unsigned Binary = getBinaryCodeForInstr(MI);
704
705   // Set the conditional execution predicate
706   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
707
708   unsigned OpIdx = 0;
709
710   // Operand 0 of a pre- and post-indexed store is the address base
711   // writeback. Skip it.
712   bool Skipped = false;
713   if (IsPrePost && Form == ARMII::StFrm) {
714     ++OpIdx;
715     Skipped = true;
716   }
717
718   // Set first operand
719   if (ImplicitRd)
720     // Special handling for implicit use (e.g. PC).
721     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
722                << ARMII::RegRdShift);
723   else
724     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
725
726   // Set second operand
727   if (ImplicitRn)
728     // Special handling for implicit use (e.g. PC).
729     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
730                << ARMII::RegRnShift);
731   else
732     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
733
734   // If this is a two-address operand, skip it. e.g. LDR_PRE.
735   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
736     ++OpIdx;
737
738   const MachineOperand &MO2 = MI.getOperand(OpIdx);
739   unsigned AM2Opc = (ImplicitRn == ARM::PC)
740     ? 0 : MI.getOperand(OpIdx+1).getImm();
741
742   // Set bit U(23) according to sign of immed value (positive or negative).
743   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
744              ARMII::U_BitShift);
745   if (!MO2.getReg()) { // is immediate
746     if (ARM_AM::getAM2Offset(AM2Opc))
747       // Set the value of offset_12 field
748       Binary |= ARM_AM::getAM2Offset(AM2Opc);
749     emitWordLE(Binary);
750     return;
751   }
752
753   // Set bit I(25), because this is not in immediate enconding.
754   Binary |= 1 << ARMII::I_BitShift;
755   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
756   // Set bit[3:0] to the corresponding Rm register
757   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
758
759   // If this instr is in scaled register offset/index instruction, set
760   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
761   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
762     Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
763     Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
764   }
765
766   emitWordLE(Binary);
767 }
768
769 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
770                                                   unsigned ImplicitRn) {
771   const TargetInstrDesc &TID = MI.getDesc();
772   unsigned Form = TID.TSFlags & ARMII::FormMask;
773   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
774
775   // Part of binary is determined by TableGn.
776   unsigned Binary = getBinaryCodeForInstr(MI);
777
778   // Set the conditional execution predicate
779   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
780
781   unsigned OpIdx = 0;
782
783   // Operand 0 of a pre- and post-indexed store is the address base
784   // writeback. Skip it.
785   bool Skipped = false;
786   if (IsPrePost && Form == ARMII::StMiscFrm) {
787     ++OpIdx;
788     Skipped = true;
789   }
790
791   // Set first operand
792   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
793
794   // Set second operand
795   if (ImplicitRn)
796     // Special handling for implicit use (e.g. PC).
797     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
798                << ARMII::RegRnShift);
799   else
800     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
801
802   // If this is a two-address operand, skip it. e.g. LDRH_POST.
803   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
804     ++OpIdx;
805
806   const MachineOperand &MO2 = MI.getOperand(OpIdx);
807   unsigned AM3Opc = (ImplicitRn == ARM::PC)
808     ? 0 : MI.getOperand(OpIdx+1).getImm();
809
810   // Set bit U(23) according to sign of immed value (positive or negative)
811   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
812              ARMII::U_BitShift);
813
814   // If this instr is in register offset/index encoding, set bit[3:0]
815   // to the corresponding Rm register.
816   if (MO2.getReg()) {
817     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
818     emitWordLE(Binary);
819     return;
820   }
821
822   // This instr is in immediate offset/index encoding, set bit 22 to 1.
823   Binary |= 1 << ARMII::AM3_I_BitShift;
824   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
825     // Set operands
826     Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
827     Binary |= (ImmOffs & 0xF);                      // immedL
828   }
829
830   emitWordLE(Binary);
831 }
832
833 static unsigned getAddrModeUPBits(unsigned Mode) {
834   unsigned Binary = 0;
835
836   // Set addressing mode by modifying bits U(23) and P(24)
837   // IA - Increment after  - bit U = 1 and bit P = 0
838   // IB - Increment before - bit U = 1 and bit P = 1
839   // DA - Decrement after  - bit U = 0 and bit P = 0
840   // DB - Decrement before - bit U = 0 and bit P = 1
841   switch (Mode) {
842   default: assert(0 && "Unknown addressing sub-mode!");
843   case ARM_AM::da:                      break;
844   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
845   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
846   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
847   }
848
849   return Binary;
850 }
851
852 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
853   // Part of binary is determined by TableGn.
854   unsigned Binary = getBinaryCodeForInstr(MI);
855
856   // Set the conditional execution predicate
857   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
858
859   // Set base address operand
860   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
861
862   // Set addressing mode by modifying bits U(23) and P(24)
863   const MachineOperand &MO = MI.getOperand(1);
864   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
865
866   // Set bit W(21)
867   if (ARM_AM::getAM4WBFlag(MO.getImm()))
868     Binary |= 0x1 << ARMII::W_BitShift;
869
870   // Set registers
871   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
872     const MachineOperand &MO = MI.getOperand(i);
873     if (!MO.isReg() || MO.isImplicit())
874       break;
875     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
876     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
877            RegNum < 16);
878     Binary |= 0x1 << RegNum;
879   }
880
881   emitWordLE(Binary);
882 }
883
884 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
885   const TargetInstrDesc &TID = MI.getDesc();
886
887   // Part of binary is determined by TableGn.
888   unsigned Binary = getBinaryCodeForInstr(MI);
889
890   // Set the conditional execution predicate
891   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
892
893   // Encode S bit if MI modifies CPSR.
894   Binary |= getAddrModeSBit(MI, TID);
895
896   // 32x32->64bit operations have two destination registers. The number
897   // of register definitions will tell us if that's what we're dealing with.
898   unsigned OpIdx = 0;
899   if (TID.getNumDefs() == 2)
900     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
901
902   // Encode Rd
903   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
904
905   // Encode Rm
906   Binary |= getMachineOpValue(MI, OpIdx++);
907
908   // Encode Rs
909   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
910
911   // Many multiple instructions (e.g. MLA) have three src operands. Encode
912   // it as Rn (for multiply, that's in the same offset as RdLo.
913   if (TID.getNumOperands() > OpIdx &&
914       !TID.OpInfo[OpIdx].isPredicate() &&
915       !TID.OpInfo[OpIdx].isOptionalDef())
916     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
917
918   emitWordLE(Binary);
919 }
920
921 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
922   const TargetInstrDesc &TID = MI.getDesc();
923
924   // Part of binary is determined by TableGn.
925   unsigned Binary = getBinaryCodeForInstr(MI);
926
927   // Set the conditional execution predicate
928   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
929
930   unsigned OpIdx = 0;
931
932   // Encode Rd
933   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
934
935   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
936   const MachineOperand &MO2 = MI.getOperand(OpIdx);
937   if (MO2.isReg()) {
938     // Two register operand form.
939     // Encode Rn.
940     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
941
942     // Encode Rm.
943     Binary |= getMachineOpValue(MI, MO2);
944     ++OpIdx;
945   } else {
946     Binary |= getMachineOpValue(MI, MO1);
947   }
948
949   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
950   if (MI.getOperand(OpIdx).isImm() &&
951       !TID.OpInfo[OpIdx].isPredicate() &&
952       !TID.OpInfo[OpIdx].isOptionalDef())
953     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
954
955   emitWordLE(Binary);
956 }
957
958 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
959   const TargetInstrDesc &TID = MI.getDesc();
960
961   // Part of binary is determined by TableGn.
962   unsigned Binary = getBinaryCodeForInstr(MI);
963
964   // Set the conditional execution predicate
965   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
966
967   unsigned OpIdx = 0;
968
969   // Encode Rd
970   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
971
972   const MachineOperand &MO = MI.getOperand(OpIdx++);
973   if (OpIdx == TID.getNumOperands() ||
974       TID.OpInfo[OpIdx].isPredicate() ||
975       TID.OpInfo[OpIdx].isOptionalDef()) {
976     // Encode Rm and it's done.
977     Binary |= getMachineOpValue(MI, MO);
978     emitWordLE(Binary);
979     return;
980   }
981
982   // Encode Rn.
983   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
984
985   // Encode Rm.
986   Binary |= getMachineOpValue(MI, OpIdx++);
987
988   // Encode shift_imm.
989   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
990   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
991   Binary |= ShiftAmt << ARMII::ShiftShift;
992   
993   emitWordLE(Binary);
994 }
995
996 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
997   const TargetInstrDesc &TID = MI.getDesc();
998
999   if (TID.Opcode == ARM::TPsoft)
1000     abort(); // FIXME
1001
1002   // Part of binary is determined by TableGn.
1003   unsigned Binary = getBinaryCodeForInstr(MI);
1004
1005   // Set the conditional execution predicate
1006   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1007
1008   // Set signed_immed_24 field
1009   Binary |= getMachineOpValue(MI, 0);
1010
1011   emitWordLE(Binary);
1012 }
1013
1014 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1015   // Remember the base address of the inline jump table.
1016   intptr_t JTBase = MCE.getCurrentPCValue();
1017   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1018   DOUT << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase << '\n';
1019
1020   // Now emit the jump table entries.
1021   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1022   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1023     if (IsPIC)
1024       // DestBB address - JT base.
1025       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1026     else
1027       // Absolute DestBB address.
1028       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1029     emitWordLE(0);
1030   }
1031 }
1032
1033 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1034   const TargetInstrDesc &TID = MI.getDesc();
1035
1036   // Handle jump tables.
1037   if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1038     // First emit a ldr pc, [] instruction.
1039     emitDataProcessingInstruction(MI, ARM::PC);
1040
1041     // Then emit the inline jump table.
1042     unsigned JTIndex = (TID.Opcode == ARM::BR_JTr)
1043       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1044     emitInlineJumpTable(JTIndex);
1045     return;
1046   } else if (TID.Opcode == ARM::BR_JTm) {
1047     // First emit a ldr pc, [] instruction.
1048     emitLoadStoreInstruction(MI, ARM::PC);
1049
1050     // Then emit the inline jump table.
1051     emitInlineJumpTable(MI.getOperand(3).getIndex());
1052     return;
1053   }
1054
1055   // Part of binary is determined by TableGn.
1056   unsigned Binary = getBinaryCodeForInstr(MI);
1057
1058   // Set the conditional execution predicate
1059   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1060
1061   if (TID.Opcode == ARM::BX_RET)
1062     // The return register is LR.
1063     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
1064   else 
1065     // otherwise, set the return register
1066     Binary |= getMachineOpValue(MI, 0);
1067
1068   emitWordLE(Binary);
1069 }
1070
1071 static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1072   unsigned RegD = MI.getOperand(OpIdx).getReg();
1073   unsigned Binary = 0;
1074   bool isSPVFP = false;
1075   RegD = ARMRegisterInfo::getRegisterNumbering(RegD, isSPVFP);
1076   if (!isSPVFP)
1077     Binary |=   RegD               << ARMII::RegRdShift;
1078   else {
1079     Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1080     Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1081   }
1082   return Binary;
1083 }
1084
1085 static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1086   unsigned RegN = MI.getOperand(OpIdx).getReg();
1087   unsigned Binary = 0;
1088   bool isSPVFP = false;
1089   RegN = ARMRegisterInfo::getRegisterNumbering(RegN, isSPVFP);
1090   if (!isSPVFP)
1091     Binary |=   RegN               << ARMII::RegRnShift;
1092   else {
1093     Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1094     Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1095   }
1096   return Binary;
1097 }
1098
1099 static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1100   unsigned RegM = MI.getOperand(OpIdx).getReg();
1101   unsigned Binary = 0;
1102   bool isSPVFP = false;
1103   RegM = ARMRegisterInfo::getRegisterNumbering(RegM, isSPVFP);
1104   if (!isSPVFP)
1105     Binary |=   RegM;
1106   else {
1107     Binary |= ((RegM & 0x1E) >> 1);
1108     Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1109   }
1110   return Binary;
1111 }
1112
1113 void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1114   const TargetInstrDesc &TID = MI.getDesc();
1115
1116   // Part of binary is determined by TableGn.
1117   unsigned Binary = getBinaryCodeForInstr(MI);
1118
1119   // Set the conditional execution predicate
1120   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1121
1122   unsigned OpIdx = 0;
1123   assert((Binary & ARMII::D_BitShift) == 0 &&
1124          (Binary & ARMII::N_BitShift) == 0 &&
1125          (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1126
1127   // Encode Dd / Sd.
1128   Binary |= encodeVFPRd(MI, OpIdx++);
1129
1130   // If this is a two-address operand, skip it, e.g. FMACD.
1131   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1132     ++OpIdx;
1133
1134   // Encode Dn / Sn.
1135   if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1136     Binary |= encodeVFPRn(MI, OpIdx++);
1137
1138   if (OpIdx == TID.getNumOperands() ||
1139       TID.OpInfo[OpIdx].isPredicate() ||
1140       TID.OpInfo[OpIdx].isOptionalDef()) {
1141     // FCMPEZD etc. has only one operand.
1142     emitWordLE(Binary);
1143     return;
1144   }
1145
1146   // Encode Dm / Sm.
1147   Binary |= encodeVFPRm(MI, OpIdx);
1148   
1149   emitWordLE(Binary);
1150 }
1151
1152 void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1153   const TargetInstrDesc &TID = MI.getDesc();
1154   unsigned Form = TID.TSFlags & ARMII::FormMask;
1155
1156   // Part of binary is determined by TableGn.
1157   unsigned Binary = getBinaryCodeForInstr(MI);
1158
1159   // Set the conditional execution predicate
1160   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1161
1162   switch (Form) {
1163   default: break;
1164   case ARMII::VFPConv1Frm:
1165   case ARMII::VFPConv2Frm:
1166   case ARMII::VFPConv3Frm:
1167     // Encode Dd / Sd.
1168     Binary |= encodeVFPRd(MI, 0);
1169     break;
1170   case ARMII::VFPConv4Frm:
1171     // Encode Dn / Sn.
1172     Binary |= encodeVFPRn(MI, 0);
1173     break;
1174   case ARMII::VFPConv5Frm:
1175     // Encode Dm / Sm.
1176     Binary |= encodeVFPRm(MI, 0);
1177     break;
1178   }
1179
1180   switch (Form) {
1181   default: break;
1182   case ARMII::VFPConv1Frm:
1183     // Encode Dm / Sm.
1184     Binary |= encodeVFPRm(MI, 1);
1185     break;
1186   case ARMII::VFPConv2Frm:
1187   case ARMII::VFPConv3Frm:
1188     // Encode Dn / Sn.
1189     Binary |= encodeVFPRn(MI, 1);
1190     break;
1191   case ARMII::VFPConv4Frm:
1192   case ARMII::VFPConv5Frm:
1193     // Encode Dd / Sd.
1194     Binary |= encodeVFPRd(MI, 1);
1195     break;
1196   }
1197
1198   if (Form == ARMII::VFPConv5Frm)
1199     // Encode Dn / Sn.
1200     Binary |= encodeVFPRn(MI, 2);
1201   else if (Form == ARMII::VFPConv3Frm)
1202     // Encode Dm / Sm.
1203     Binary |= encodeVFPRm(MI, 2);
1204
1205   emitWordLE(Binary);
1206 }
1207
1208 void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1209   // Part of binary is determined by TableGn.
1210   unsigned Binary = getBinaryCodeForInstr(MI);
1211
1212   // Set the conditional execution predicate
1213   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1214
1215   unsigned OpIdx = 0;
1216
1217   // Encode Dd / Sd.
1218   Binary |= encodeVFPRd(MI, OpIdx++);
1219
1220   // Encode address base.
1221   const MachineOperand &Base = MI.getOperand(OpIdx++);
1222   Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1223
1224   // If there is a non-zero immediate offset, encode it.
1225   if (Base.isReg()) {
1226     const MachineOperand &Offset = MI.getOperand(OpIdx);
1227     if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1228       if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1229         Binary |= 1 << ARMII::U_BitShift;
1230       Binary |= ImmOffs;
1231       emitWordLE(Binary);
1232       return;
1233     }
1234   }
1235
1236   // If immediate offset is omitted, default to +0.
1237   Binary |= 1 << ARMII::U_BitShift;
1238
1239   emitWordLE(Binary);
1240 }
1241
1242 void
1243 ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1244   // Part of binary is determined by TableGn.
1245   unsigned Binary = getBinaryCodeForInstr(MI);
1246
1247   // Set the conditional execution predicate
1248   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1249
1250   // Set base address operand
1251   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
1252
1253   // Set addressing mode by modifying bits U(23) and P(24)
1254   const MachineOperand &MO = MI.getOperand(1);
1255   Binary |= getAddrModeUPBits(ARM_AM::getAM5SubMode(MO.getImm()));
1256
1257   // Set bit W(21)
1258   if (ARM_AM::getAM5WBFlag(MO.getImm()))
1259     Binary |= 0x1 << ARMII::W_BitShift;
1260
1261   // First register is encoded in Dd.
1262   Binary |= encodeVFPRd(MI, 4);
1263
1264   // Number of registers are encoded in offset field.
1265   unsigned NumRegs = 1;
1266   for (unsigned i = 5, e = MI.getNumOperands(); i != e; ++i) {
1267     const MachineOperand &MO = MI.getOperand(i);
1268     if (!MO.isReg() || MO.isImplicit())
1269       break;
1270     ++NumRegs;
1271   }
1272   Binary |= NumRegs * 2;
1273
1274   emitWordLE(Binary);
1275 }
1276
1277 void ARMCodeEmitter::emitMiscInstruction(const MachineInstr &MI) {
1278   // Part of binary is determined by TableGn.
1279   unsigned Binary = getBinaryCodeForInstr(MI);
1280
1281   // Set the conditional execution predicate
1282   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1283
1284   emitWordLE(Binary);
1285 }
1286
1287 #include "ARMGenCodeEmitter.inc"