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