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