Fix the last crimes against nature that used the 'ir' ordering to use the
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
index 07b1a0bcc3fdd53be5054d0ca0660e7b9d0b5627..a28d0ee86db8ca2a21f85a13c3b8f68fa325a1b9 100644 (file)
@@ -1,19 +1,35 @@
-//===-- X86/MachineCodeEmitter.cpp - Convert X86 code to machine code -----===//
+//===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
 //
 // This file contains the pass that transforms the X86 machine instructions into
 // actual executable machine code.
 //
 //===----------------------------------------------------------------------===//
 
+#define DEBUG_TYPE "jit"
 #include "X86TargetMachine.h"
 #include "X86.h"
 #include "llvm/PassManager.h"
 #include "llvm/CodeGen/MachineCodeEmitter.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstr.h"
-#include "llvm/Value.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/Function.h"
+#include "Support/Debug.h"
+#include "Support/Statistic.h"
+#include "Config/alloca.h"
+using namespace llvm;
 
 namespace {
+  Statistic<>
+  NumEmitted("x86-emitter", "Number of machine instructions emitted");
+
   class JITResolver {
     MachineCodeEmitter &MCE;
 
@@ -35,10 +51,28 @@ namespace {
     unsigned resolveFunctionReference(unsigned RetAddr);
   };
 
-  JITResolver *TheJITResolver;
+  static JITResolver &getResolver(MachineCodeEmitter &MCE) {
+    static JITResolver *TheJITResolver = 0;
+    if (TheJITResolver == 0)
+      TheJITResolver = new JITResolver(MCE);
+    return *TheJITResolver;
+  }
 }
 
 
+void *X86JITInfo::getJITStubForFunction(Function *F, MachineCodeEmitter &MCE) {
+  return (void*)((unsigned long)getResolver(MCE).getLazyResolver(F));
+}
+
+void X86JITInfo::replaceMachineCodeForFunction (void *Old, void *New) {
+  char *OldByte = (char *) Old;
+  *OldByte++ = 0xE9;                // Emit JMP opcode.
+  int32_t *OldWord = (int32_t *) OldByte;
+  int32_t NewAddr = (intptr_t) New;
+  int32_t OldAddr = (intptr_t) OldWord;
+  *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
+}
+
 /// addFunctionReference - This method is called when we need to emit the
 /// address of a function that has not yet been emitted, so we don't know the
 /// address.  Instead, we emit a call to the CompilationCallback method, and
@@ -70,11 +104,19 @@ unsigned JITResolver::getLazyResolver(Function *F) {
 
 void JITResolver::CompilationCallback() {
   unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
-  unsigned RetAddr = (unsigned)__builtin_return_address(0);
-
+  unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
   assert(StackPtr[1] == RetAddr &&
          "Could not find return address on the stack!");
-  bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD;  // Interrupt marker?
+
+  // It's a stub if there is an interrupt marker after the call...
+  bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
+
+  // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
+  // pointer elimination has been performed.  Having a variable sized alloca
+  // disables frame pointer elimination currently, even if it's dead.  This is a
+  // gross hack.
+  alloca(10+isStub);
+  // FIXME FIXME FIXME FIXME
 
   // The call instruction should have pushed the return value onto the stack...
   RetAddr -= 4;  // Backtrack to the reference itself...
@@ -87,20 +129,21 @@ void JITResolver::CompilationCallback() {
 #endif
 
   // Sanity check to make sure this really is a call instruction...
-  assert(((unsigned char*)RetAddr)[-1] == 0xE8 && "Not a call instr!");
+  assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
   
-  unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
+  JITResolver &JR = getResolver(*(MachineCodeEmitter*)0);
+  unsigned NewVal = JR.resolveFunctionReference(RetAddr);
 
   // Rewrite the call target... so that we don't fault every time we execute
   // the call.
-  *(unsigned*)RetAddr = NewVal-RetAddr-4;    
+  *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;    
 
   if (isStub) {
     // If this is a stub, rewrite the call into an unconditional branch
     // instruction so that two return addresses are not pushed onto the stack
     // when the requested function finally gets called.  This also makes the
     // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
-    ((unsigned char*)RetAddr)[-1] = 0xE9;
+    ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
   }
 
   // Change the return address to reexecute the call instruction...
@@ -130,8 +173,8 @@ namespace {
   class Emitter : public MachineFunctionPass {
     const X86InstrInfo  *II;
     MachineCodeEmitter  &MCE;
-    std::map<BasicBlock*, unsigned> BasicBlockAddrs;
-    std::vector<std::pair<BasicBlock*, unsigned> > BBRefs;
+    std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
+    std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
   public:
     Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
 
@@ -161,14 +204,16 @@ namespace {
 }
 
 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
-/// machine code emitted.  This uses a MAchineCodeEmitter object to handle
+/// machine code emitted.  This uses a MachineCodeEmitter object to handle
 /// actually outputting the machine code and resolving things like the address
 /// of functions.  This method should returns true if machine code emission is
 /// not supported.
 ///
-bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
+bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
                                                   MachineCodeEmitter &MCE) {
   PM.add(new Emitter(MCE));
+  // Delete machine code for this function
+  PM.add(createMachineCodeDeleter());
   return false;
 }
 
@@ -185,7 +230,7 @@ bool Emitter::runOnMachineFunction(MachineFunction &MF) {
   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
     unsigned Location = BasicBlockAddrs[BBRefs[i].first];
     unsigned Ref = BBRefs[i].second;
-    *(unsigned*)Ref = Location-Ref-4;
+    *(unsigned*)(intptr_t)Ref = Location-Ref-4;
   }
   BBRefs.clear();
   BasicBlockAddrs.clear();
@@ -197,7 +242,7 @@ void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
     BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
 
   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
-    emitInstruction(**I);
+    emitInstruction(*I);
 }
 
 
@@ -228,15 +273,10 @@ void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
   // Get the address from the backend...
   unsigned Address = MCE.getGlobalValueAddress(GV);
   
-  // If the machine code emitter doesn't know what the address IS yet, we have
-  // to take special measures.
-  //
   if (Address == 0) {
     // FIXME: this is JIT specific!
-    if (TheJITResolver == 0)
-      TheJITResolver = new JITResolver(MCE);
-    Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
-                                                   (Function*)GV);
+    Address = getResolver(MCE).addFunctionReference(MCE.getCurrentPCValue(),
+                                                    cast<Function>(GV));
   }
   emitMaybePCRelativeValue(Address, true);
 }
@@ -254,9 +294,7 @@ void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
   //
   if (Address == 0) {
     // FIXME: this is JIT specific!
-    if (TheJITResolver == 0)
-      TheJITResolver = new JITResolver(MCE);
-    Address = TheJITResolver->getLazyResolver((Function*)GV);
+    Address = getResolver(MCE).getLazyResolver((Function*)GV);
   }
 
   emitMaybePCRelativeValue(Address, false);
@@ -264,8 +302,9 @@ void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
 
 
 
-
-namespace N86 {  // Native X86 Register numbers...
+/// N86 namespace - Native X86 Register numbers... used by X86 backend.
+///
+namespace N86 {
   enum {
     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
   };
@@ -290,7 +329,7 @@ static unsigned getX86RegNum(unsigned RegNo) {
   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
     return RegNo-X86::ST0;
   default:
-    assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
+    assert(MRegisterInfo::isVirtualRegister(RegNo) &&
            "Unknown physical register!");
     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
     return 0;
@@ -428,16 +467,22 @@ static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
 }
 
 void Emitter::emitInstruction(MachineInstr &MI) {
+  NumEmitted++;  // Keep track of the # of mi's emitted
+
   unsigned Opcode = MI.getOpcode();
   const TargetInstrDescriptor &Desc = II->get(Opcode);
 
-  // Emit instruction prefixes if neccesary
+  // Emit the repeat opcode prefix as needed.
+  if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
+
+  // Emit instruction prefixes if necessary
   if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
 
   switch (Desc.TSFlags & X86II::Op0Mask) {
   case X86II::TB:
     MCE.emitByte(0x0F);   // Two-byte opcode prefix
     break;
+  case X86II::REP: break; // already handled.
   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
     MCE.emitByte(0xD8+
@@ -452,7 +497,9 @@ void Emitter::emitInstruction(MachineInstr &MI) {
   switch (Desc.TSFlags & X86II::FormMask) {
   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
   case X86II::Pseudo:
-    if (Opcode != X86::IMPLICIT_USE)
+    if (Opcode != X86::IMPLICIT_USE &&
+        Opcode != X86::IMPLICIT_DEF &&
+        Opcode != X86::FP_REG_KILL)
       std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
     break;
 
@@ -505,10 +552,10 @@ void Emitter::emitInstruction(MachineInstr &MI) {
 
   case X86II::MRMDestReg: {
     MCE.emitByte(BaseOpcode);
-    MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
-    emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
-    if (MI.getNumOperands() == 4)
-      emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
+    emitRegModRMByte(MI.getOperand(0).getReg(),
+                     getX86RegNum(MI.getOperand(1).getReg()));
+    if (MI.getNumOperands() == 3)
+      emitConstant(MI.getOperand(2).getImmedValue(), sizeOfPtr(Desc));
     break;
   }
   case X86II::MRMDestMem:
@@ -518,8 +565,11 @@ void Emitter::emitInstruction(MachineInstr &MI) {
 
   case X86II::MRMSrcReg:
     MCE.emitByte(BaseOpcode);
-    emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
+
+    emitRegModRMByte(MI.getOperand(1).getReg(),
                      getX86RegNum(MI.getOperand(0).getReg()));
+    if (MI.getNumOperands() == 3)
+      emitConstant(MI.getOperand(2).getImmedValue(), sizeOfPtr(Desc));
     break;
 
   case X86II::MRMSrcMem: