Use better data structure for ConstPoolId2AddrMap.
[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 getAddrModeNoneInstrBinary(const MachineInstr &MI,
73                                         const TargetInstrDesc &TID,
74                                         unsigned Binary);
75
76     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
77                                     const TargetInstrDesc &TID,
78                                     const MachineOperand &MO,
79                                     unsigned OpIdx);
80
81     unsigned getMachineSoImmOpValue(const MachineInstr &MI,
82                                     const TargetInstrDesc &TID,
83                                     const MachineOperand &MO);
84
85     unsigned getAddrMode1SBit(const MachineInstr &MI,
86                               const TargetInstrDesc &TID) const;
87
88     unsigned getAddrMode1InstrBinary(const MachineInstr &MI,
89                                      const TargetInstrDesc &TID,
90                                      unsigned Binary);
91     unsigned getAddrMode2InstrBinary(const MachineInstr &MI,
92                                      const TargetInstrDesc &TID,
93                                      unsigned Binary);
94     unsigned getAddrMode3InstrBinary(const MachineInstr &MI,
95                                      const TargetInstrDesc &TID,
96                                      unsigned Binary);
97     unsigned getAddrMode4InstrBinary(const MachineInstr &MI,
98                                      const TargetInstrDesc &TID,
99                                      unsigned Binary);
100
101     /// getInstrBinary - Return binary encoding for the specified
102     /// machine instruction.
103     unsigned getInstrBinary(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 machine operand.
125     ///
126     unsigned getShiftOp(const MachineOperand &MO) 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->ResizeConstPoolMap(MCPEs->size());
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 machine operand.
176 ///
177 unsigned ARMCodeEmitter::getShiftOp(const MachineOperand &MO) const {
178   switch (ARM_AM::getAM2ShiftOpc(MO.getImm())) {
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::emitInstruction(const MachineInstr &MI) {
257   DOUT << "JIT: " << "0x" << MCE.getCurrentPCValue() << ":\t" << MI;
258
259   NumEmitted++;  // Keep track of the # of mi's emitted
260   if ((MI.getDesc().TSFlags & ARMII::FormMask) == ARMII::Pseudo)
261     emitPseudoInstruction(MI);
262   else
263     MCE.emitWordLE(getInstrBinary(MI));
264 }
265
266 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
267   unsigned CPI = MI.getOperand(0).getImm();
268   unsigned CPIndex = MI.getOperand(1).getIndex();
269   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
270   
271   // Remember the CONSTPOOL_ENTRY address for later relocation.
272   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
273
274   // Emit constpool island entry. In most cases, the actual values will be
275   // resolved and relocated after code emission.
276   if (MCPE.isMachineConstantPoolEntry()) {
277     ARMConstantPoolValue *ACPV =
278       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
279
280     DOUT << "\t** ARM constant pool #" << CPI << " @ "
281          << (void*)MCE.getCurrentPCValue() << " '" << *ACPV << "'\n";
282
283     GlobalValue *GV = ACPV->getGV();
284     if (GV) {
285       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
286       emitGlobalAddress(GV, ARM::reloc_arm_absolute, false);
287     } else  {
288       assert(!ACPV->isNonLazyPointer() && "Don't know how to deal this yet!");
289       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
290     }
291     MCE.emitWordLE(0);
292   } else {
293     Constant *CV = MCPE.Val.ConstVal;
294
295     DOUT << "\t** Constant pool #" << CPI << " @ "
296          << (void*)MCE.getCurrentPCValue() << " '" << *CV << "'\n";
297
298     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
299       emitGlobalAddress(GV, ARM::reloc_arm_absolute, false);
300       MCE.emitWordLE(0);
301     } else {
302       assert(CV->getType()->isInteger() &&
303              "Not expecting non-integer constpool entries yet!");
304       const ConstantInt *CI = dyn_cast<ConstantInt>(CV);
305       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
306       MCE.emitWordLE(Val);
307     }
308   }
309 }
310
311 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
312   unsigned Opcode = MI.getDesc().Opcode;
313   switch (Opcode) {
314   default:
315     abort(); // FIXME:
316   case ARM::CONSTPOOL_ENTRY:
317     emitConstPoolInstruction(MI);
318     break;
319   case ARM::PICADD: {
320     // PICADD is just an add instruction that implicitly read pc.
321     unsigned Binary = getBinaryCodeForInstr(MI);
322     const TargetInstrDesc &TID = MI.getDesc();
323     MCE.emitWordLE(getAddrMode1InstrBinary(MI, TID, Binary));
324     break;
325   }
326   }
327 }
328
329
330 unsigned ARMCodeEmitter::getAddrModeNoneInstrBinary(const MachineInstr &MI,
331                                                     const TargetInstrDesc &TID,
332                                                     unsigned Binary) {
333   // Set the conditional execution predicate
334   Binary |= II->getPredicate(&MI) << 28;
335
336   switch (TID.TSFlags & ARMII::FormMask) {
337   default:
338     assert(0 && "Unknown instruction subtype!");
339     break;
340   case ARMII::Branch: {
341     // Set signed_immed_24 field
342     Binary |= getMachineOpValue(MI, 0);
343
344     // if it is a conditional branch, set cond field
345     if (TID.Opcode == ARM::Bcc) {
346       Binary &= 0x0FFFFFFF;                      // clear conditional field
347       Binary |= getMachineOpValue(MI, 1) << 28;  // set conditional field
348     }
349     break;
350   }
351   case ARMII::BranchMisc: {
352     if (TID.Opcode == ARM::BX)
353       abort(); // FIXME
354     if (TID.Opcode == ARM::BX_RET)
355       Binary |= 0xe; // the return register is LR
356     else 
357       // otherwise, set the return register
358       Binary |= getMachineOpValue(MI, 0);
359     break;
360   }
361   }
362
363   return Binary;
364 }
365
366 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
367                                                 const TargetInstrDesc &TID,
368                                                 const MachineOperand &MO,
369                                                 unsigned OpIdx) {
370   unsigned Binary = getMachineOpValue(MI, MO);
371
372   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
373   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
374   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
375
376   // Encode the shift opcode.
377   unsigned SBits = 0;
378   unsigned Rs = MO1.getReg();
379   if (Rs) {
380     // Set shift operand (bit[7:4]).
381     // LSL - 0001
382     // LSR - 0011
383     // ASR - 0101
384     // ROR - 0111
385     // RRX - 0110 and bit[11:8] clear.
386     switch (SOpc) {
387     default: assert(0 && "Unknown shift opc!");
388     case ARM_AM::lsl: SBits = 0x1; break;
389     case ARM_AM::lsr: SBits = 0x3; break;
390     case ARM_AM::asr: SBits = 0x5; break;
391     case ARM_AM::ror: SBits = 0x7; break;
392     case ARM_AM::rrx: SBits = 0x6; break;
393     }
394   } else {
395     // Set shift operand (bit[6:4]).
396     // LSL - 000
397     // LSR - 010
398     // ASR - 100
399     // ROR - 110
400     switch (SOpc) {
401     default: assert(0 && "Unknown shift opc!");
402     case ARM_AM::lsl: SBits = 0x0; break;
403     case ARM_AM::lsr: SBits = 0x2; break;
404     case ARM_AM::asr: SBits = 0x4; break;
405     case ARM_AM::ror: SBits = 0x6; break;
406     }
407   }
408   Binary |= SBits << 4;
409   if (SOpc == ARM_AM::rrx)
410     return Binary;
411
412   // Encode the shift operation Rs or shift_imm (except rrx).
413   if (Rs) {
414     // Encode Rs bit[11:8].
415     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
416     return Binary |
417       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
418   }
419
420   // Encode shift_imm bit[11:7].
421   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
422 }
423
424 unsigned ARMCodeEmitter::getMachineSoImmOpValue(const MachineInstr &MI,
425                                                 const TargetInstrDesc &TID,
426                                                 const MachineOperand &MO) {
427   unsigned SoImm = MO.getImm();
428   // Encode rotate_imm.
429   unsigned Binary = ARM_AM::getSOImmValRot(SoImm) << ARMII::RotImmShift;
430   // Encode immed_8.
431   Binary |= ARM_AM::getSOImmVal(SoImm);
432   return Binary;
433 }
434
435 unsigned ARMCodeEmitter::getAddrMode1SBit(const MachineInstr &MI,
436                                           const TargetInstrDesc &TID) const {
437   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
438     const MachineOperand &MO = MI.getOperand(i-1);
439     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
440       return 1 << ARMII::S_BitShift;
441   }
442   return 0;
443 }
444
445 unsigned ARMCodeEmitter::getAddrMode1InstrBinary(const MachineInstr &MI,
446                                                  const TargetInstrDesc &TID,
447                                                  unsigned Binary) {
448   // Set the conditional execution predicate
449   Binary |= II->getPredicate(&MI) << 28;
450
451   // Encode S bit if MI modifies CPSR.
452   Binary |= getAddrMode1SBit(MI, TID);
453
454   // Encode register def if there is one.
455   unsigned NumDefs = TID.getNumDefs();
456   unsigned OpIdx = 0;
457   if (NumDefs) {
458     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdShift;
459     ++OpIdx;
460   }
461
462   // Encode first non-shifter register operand if there is one.
463   unsigned Format = TID.TSFlags & ARMII::FormMask;
464   bool HasRnReg = !(Format == ARMII::DPRdMisc  ||
465                     Format == ARMII::DPRdIm    ||
466                     Format == ARMII::DPRdReg   ||
467                     Format == ARMII::DPRdSoReg);
468   if (HasRnReg) {
469     if (TID.getOpcode() == ARM::PICADD)
470       // Special handling for PICADD. It implicitly use add.
471       Binary |=
472         ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
473     else {
474       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
475       ++OpIdx;
476     }
477   }
478
479   // Encode shifter operand.
480   bool HasSoReg = (Format == ARMII::DPRdSoReg ||
481                    Format == ARMII::DPRnSoReg ||
482                    Format == ARMII::DPRSoReg  ||
483                    Format == ARMII::DPRSoRegS);
484
485   const MachineOperand &MO = MI.getOperand(OpIdx);
486   if (HasSoReg)
487     // Encode SoReg.
488     return Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx);
489
490   if (MO.isReg())
491     // Encode register Rm.
492     return Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg());
493
494   // Encode so_imm.
495   // Set bit I(25) to identify this is the immediate form of <shifter_op>
496   Binary |= 1 << ARMII::I_BitShift;
497   Binary |= getMachineSoImmOpValue(MI, TID, MO);
498   return Binary;
499 }
500
501 unsigned ARMCodeEmitter::getAddrMode2InstrBinary(const MachineInstr &MI,
502                                                  const TargetInstrDesc &TID,
503                                                  unsigned Binary) {
504   // Set the conditional execution predicate
505   Binary |= II->getPredicate(&MI) << 28;
506
507   // Set first operand
508   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
509
510   // Set second operand
511   Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
512
513   const MachineOperand &MO2 = MI.getOperand(2);
514   const MachineOperand &MO3 = MI.getOperand(3);
515
516   // Set bit U(23) according to sign of immed value (positive or negative).
517   Binary |= ((ARM_AM::getAM2Op(MO3.getImm()) == ARM_AM::add ? 1 : 0) <<
518              ARMII::U_BitShift);
519   if (!MO2.getReg()) { // is immediate
520     if (ARM_AM::getAM2Offset(MO3.getImm()))
521       // Set the value of offset_12 field
522       Binary |= ARM_AM::getAM2Offset(MO3.getImm());
523     return Binary;
524   }
525
526   // Set bit I(25), because this is not in immediate enconding.
527   Binary |= 1 << ARMII::I_BitShift;
528   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
529   // Set bit[3:0] to the corresponding Rm register
530   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
531
532   // if this instr is in scaled register offset/index instruction, set
533   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
534   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm())) {
535     Binary |= getShiftOp(MO3) << 5;  // shift
536     Binary |= ShImm           << 7;  // shift_immed
537   }
538
539   return Binary;
540 }
541
542 unsigned ARMCodeEmitter::getAddrMode3InstrBinary(const MachineInstr &MI,
543                                                  const TargetInstrDesc &TID,
544                                                  unsigned Binary) {
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     return Binary;
566   }
567
568   // if this instr is in immediate offset/index encoding, set bit 22 to 1
569   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm())) {
570     Binary |= 1 << 22;
571     // Set operands
572     Binary |= (ImmOffs >> 4) << 8;  // immedH
573     Binary |= (ImmOffs & ~0xF);     // immedL
574   }
575
576   return Binary;
577 }
578
579 unsigned ARMCodeEmitter::getAddrMode4InstrBinary(const MachineInstr &MI,
580                                                  const TargetInstrDesc &TID,
581                                                  unsigned Binary) {
582   // Set the conditional execution predicate
583   Binary |= II->getPredicate(&MI) << 28;
584
585   // Set first operand
586   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
587
588   // Set addressing mode by modifying bits U(23) and P(24)
589   // IA - Increment after  - bit U = 1 and bit P = 0
590   // IB - Increment before - bit U = 1 and bit P = 1
591   // DA - Decrement after  - bit U = 0 and bit P = 0
592   // DB - Decrement before - bit U = 0 and bit P = 1
593   const MachineOperand &MO = MI.getOperand(1);
594   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
595   switch (Mode) {
596   default: assert(0 && "Unknown addressing sub-mode!");
597   case ARM_AM::da:                      break;
598   case ARM_AM::db: Binary |= 0x1 << 24; break;
599   case ARM_AM::ia: Binary |= 0x1 << 23; break;
600   case ARM_AM::ib: Binary |= 0x3 << 23; break;
601   }
602
603   // Set bit W(21)
604   if (ARM_AM::getAM4WBFlag(MO.getImm()))
605     Binary |= 0x1 << 21;
606
607   // Set registers
608   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
609     const MachineOperand &MO = MI.getOperand(i);
610     if (MO.isReg() && MO.isImplicit())
611       continue;
612     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
613     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
614            RegNum < 16);
615     Binary |= 0x1 << RegNum;
616   }
617
618   return Binary;
619 }
620
621 /// getInstrBinary - Return binary encoding for the specified
622 /// machine instruction.
623 unsigned ARMCodeEmitter::getInstrBinary(const MachineInstr &MI) {
624   // Part of binary is determined by TableGn.
625   unsigned Binary = getBinaryCodeForInstr(MI);
626
627   const TargetInstrDesc &TID = MI.getDesc();
628   switch (TID.TSFlags & ARMII::AddrModeMask) {
629   case ARMII::AddrModeNone:
630     return getAddrModeNoneInstrBinary(MI, TID, Binary);
631   case ARMII::AddrMode1:
632     return getAddrMode1InstrBinary(MI, TID, Binary);
633   case ARMII::AddrMode2:
634     return getAddrMode2InstrBinary(MI, TID, Binary);
635   case ARMII::AddrMode3:
636     return getAddrMode3InstrBinary(MI, TID, Binary);
637   case ARMII::AddrMode4:
638     return getAddrMode4InstrBinary(MI, TID, Binary);
639   }
640
641   abort();
642   return 0;
643 }
644
645 #include "ARMGenCodeEmitter.inc"