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