Fix so_imm encoding bug; add support for MOVi2pieces.
[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/Passes.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 using namespace llvm;
36
37 STATISTIC(NumEmitted, "Number of machine instructions emitted");
38
39 namespace {
40   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
41     ARMJITInfo                *JTI;
42     const ARMInstrInfo        *II;
43     const TargetData          *TD;
44     TargetMachine             &TM;
45     MachineCodeEmitter        &MCE;
46     const std::vector<MachineConstantPoolEntry> *MCPEs;
47     
48   public:
49     static char ID;
50     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
51       : MachineFunctionPass(&ID), JTI(0), II(0), TD(0), TM(tm),
52       MCE(mce), MCPEs(0) {}
53     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
54             const ARMInstrInfo &ii, const TargetData &td)
55       : MachineFunctionPass(&ID), JTI(0), II(&ii), TD(&td), TM(tm),
56       MCE(mce), MCPEs(0) {}
57
58     bool runOnMachineFunction(MachineFunction &MF);
59
60     virtual const char *getPassName() const {
61       return "ARM Machine Code Emitter";
62     }
63
64     void emitInstruction(const MachineInstr &MI);
65
66   private:
67
68     void emitWordLE(unsigned Binary);
69
70     void emitConstPoolInstruction(const MachineInstr &MI);
71
72     void emitMOVi2piecesInstruction(const MachineInstr &MI);
73
74     void addPCLabel(unsigned LabelID);
75
76     void emitPseudoInstruction(const MachineInstr &MI);
77
78     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
79                                     const TargetInstrDesc &TID,
80                                     const MachineOperand &MO,
81                                     unsigned OpIdx);
82
83     unsigned getMachineSoImmOpValue(unsigned SoImm);
84
85     unsigned getAddrModeSBit(const MachineInstr &MI,
86                              const TargetInstrDesc &TID) const;
87
88     void emitDataProcessingInstruction(const MachineInstr &MI,
89                                        unsigned ImplicitRn = 0);
90
91     void emitLoadStoreInstruction(const MachineInstr &MI,
92                                   unsigned ImplicitRn = 0);
93
94     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
95                                       unsigned ImplicitRn = 0);
96
97     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
98
99     void emitMulFrmInstruction(const MachineInstr &MI);
100
101     void emitBranchInstruction(const MachineInstr &MI);
102
103     void emitMiscBranchInstruction(const MachineInstr &MI);
104
105     /// getBinaryCodeForInstr - This function, generated by the
106     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
107     /// machine instructions.
108     ///
109     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
110
111     /// getMachineOpValue - Return binary encoding of operand. If the machine
112     /// operand requires relocation, record the relocation and return zero.
113     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
114     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
115       return getMachineOpValue(MI, MI.getOperand(OpIdx));
116     }
117
118     /// getBaseOpcodeFor - Return the opcode value.
119     ///
120     unsigned getBaseOpcodeFor(const TargetInstrDesc &TID) const {
121       return (TID.TSFlags & ARMII::OpcodeMask) >> ARMII::OpcodeShift;
122     }
123
124     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
125     ///
126     unsigned getShiftOp(unsigned Imm) const ;
127
128     /// Routines that handle operands which add machine relocations which are
129     /// fixed up by the JIT fixup stage.
130     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
131                            bool NeedStub);
132     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
133     void emitConstPoolAddress(unsigned CPI, unsigned Reloc,
134                               int Disp = 0, unsigned PCAdj = 0 );
135     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
136                               unsigned PCAdj = 0);
137     void emitGlobalConstant(const Constant *CV);
138     void emitMachineBasicBlock(MachineBasicBlock *BB);
139   };
140   char ARMCodeEmitter::ID = 0;
141 }
142
143 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
144 /// to the specified MCE object.
145 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
146                                              MachineCodeEmitter &MCE) {
147   return new ARMCodeEmitter(TM, MCE);
148 }
149
150 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
151   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
152           MF.getTarget().getRelocationModel() != Reloc::Static) &&
153          "JIT relocation model must be set to static or default!");
154   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
155   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
156   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
157   MCPEs = &MF.getConstantPool()->getConstants();
158   JTI->Initialize(MCPEs);
159
160   do {
161     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
162     MCE.startFunction(MF);
163     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
164          MBB != E; ++MBB) {
165       MCE.StartMachineBasicBlock(MBB);
166       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
167            I != E; ++I)
168         emitInstruction(*I);
169     }
170   } while (MCE.finishFunction(MF));
171
172   return false;
173 }
174
175 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
176 ///
177 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
178   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
179   default: assert(0 && "Unknown shift opc!");
180   case ARM_AM::asr: return 2;
181   case ARM_AM::lsl: return 0;
182   case ARM_AM::lsr: return 1;
183   case ARM_AM::ror:
184   case ARM_AM::rrx: return 3;
185   }
186   return 0;
187 }
188
189 /// getMachineOpValue - Return binary encoding of operand. If the machine
190 /// operand requires relocation, record the relocation and return zero.
191 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
192                                            const MachineOperand &MO) {
193   if (MO.isReg())
194     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
195   else if (MO.isImm())
196     return static_cast<unsigned>(MO.getImm());
197   else if (MO.isGlobal())
198     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true);
199   else if (MO.isSymbol())
200     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
201   else if (MO.isCPI())
202     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
203   else if (MO.isJTI())
204     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
205   else if (MO.isMBB())
206     emitMachineBasicBlock(MO.getMBB());
207   else {
208     cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
209     abort();
210   }
211   return 0;
212 }
213
214 /// emitGlobalAddress - Emit the specified address to the code stream.
215 ///
216 void ARMCodeEmitter::emitGlobalAddress(GlobalValue *GV,
217                                        unsigned Reloc, bool NeedStub) {
218   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
219                                              Reloc, GV, 0, NeedStub));
220 }
221
222 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
223 /// be emitted to the current location in the function, and allow it to be PC
224 /// relative.
225 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
226   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
227                                                  Reloc, ES));
228 }
229
230 /// emitConstPoolAddress - Arrange for the address of an constant pool
231 /// to be emitted to the current location in the function, and allow it to be PC
232 /// relative.
233 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
234                                           int Disp /* = 0 */,
235                                           unsigned PCAdj /* = 0 */) {
236   // Tell JIT emitter we'll resolve the address.
237   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
238                                                     Reloc, CPI, PCAdj, true));
239 }
240
241 /// emitJumpTableAddress - Arrange for the address of a jump table to
242 /// be emitted to the current location in the function, and allow it to be PC
243 /// relative.
244 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
245                                           unsigned PCAdj /* = 0 */) {
246   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
247                                                     Reloc, JTIndex, PCAdj));
248 }
249
250 /// emitMachineBasicBlock - Emit the specified address basic block.
251 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB) {
252   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
253                                              ARM::reloc_arm_branch, BB));
254 }
255
256 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
257   DOUT << "\t" << (void*)Binary << "\n";
258   MCE.emitWordLE(Binary);
259 }
260
261 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
262   DOUT << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI;
263
264   NumEmitted++;  // Keep track of the # of mi's emitted
265   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
266   default:
267     assert(0 && "Unhandled instruction encoding format!");
268     break;
269   case ARMII::Pseudo:
270     emitPseudoInstruction(MI);
271     break;
272   case ARMII::DPFrm:
273   case ARMII::DPSoRegFrm:
274     emitDataProcessingInstruction(MI);
275     break;
276   case ARMII::LdFrm:
277   case ARMII::StFrm:
278     emitLoadStoreInstruction(MI);
279     break;
280   case ARMII::LdMiscFrm:
281   case ARMII::StMiscFrm:
282     emitMiscLoadStoreInstruction(MI);
283     break;
284   case ARMII::LdMulFrm:
285   case ARMII::StMulFrm:
286     emitLoadStoreMultipleInstruction(MI);
287     break;
288   case ARMII::MulFrm:
289     emitMulFrmInstruction(MI);
290     break;
291   case ARMII::Branch:
292     emitBranchInstruction(MI);
293     break;
294   case ARMII::BranchMisc:
295     emitMiscBranchInstruction(MI);
296     break;
297   }
298 }
299
300 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
301   unsigned CPI = MI.getOperand(0).getImm();
302   unsigned CPIndex = MI.getOperand(1).getIndex();
303   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
304   
305   // Remember the CONSTPOOL_ENTRY address for later relocation.
306   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
307
308   // Emit constpool island entry. In most cases, the actual values will be
309   // resolved and relocated after code emission.
310   if (MCPE.isMachineConstantPoolEntry()) {
311     ARMConstantPoolValue *ACPV =
312       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
313
314     DOUT << "\t** ARM constant pool #" << CPI << " @ "
315          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << "\n";
316
317     GlobalValue *GV = ACPV->getGV();
318     if (GV) {
319       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
320       MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
321                                                 ARM::reloc_arm_machine_cp_entry,
322                                                 GV, CPIndex, false));
323      } else  {
324       assert(!ACPV->isNonLazyPointer() && "Don't know how to deal this yet!");
325       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
326     }
327     emitWordLE(0);
328   } else {
329     Constant *CV = MCPE.Val.ConstVal;
330
331     DOUT << "\t** Constant pool #" << CPI << " @ "
332          << (void*)MCE.getCurrentPCValue() << " " << *CV << "\n";
333
334     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
335       emitGlobalAddress(GV, ARM::reloc_arm_absolute, false);
336       emitWordLE(0);
337     } else {
338       assert(CV->getType()->isInteger() &&
339              "Not expecting non-integer constpool entries yet!");
340       const ConstantInt *CI = dyn_cast<ConstantInt>(CV);
341       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
342       emitWordLE(Val);
343     }
344   }
345 }
346
347 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
348   const MachineOperand &MO0 = MI.getOperand(0);
349   const MachineOperand &MO1 = MI.getOperand(1);
350   assert(MO1.isImm() && "Not a valid so_imm value!");
351   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
352   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
353
354   // Emit the 'mov' instruction.
355   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
356
357   // Set the conditional execution predicate.
358   Binary |= II->getPredicate(&MI) << 28;
359
360   // Encode Rd.
361   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
362
363   // Encode so_imm.
364   // Set bit I(25) to identify this is the immediate form of <shifter_op>
365   Binary |= 1 << ARMII::I_BitShift;
366   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V1));
367   emitWordLE(Binary);
368
369   // Now the 'orr' instruction.
370   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
371
372   // Set the conditional execution predicate.
373   Binary |= II->getPredicate(&MI) << 28;
374
375   // Encode Rd.
376   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
377
378   // Encode Rn.
379   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
380
381   // Encode so_imm.
382   // Set bit I(25) to identify this is the immediate form of <shifter_op>
383   Binary |= 1 << ARMII::I_BitShift;
384   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V2));
385   emitWordLE(Binary);
386 }
387
388 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
389   DOUT << "\t** LPC" << LabelID << " @ "
390        << (void*)MCE.getCurrentPCValue() << '\n';
391   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
392 }
393
394 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
395   unsigned Opcode = MI.getDesc().Opcode;
396   switch (Opcode) {
397   default:
398     abort(); // FIXME:
399   case ARM::CONSTPOOL_ENTRY:
400     emitConstPoolInstruction(MI);
401     break;
402   case ARM::PICADD: {
403     // Remember of the address of the PC label for relocation later.
404     addPCLabel(MI.getOperand(2).getImm());
405     // PICADD is just an add instruction that implicitly read pc.
406     emitDataProcessingInstruction(MI, ARM::PC);
407     break;
408   }
409   case ARM::PICLDR:
410   case ARM::PICLDRB:
411   case ARM::PICSTR:
412   case ARM::PICSTRB: {
413     // Remember of the address of the PC label for relocation later.
414     addPCLabel(MI.getOperand(2).getImm());
415     // These are just load / store instructions that implicitly read pc.
416     emitLoadStoreInstruction(MI, ARM::PC);
417     break;
418   }
419   case ARM::PICLDRH:
420   case ARM::PICLDRSH:
421   case ARM::PICLDRSB:
422   case ARM::PICSTRH: {
423     // Remember of the address of the PC label for relocation later.
424     addPCLabel(MI.getOperand(2).getImm());
425     // These are just load / store instructions that implicitly read pc.
426     emitMiscLoadStoreInstruction(MI, ARM::PC);
427     break;
428   }
429   case ARM::MOVi2pieces:
430     // Two instructions to materialize a constant.
431     emitMOVi2piecesInstruction(MI);
432     break;
433   }
434 }
435
436
437 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
438                                                 const TargetInstrDesc &TID,
439                                                 const MachineOperand &MO,
440                                                 unsigned OpIdx) {
441   unsigned Binary = getMachineOpValue(MI, MO);
442
443   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
444   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
445   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
446
447   // Encode the shift opcode.
448   unsigned SBits = 0;
449   unsigned Rs = MO1.getReg();
450   if (Rs) {
451     // Set shift operand (bit[7:4]).
452     // LSL - 0001
453     // LSR - 0011
454     // ASR - 0101
455     // ROR - 0111
456     // RRX - 0110 and bit[11:8] clear.
457     switch (SOpc) {
458     default: assert(0 && "Unknown shift opc!");
459     case ARM_AM::lsl: SBits = 0x1; break;
460     case ARM_AM::lsr: SBits = 0x3; break;
461     case ARM_AM::asr: SBits = 0x5; break;
462     case ARM_AM::ror: SBits = 0x7; break;
463     case ARM_AM::rrx: SBits = 0x6; break;
464     }
465   } else {
466     // Set shift operand (bit[6:4]).
467     // LSL - 000
468     // LSR - 010
469     // ASR - 100
470     // ROR - 110
471     switch (SOpc) {
472     default: assert(0 && "Unknown shift opc!");
473     case ARM_AM::lsl: SBits = 0x0; break;
474     case ARM_AM::lsr: SBits = 0x2; break;
475     case ARM_AM::asr: SBits = 0x4; break;
476     case ARM_AM::ror: SBits = 0x6; break;
477     }
478   }
479   Binary |= SBits << 4;
480   if (SOpc == ARM_AM::rrx)
481     return Binary;
482
483   // Encode the shift operation Rs or shift_imm (except rrx).
484   if (Rs) {
485     // Encode Rs bit[11:8].
486     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
487     return Binary |
488       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
489   }
490
491   // Encode shift_imm bit[11:7].
492   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
493 }
494
495 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
496   // Encode rotate_imm.
497   unsigned Binary = (ARM_AM::getSOImmValRot(SoImm) >> 1) << ARMII::RotImmShift;
498   // Encode immed_8.
499   Binary |= ARM_AM::getSOImmValImm(SoImm);
500   return Binary;
501 }
502
503 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
504                                          const TargetInstrDesc &TID) const {
505   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
506     const MachineOperand &MO = MI.getOperand(i-1);
507     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
508       return 1 << ARMII::S_BitShift;
509   }
510   return 0;
511 }
512
513 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
514                                                    unsigned ImplicitRn) {
515   const TargetInstrDesc &TID = MI.getDesc();
516
517   // Part of binary is determined by TableGn.
518   unsigned Binary = getBinaryCodeForInstr(MI);
519
520   // Set the conditional execution predicate
521   Binary |= II->getPredicate(&MI) << 28;
522
523   // Encode S bit if MI modifies CPSR.
524   Binary |= getAddrModeSBit(MI, TID);
525
526   // Encode register def if there is one.
527   unsigned NumDefs = TID.getNumDefs();
528   unsigned OpIdx = 0;
529   if (NumDefs) {
530     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdShift;
531     ++OpIdx;
532   }
533
534   // Encode first non-shifter register operand if there is one.
535   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
536   if (!isUnary) {
537     if (ImplicitRn)
538       // Special handling for implicit use (e.g. PC).
539       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
540                  << ARMII::RegRnShift);
541     else {
542       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
543       ++OpIdx;
544     }
545   }
546
547   // Encode shifter operand.
548   const MachineOperand &MO = MI.getOperand(OpIdx);
549   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
550     // Encode SoReg.
551     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
552     return;
553   }
554
555   if (MO.isReg()) {
556     // Encode register Rm.
557     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
558     return;
559   }
560
561   // Encode so_imm.
562   // Set bit I(25) to identify this is the immediate form of <shifter_op>
563   Binary |= 1 << ARMII::I_BitShift;
564   Binary |= getMachineSoImmOpValue(MO.getImm());
565
566   emitWordLE(Binary);
567 }
568
569 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
570                                               unsigned ImplicitRn) {
571   const TargetInstrDesc &TID = MI.getDesc();
572
573   // Part of binary is determined by TableGn.
574   unsigned Binary = getBinaryCodeForInstr(MI);
575
576   // Set the conditional execution predicate
577   Binary |= II->getPredicate(&MI) << 28;
578
579   // Set first operand
580   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
581
582   // Set second operand
583   unsigned OpIdx = 1;
584   if (ImplicitRn)
585     // Special handling for implicit use (e.g. PC).
586     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
587                << ARMII::RegRnShift);
588   else {
589     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
590     ++OpIdx;
591   }
592
593   const MachineOperand &MO2 = MI.getOperand(OpIdx);
594   unsigned AM2Opc = (OpIdx == TID.getNumOperands())
595     ? 0 : MI.getOperand(OpIdx+1).getImm();
596
597   // Set bit U(23) according to sign of immed value (positive or negative).
598   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
599              ARMII::U_BitShift);
600   if (!MO2.getReg()) { // is immediate
601     if (ARM_AM::getAM2Offset(AM2Opc))
602       // Set the value of offset_12 field
603       Binary |= ARM_AM::getAM2Offset(AM2Opc);
604     emitWordLE(Binary);
605     return;
606   }
607
608   // Set bit I(25), because this is not in immediate enconding.
609   Binary |= 1 << ARMII::I_BitShift;
610   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
611   // Set bit[3:0] to the corresponding Rm register
612   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
613
614   // if this instr is in scaled register offset/index instruction, set
615   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
616   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
617     Binary |= getShiftOp(AM2Opc) << 5;  // shift
618     Binary |= ShImm              << 7;  // shift_immed
619   }
620
621   emitWordLE(Binary);
622 }
623
624 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
625                                                   unsigned ImplicitRn) {
626   const TargetInstrDesc &TID = MI.getDesc();
627
628   // Part of binary is determined by TableGn.
629   unsigned Binary = getBinaryCodeForInstr(MI);
630
631   // Set the conditional execution predicate
632   Binary |= II->getPredicate(&MI) << 28;
633
634   // Set first operand
635   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
636
637   // Set second operand
638   unsigned OpIdx = 1;
639   if (ImplicitRn)
640     // Special handling for implicit use (e.g. PC).
641     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
642                << ARMII::RegRnShift);
643   else {
644     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
645     ++OpIdx;
646   }
647
648   const MachineOperand &MO2 = MI.getOperand(OpIdx);
649   unsigned AM3Opc = (OpIdx == TID.getNumOperands())
650     ? 0 : MI.getOperand(OpIdx+1).getImm();
651
652   // Set bit U(23) according to sign of immed value (positive or negative)
653   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
654              ARMII::U_BitShift);
655
656   // If this instr is in register offset/index encoding, set bit[3:0]
657   // to the corresponding Rm register.
658   if (MO2.getReg()) {
659     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
660     emitWordLE(Binary);
661     return;
662   }
663
664   // if this instr is in immediate offset/index encoding, set bit 22 to 1
665   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
666     Binary |= 1 << 22;
667     // Set operands
668     Binary |= (ImmOffs >> 4) << 8;  // immedH
669     Binary |= (ImmOffs & ~0xF);     // immedL
670   }
671
672   emitWordLE(Binary);
673 }
674
675 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
676   // Part of binary is determined by TableGn.
677   unsigned Binary = getBinaryCodeForInstr(MI);
678
679   // Set the conditional execution predicate
680   Binary |= II->getPredicate(&MI) << 28;
681
682   // Set first operand
683   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
684
685   // Set addressing mode by modifying bits U(23) and P(24)
686   // IA - Increment after  - bit U = 1 and bit P = 0
687   // IB - Increment before - bit U = 1 and bit P = 1
688   // DA - Decrement after  - bit U = 0 and bit P = 0
689   // DB - Decrement before - bit U = 0 and bit P = 1
690   const MachineOperand &MO = MI.getOperand(1);
691   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
692   switch (Mode) {
693   default: assert(0 && "Unknown addressing sub-mode!");
694   case ARM_AM::da:                      break;
695   case ARM_AM::db: Binary |= 0x1 << 24; break;
696   case ARM_AM::ia: Binary |= 0x1 << 23; break;
697   case ARM_AM::ib: Binary |= 0x3 << 23; break;
698   }
699
700   // Set bit W(21)
701   if (ARM_AM::getAM4WBFlag(MO.getImm()))
702     Binary |= 0x1 << 21;
703
704   // Set registers
705   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
706     const MachineOperand &MO = MI.getOperand(i);
707     if (MO.isReg() && MO.isImplicit())
708       continue;
709     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
710     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
711            RegNum < 16);
712     Binary |= 0x1 << RegNum;
713   }
714
715   emitWordLE(Binary);
716 }
717
718 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
719   const TargetInstrDesc &TID = MI.getDesc();
720
721   // Part of binary is determined by TableGn.
722   unsigned Binary = getBinaryCodeForInstr(MI);
723
724   // Set the conditional execution predicate
725   Binary |= II->getPredicate(&MI) << 28;
726
727   // Encode S bit if MI modifies CPSR.
728   Binary |= getAddrModeSBit(MI, TID);
729
730   // 32x32->64bit operations have two destination registers. The number
731   // of register definitions will tell us if that's what we're dealing with.
732   int OpIdx = 0;
733   if (TID.getNumDefs() == 2)
734     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
735
736   // Encode Rd
737   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
738
739   // Encode Rm
740   Binary |= getMachineOpValue(MI, OpIdx++);
741
742   // Encode Rs
743   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
744
745   // Many multiple instructions (e.g. MLA) have three src operands. Encode
746   // it as Rn (for multiply, that's in the same offset as RdLo.
747   if (TID.getNumOperands() - TID.getNumDefs() == 3)
748     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdLoShift;
749
750   emitWordLE(Binary);
751 }
752
753 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
754   const TargetInstrDesc &TID = MI.getDesc();
755
756   // Part of binary is determined by TableGn.
757   unsigned Binary = getBinaryCodeForInstr(MI);
758
759   // Set the conditional execution predicate
760   Binary |= II->getPredicate(&MI) << 28;
761
762   // Set signed_immed_24 field
763   Binary |= getMachineOpValue(MI, 0);
764
765   // if it is a conditional branch, set cond field
766   if (TID.Opcode == ARM::Bcc) {
767     Binary &= 0x0FFFFFFF;                      // clear conditional field
768     Binary |= getMachineOpValue(MI, 1) << 28;  // set conditional field
769   }
770
771   emitWordLE(Binary);
772 }
773
774 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
775   const TargetInstrDesc &TID = MI.getDesc();
776   if (TID.Opcode == ARM::BX)
777     abort(); // FIXME
778
779   // Part of binary is determined by TableGn.
780   unsigned Binary = getBinaryCodeForInstr(MI);
781
782   // Set the conditional execution predicate
783   Binary |= II->getPredicate(&MI) << 28;
784
785   if (TID.Opcode == ARM::BX_RET)
786     // The return register is LR.
787     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
788   else 
789     // otherwise, set the return register
790     Binary |= getMachineOpValue(MI, 0);
791
792   emitWordLE(Binary);
793 }
794
795 #include "ARMGenCodeEmitter.inc"