Temporarily Revert "Nuke the old JIT." as it's not quite ready to
[oota-llvm.git] / lib / Target / Mips / MipsCodeEmitter.cpp
1 //===-- Mips/MipsCodeEmitter.cpp - Convert Mips 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 Mips machine instructions
11 // into relocatable machine code.
12 //
13 //===---------------------------------------------------------------------===//
14
15 #include "Mips.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsInstrInfo.h"
18 #include "MipsRelocations.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/JITCodeEmitter.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/PassManager.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #ifndef NDEBUG
38 #include <iomanip>
39 #endif
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "jit"
44
45 STATISTIC(NumEmitted, "Number of machine instructions emitted");
46
47 namespace {
48
49 class MipsCodeEmitter : public MachineFunctionPass {
50   MipsJITInfo *JTI;
51   const MipsInstrInfo *II;
52   const DataLayout *TD;
53   const MipsSubtarget *Subtarget;
54   TargetMachine &TM;
55   JITCodeEmitter &MCE;
56   const std::vector<MachineConstantPoolEntry> *MCPEs;
57   const std::vector<MachineJumpTableEntry> *MJTEs;
58   bool IsPIC;
59
60   void getAnalysisUsage(AnalysisUsage &AU) const override {
61     AU.addRequired<MachineModuleInfo> ();
62     MachineFunctionPass::getAnalysisUsage(AU);
63   }
64
65   static char ID;
66
67 public:
68   MipsCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
69     : MachineFunctionPass(ID), JTI(nullptr), II(nullptr), TD(nullptr),
70       TM(tm), MCE(mce), MCPEs(nullptr), MJTEs(nullptr),
71       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
72
73   bool runOnMachineFunction(MachineFunction &MF) override;
74
75   const char *getPassName() const override {
76     return "Mips Machine Code Emitter";
77   }
78
79   /// getBinaryCodeForInstr - This function, generated by the
80   /// CodeEmitterGenerator using TableGen, produces the binary encoding for
81   /// machine instructions.
82   uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
83
84   void emitInstruction(MachineBasicBlock::instr_iterator MI,
85                        MachineBasicBlock &MBB);
86
87 private:
88
89   void emitWord(unsigned Word);
90
91   /// Routines that handle operands which add machine relocations which are
92   /// fixed up by the relocation stage.
93   void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
94                          bool MayNeedFarStub) const;
95   void emitExternalSymbolAddress(const char *ES, unsigned Reloc) const;
96   void emitConstPoolAddress(unsigned CPI, unsigned Reloc) const;
97   void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const;
98   void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc) const;
99
100   /// getMachineOpValue - Return binary encoding of operand. If the machine
101   /// operand requires relocation, record the relocation and return zero.
102   unsigned getMachineOpValue(const MachineInstr &MI,
103                              const MachineOperand &MO) const;
104
105   unsigned getRelocation(const MachineInstr &MI,
106                          const MachineOperand &MO) const;
107
108   unsigned getJumpTargetOpValue(const MachineInstr &MI, unsigned OpNo) const;
109   unsigned getJumpTargetOpValueMM(const MachineInstr &MI, unsigned OpNo) const;
110   unsigned getBranchTargetOpValueMM(const MachineInstr &MI,
111                                     unsigned OpNo) const;
112
113   unsigned getBranchTarget21OpValue(const MachineInstr &MI,
114                                     unsigned OpNo) const;
115   unsigned getBranchTarget26OpValue(const MachineInstr &MI,
116                                     unsigned OpNo) const;
117   unsigned getJumpOffset16OpValue(const MachineInstr &MI, unsigned OpNo) const;
118
119   unsigned getBranchTargetOpValue(const MachineInstr &MI, unsigned OpNo) const;
120   unsigned getMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
121   unsigned getMemEncodingMMImm12(const MachineInstr &MI, unsigned OpNo) const;
122   unsigned getMSAMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
123   unsigned getSizeExtEncoding(const MachineInstr &MI, unsigned OpNo) const;
124   unsigned getSizeInsEncoding(const MachineInstr &MI, unsigned OpNo) const;
125   unsigned getLSAImmEncoding(const MachineInstr &MI, unsigned OpNo) const;
126   unsigned getSimm19Lsl2Encoding(const MachineInstr &MI, unsigned OpNo) const;
127   unsigned getSimm18Lsl3Encoding(const MachineInstr &MI, unsigned OpNo) const;
128
129   /// Expand pseudo instructions with accumulator register operands.
130   void expandACCInstr(MachineBasicBlock::instr_iterator MI,
131                       MachineBasicBlock &MBB, unsigned Opc) const;
132
133   void expandPseudoIndirectBranch(MachineBasicBlock::instr_iterator MI,
134                                   MachineBasicBlock &MBB) const;
135
136   /// \brief Expand pseudo instruction. Return true if MI was expanded.
137   bool expandPseudos(MachineBasicBlock::instr_iterator &MI,
138                      MachineBasicBlock &MBB) const;
139 };
140 }
141
142 char MipsCodeEmitter::ID = 0;
143
144 bool MipsCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
145   MipsTargetMachine &Target = static_cast<MipsTargetMachine &>(
146                                 const_cast<TargetMachine &>(MF.getTarget()));
147   // Initialize the subtarget so that we can grab the subtarget dependent
148   // variables from it.
149   Subtarget = &TM.getSubtarget<MipsSubtarget>();
150   JTI = Target.getSubtargetImpl()->getJITInfo();
151   II = Subtarget->getInstrInfo();
152   TD = Subtarget->getDataLayout();
153   MCPEs = &MF.getConstantPool()->getConstants();
154   MJTEs = nullptr;
155   if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
156   JTI->Initialize(MF, IsPIC, Subtarget->isLittle());
157   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo> ());
158
159   do {
160     DEBUG(errs() << "JITTing function '"
161         << MF.getName() << "'\n");
162     MCE.startFunction(MF);
163
164     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
165         MBB != E; ++MBB){
166       MCE.StartMachineBasicBlock(MBB);
167       for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(),
168            E = MBB->instr_end(); I != E;)
169         emitInstruction(*I++, *MBB);
170     }
171   } while (MCE.finishFunction(MF));
172
173   return false;
174 }
175
176 unsigned MipsCodeEmitter::getRelocation(const MachineInstr &MI,
177                                         const MachineOperand &MO) const {
178   // NOTE: This relocations are for static.
179   uint64_t TSFlags = MI.getDesc().TSFlags;
180   uint64_t Form = TSFlags & MipsII::FormMask;
181   if (Form == MipsII::FrmJ)
182     return Mips::reloc_mips_26;
183   if ((Form == MipsII::FrmI || Form == MipsII::FrmFI)
184        && MI.isBranch())
185     return Mips::reloc_mips_pc16;
186   if (Form == MipsII::FrmI && MI.getOpcode() == Mips::LUi)
187     return Mips::reloc_mips_hi;
188   return Mips::reloc_mips_lo;
189 }
190
191 unsigned MipsCodeEmitter::getJumpTargetOpValue(const MachineInstr &MI,
192                                                unsigned OpNo) const {
193   MachineOperand MO = MI.getOperand(OpNo);
194   if (MO.isGlobal())
195     emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
196   else if (MO.isSymbol())
197     emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
198   else if (MO.isMBB())
199     emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
200   else
201     llvm_unreachable("Unexpected jump target operand kind.");
202   return 0;
203 }
204
205 unsigned MipsCodeEmitter::getJumpTargetOpValueMM(const MachineInstr &MI,
206                                                  unsigned OpNo) const {
207   llvm_unreachable("Unimplemented function.");
208   return 0;
209 }
210
211 unsigned MipsCodeEmitter::getBranchTargetOpValueMM(const MachineInstr &MI,
212                                                    unsigned OpNo) const {
213   llvm_unreachable("Unimplemented function.");
214   return 0;
215 }
216
217 unsigned MipsCodeEmitter::getBranchTarget21OpValue(const MachineInstr &MI,
218                                                    unsigned OpNo) const {
219   llvm_unreachable("Unimplemented function.");
220   return 0;
221 }
222
223 unsigned MipsCodeEmitter::getBranchTarget26OpValue(const MachineInstr &MI,
224                                                    unsigned OpNo) const {
225   llvm_unreachable("Unimplemented function.");
226   return 0;
227 }
228
229 unsigned MipsCodeEmitter::getJumpOffset16OpValue(const MachineInstr &MI,
230                                                  unsigned OpNo) const {
231   llvm_unreachable("Unimplemented function.");
232   return 0;
233 }
234
235 unsigned MipsCodeEmitter::getBranchTargetOpValue(const MachineInstr &MI,
236                                                  unsigned OpNo) const {
237   MachineOperand MO = MI.getOperand(OpNo);
238   emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
239   return 0;
240 }
241
242 unsigned MipsCodeEmitter::getMemEncoding(const MachineInstr &MI,
243                                          unsigned OpNo) const {
244   // Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
245   assert(MI.getOperand(OpNo).isReg());
246   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo)) << 16;
247   return (getMachineOpValue(MI, MI.getOperand(OpNo+1)) & 0xFFFF) | RegBits;
248 }
249
250 unsigned MipsCodeEmitter::getMemEncodingMMImm12(const MachineInstr &MI,
251                                                 unsigned OpNo) const {
252   llvm_unreachable("Unimplemented function.");
253   return 0;
254 }
255
256 unsigned MipsCodeEmitter::getMSAMemEncoding(const MachineInstr &MI,
257                                             unsigned OpNo) const {
258   llvm_unreachable("Unimplemented function.");
259   return 0;
260 }
261
262 unsigned MipsCodeEmitter::getSizeExtEncoding(const MachineInstr &MI,
263                                              unsigned OpNo) const {
264   // size is encoded as size-1.
265   return getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
266 }
267
268 unsigned MipsCodeEmitter::getSizeInsEncoding(const MachineInstr &MI,
269                                              unsigned OpNo) const {
270   // size is encoded as pos+size-1.
271   return getMachineOpValue(MI, MI.getOperand(OpNo-1)) +
272          getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
273 }
274
275 unsigned MipsCodeEmitter::getLSAImmEncoding(const MachineInstr &MI,
276                                             unsigned OpNo) const {
277   llvm_unreachable("Unimplemented function.");
278   return 0;
279 }
280
281 unsigned MipsCodeEmitter::getSimm18Lsl3Encoding(const MachineInstr &MI,
282                                                 unsigned OpNo) const {
283   llvm_unreachable("Unimplemented function.");
284   return 0;
285 }
286
287 unsigned MipsCodeEmitter::getSimm19Lsl2Encoding(const MachineInstr &MI,
288                                                 unsigned OpNo) const {
289   llvm_unreachable("Unimplemented function.");
290   return 0;
291 }
292
293 /// getMachineOpValue - Return binary encoding of operand. If the machine
294 /// operand requires relocation, record the relocation and return zero.
295 unsigned MipsCodeEmitter::getMachineOpValue(const MachineInstr &MI,
296                                             const MachineOperand &MO) const {
297   if (MO.isReg())
298     return TM.getSubtargetImpl()->getRegisterInfo()->getEncodingValue(
299         MO.getReg());
300   else if (MO.isImm())
301     return static_cast<unsigned>(MO.getImm());
302   else if (MO.isGlobal())
303     emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
304   else if (MO.isSymbol())
305     emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
306   else if (MO.isCPI())
307     emitConstPoolAddress(MO.getIndex(), getRelocation(MI, MO));
308   else if (MO.isJTI())
309     emitJumpTableAddress(MO.getIndex(), getRelocation(MI, MO));
310   else if (MO.isMBB())
311     emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
312   else
313     llvm_unreachable("Unable to encode MachineOperand!");
314   return 0;
315 }
316
317 void MipsCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
318                                         bool MayNeedFarStub) const {
319   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
320                                              const_cast<GlobalValue *>(GV), 0,
321                                              MayNeedFarStub));
322 }
323
324 void MipsCodeEmitter::
325 emitExternalSymbolAddress(const char *ES, unsigned Reloc) const {
326   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
327                                                  Reloc, ES, 0, 0));
328 }
329
330 void MipsCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) const {
331   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
332                                                     Reloc, CPI, 0, false));
333 }
334
335 void MipsCodeEmitter::
336 emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const {
337   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
338                                                     Reloc, JTIndex, 0, false));
339 }
340
341 void MipsCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
342                                             unsigned Reloc) const {
343   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
344                                              Reloc, BB));
345 }
346
347 void MipsCodeEmitter::emitInstruction(MachineBasicBlock::instr_iterator MI,
348                                       MachineBasicBlock &MBB) {
349   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << *MI);
350
351   // Expand pseudo instruction. Skip if MI was not expanded.
352   if (((MI->getDesc().TSFlags & MipsII::FormMask) == MipsII::Pseudo) &&
353       !expandPseudos(MI, MBB))
354     return;
355
356   MCE.processDebugLoc(MI->getDebugLoc(), true);
357
358   emitWord(getBinaryCodeForInstr(*MI));
359   ++NumEmitted;  // Keep track of the # of mi's emitted
360
361   MCE.processDebugLoc(MI->getDebugLoc(), false);
362 }
363
364 void MipsCodeEmitter::emitWord(unsigned Word) {
365   DEBUG(errs() << "  0x";
366         errs().write_hex(Word) << "\n");
367   if (Subtarget->isLittle())
368     MCE.emitWordLE(Word);
369   else
370     MCE.emitWordBE(Word);
371 }
372
373 void MipsCodeEmitter::expandACCInstr(MachineBasicBlock::instr_iterator MI,
374                                      MachineBasicBlock &MBB,
375                                      unsigned Opc) const {
376   // Expand "pseudomult $ac0, $t0, $t1" to "mult $t0, $t1".
377   BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Opc))
378     .addReg(MI->getOperand(1).getReg()).addReg(MI->getOperand(2).getReg());
379 }
380
381 void MipsCodeEmitter::expandPseudoIndirectBranch(
382     MachineBasicBlock::instr_iterator MI, MachineBasicBlock &MBB) const {
383   // This logic is duplicated from MipsAsmPrinter::emitPseudoIndirectBranch()
384   bool HasLinkReg = false;
385   unsigned Opcode = 0;
386
387   if (Subtarget->hasMips64r6()) {
388     // MIPS64r6 should use (JALR64 ZERO_64, $rs)
389     Opcode = Mips::JALR64;
390     HasLinkReg = true;
391   } else if (Subtarget->hasMips32r6()) {
392     // MIPS32r6 should use (JALR ZERO, $rs)
393     Opcode = Mips::JALR;
394     HasLinkReg = true;
395   } else if (Subtarget->inMicroMipsMode())
396     // microMIPS should use (JR_MM $rs)
397     Opcode = Mips::JR_MM;
398   else {
399     // Everything else should use (JR $rs)
400     Opcode = Mips::JR;
401   }
402
403   auto MIB = BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Opcode));
404
405   if (HasLinkReg) {
406     unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
407     MIB.addReg(ZeroReg);
408   }
409
410   MIB.addReg(MI->getOperand(0).getReg());
411 }
412
413 bool MipsCodeEmitter::expandPseudos(MachineBasicBlock::instr_iterator &MI,
414                                     MachineBasicBlock &MBB) const {
415   switch (MI->getOpcode()) {
416   default:
417     llvm_unreachable("Unhandled pseudo");
418     return false;
419   case Mips::NOP:
420     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::SLL), Mips::ZERO)
421       .addReg(Mips::ZERO).addImm(0);
422     break;
423   case Mips::B:
424     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BEQ)).addReg(Mips::ZERO)
425       .addReg(Mips::ZERO).addOperand(MI->getOperand(0));
426     break;
427   case Mips::TRAP:
428     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BREAK)).addImm(0)
429       .addImm(0);
430     break;
431   case Mips::JALRPseudo:
432     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::JALR), Mips::RA)
433       .addReg(MI->getOperand(0).getReg());
434     break;
435   case Mips::PseudoMULT:
436     expandACCInstr(MI, MBB, Mips::MULT);
437     break;
438   case Mips::PseudoMULTu:
439     expandACCInstr(MI, MBB, Mips::MULTu);
440     break;
441   case Mips::PseudoSDIV:
442     expandACCInstr(MI, MBB, Mips::SDIV);
443     break;
444   case Mips::PseudoUDIV:
445     expandACCInstr(MI, MBB, Mips::UDIV);
446     break;
447   case Mips::PseudoMADD:
448     expandACCInstr(MI, MBB, Mips::MADD);
449     break;
450   case Mips::PseudoMADDU:
451     expandACCInstr(MI, MBB, Mips::MADDU);
452     break;
453   case Mips::PseudoMSUB:
454     expandACCInstr(MI, MBB, Mips::MSUB);
455     break;
456   case Mips::PseudoMSUBU:
457     expandACCInstr(MI, MBB, Mips::MSUBU);
458     break;
459   case Mips::PseudoReturn:
460   case Mips::PseudoReturn64:
461   case Mips::PseudoIndirectBranch:
462   case Mips::PseudoIndirectBranch64:
463       expandPseudoIndirectBranch(MI, MBB);
464       break;
465   case TargetOpcode::CFI_INSTRUCTION:
466   case TargetOpcode::IMPLICIT_DEF:
467   case TargetOpcode::KILL:
468       // Do nothing
469       return false;
470   }
471
472   (MI--)->eraseFromBundle();
473   return true;
474 }
475
476 /// createMipsJITCodeEmitterPass - Return a pass that emits the collected Mips
477 /// code to the specified MCE object.
478 FunctionPass *llvm::createMipsJITCodeEmitterPass(MipsTargetMachine &TM,
479                                                  JITCodeEmitter &JCE) {
480   return new MipsCodeEmitter(TM, JCE);
481 }
482
483 #include "MipsGenCodeEmitter.inc"