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