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