gallivm: Fix build with LLVM 3.6 (r221751).
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_debug.cpp
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/Format.h>
35
36 #if HAVE_LLVM >= 0x0306
37 #include <llvm/Target/TargetSubtargetInfo.h>
38 #else
39 #include <llvm/Support/MemoryObject.h>
40 #endif
41
42 #include <llvm/Support/TargetRegistry.h>
43 #include <llvm/MC/MCSubtargetInfo.h>
44
45 #include <llvm/Support/Host.h>
46
47 #include <llvm/IR/Module.h>
48
49 #include <llvm/MC/MCDisassembler.h>
50 #include <llvm/MC/MCAsmInfo.h>
51 #include <llvm/MC/MCInst.h>
52 #include <llvm/MC/MCInstPrinter.h>
53 #include <llvm/MC/MCRegisterInfo.h>
54
55 #if HAVE_LLVM >= 0x0305
56 #define OwningPtr std::unique_ptr
57 #else
58 #include <llvm/ADT/OwningPtr.h>
59 #endif
60
61 #if HAVE_LLVM >= 0x0305
62 #include <llvm/MC/MCContext.h>
63 #endif
64
65 #include "util/u_math.h"
66 #include "util/u_debug.h"
67
68 #include "lp_bld_debug.h"
69
70 #ifdef __linux__
71 #include <sys/stat.h>
72 #include <fcntl.h>
73 #endif
74
75
76
77 /**
78 * Check alignment.
79 *
80 * It is important that this check is not implemented as a macro or inlined
81 * function, as the compiler assumptions in respect to alignment of global
82 * and stack variables would often make the check a no op, defeating the
83 * whole purpose of the exercise.
84 */
85 extern "C" boolean
86 lp_check_alignment(const void *ptr, unsigned alignment)
87 {
88 assert(util_is_power_of_two(alignment));
89 return ((uintptr_t)ptr & (alignment - 1)) == 0;
90 }
91
92
93 class raw_debug_ostream :
94 public llvm::raw_ostream
95 {
96 private:
97 uint64_t pos;
98
99 public:
100 raw_debug_ostream() : pos(0) { }
101
102 void write_impl(const char *Ptr, size_t Size);
103
104 uint64_t current_pos() const { return pos; }
105 size_t preferred_buffer_size() const { return 512; }
106 };
107
108
109 void
110 raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
111 {
112 if (Size > 0) {
113 char *lastPtr = (char *)&Ptr[Size];
114 char last = *lastPtr;
115 *lastPtr = 0;
116 _debug_printf("%*s", Size, Ptr);
117 *lastPtr = last;
118 pos += Size;
119 }
120 }
121
122
123 extern "C" const char *
124 lp_get_module_id(LLVMModuleRef module)
125 {
126 return llvm::unwrap(module)->getModuleIdentifier().c_str();
127 }
128
129
130 /**
131 * Same as LLVMDumpValue, but through our debugging channels.
132 */
133 extern "C" void
134 lp_debug_dump_value(LLVMValueRef value)
135 {
136 #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
137 raw_debug_ostream os;
138 llvm::unwrap(value)->print(os);
139 os.flush();
140 #else
141 LLVMDumpValue(value);
142 #endif
143 }
144
145
146 #if HAVE_LLVM < 0x0306
147
148 /*
149 * MemoryObject wrapper around a buffer of memory, to be used by MC
150 * disassembler.
151 */
152 class BufferMemoryObject:
153 public llvm::MemoryObject
154 {
155 private:
156 const uint8_t *Bytes;
157 uint64_t Length;
158 public:
159 BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
160 Bytes(bytes), Length(length)
161 {
162 }
163
164 uint64_t getBase() const
165 {
166 return 0;
167 }
168
169 uint64_t getExtent() const
170 {
171 return Length;
172 }
173
174 int readByte(uint64_t addr, uint8_t *byte) const
175 {
176 if (addr > getExtent())
177 return -1;
178 *byte = Bytes[addr];
179 return 0;
180 }
181 };
182
183 #endif /* HAVE_LLVM < 0x0306 */
184
185
186 /*
187 * Disassemble a function, using the LLVM MC disassembler.
188 *
189 * See also:
190 * - http://blog.llvm.org/2010/01/x86-disassembler.html
191 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
192 */
193 static size_t
194 disassemble(const void* func, llvm::raw_ostream & Out)
195 {
196 using namespace llvm;
197
198 const uint8_t *bytes = (const uint8_t *)func;
199
200 /*
201 * Limit disassembly to this extent
202 */
203 const uint64_t extent = 96 * 1024;
204
205 uint64_t max_pc = 0;
206
207 /*
208 * Initialize all used objects.
209 */
210
211 std::string Triple = sys::getDefaultTargetTriple();
212
213 std::string Error;
214 const Target *T = TargetRegistry::lookupTarget(Triple, Error);
215
216 #if HAVE_LLVM >= 0x0304
217 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));
218 #else
219 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
220 #endif
221
222 if (!AsmInfo) {
223 Out << "error: no assembly info for target " << Triple << "\n";
224 Out.flush();
225 return 0;
226 }
227
228 unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
229
230 OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple));
231 if (!MRI) {
232 Out << "error: no register info for target " << Triple.c_str() << "\n";
233 Out.flush();
234 return 0;
235 }
236
237 OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
238 if (!MII) {
239 Out << "error: no instruction info for target " << Triple.c_str() << "\n";
240 Out.flush();
241 return 0;
242 }
243
244 #if HAVE_LLVM >= 0x0305
245 OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
246 OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));
247 OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx));
248 #else
249 OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
250 OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
251 #endif
252 if (!DisAsm) {
253 Out << "error: no disassembler for target " << Triple << "\n";
254 Out.flush();
255 return 0;
256 }
257
258
259 OwningPtr<MCInstPrinter> Printer(
260 T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
261 if (!Printer) {
262 Out << "error: no instruction printer for target " << Triple.c_str() << "\n";
263 Out.flush();
264 return 0;
265 }
266
267 TargetOptions options;
268 #if defined(DEBUG)
269 options.JITEmitDebugInfo = true;
270 #endif
271 #if defined(PIPE_ARCH_X86)
272 options.StackAlignmentOverride = 4;
273 #endif
274 #if defined(DEBUG) || defined(PROFILE)
275 options.NoFramePointerElim = true;
276 #endif
277 OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options));
278
279 #if HAVE_LLVM >= 0x0306
280 const TargetInstrInfo *TII = TM->getSubtargetImpl()->getInstrInfo();
281 #else
282 const TargetInstrInfo *TII = TM->getInstrInfo();
283 #endif
284
285 /*
286 * Wrap the data in a MemoryObject
287 */
288 #if HAVE_LLVM >= 0x0306
289 ArrayRef<uint8_t> memoryObject((const uint8_t *)bytes, extent);
290 #else
291 BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
292 #endif
293
294 uint64_t pc;
295 pc = 0;
296 while (true) {
297 MCInst Inst;
298 uint64_t Size;
299
300 /*
301 * Print address. We use addresses relative to the start of the function,
302 * so that between runs.
303 */
304
305 Out << llvm::format("%6lu:\t", (unsigned long)pc);
306
307 if (!DisAsm->getInstruction(Inst, Size, memoryObject,
308 pc,
309 nulls(), nulls())) {
310 Out << "invalid";
311 pc += 1;
312 }
313
314 /*
315 * Output the bytes in hexidecimal format.
316 */
317
318 if (0) {
319 unsigned i;
320 for (i = 0; i < Size; ++i) {
321 Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]);
322 }
323 for (; i < 16; ++i) {
324 Out << " ";
325 }
326 }
327
328 /*
329 * Print the instruction.
330 */
331 Printer->printInst(&Inst, Out, "");
332
333 /*
334 * Advance.
335 */
336
337 pc += Size;
338
339 const MCInstrDesc &TID = TII->get(Inst.getOpcode());
340
341 /*
342 * Keep track of forward jumps to a nearby address.
343 */
344
345 if (TID.isBranch()) {
346 for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
347 const MCOperand &operand = Inst.getOperand(i);
348 if (operand.isImm()) {
349 uint64_t jump;
350
351 /*
352 * FIXME: Handle both relative and absolute addresses correctly.
353 * EDInstInfo actually has this info, but operandTypes and
354 * operandFlags enums are not exposed in the public interface.
355 */
356
357 if (1) {
358 /*
359 * PC relative addr.
360 */
361
362 jump = pc + operand.getImm();
363 } else {
364 /*
365 * Absolute addr.
366 */
367
368 jump = (uint64_t)operand.getImm();
369 }
370
371 /*
372 * Output the address relative to the function start, given
373 * that MC will print the addresses relative the current pc.
374 */
375 Out << "\t\t; " << jump;
376
377 /*
378 * Ignore far jumps given it could be actually a tail return to
379 * a random address.
380 */
381
382 if (jump > max_pc &&
383 jump < extent) {
384 max_pc = jump;
385 }
386 }
387 }
388 }
389
390 Out << "\n";
391
392 /*
393 * Stop disassembling on return statements, if there is no record of a
394 * jump to a successive address.
395 */
396
397 if (TID.isReturn()) {
398 if (pc > max_pc) {
399 break;
400 }
401 }
402 }
403
404 /*
405 * Print GDB command, useful to verify output.
406 */
407
408 if (0) {
409 _debug_printf("disassemble %p %p\n", bytes, bytes + pc);
410 }
411
412 Out << "\n";
413 Out.flush();
414
415 return pc;
416 }
417
418
419 extern "C" void
420 lp_disassemble(LLVMValueRef func, const void *code) {
421 raw_debug_ostream Out;
422 Out << LLVMGetValueName(func) << ":\n";
423 disassemble(code, Out);
424 }
425
426
427 /*
428 * Linux perf profiler integration.
429 *
430 * See also:
431 * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
432 * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
433 * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
434 */
435 extern "C" void
436 lp_profile(LLVMValueRef func, const void *code)
437 {
438 #if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
439 static boolean first_time = TRUE;
440 static FILE *perf_map_file = NULL;
441 static int perf_asm_fd = -1;
442 if (first_time) {
443 /*
444 * We rely on the disassembler for determining a function's size, but
445 * the disassembly is a leaky and slow operation, so avoid running
446 * this except when running inside linux perf, which can be inferred
447 * by the PERF_BUILDID_DIR environment variable.
448 */
449 if (getenv("PERF_BUILDID_DIR")) {
450 pid_t pid = getpid();
451 char filename[256];
452 util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
453 perf_map_file = fopen(filename, "wt");
454 util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
455 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
456 perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
457 }
458 first_time = FALSE;
459 }
460 if (perf_map_file) {
461 const char *symbol = LLVMGetValueName(func);
462 unsigned long addr = (uintptr_t)code;
463 llvm::raw_fd_ostream Out(perf_asm_fd, false);
464 Out << symbol << ":\n";
465 unsigned long size = disassemble(code, Out);
466 fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
467 fflush(perf_map_file);
468 }
469 #else
470 (void)func;
471 (void)code;
472 #endif
473 }
474
475