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