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