lp_bld_debug.cpp revision d5a6c172547d8964f4d4bb79637651decaf9deee
1/**************************************************************************
2 *
3 * Copyright 2009-2011 VMware, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include <stddef.h>
29
30#include <llvm-c/Core.h>
31#include <llvm/Target/TargetMachine.h>
32#include <llvm/Target/TargetInstrInfo.h>
33#include <llvm/Support/raw_ostream.h>
34#include <llvm/Support/MemoryObject.h>
35
36#if HAVE_LLVM >= 0x0300
37#include <llvm/Support/TargetRegistry.h>
38#include <llvm/Support/TargetSelect.h>
39#else /* HAVE_LLVM < 0x0300 */
40#include <llvm/Target/TargetRegistry.h>
41#include <llvm/Target/TargetSelect.h>
42#endif /* HAVE_LLVM < 0x0300 */
43
44#if HAVE_LLVM >= 0x0209
45#include <llvm/Support/Host.h>
46#else /* HAVE_LLVM < 0x0209 */
47#include <llvm/System/Host.h>
48#endif /* HAVE_LLVM < 0x0209 */
49
50#if HAVE_LLVM >= 0x0207
51#include <llvm/MC/MCDisassembler.h>
52#include <llvm/MC/MCAsmInfo.h>
53#include <llvm/MC/MCInst.h>
54#include <llvm/MC/MCInstPrinter.h>
55#endif /* HAVE_LLVM >= 0x0207 */
56
57#include "util/u_math.h"
58#include "util/u_debug.h"
59
60#include "lp_bld_debug.h"
61
62
63
64/**
65 * Check alignment.
66 *
67 * It is important that this check is not implemented as a macro or inlined
68 * function, as the compiler assumptions in respect to alignment of global
69 * and stack variables would often make the check a no op, defeating the
70 * whole purpose of the exercise.
71 */
72extern "C" boolean
73lp_check_alignment(const void *ptr, unsigned alignment)
74{
75   assert(util_is_power_of_two(alignment));
76   return ((uintptr_t)ptr & (alignment - 1)) == 0;
77}
78
79
80class raw_debug_ostream :
81   public llvm::raw_ostream
82{
83   uint64_t pos;
84
85   void write_impl(const char *Ptr, size_t Size);
86   uint64_t current_pos() { return pos; }
87   uint64_t current_pos() const { return pos; }
88
89#if HAVE_LLVM >= 0x207
90   uint64_t preferred_buffer_size() { return 512; }
91#else
92   size_t preferred_buffer_size() { return 512; }
93#endif
94};
95
96
97void
98raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
99{
100   if (Size > 0) {
101      char *lastPtr = (char *)&Ptr[Size];
102      char last = *lastPtr;
103      *lastPtr = 0;
104      _debug_printf("%*s", Size, Ptr);
105      *lastPtr = last;
106      pos += Size;
107   }
108}
109
110
111/**
112 * Same as LLVMDumpValue, but through our debugging channels.
113 */
114extern "C" void
115lp_debug_dump_value(LLVMValueRef value)
116{
117#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
118   raw_debug_ostream os;
119   llvm::unwrap(value)->print(os);
120   os.flush();
121#else
122   LLVMDumpValue(value);
123#endif
124}
125
126
127#if HAVE_LLVM >= 0x0207
128/*
129 * MemoryObject wrapper around a buffer of memory, to be used by MC
130 * disassembler.
131 */
132class BufferMemoryObject:
133   public llvm::MemoryObject
134{
135private:
136   const uint8_t *Bytes;
137   uint64_t Length;
138public:
139   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
140      Bytes(bytes), Length(length)
141   {
142   }
143
144   uint64_t getBase() const
145   {
146      return 0;
147   }
148
149#if HAVE_LLVM >= 0x0301
150   uint64_t getExtent()
151#else
152   uint64_t getExtent() const
153#endif
154   {
155      return Length;
156   }
157
158#if HAVE_LLVM >= 0x0301
159   int readByte(uint64_t addr, uint8_t *byte)
160#else
161   int readByte(uint64_t addr, uint8_t *byte) const
162#endif
163   {
164      if (addr > getExtent())
165         return -1;
166      *byte = Bytes[addr];
167      return 0;
168   }
169};
170#endif /* HAVE_LLVM >= 0x0207 */
171
172
173/*
174 * Disassemble a function, using the LLVM MC disassembler.
175 *
176 * See also:
177 * - http://blog.llvm.org/2010/01/x86-disassembler.html
178 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
179 */
180extern "C" void
181lp_disassemble(const void* func)
182{
183#if HAVE_LLVM >= 0x0207
184   using namespace llvm;
185
186   const uint8_t *bytes = (const uint8_t *)func;
187
188   /*
189    * Limit disassembly to this extent
190    */
191   const uint64_t extent = 0x10000;
192
193   uint64_t max_pc = 0;
194
195   /*
196    * Initialize all used objects.
197    */
198
199#if HAVE_LLVM >= 0x0301
200   std::string Triple = sys::getDefaultTargetTriple();
201#else
202   std::string Triple = sys::getHostTriple();
203#endif
204
205   std::string Error;
206   const Target *T = TargetRegistry::lookupTarget(Triple, Error);
207
208#if HAVE_LLVM >= 0x0208
209   InitializeNativeTargetAsmPrinter();
210#elif LLVM_NATIVE_ARCH == X86Target
211   LLVMInitializeX86AsmPrinter();
212#elif LLVM_NATIVE_ARCH == ARMTarget
213   LLVMInitializeARMAsmPrinter();
214#endif
215
216#if (LLVM_NATIVE_ARCH == X86 || LLVM_NATIVE_ARCH == X86Target)
217   LLVMInitializeX86Disassembler();
218#elif (LLVM_NATIVE_ARCH == ARM || LLVM_NATIVE_ARCH == ARMTarget)
219   LLVMInitializeARMDisassembler();
220#endif
221
222#if HAVE_LLVM >= 0x0300
223   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
224#else
225   OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple));
226#endif
227
228   if (!AsmInfo) {
229      debug_printf("error: no assembly info for target %s\n", Triple.c_str());
230      return;
231   }
232
233#if HAVE_LLVM >= 0x0300
234   const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "");
235   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
236#else
237   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
238#endif
239   if (!DisAsm) {
240      debug_printf("error: no disassembler for target %s\n", Triple.c_str());
241      return;
242   }
243
244   raw_debug_ostream Out;
245
246#if HAVE_LLVM >= 0x0300
247   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
248#else
249   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
250#endif
251
252#if HAVE_LLVM >= 0x0300
253   OwningPtr<MCInstPrinter> Printer(
254         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI));
255#elif HAVE_LLVM >= 0x0208
256   OwningPtr<MCInstPrinter> Printer(
257         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
258#else
259   OwningPtr<MCInstPrinter> Printer(
260         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
261#endif
262   if (!Printer) {
263      debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
264      return;
265   }
266
267#if HAVE_LLVM >= 0x0301
268   TargetOptions options;
269#if defined(DEBUG)
270   options.JITEmitDebugInfo = true;
271#endif
272#if defined(PIPE_ARCH_X86)
273   options.StackAlignmentOverride = 4;
274#endif
275#if defined(DEBUG) || defined(PROFILE)
276   options.NoFramePointerElim = true;
277#endif
278   TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "", options);
279#elif HAVE_LLVM == 0x0300
280   TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "");
281#else
282   TargetMachine *TM = T->createTargetMachine(Triple, "");
283#endif
284
285   const TargetInstrInfo *TII = TM->getInstrInfo();
286
287   /*
288    * Wrap the data in a MemoryObject
289    */
290   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
291
292   uint64_t pc;
293   pc = 0;
294   while (true) {
295      MCInst Inst;
296      uint64_t Size;
297
298      /*
299       * Print address.  We use addresses relative to the start of the function,
300       * so that between runs.
301       */
302
303      debug_printf("%6lu:\t", (unsigned long)pc);
304
305      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
306                                 pc,
307#if HAVE_LLVM >= 0x0300
308				  nulls(), nulls())) {
309#else
310				  nulls())) {
311#endif
312         debug_printf("invalid\n");
313         pc += 1;
314      }
315
316      /*
317       * Output the bytes in hexidecimal format.
318       */
319
320      if (0) {
321         unsigned i;
322         for (i = 0; i < Size; ++i) {
323            debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
324         }
325         for (; i < 16; ++i) {
326            debug_printf("   ");
327         }
328      }
329
330      /*
331       * Print the instruction.
332       */
333
334#if HAVE_LLVM >= 0x0300
335      Printer->printInst(&Inst, Out, "");
336#elif HAVE_LLVM >= 0x208
337      Printer->printInst(&Inst, Out);
338#else
339      Printer->printInst(&Inst);
340#endif
341      Out.flush();
342
343      /*
344       * Advance.
345       */
346
347      pc += Size;
348
349#if HAVE_LLVM >= 0x0300
350      const MCInstrDesc &TID = TII->get(Inst.getOpcode());
351#else
352      const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
353#endif
354
355      /*
356       * Keep track of forward jumps to a nearby address.
357       */
358
359      if (TID.isBranch()) {
360         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
361            const MCOperand &operand = Inst.getOperand(i);
362            if (operand.isImm()) {
363               uint64_t jump;
364
365               /*
366                * FIXME: Handle both relative and absolute addresses correctly.
367                * EDInstInfo actually has this info, but operandTypes and
368                * operandFlags enums are not exposed in the public interface.
369                */
370
371               if (1) {
372                  /*
373                   * PC relative addr.
374                   */
375
376                  jump = pc + operand.getImm();
377               } else {
378                  /*
379                   * Absolute addr.
380                   */
381
382                  jump = (uint64_t)operand.getImm();
383               }
384
385               /*
386                * Output the address relative to the function start, given
387                * that MC will print the addresses relative the current pc.
388                */
389               debug_printf("\t\t; %lu", (unsigned long)jump);
390
391               /*
392                * Ignore far jumps given it could be actually a tail return to
393                * a random address.
394                */
395
396               if (jump > max_pc &&
397                   jump < extent) {
398                  max_pc = jump;
399               }
400            }
401         }
402      }
403
404      debug_printf("\n");
405
406      /*
407       * Stop disassembling on return statements, if there is no record of a
408       * jump to a successive address.
409       */
410
411      if (TID.isReturn()) {
412         if (pc > max_pc) {
413            break;
414         }
415      }
416   }
417
418   /*
419    * Print GDB command, useful to verify output.
420    */
421
422   if (0) {
423      debug_printf("disassemble %p %p\n", bytes, bytes + pc);
424   }
425
426   debug_printf("\n");
427#else /* HAVE_LLVM < 0x0207 */
428   (void)func;
429#endif /* HAVE_LLVM < 0x0207 */
430}
431
432