Refactor the machine code emitter interface to pull the pointers for the current
[oota-llvm.git] / lib / Target / PowerPC / PPCCodeEmitter.cpp
1 //===-- PPCCodeEmitter.cpp - JIT Code Emitter for PowerPC32 -------*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PowerPC 32-bit CodeEmitter and associated machinery to
11 // JIT-compile bytecode to native PowerPC.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPCTargetMachine.h"
16 #include "PPCRelocations.h"
17 #include "PPC.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include <iostream>
27 using namespace llvm;
28
29 namespace {
30   class PPCCodeEmitter : public MachineFunctionPass {
31     TargetMachine &TM;
32     MachineCodeEmitter &MCE;
33
34     // Tracks which instruction references which BasicBlock
35     std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs;
36     // Tracks where each BasicBlock starts
37     std::map<MachineBasicBlock*, uint64_t> BBLocations;
38
39     /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
40     ///
41     int getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
42
43   public:
44     PPCCodeEmitter(TargetMachine &T, MachineCodeEmitter &M)
45       : TM(T), MCE(M) {}
46
47     const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
48
49     /// runOnMachineFunction - emits the given MachineFunction to memory
50     ///
51     bool runOnMachineFunction(MachineFunction &MF);
52
53     /// emitBasicBlock - emits the given MachineBasicBlock to memory
54     ///
55     void emitBasicBlock(MachineBasicBlock &MBB);
56
57     /// emitWord - write a 32-bit word to memory at the current PC
58     ///
59     void emitWord(unsigned w) { MCE.emitWord(w); }
60
61     /// getValueBit - return the particular bit of Val
62     ///
63     unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
64
65     /// getBinaryCodeForInstr - This function, generated by the
66     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
67     /// machine instructions.
68     ///
69     unsigned getBinaryCodeForInstr(MachineInstr &MI);
70   };
71 }
72
73 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
74 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
75 /// actually outputting the machine code and resolving things like the address
76 /// of functions.  This method should returns true if machine code emission is
77 /// not supported.
78 ///
79 bool PPCTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
80                                                   MachineCodeEmitter &MCE) {
81   // Machine code emitter pass for PowerPC
82   PM.add(new PPCCodeEmitter(*this, MCE));
83   // Delete machine code for this function after emitting it
84   PM.add(createMachineCodeDeleter());
85   return false;
86 }
87
88 bool PPCCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
89   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
90           MF.getTarget().getRelocationModel() != Reloc::Static) &&
91          "JIT relocation model must be set to static or default!");
92   do {
93     BBRefs.clear();
94     BBLocations.clear();
95
96     MCE.startFunction(MF);
97     MCE.emitConstantPool(MF.getConstantPool());
98     MCE.initJumpTableInfo(MF.getJumpTableInfo());
99     for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
100       emitBasicBlock(*BB);
101     MCE.emitJumpTableInfo(MF.getJumpTableInfo(), BBLocations);
102   } while (MCE.finishFunction(MF));
103
104   // Resolve branches to BasicBlocks for the entire function
105   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
106     intptr_t Location = BBLocations[BBRefs[i].first];
107     unsigned *Ref = BBRefs[i].second;
108     DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location
109                     << "\n");
110     unsigned Instr = *Ref;
111     intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2;
112
113     switch (Instr >> 26) {
114     default: assert(0 && "Unknown branch user!");
115     case 18:  // This is B or BL
116       *Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2;
117       break;
118     case 16:  // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction
119       *Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2;
120       break;
121     }
122   }
123   BBRefs.clear();
124   BBLocations.clear();
125
126   return false;
127 }
128
129 void PPCCodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
130   BBLocations[&MBB] = MCE.getCurrentPCValue();
131   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
132     MachineInstr &MI = *I;
133     unsigned Opcode = MI.getOpcode();
134     switch (MI.getOpcode()) {
135     default:
136       emitWord(getBinaryCodeForInstr(*I));
137       break;
138     case PPC::IMPLICIT_DEF_GPR:
139     case PPC::IMPLICIT_DEF_F8:
140     case PPC::IMPLICIT_DEF_F4:
141     case PPC::IMPLICIT_DEF_VRRC:
142       break; // pseudo opcode, no side effects
143     case PPC::MovePCtoLR:
144       assert(0 && "CodeEmitter does not support MovePCtoLR instruction");
145       break;
146     }
147   }
148 }
149
150 int PPCCodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) {
151
152   int rv = 0; // Return value; defaults to 0 for unhandled cases
153                   // or things that get fixed up later by the JIT.
154   if (MO.isRegister()) {
155     rv = PPCRegisterInfo::getRegisterNumbering(MO.getReg());
156
157     // Special encoding for MTCRF and MFOCRF, which uses a bit mask for the
158     // register, not the register number directly.
159     if ((MI.getOpcode() == PPC::MTCRF || MI.getOpcode() == PPC::MFOCRF) &&
160         (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7)) {
161       rv = 0x80 >> rv;
162     }
163   } else if (MO.isImmediate()) {
164     rv = MO.getImmedValue();
165   } else if (MO.isGlobalAddress() || MO.isExternalSymbol()) {
166     unsigned Reloc = 0;
167     if (MI.getOpcode() == PPC::BL)
168       Reloc = PPC::reloc_pcrel_bx;
169     else {
170       switch (MI.getOpcode()) {
171       default: MI.dump(); assert(0 && "Unknown instruction for relocation!");
172       case PPC::LIS:
173         Reloc = PPC::reloc_absolute_high;       // Pointer to symbol
174         break;
175       case PPC::LI:
176       case PPC::LA:
177       case PPC::LBZ:
178       case PPC::LHA:
179       case PPC::LHZ:
180       case PPC::LWZ:
181       case PPC::LFS:
182       case PPC::LFD:
183       case PPC::STB:
184       case PPC::STH:
185       case PPC::STW:
186       case PPC::STFS:
187       case PPC::STFD:
188         Reloc = PPC::reloc_absolute_low;
189         break;
190       }
191     }
192     if (MO.isGlobalAddress())
193       MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
194                                           Reloc, MO.getGlobal(), 0));
195     else
196       MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
197                                           Reloc, MO.getSymbolName(), 0));
198   } else if (MO.isMachineBasicBlock()) {
199     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
200     BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC));
201   } else if (MO.isConstantPoolIndex() || MO.isJumpTableIndex()) {
202     if (MO.isConstantPoolIndex())
203       rv = MCE.getConstantPoolEntryAddress(MO.getConstantPoolIndex());
204     else
205       rv = MCE.getJumpTableEntryAddress(MO.getJumpTableIndex());
206
207     unsigned Opcode = MI.getOpcode();
208     if (Opcode == PPC::LIS || Opcode == PPC::ADDIS) {
209       // lis wants hi16(addr)
210       if ((short)rv < 0) rv += 1 << 16;
211       rv >>= 16;
212     } else if (Opcode == PPC::LWZ || Opcode == PPC::LA ||
213                Opcode == PPC::LI ||
214                Opcode == PPC::LFS || Opcode == PPC::LFD) {
215       // These load opcodes want lo16(addr)
216       rv &= 0xffff;
217     } else {
218       assert(0 && "Unknown constant pool or jump table using instruction!");
219     }
220   } else {
221     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
222     abort();
223   }
224
225   return rv;
226 }
227
228 #include "PPCGenCodeEmitter.inc"
229