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