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