Tidy up several unbeseeming casts from pointer to intptr_t.
[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 "arm-emitter"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMInstrInfo.h"
19 #include "ARMRelocations.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/CodeGen/MachineCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
29 using namespace llvm;
30
31 STATISTIC(NumEmitted, "Number of machine instructions emitted");
32
33 namespace {
34   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
35     const ARMInstrInfo  *II;
36     const TargetData    *TD;
37     TargetMachine       &TM;
38     MachineCodeEmitter  &MCE;
39   public:
40     static char ID;
41     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
42       : MachineFunctionPass(&ID), II(0), TD(0), TM(tm),
43       MCE(mce) {}
44     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
45             const ARMInstrInfo &ii, const TargetData &td)
46       : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm),
47       MCE(mce) {}
48
49     bool runOnMachineFunction(MachineFunction &MF);
50
51     virtual const char *getPassName() const {
52       return "ARM Machine Code Emitter";
53     }
54
55     void emitInstruction(const MachineInstr &MI);
56
57   private:
58     unsigned getAddrModeNoneInstrBinary(const MachineInstr &MI,
59                                         const TargetInstrDesc &Desc,
60                                         unsigned Binary) ;
61     unsigned getAddrMode1InstrBinary(const MachineInstr &MI,
62                                      const TargetInstrDesc &Desc,
63                                      unsigned Binary);
64     unsigned getAddrMode2InstrBinary(const MachineInstr &MI,
65                                      const TargetInstrDesc &Desc,
66                                      unsigned Binary);
67     unsigned getAddrMode3InstrBinary(const MachineInstr &MI,
68                                      const TargetInstrDesc &Desc,
69                                      unsigned Binary);
70     unsigned getAddrMode4InstrBinary(const MachineInstr &MI,
71                                      const TargetInstrDesc &Desc,
72                                      unsigned Binary);
73
74     /// getInstrBinary - Return binary encoding for the specified
75     /// machine instruction.
76     unsigned getInstrBinary(const MachineInstr &MI);
77
78     /// getBinaryCodeForInstr - This function, generated by the
79     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
80     /// machine instructions.
81     ///
82     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
83
84     /// getMachineOpValue - Return binary encoding of operand. If the machine
85     /// operand requires relocation, record the relocation and return zero.
86     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
87       return getMachineOpValue(MI, MI.getOperand(OpIdx));
88     }
89     unsigned getMachineOpValue(const MachineInstr &MI,
90                                const MachineOperand &MO);
91
92     /// getBaseOpcodeFor - Return the opcode value.
93     ///
94     unsigned getBaseOpcodeFor(const TargetInstrDesc &TID) const {
95       return (TID.TSFlags & ARMII::OpcodeMask) >> ARMII::OpcodeShift;
96     }
97
98     /// getShiftOp - Return the shift opcode (bit[6:5]) of the machine operand.
99     ///
100     unsigned getShiftOp(const MachineOperand &MO) const ;
101
102     /// Routines that handle operands which add machine relocations which are
103     /// fixed up by the JIT fixup stage.
104     void emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub);
105     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
106     void emitConstPoolAddress(unsigned CPI, unsigned Reloc,
107                               int Disp = 0, unsigned PCAdj = 0 );
108     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
109                               unsigned PCAdj = 0);
110     void emitGlobalConstant(const Constant *CV);
111     void emitMachineBasicBlock(MachineBasicBlock *BB);
112   };
113   char ARMCodeEmitter::ID = 0;
114 }
115
116 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
117 /// to the specified MCE object.
118 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
119                                              MachineCodeEmitter &MCE) {
120   return new ARMCodeEmitter(TM, MCE);
121 }
122
123 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
124   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
125           MF.getTarget().getRelocationModel() != Reloc::Static) &&
126          "JIT relocation model must be set to static or default!");
127   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
128   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
129
130   do {
131     MCE.startFunction(MF);
132     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
133          MBB != E; ++MBB) {
134       MCE.StartMachineBasicBlock(MBB);
135       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
136            I != E; ++I)
137         emitInstruction(*I);
138     }
139   } while (MCE.finishFunction(MF));
140
141   return false;
142 }
143
144 /// getShiftOp - Return the shift opcode (bit[6:5]) of the machine operand.
145 ///
146 unsigned ARMCodeEmitter::getShiftOp(const MachineOperand &MO) const {
147   switch (ARM_AM::getAM2ShiftOpc(MO.getImm())) {
148   default: assert(0 && "Unknown shift opc!");
149   case ARM_AM::asr: return 2;
150   case ARM_AM::lsl: return 0;
151   case ARM_AM::lsr: return 1;
152   case ARM_AM::ror:
153   case ARM_AM::rrx: return 3;
154   }
155   return 0;
156 }
157
158 /// getMachineOpValue - Return binary encoding of operand. If the machine
159 /// operand requires relocation, record the relocation and return zero.
160 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
161                                            const MachineOperand &MO) {
162   if (MO.isRegister())
163     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
164   else if (MO.isImmediate())
165     return static_cast<unsigned>(MO.getImm());
166   else if (MO.isGlobalAddress())
167     emitGlobalAddressForCall(MO.getGlobal(), false);
168   else if (MO.isExternalSymbol())
169     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
170   else if (MO.isConstantPoolIndex())
171     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_relative);
172   else if (MO.isJumpTableIndex())
173     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
174   else if (MO.isMachineBasicBlock())
175     emitMachineBasicBlock(MO.getMBB());
176
177   abort();
178   return 0;
179 }
180
181 /// emitGlobalAddressForCall - Emit the specified address to the code stream
182 /// assuming this is part of a function call, which is PC relative.
183 ///
184 void ARMCodeEmitter::emitGlobalAddressForCall(GlobalValue *GV,
185                                               bool DoesntNeedStub) {
186   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
187                                              ARM::reloc_arm_branch, GV, 0,
188                                              DoesntNeedStub));
189 }
190
191 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
192 /// be emitted to the current location in the function, and allow it to be PC
193 /// relative.
194 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
195   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
196                                                  Reloc, ES));
197 }
198
199 /// emitConstPoolAddress - Arrange for the address of an constant pool
200 /// to be emitted to the current location in the function, and allow it to be PC
201 /// relative.
202 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
203                                           int Disp /* = 0 */,
204                                           unsigned PCAdj /* = 0 */) {
205   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
206                                                     Reloc, CPI, PCAdj));
207 }
208
209 /// emitJumpTableAddress - Arrange for the address of a jump table to
210 /// be emitted to the current location in the function, and allow it to be PC
211 /// relative.
212 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
213                                           unsigned PCAdj /* = 0 */) {
214   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
215                                                     Reloc, JTI, PCAdj));
216 }
217
218 /// emitMachineBasicBlock - Emit the specified address basic block.
219 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB) {
220   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
221                                              ARM::reloc_arm_branch, BB));
222 }
223
224 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
225   NumEmitted++;  // Keep track of the # of mi's emitted
226   MCE.emitWordLE(getInstrBinary(MI));
227 }
228
229 unsigned ARMCodeEmitter::getAddrModeNoneInstrBinary(const MachineInstr &MI,
230                                                     const TargetInstrDesc &Desc,
231                                                     unsigned Binary) {
232   switch (Desc.TSFlags & ARMII::FormMask) {
233   default:
234     assert(0 && "Unknown instruction subtype!");
235     break;
236   case ARMII::Branch: {
237     // Set signed_immed_24 field
238     Binary |= getMachineOpValue(MI, 0);
239
240     // if it is a conditional branch, set cond field
241     if (Desc.Opcode == ARM::Bcc) {
242       Binary &= 0x0FFFFFFF;                      // clear conditional field
243       Binary |= getMachineOpValue(MI, 1) << 28;  // set conditional field
244     }
245     break;
246   }
247   case ARMII::BranchMisc: {
248     // Set bit[19:8] to 0xFFF
249     Binary |= 0xfff << 8;
250     if (Desc.Opcode == ARM::BX_RET)
251       Binary |= 0xe; // the return register is LR
252     else 
253       // otherwise, set the return register
254       Binary |= getMachineOpValue(MI, 0);
255     break;
256   }
257   }
258
259   return Binary;
260 }
261
262 unsigned ARMCodeEmitter::getAddrMode1InstrBinary(const MachineInstr &MI,
263                                                  const TargetInstrDesc &Desc,
264                                                  unsigned Binary) {
265   // FIXME: Clean up.
266   // Treat 3 special instructions: MOVsra_flag, MOVsrl_flag and MOVrx.
267   unsigned Format = Desc.TSFlags & ARMII::FormMask;
268   if (Format == ARMII::DPRdMisc) {
269     Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
270     Binary |= getMachineOpValue(MI, 1);
271     switch (Desc.Opcode) {
272     case ARM::MOVsra_flag:
273       Binary |= 0x1 << 6;
274       Binary |= 0x1 << 7;
275       break;
276     case ARM::MOVsrl_flag:
277       Binary |= 0x1 << 5;
278       Binary |= 0x1 << 7;
279       break;
280     case ARM::MOVrx:
281       Binary |= 0x3 << 5;
282       break;
283     }
284     return Binary;
285   }
286
287   // FIXME: Clean up this part.
288   // Data processing operand instructions has 3 possible encodings (for more
289   // information, see ARM-ARM page A3-10):
290   // 1. <instr> <Rd>,<shifter_operand>
291   // 2. <instr> <Rn>,<shifter_operand>
292   // 3. <instr> <Rd>,<Rn>,<shifter_operand>
293   bool IsDataProcessing1 = Format == ARMII::DPRdIm    ||
294                            Format == ARMII::DPRdReg   ||
295                            Format == ARMII::DPRdSoReg;
296   bool IsDataProcessing2 = Format == ARMII::DPRnIm    ||
297                            Format == ARMII::DPRnReg   ||
298                            Format == ARMII::DPRnSoReg;
299   bool IsDataProcessing3 = false;
300
301   if (Format == ARMII::DPRImS || Format == ARMII::DPRRegS ||
302       Format == ARMII::DPRSoRegS || IsDataProcessing2)
303     IsDataProcessing3 = !IsDataProcessing2;
304
305   IsDataProcessing3 = Format == ARMII::DPRIm     ||
306                       Format == ARMII::DPRReg    ||
307                       Format == ARMII::DPRSoReg  ||
308                       IsDataProcessing3;
309
310   // Set first operand
311   if (IsDataProcessing1 || IsDataProcessing3) {
312     Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
313   } else if (IsDataProcessing2) {
314     Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
315   }
316
317   // Set second operand of data processing #3 instructions
318   if (IsDataProcessing3)
319     Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
320
321   unsigned OpIdx = IsDataProcessing3 ? 2 : 1;
322   switch (Format) {
323   default:
324     assert(false && "Unknown operand type!");
325     break;
326   case ARMII::DPRdIm: case ARMII::DPRnIm:
327   case ARMII::DPRIm:  case ARMII::DPRImS: {
328     // Set bit I(25) to identify this is the immediate form of <shifter_op>
329     Binary |= 1 << ARMII::I_BitShift;
330     // Set immed_8 field
331     const MachineOperand &MO = MI.getOperand(OpIdx);
332     Binary |= ARM_AM::getSOImmVal(MO.getImm());
333     break;
334   }
335   case ARMII::DPRdReg: case ARMII::DPRnReg:
336   case ARMII::DPRReg:  case ARMII::DPRRegS: {
337     // Set last operand (register Rm)
338     Binary |= getMachineOpValue(MI, OpIdx);
339     break;
340   }
341   case ARMII::DPRdSoReg: case ARMII::DPRnSoReg:
342   case ARMII::DPRSoReg:  case ARMII::DPRSoRegS: {
343     // Set last operand (register Rm)
344     Binary |= getMachineOpValue(MI, OpIdx);
345
346     const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
347     const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
348
349     // Identify it the instr is in immed or register shifts encoding
350     bool IsShiftByRegister = MO1.getReg() > 0;
351     // Set shift operand (bit[6:4]).
352     // ASR - 101 if it is in register shifts encoding; 100, otherwise.
353     // LSL - 001 if it is in register shifts encoding; 000, otherwise.
354     // LSR - 011 if it is in register shifts encoding; 010, otherwise.
355     // ROR - 111 if it is in register shifts encoding; 110, otherwise.
356     // RRX - 110 and bit[11:7] clear.
357     switch (ARM_AM::getSORegShOp(MO2.getImm())) {
358     default: assert(0 && "Unknown shift opc!");
359     case ARM_AM::asr:
360       if (IsShiftByRegister)
361         Binary |= 0x5 << 4;
362       else
363         Binary |= 0x1 << 6;
364       break;
365     case ARM_AM::lsl:
366       if (IsShiftByRegister)
367         Binary |= 0x1 << 4;
368       break;
369     case ARM_AM::lsr:
370       if (IsShiftByRegister)
371         Binary |= 0x3 << 4;
372       else
373         Binary |= 0x1 << 5;
374       break;
375     case ARM_AM::ror:
376       if (IsShiftByRegister)
377         Binary |= 0x7 << 4;
378       else
379         Binary |= 0x3 << 5;
380       break;
381     case ARM_AM::rrx:
382       Binary |= 0x3 << 5;
383       break;
384     }
385
386     // Set the field related to shift operations (except rrx).
387     if (ARM_AM::getSORegShOp(MO2.getImm()) != ARM_AM::rrx) {
388       if (IsShiftByRegister) {
389         // Set the value of bit[11:8] (register Rs).
390         assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
391         Binary |= (ARMRegisterInfo::getRegisterNumbering(MO1.getReg()) <<
392                    ARMII::RegRsShift);
393       } else
394         // Set the value of bit [11:7] (shift_immed field).
395         Binary |= ARM_AM::getSORegOffset(MO2.getImm()) << 7;
396     }
397     break;
398   }
399   }
400
401   return Binary;
402 }
403
404 unsigned ARMCodeEmitter::getAddrMode2InstrBinary(const MachineInstr &MI,
405                                                  const TargetInstrDesc &Desc,
406                                                  unsigned Binary) {
407   // Set first operand
408   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
409
410   // Set second operand
411   Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
412
413   const MachineOperand &MO2 = MI.getOperand(2);
414   const MachineOperand &MO3 = MI.getOperand(3);
415
416   // Set bit U(23) according to signal of immed value (positive or negative).
417   Binary |= ((ARM_AM::getAM2Op(MO3.getImm()) == ARM_AM::add ? 1 : 0) <<
418             ARMII::U_BitShift);
419   if (!MO2.getReg()) { // is immediate
420     if (ARM_AM::getAM2Offset(MO3.getImm()))
421       // Set the value of offset_12 field
422       Binary |= ARM_AM::getAM2Offset(MO3.getImm());
423     return Binary;
424   }
425
426   // Set bit I(25), because this is not in immediate enconding.
427   Binary |= 1 << ARMII::I_BitShift;
428   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
429   // Set bit[3:0] to the corresponding Rm register
430   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
431
432   // if this instr is in scaled register offset/index instruction, set
433   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
434   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm())) {
435     Binary |= getShiftOp(MO3) << 5;  // shift
436     Binary |= ShImm           << 7;  // shift_immed
437   }
438
439   return Binary;
440 }
441
442 unsigned ARMCodeEmitter::getAddrMode3InstrBinary(const MachineInstr &MI,
443                                                  const TargetInstrDesc &Desc,
444                                                  unsigned Binary) {
445   // Set first operand
446   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
447
448   // Set second operand
449   Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
450
451   const MachineOperand &MO2 = MI.getOperand(2);
452   const MachineOperand &MO3 = MI.getOperand(3);
453
454   // Set bit U(23) according to signal of immed value (positive or negative)
455   Binary |= ((ARM_AM::getAM2Op(MO3.getImm()) == ARM_AM::add ? 1 : 0) <<
456              ARMII::U_BitShift);
457
458   // If this instr is in register offset/index encoding, set bit[3:0]
459   // to the corresponding Rm register.
460   if (MO2.getReg()) {
461     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
462     return Binary;
463   }
464
465   // if this instr is in immediate offset/index encoding, set bit 22 to 1
466   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm())) {
467     Binary |= 1 << 22;
468     // Set operands
469     Binary |= (ImmOffs >> 4) << 8;  // immedH
470     Binary |= (ImmOffs & ~0xF);     // immedL
471   }
472
473   return Binary;
474 }
475
476 unsigned ARMCodeEmitter::getAddrMode4InstrBinary(const MachineInstr &MI,
477                                                  const TargetInstrDesc &Desc,
478                                                  unsigned Binary) {
479   // Set first operand
480   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
481
482   // Set addressing mode by modifying bits U(23) and P(24)
483   // IA - Increment after  - bit U = 1 and bit P = 0
484   // IB - Increment before - bit U = 1 and bit P = 1
485   // DA - Decrement after  - bit U = 0 and bit P = 0
486   // DB - Decrement before - bit U = 0 and bit P = 1
487   const MachineOperand &MO = MI.getOperand(1);
488   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
489   switch (Mode) {
490   default: assert(0 && "Unknown addressing sub-mode!");
491   case ARM_AM::da:                      break;
492   case ARM_AM::db: Binary |= 0x1 << 24; break;
493   case ARM_AM::ia: Binary |= 0x1 << 23; break;
494   case ARM_AM::ib: Binary |= 0x3 << 23; break;
495   }
496
497   // Set bit W(21)
498   if (ARM_AM::getAM4WBFlag(MO.getImm()))
499     Binary |= 0x1 << 21;
500
501   // Set registers
502   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
503     const MachineOperand &MO = MI.getOperand(i);
504     if (MO.isRegister() && MO.isImplicit())
505       continue;
506     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
507     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
508            RegNum < 16);
509     Binary |= 0x1 << RegNum;
510   }
511
512   return Binary;
513 }
514
515 /// getInstrBinary - Return binary encoding for the specified
516 /// machine instruction.
517 unsigned ARMCodeEmitter::getInstrBinary(const MachineInstr &MI) {
518   // Part of binary is determined by TableGn.
519   unsigned Binary = getBinaryCodeForInstr(MI);
520
521   const TargetInstrDesc &Desc = MI.getDesc();
522   switch (Desc.TSFlags & ARMII::AddrModeMask) {
523   case ARMII::AddrModeNone:
524     return getAddrModeNoneInstrBinary(MI, Desc, Binary);
525   case ARMII::AddrMode1:
526     return getAddrMode1InstrBinary(MI, Desc, Binary);
527   case ARMII::AddrMode2:
528     return getAddrMode2InstrBinary(MI, Desc, Binary);
529   case ARMII::AddrMode3:
530     return getAddrMode3InstrBinary(MI, Desc, Binary);
531   case ARMII::AddrMode4:
532     return getAddrMode4InstrBinary(MI, Desc, Binary);
533   }
534
535   abort();
536   return 0;
537 }
538
539 #include "ARMGenCodeEmitter.inc"