gallivm: Fix build for LLVM 3.2
[mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_init.c
1 /**************************************************************************
2 *
3 * Copyright 2009 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
29 #include "pipe/p_config.h"
30 #include "pipe/p_compiler.h"
31 #include "util/u_cpu_detect.h"
32 #include "util/u_debug.h"
33 #include "util/u_memory.h"
34 #include "util/u_simple_list.h"
35 #include "os/os_time.h"
36 #include "lp_bld.h"
37 #include "lp_bld_debug.h"
38 #include "lp_bld_misc.h"
39 #include "lp_bld_init.h"
40
41 #include <llvm-c/Analysis.h>
42 #include <llvm-c/Transforms/Scalar.h>
43 #include <llvm-c/BitWriter.h>
44
45
46 /* Only MCJIT is available as of LLVM SVN r216982 */
47 #if HAVE_LLVM >= 0x0306
48
49 #define USE_MCJIT 1
50 #define HAVE_AVX 1
51
52 #else
53
54 /**
55 * AVX is supported in:
56 * - standard JIT from LLVM 3.2 onwards
57 * - MC-JIT from LLVM 3.1
58 * - MC-JIT supports limited OSes (MacOSX and Linux)
59 * - standard JIT in LLVM 3.1, with backports
60 */
61 #if defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
62 # define USE_MCJIT 1
63 # define HAVE_AVX 0
64 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
65 # define USE_MCJIT 0
66 # define HAVE_AVX 1
67 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
68 # define USE_MCJIT 1
69 # define HAVE_AVX 1
70 #else
71 # define USE_MCJIT 0
72 # define HAVE_AVX 0
73 #endif
74
75 #endif /* HAVE_LLVM >= 0x0306 */
76
77 #if USE_MCJIT
78 void LLVMLinkInMCJIT();
79 #endif
80
81 #ifdef DEBUG
82 unsigned gallivm_debug = 0;
83
84 static const struct debug_named_value lp_bld_debug_flags[] = {
85 { "tgsi", GALLIVM_DEBUG_TGSI, NULL },
86 { "ir", GALLIVM_DEBUG_IR, NULL },
87 { "asm", GALLIVM_DEBUG_ASM, NULL },
88 { "nopt", GALLIVM_DEBUG_NO_OPT, NULL },
89 { "perf", GALLIVM_DEBUG_PERF, NULL },
90 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR, NULL },
91 { "no_rho_approx", GALLIVM_DEBUG_NO_RHO_APPROX, NULL },
92 { "no_quad_lod", GALLIVM_DEBUG_NO_QUAD_LOD, NULL },
93 { "gc", GALLIVM_DEBUG_GC, NULL },
94 DEBUG_NAMED_VALUE_END
95 };
96
97 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
98 #endif
99
100
101 static boolean gallivm_initialized = FALSE;
102
103 unsigned lp_native_vector_width;
104
105
106 /*
107 * Optimization values are:
108 * - 0: None (-O0)
109 * - 1: Less (-O1)
110 * - 2: Default (-O2, -Os)
111 * - 3: Aggressive (-O3)
112 *
113 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
114 */
115 enum LLVM_CodeGenOpt_Level {
116 None, // -O0
117 Less, // -O1
118 Default, // -O2, -Os
119 Aggressive // -O3
120 };
121
122
123 /**
124 * Create the LLVM (optimization) pass manager and install
125 * relevant optimization passes.
126 * \return TRUE for success, FALSE for failure
127 */
128 static boolean
129 create_pass_manager(struct gallivm_state *gallivm)
130 {
131 char *td_str;
132 assert(!gallivm->passmgr);
133 assert(gallivm->target);
134
135 gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(gallivm->module);
136 if (!gallivm->passmgr)
137 return FALSE;
138
139 // Old versions of LLVM get the DataLayout from the pass manager.
140 LLVMAddTargetData(gallivm->target, gallivm->passmgr);
141
142 // New ones from the Module.
143 td_str = LLVMCopyStringRepOfTargetData(gallivm->target);
144 LLVMSetDataLayout(gallivm->module, td_str);
145 free(td_str);
146
147 if ((gallivm_debug & GALLIVM_DEBUG_NO_OPT) == 0) {
148 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
149 * but there are more on SVN.
150 * TODO: Add more passes.
151 */
152 LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
153 LLVMAddLICMPass(gallivm->passmgr);
154 LLVMAddCFGSimplificationPass(gallivm->passmgr);
155 LLVMAddReassociatePass(gallivm->passmgr);
156 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
157 LLVMAddConstantPropagationPass(gallivm->passmgr);
158 LLVMAddInstructionCombiningPass(gallivm->passmgr);
159 LLVMAddGVNPass(gallivm->passmgr);
160 }
161 else {
162 /* We need at least this pass to prevent the backends to fail in
163 * unexpected ways.
164 */
165 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
166 }
167
168 return TRUE;
169 }
170
171
172 /**
173 * Free gallivm object's LLVM allocations, but not any generated code
174 * nor the gallivm object itself.
175 */
176 void
177 gallivm_free_ir(struct gallivm_state *gallivm)
178 {
179 if (gallivm->passmgr) {
180 LLVMDisposePassManager(gallivm->passmgr);
181 }
182
183 if (gallivm->engine) {
184 /* This will already destroy any associated module */
185 LLVMDisposeExecutionEngine(gallivm->engine);
186 } else if (gallivm->module) {
187 LLVMDisposeModule(gallivm->module);
188 }
189
190 #if !USE_MCJIT
191 /* Don't free the TargetData, it's owned by the exec engine */
192 #else
193 if (gallivm->target) {
194 LLVMDisposeTargetData(gallivm->target);
195 }
196 #endif
197
198 if (gallivm->builder)
199 LLVMDisposeBuilder(gallivm->builder);
200
201 /* The LLVMContext should be owned by the parent of gallivm. */
202
203 gallivm->engine = NULL;
204 gallivm->target = NULL;
205 gallivm->module = NULL;
206 gallivm->passmgr = NULL;
207 gallivm->context = NULL;
208 gallivm->builder = NULL;
209 }
210
211
212 /**
213 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
214 */
215 static void
216 gallivm_free_code(struct gallivm_state *gallivm)
217 {
218 assert(!gallivm->module);
219 assert(!gallivm->engine);
220 lp_free_generated_code(gallivm->code);
221 gallivm->code = NULL;
222 lp_free_memory_manager(gallivm->memorymgr);
223 gallivm->memorymgr = NULL;
224 }
225
226
227 static boolean
228 init_gallivm_engine(struct gallivm_state *gallivm)
229 {
230 if (1) {
231 enum LLVM_CodeGenOpt_Level optlevel;
232 char *error = NULL;
233 int ret;
234
235 if (gallivm_debug & GALLIVM_DEBUG_NO_OPT) {
236 optlevel = None;
237 }
238 else {
239 optlevel = Default;
240 }
241
242 ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
243 &gallivm->code,
244 gallivm->module,
245 gallivm->memorymgr,
246 (unsigned) optlevel,
247 USE_MCJIT,
248 &error);
249 if (ret) {
250 _debug_printf("%s\n", error);
251 LLVMDisposeMessage(error);
252 goto fail;
253 }
254 }
255
256 #if !USE_MCJIT
257 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
258 if (!gallivm->target)
259 goto fail;
260 #else
261 if (0) {
262 /*
263 * Dump the data layout strings.
264 */
265
266 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
267 char *data_layout;
268 char *engine_data_layout;
269
270 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
271 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
272
273 if (1) {
274 debug_printf("module target data = %s\n", data_layout);
275 debug_printf("engine target data = %s\n", engine_data_layout);
276 }
277
278 free(data_layout);
279 free(engine_data_layout);
280 }
281 #endif
282
283 return TRUE;
284
285 fail:
286 return FALSE;
287 }
288
289
290 /**
291 * Allocate gallivm LLVM objects.
292 * \return TRUE for success, FALSE for failure
293 */
294 static boolean
295 init_gallivm_state(struct gallivm_state *gallivm, const char *name,
296 LLVMContextRef context)
297 {
298 assert(!gallivm->context);
299 assert(!gallivm->module);
300
301 if (!lp_build_init())
302 return FALSE;
303
304 gallivm->context = context;
305
306 if (!gallivm->context)
307 goto fail;
308
309 gallivm->module = LLVMModuleCreateWithNameInContext(name,
310 gallivm->context);
311 if (!gallivm->module)
312 goto fail;
313
314 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
315 if (!gallivm->builder)
316 goto fail;
317
318 #if HAVE_LLVM < 0x0306
319 gallivm->memorymgr = lp_get_default_memory_manager();
320 if (!gallivm->memorymgr)
321 goto fail;
322 #else
323 gallivm->memorymgr = 0;
324 #endif
325
326 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
327 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
328 * now.
329 */
330 #if !USE_MCJIT
331 if (!init_gallivm_engine(gallivm)) {
332 goto fail;
333 }
334 #else
335 /*
336 * MC-JIT engine compiles the module immediately on creation, so we can't
337 * obtain the target data from it. Instead we create a target data layout
338 * from a string.
339 *
340 * The produced layout strings are not precisely the same, but should make
341 * no difference for the kind of optimization passes we run.
342 *
343 * For reference this is the layout string on x64:
344 *
345 * e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-f128:128:128-n8:16:32:64
346 *
347 * See also:
348 * - http://llvm.org/docs/LangRef.html#datalayout
349 */
350
351 {
352 const unsigned pointer_size = 8 * sizeof(void *);
353 char layout[512];
354 util_snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
355 #ifdef PIPE_ARCH_LITTLE_ENDIAN
356 'e', // little endian
357 #else
358 'E', // big endian
359 #endif
360 pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
361 pointer_size, // aggregate preferred alignment
362 pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
363
364 gallivm->target = LLVMCreateTargetData(layout);
365 if (!gallivm->target) {
366 return FALSE;
367 }
368 }
369 #endif
370
371 if (!create_pass_manager(gallivm))
372 goto fail;
373
374 return TRUE;
375
376 fail:
377 gallivm_free_ir(gallivm);
378 gallivm_free_code(gallivm);
379 return FALSE;
380 }
381
382
383 boolean
384 lp_build_init(void)
385 {
386 if (gallivm_initialized)
387 return TRUE;
388
389 /* XXX: Remove this once lp_bld_misc.cpp has been adapted to the removal
390 * of JITMemoryManager
391 */
392 #if HAVE_LLVM >= 0x0306
393 return FALSE;
394 #endif
395
396 #ifdef DEBUG
397 gallivm_debug = debug_get_option_gallivm_debug();
398 #endif
399
400 lp_set_target_options();
401
402 #if USE_MCJIT
403 LLVMLinkInMCJIT();
404 #else
405 LLVMLinkInJIT();
406 #endif
407
408 util_cpu_detect();
409
410 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
411 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
412 * actually more efficient to use 4-wide vectors on this processor.
413 *
414 * See also:
415 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
416 */
417 if (HAVE_AVX &&
418 util_cpu_caps.has_avx &&
419 util_cpu_caps.has_intel) {
420 lp_native_vector_width = 256;
421 } else {
422 /* Leave it at 128, even when no SIMD extensions are available.
423 * Really needs to be a multiple of 128 so can fit 4 floats.
424 */
425 lp_native_vector_width = 128;
426 }
427
428 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
429 lp_native_vector_width);
430
431 if (lp_native_vector_width <= 128) {
432 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
433 * "util_cpu_caps.has_avx" predicate, and lack the
434 * "lp_native_vector_width > 128" predicate. And also to ensure a more
435 * consistent behavior, allowing one to test SSE2 on AVX machines.
436 * XXX: should not play games with util_cpu_caps directly as it might
437 * get used for other things outside llvm too.
438 */
439 util_cpu_caps.has_avx = 0;
440 util_cpu_caps.has_avx2 = 0;
441 }
442
443 if (!HAVE_AVX) {
444 /*
445 * note these instructions are VEX-only, so can only emit if we use
446 * avx (don't want to base it on has_avx & has_f16c later as that would
447 * omit it unnecessarily on amd cpus, see above).
448 */
449 util_cpu_caps.has_f16c = 0;
450 util_cpu_caps.has_xop = 0;
451 }
452
453 #ifdef PIPE_ARCH_PPC_64
454 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
455 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
456 * that some rounding and half-float to float handling does not round
457 * incorrectly to 0.
458 * XXX: should eventually follow same logic on all platforms.
459 * Right now denorms get explicitly disabled (but elsewhere) for x86,
460 * whereas ppc64 explicitly enables them...
461 */
462 if (util_cpu_caps.has_altivec) {
463 unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
464 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
465 __asm (
466 "mfvscr %%v1\n"
467 "vand %0,%%v1,%0\n"
468 "mtvscr %0"
469 :
470 : "r" (*mask)
471 );
472 }
473 #endif
474
475 gallivm_initialized = TRUE;
476
477 #if 0
478 /* For simulating less capable machines */
479 util_cpu_caps.has_sse3 = 0;
480 util_cpu_caps.has_ssse3 = 0;
481 util_cpu_caps.has_sse4_1 = 0;
482 util_cpu_caps.has_avx = 0;
483 util_cpu_caps.has_f16c = 0;
484 #endif
485
486 return TRUE;
487 }
488
489
490
491 /**
492 * Create a new gallivm_state object.
493 */
494 struct gallivm_state *
495 gallivm_create(const char *name, LLVMContextRef context)
496 {
497 struct gallivm_state *gallivm;
498
499 gallivm = CALLOC_STRUCT(gallivm_state);
500 if (gallivm) {
501 if (!init_gallivm_state(gallivm, name, context)) {
502 FREE(gallivm);
503 gallivm = NULL;
504 }
505 }
506
507 return gallivm;
508 }
509
510
511 /**
512 * Destroy a gallivm_state object.
513 */
514 void
515 gallivm_destroy(struct gallivm_state *gallivm)
516 {
517 gallivm_free_ir(gallivm);
518 gallivm_free_code(gallivm);
519 FREE(gallivm);
520 }
521
522
523 /**
524 * Validate a function.
525 * Verification is only done with debug builds.
526 */
527 void
528 gallivm_verify_function(struct gallivm_state *gallivm,
529 LLVMValueRef func)
530 {
531 /* Verify the LLVM IR. If invalid, dump and abort */
532 #ifdef DEBUG
533 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
534 lp_debug_dump_value(func);
535 assert(0);
536 return;
537 }
538 #endif
539
540 if (gallivm_debug & GALLIVM_DEBUG_IR) {
541 /* Print the LLVM IR to stderr */
542 lp_debug_dump_value(func);
543 debug_printf("\n");
544 }
545 }
546
547
548 /**
549 * Compile a module.
550 * This does IR optimization on all functions in the module.
551 */
552 void
553 gallivm_compile_module(struct gallivm_state *gallivm)
554 {
555 LLVMValueRef func;
556 int64_t time_begin;
557
558 assert(!gallivm->compiled);
559
560 if (gallivm->builder) {
561 LLVMDisposeBuilder(gallivm->builder);
562 gallivm->builder = NULL;
563 }
564
565 if (gallivm_debug & GALLIVM_DEBUG_PERF)
566 time_begin = os_time_get();
567
568 /* Run optimization passes */
569 LLVMInitializeFunctionPassManager(gallivm->passmgr);
570 func = LLVMGetFirstFunction(gallivm->module);
571 while (func) {
572 if (0) {
573 debug_printf("optimizing func %s...\n", LLVMGetValueName(func));
574 }
575 LLVMRunFunctionPassManager(gallivm->passmgr, func);
576 func = LLVMGetNextFunction(func);
577 }
578 LLVMFinalizeFunctionPassManager(gallivm->passmgr);
579
580 if (gallivm_debug & GALLIVM_DEBUG_PERF) {
581 int64_t time_end = os_time_get();
582 int time_msec = (int)(time_end - time_begin) / 1000;
583 debug_printf("optimizing module %s took %d msec\n",
584 lp_get_module_id(gallivm->module), time_msec);
585 }
586
587 /* Dump byte code to a file */
588 if (0) {
589 LLVMWriteBitcodeToFile(gallivm->module, "llvmpipe.bc");
590 debug_printf("llvmpipe.bc written\n");
591 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
592 }
593
594 #if USE_MCJIT
595 assert(!gallivm->engine);
596 if (!init_gallivm_engine(gallivm)) {
597 assert(0);
598 }
599 #endif
600 assert(gallivm->engine);
601
602 ++gallivm->compiled;
603 }
604
605
606
607 func_pointer
608 gallivm_jit_function(struct gallivm_state *gallivm,
609 LLVMValueRef func)
610 {
611 void *code;
612 func_pointer jit_func;
613
614 assert(gallivm->compiled);
615 assert(gallivm->engine);
616
617 code = LLVMGetPointerToGlobal(gallivm->engine, func);
618 assert(code);
619 jit_func = pointer_to_func(code);
620
621 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
622 lp_disassemble(func, code);
623 }
624
625 #if defined(PROFILE)
626 lp_profile(func, code);
627 #endif
628
629 return jit_func;
630 }