gallivm: Use LLVMPrintValueToString where available.
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_debug.cpp
index 4f9546a1f5d42bb551c74ff355ebb2cd8c3b55f0..a8c3899ea6674e5516af7aa47343f0abbe13f34a 100644 (file)
  **************************************************************************/
 
 #include <stddef.h>
+#include <fstream>
+#include <sstream>
+#include <iomanip>
 
 #include <llvm-c/Core.h>
-#include <llvm/Target/TargetMachine.h>
-#include <llvm/Target/TargetInstrInfo.h>
+#include <llvm-c/Disassembler.h>
 #include <llvm/Support/raw_ostream.h>
 #include <llvm/Support/Format.h>
-#include <llvm/Support/MemoryObject.h>
-
-#if HAVE_LLVM >= 0x0306
-#include <llvm/Target/TargetSubtargetInfo.h>
-#endif
-
-#include <llvm/Support/TargetRegistry.h>
-#include <llvm/MC/MCSubtargetInfo.h>
-
 #include <llvm/Support/Host.h>
-
 #include <llvm/IR/Module.h>
 
-#include <llvm/MC/MCDisassembler.h>
-#include <llvm/MC/MCAsmInfo.h>
-#include <llvm/MC/MCInst.h>
-#include <llvm/MC/MCInstPrinter.h>
-#include <llvm/MC/MCRegisterInfo.h>
-
-#if HAVE_LLVM >= 0x0305
-#define OwningPtr std::unique_ptr
-#else
-#include <llvm/ADT/OwningPtr.h>
-#endif
-
-#if HAVE_LLVM >= 0x0305
-#include <llvm/MC/MCContext.h>
-#endif
-
 #include "util/u_math.h"
 #include "util/u_debug.h"
 
@@ -89,36 +65,6 @@ lp_check_alignment(const void *ptr, unsigned alignment)
 }
 
 
-class raw_debug_ostream :
-   public llvm::raw_ostream
-{
-private:
-   uint64_t pos;
-
-public:
-   raw_debug_ostream() : pos(0) { }
-
-   void write_impl(const char *Ptr, size_t Size);
-
-   uint64_t current_pos() const { return pos; }
-   size_t preferred_buffer_size() const { return 512; }
-};
-
-
-void
-raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
-{
-   if (Size > 0) {
-      char *lastPtr = (char *)&Ptr[Size];
-      char last = *lastPtr;
-      *lastPtr = 0;
-      _debug_printf("%*s", Size, Ptr);
-      *lastPtr = last;
-      pos += Size;
-   }
-}
-
-
 extern "C" const char *
 lp_get_module_id(LLVMModuleRef module)
 {
@@ -132,52 +78,23 @@ lp_get_module_id(LLVMModuleRef module)
 extern "C" void
 lp_debug_dump_value(LLVMValueRef value)
 {
-#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
-   raw_debug_ostream os;
+#if HAVE_LLVM >= 0x0304
+   char *str = LLVMPrintValueToString(value);
+   if (str) {
+      os_log_message(str);
+      LLVMDisposeMessage(str);
+   }
+#elif defined(PIPE_OS_WINDOWS) || defined(PIPE_OS_EMBEDDED)
+   std::string str;
+   llvm::raw_string_ostream os(str);
    llvm::unwrap(value)->print(os);
-   os.flush();
+   os_log_message(str.c_str());
 #else
    LLVMDumpValue(value);
 #endif
 }
 
 
-/*
- * MemoryObject wrapper around a buffer of memory, to be used by MC
- * disassembler.
- */
-class BufferMemoryObject:
-   public llvm::MemoryObject
-{
-private:
-   const uint8_t *Bytes;
-   uint64_t Length;
-public:
-   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
-      Bytes(bytes), Length(length)
-   {
-   }
-
-   uint64_t getBase() const
-   {
-      return 0;
-   }
-
-   uint64_t getExtent() const
-   {
-      return Length;
-   }
-
-   int readByte(uint64_t addr, uint8_t *byte) const
-   {
-      if (addr > getExtent())
-         return -1;
-      *byte = Bytes[addr];
-      return 0;
-   }
-};
-
-
 /*
  * Disassemble a function, using the LLVM MC disassembler.
  *
@@ -186,10 +103,8 @@ public:
  * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
  */
 static size_t
-disassemble(const void* func, llvm::raw_ostream & Out)
+disassemble(const void* func, std::ostream &buffer)
 {
-   using namespace llvm;
-
    const uint8_t *bytes = (const uint8_t *)func;
 
    /*
@@ -197,109 +112,39 @@ disassemble(const void* func, llvm::raw_ostream & Out)
     */
    const uint64_t extent = 96 * 1024;
 
-   uint64_t max_pc = 0;
-
    /*
     * Initialize all used objects.
     */
 
-   std::string Triple = sys::getDefaultTargetTriple();
-
-   std::string Error;
-   const Target *T = TargetRegistry::lookupTarget(Triple, Error);
-
-#if HAVE_LLVM >= 0x0304
-   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));
-#else
-   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
-#endif
-
-   if (!AsmInfo) {
-      Out << "error: no assembly info for target " << Triple << "\n";
-      Out.flush();
-      return 0;
-   }
-
-   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
-
-   OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple));
-   if (!MRI) {
-      Out << "error: no register info for target " << Triple.c_str() << "\n";
-      Out.flush();
-      return 0;
-   }
-
-   OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
-   if (!MII) {
-      Out << "error: no instruction info for target " << Triple.c_str() << "\n";
-      Out.flush();
-      return 0;
-   }
-
-#if HAVE_LLVM >= 0x0305
-   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
-   OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));
-   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx));
-#else
-   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
-   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
-#endif
-   if (!DisAsm) {
-      Out << "error: no disassembler for target " << Triple << "\n";
-      Out.flush();
-      return 0;
-   }
-
+   std::string Triple = llvm::sys::getProcessTriple();
+   LLVMDisasmContextRef D = LLVMCreateDisasm(Triple.c_str(), NULL, 0, NULL, NULL);
+   char outline[1024];
 
-   OwningPtr<MCInstPrinter> Printer(
-         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
-   if (!Printer) {
-      Out << "error: no instruction printer for target " << Triple.c_str() << "\n";
-      Out.flush();
+   if (!D) {
+      buffer << "error: could not create disassembler for triple "
+             << Triple.c_str() << '\n';
       return 0;
    }
 
-   TargetOptions options;
-#if defined(DEBUG)
-   options.JITEmitDebugInfo = true;
-#endif
-#if defined(PIPE_ARCH_X86)
-   options.StackAlignmentOverride = 4;
-#endif
-#if defined(DEBUG) || defined(PROFILE)
-   options.NoFramePointerElim = true;
-#endif
-   OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options));
-
-#if HAVE_LLVM >= 0x0306
-   const TargetInstrInfo *TII = TM->getSubtargetImpl()->getInstrInfo();
-#else
-   const TargetInstrInfo *TII = TM->getInstrInfo();
-#endif
-
-   /*
-    * Wrap the data in a MemoryObject
-    */
-   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
-
    uint64_t pc;
    pc = 0;
-   while (true) {
-      MCInst Inst;
-      uint64_t Size;
+   while (pc < extent) {
+      size_t Size;
 
       /*
        * Print address.  We use addresses relative to the start of the function,
        * so that between runs.
        */
 
-      Out << llvm::format("%6lu:\t", (unsigned long)pc);
+      buffer << std::setw(6) << (unsigned long)pc << ":\t";
 
-      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
-                                 pc,
-                                 nulls(), nulls())) {
-         Out << "invalid";
+      Size = LLVMDisasmInstruction(D, (uint8_t *)bytes + pc, extent - pc, 0, outline,
+                                   sizeof outline);
+
+      if (!Size) {
+         buffer << "invalid\n";
          pc += 1;
+         break;
       }
 
       /*
@@ -309,109 +154,72 @@ disassemble(const void* func, llvm::raw_ostream & Out)
       if (0) {
          unsigned i;
          for (i = 0; i < Size; ++i) {
-            Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]);
+            buffer << std::hex << std::setfill('0') << std::setw(2)
+                   << static_cast<int> (bytes[pc + i]);
          }
          for (; i < 16; ++i) {
-            Out << "   ";
+            buffer << std::dec << "   ";
          }
       }
 
       /*
        * Print the instruction.
        */
-      Printer->printInst(&Inst, Out, "");
-
-      /*
-       * Advance.
-       */
-
-      pc += Size;
 
-      const MCInstrDesc &TID = TII->get(Inst.getOpcode());
+      buffer << std::setw(Size) << outline << '\n';
 
       /*
-       * Keep track of forward jumps to a nearby address.
+       * Stop disassembling on return statements, if there is no record of a
+       * jump to a successive address.
+       *
+       * XXX: This currently assumes x86
        */
 
-      if (TID.isBranch()) {
-         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
-            const MCOperand &operand = Inst.getOperand(i);
-            if (operand.isImm()) {
-               uint64_t jump;
-
-               /*
-                * FIXME: Handle both relative and absolute addresses correctly.
-                * EDInstInfo actually has this info, but operandTypes and
-                * operandFlags enums are not exposed in the public interface.
-                */
-
-               if (1) {
-                  /*
-                   * PC relative addr.
-                   */
-
-                  jump = pc + operand.getImm();
-               } else {
-                  /*
-                   * Absolute addr.
-                   */
-
-                  jump = (uint64_t)operand.getImm();
-               }
-
-               /*
-                * Output the address relative to the function start, given
-                * that MC will print the addresses relative the current pc.
-                */
-               Out << "\t\t; " << jump;
-
-               /*
-                * Ignore far jumps given it could be actually a tail return to
-                * a random address.
-                */
-
-               if (jump > max_pc &&
-                   jump < extent) {
-                  max_pc = jump;
-               }
-            }
-         }
+#if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
+      if (Size == 1 && bytes[pc] == 0xc3) {
+         break;
       }
-
-      Out << "\n";
+#endif
 
       /*
-       * Stop disassembling on return statements, if there is no record of a
-       * jump to a successive address.
+       * Advance.
        */
 
-      if (TID.isReturn()) {
-         if (pc > max_pc) {
-            break;
-         }
+      pc += Size;
+
+      if (pc >= extent) {
+         buffer << "disassembly larger than " << extent << " bytes, aborting\n";
+         break;
       }
    }
 
+   buffer << '\n';
+
+   LLVMDisasmDispose(D);
+
    /*
     * Print GDB command, useful to verify output.
     */
-
    if (0) {
-      _debug_printf("disassemble %p %p\n", bytes, bytes + pc);
+      buffer << "disassemble " << static_cast<const void*>(bytes) << ' '
+             << static_cast<const void*>(bytes + pc) << '\n';
    }
 
-   Out << "\n";
-   Out.flush();
-
    return pc;
 }
 
 
 extern "C" void
-lp_disassemble(LLVMValueRef func, const void *code) {
-   raw_debug_ostream Out;
-   Out << LLVMGetValueName(func) << ":\n";
-   disassemble(code, Out);
+lp_disassemble(LLVMValueRef func, const void *code)
+{
+   std::ostringstream buffer;
+   std::string s;
+
+   buffer << LLVMGetValueName(func) << ":\n";
+   disassemble(code, buffer);
+   s = buffer.str();
+   os_log_message(s.c_str());
+   os_log_message("\n");
 }
 
 
@@ -426,10 +234,10 @@ lp_disassemble(LLVMValueRef func, const void *code) {
 extern "C" void
 lp_profile(LLVMValueRef func, const void *code)
 {
-#if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
+#if defined(__linux__) && defined(PROFILE)
+   static std::ofstream perf_asm_file;
    static boolean first_time = TRUE;
    static FILE *perf_map_file = NULL;
-   static int perf_asm_fd = -1;
    if (first_time) {
       /*
        * We rely on the disassembler for determining a function's size, but
@@ -443,17 +251,16 @@ lp_profile(LLVMValueRef func, const void *code)
          util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
          perf_map_file = fopen(filename, "wt");
          util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
-         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
-         perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
+         perf_asm_file.open(filename);
       }
       first_time = FALSE;
    }
    if (perf_map_file) {
       const char *symbol = LLVMGetValueName(func);
       unsigned long addr = (uintptr_t)code;
-      llvm::raw_fd_ostream Out(perf_asm_fd, false);
-      Out << symbol << ":\n";
-      unsigned long size = disassemble(code, Out);
+      perf_asm_file << symbol << ":\n";
+      unsigned long size = disassemble(code, perf_asm_file);
+      perf_asm_file.flush();
       fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
       fflush(perf_map_file);
    }