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