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