1 /**************************************************************************
3 * Copyright 2009 VMware, Inc.
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:
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
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.
26 **************************************************************************/
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"
36 #include "lp_bld_debug.h"
37 #include "lp_bld_misc.h"
38 #include "lp_bld_init.h"
40 #include <llvm-c/Analysis.h>
41 #include <llvm-c/Transforms/Scalar.h>
42 #include <llvm-c/BitWriter.h>
46 * AVX is supported in:
47 * - standard JIT from LLVM 3.2 onwards
48 * - MC-JIT from LLVM 3.1
49 * - MC-JIT supports limited OSes (MacOSX and Linux)
50 * - standard JIT in LLVM 3.1, with backports
52 #if defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
55 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
58 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
68 void LLVMLinkInMCJIT();
73 unsigned gallivm_debug
= 0;
75 static const struct debug_named_value lp_bld_debug_flags
[] = {
76 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
77 { "ir", GALLIVM_DEBUG_IR
, NULL
},
78 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
79 { "nopt", GALLIVM_DEBUG_NO_OPT
, NULL
},
80 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
81 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR
, NULL
},
82 { "no_rho_approx", GALLIVM_DEBUG_NO_RHO_APPROX
, NULL
},
83 { "no_quad_lod", GALLIVM_DEBUG_NO_QUAD_LOD
, NULL
},
84 { "gc", GALLIVM_DEBUG_GC
, NULL
},
88 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
92 static boolean gallivm_initialized
= FALSE
;
94 unsigned lp_native_vector_width
;
98 * Optimization values are:
101 * - 2: Default (-O2, -Os)
102 * - 3: Aggressive (-O3)
104 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
106 enum LLVM_CodeGenOpt_Level
{
115 * Create the LLVM (optimization) pass manager and install
116 * relevant optimization passes.
117 * \return TRUE for success, FALSE for failure
120 create_pass_manager(struct gallivm_state
*gallivm
)
122 assert(!gallivm
->passmgr
);
123 assert(gallivm
->target
);
125 gallivm
->passmgr
= LLVMCreateFunctionPassManagerForModule(gallivm
->module
);
126 if (!gallivm
->passmgr
)
129 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
131 if ((gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) == 0) {
132 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
133 * but there are more on SVN.
134 * TODO: Add more passes.
136 LLVMAddScalarReplAggregatesPass(gallivm
->passmgr
);
137 LLVMAddLICMPass(gallivm
->passmgr
);
138 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
139 LLVMAddReassociatePass(gallivm
->passmgr
);
141 if (sizeof(void*) == 4) {
142 /* XXX: For LLVM >= 2.7 and 32-bit build, use this order of passes to
143 * avoid generating bad code.
144 * Test with piglit glsl-vs-sqrt-zero test.
146 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
147 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
150 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
151 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
154 if (util_cpu_caps
.has_sse4_1
) {
155 /* FIXME: There is a bug in this pass, whereby the combination
156 * of fptosi and sitofp (necessary for trunc/floor/ceil/round
157 * implementation) somehow becomes invalid code.
159 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
161 LLVMAddGVNPass(gallivm
->passmgr
);
164 /* We need at least this pass to prevent the backends to fail in
167 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
175 * Free gallivm object's LLVM allocations, but not the gallivm object itself.
178 free_gallivm_state(struct gallivm_state
*gallivm
)
180 if (gallivm
->passmgr
) {
181 LLVMDisposePassManager(gallivm
->passmgr
);
184 if (gallivm
->engine
) {
185 /* This will already destroy any associated module */
186 LLVMDisposeExecutionEngine(gallivm
->engine
);
187 } else if (gallivm
->module
) {
188 LLVMDisposeModule(gallivm
->module
);
192 /* Don't free the TargetData, it's owned by the exec engine */
194 if (gallivm
->target
) {
195 LLVMDisposeTargetData(gallivm
->target
);
199 /* Never free the LLVM context.
202 if (gallivm
->context
)
203 LLVMContextDispose(gallivm
->context
);
206 if (gallivm
->builder
)
207 LLVMDisposeBuilder(gallivm
->builder
);
209 gallivm
->engine
= NULL
;
210 gallivm
->target
= NULL
;
211 gallivm
->module
= NULL
;
212 gallivm
->passmgr
= NULL
;
213 gallivm
->context
= NULL
;
214 gallivm
->builder
= NULL
;
219 init_gallivm_engine(struct gallivm_state
*gallivm
)
222 enum LLVM_CodeGenOpt_Level optlevel
;
226 if (gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) {
233 ret
= lp_build_create_jit_compiler_for_module(&gallivm
->engine
,
239 _debug_printf("%s\n", error
);
240 LLVMDisposeMessage(error
);
246 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
247 if (!gallivm
->target
)
252 * Dump the data layout strings.
255 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
257 char *engine_data_layout
;
259 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
260 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
263 debug_printf("module target data = %s\n", data_layout
);
264 debug_printf("engine target data = %s\n", engine_data_layout
);
268 free(engine_data_layout
);
282 * We must never free LLVM contexts, because LLVM has several global caches
283 * which pointing/derived from objects owned by the context, causing false
284 * memory leaks and false cache hits when these objects are destroyed.
286 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
287 * context per thread, and put them in a pool when threads are destroyed.
289 static LLVMContextRef gallivm_context
= NULL
;
293 * Allocate gallivm LLVM objects.
294 * \return TRUE for success, FALSE for failure
297 init_gallivm_state(struct gallivm_state
*gallivm
)
299 assert(!gallivm
->context
);
300 assert(!gallivm
->module
);
304 if (!gallivm_context
) {
305 gallivm_context
= LLVMContextCreate();
307 gallivm
->context
= gallivm_context
;
308 if (!gallivm
->context
)
311 gallivm
->module
= LLVMModuleCreateWithNameInContext("gallivm",
313 if (!gallivm
->module
)
316 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
317 if (!gallivm
->builder
)
320 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
321 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
325 if (!init_gallivm_engine(gallivm
)) {
330 * MC-JIT engine compiles the module immediately on creation, so we can't
331 * obtain the target data from it. Instead we create a target data layout
334 * The produced layout strings are not precisely the same, but should make
335 * no difference for the kind of optimization passes we run.
337 * For reference this is the layout string on x64:
339 * 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
342 * - http://llvm.org/docs/LangRef.html#datalayout
346 const unsigned pointer_size
= 8 * sizeof(void *);
348 util_snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
349 #ifdef PIPE_ARCH_LITTLE_ENDIAN
350 'e', // little endian
354 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
355 pointer_size
, // aggregate preferred alignment
356 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
358 gallivm
->target
= LLVMCreateTargetData(layout
);
359 if (!gallivm
->target
) {
365 if (!create_pass_manager(gallivm
))
371 free_gallivm_state(gallivm
);
379 if (gallivm_initialized
)
383 gallivm_debug
= debug_get_option_gallivm_debug();
386 lp_set_target_options();
396 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
397 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
398 * actually more efficient to use 4-wide vectors on this processor.
401 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
404 util_cpu_caps
.has_avx
&&
405 util_cpu_caps
.has_intel
) {
406 lp_native_vector_width
= 256;
408 /* Leave it at 128, even when no SIMD extensions are available.
409 * Really needs to be a multiple of 128 so can fit 4 floats.
411 lp_native_vector_width
= 128;
414 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
415 lp_native_vector_width
);
417 if (lp_native_vector_width
<= 128) {
418 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
419 * "util_cpu_caps.has_avx" predicate, and lack the
420 * "lp_native_vector_width > 128" predicate. And also to ensure a more
421 * consistent behavior, allowing one to test SSE2 on AVX machines.
422 * XXX: should not play games with util_cpu_caps directly as it might
423 * get used for other things outside llvm too.
425 util_cpu_caps
.has_avx
= 0;
426 util_cpu_caps
.has_avx2
= 0;
431 * note these instructions are VEX-only, so can only emit if we use
432 * avx (don't want to base it on has_avx & has_f16c later as that would
433 * omit it unnecessarily on amd cpus, see above).
435 util_cpu_caps
.has_f16c
= 0;
436 util_cpu_caps
.has_xop
= 0;
439 #ifdef PIPE_ARCH_PPC_64
440 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
441 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
442 * that some rounding and half-float to float handling does not round
444 * XXX: should eventually follow same logic on all platforms.
445 * Right now denorms get explicitly disabled (but elsewhere) for x86,
446 * whereas ppc64 explicitly enables them...
448 if (util_cpu_caps
.has_altivec
) {
449 unsigned short mask
[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
450 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
461 gallivm_initialized
= TRUE
;
464 /* For simulating less capable machines */
465 util_cpu_caps
.has_sse3
= 0;
466 util_cpu_caps
.has_ssse3
= 0;
467 util_cpu_caps
.has_sse4_1
= 0;
468 util_cpu_caps
.has_avx
= 0;
469 util_cpu_caps
.has_f16c
= 0;
476 * Create a new gallivm_state object.
477 * Note that we return a singleton.
479 struct gallivm_state
*
482 struct gallivm_state
*gallivm
;
484 gallivm
= CALLOC_STRUCT(gallivm_state
);
486 if (!init_gallivm_state(gallivm
)) {
497 * Destroy a gallivm_state object.
500 gallivm_destroy(struct gallivm_state
*gallivm
)
502 free_gallivm_state(gallivm
);
508 * Validate and optimze a function.
511 gallivm_optimize_function(struct gallivm_state
*gallivm
,
515 debug_printf("optimizing %s...\n", LLVMGetValueName(func
));
518 assert(gallivm
->passmgr
);
520 /* Apply optimizations to LLVM IR */
521 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
524 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
525 /* Print the LLVM IR to stderr */
526 lp_debug_dump_value(func
);
534 * Validate a function.
537 gallivm_verify_function(struct gallivm_state
*gallivm
,
540 /* Verify the LLVM IR. If invalid, dump and abort */
542 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
543 lp_debug_dump_value(func
);
549 gallivm_optimize_function(gallivm
, func
);
551 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
552 /* Print the LLVM IR to stderr */
553 lp_debug_dump_value(func
);
560 gallivm_compile_module(struct gallivm_state
*gallivm
)
562 assert(!gallivm
->compiled
);
564 /* Dump byte code to a file */
566 LLVMWriteBitcodeToFile(gallivm
->module
, "llvmpipe.bc");
567 debug_printf("llvmpipe.bc written\n");
568 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
572 assert(!gallivm
->engine
);
573 if (!init_gallivm_engine(gallivm
)) {
577 assert(gallivm
->engine
);
585 gallivm_jit_function(struct gallivm_state
*gallivm
,
589 func_pointer jit_func
;
591 assert(gallivm
->compiled
);
592 assert(gallivm
->engine
);
594 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
596 jit_func
= pointer_to_func(code
);
598 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
599 lp_disassemble(func
, code
);
603 lp_profile(func
, code
);
606 /* Free the function body to save memory */
607 lp_func_delete_body(func
);
614 * Free the function (and its machine code).
617 gallivm_free_function(struct gallivm_state
*gallivm
,
623 LLVMFreeMachineCodeForFunction(gallivm
->engine
, func
);
626 LLVMDeleteFunction(func
);