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/simple_list.h"
35 #include "os/os_time.h"
37 #include "lp_bld_debug.h"
38 #include "lp_bld_misc.h"
39 #include "lp_bld_init.h"
41 #include <llvm-c/Analysis.h>
42 #include <llvm-c/Transforms/Scalar.h>
43 #include <llvm-c/BitWriter.h>
46 /* Only MCJIT is available as of LLVM SVN r216982 */
47 #if HAVE_LLVM >= 0x0306
49 #elif defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
56 void LLVMLinkInMCJIT();
60 unsigned gallivm_debug
= 0;
62 static const struct debug_named_value lp_bld_debug_flags
[] = {
63 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
64 { "ir", GALLIVM_DEBUG_IR
, NULL
},
65 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
66 { "nopt", GALLIVM_DEBUG_NO_OPT
, NULL
},
67 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
68 { "no_brilinear", GALLIVM_DEBUG_NO_BRILINEAR
, NULL
},
69 { "no_rho_approx", GALLIVM_DEBUG_NO_RHO_APPROX
, NULL
},
70 { "no_quad_lod", GALLIVM_DEBUG_NO_QUAD_LOD
, NULL
},
71 { "gc", GALLIVM_DEBUG_GC
, NULL
},
75 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
79 static boolean gallivm_initialized
= FALSE
;
81 unsigned lp_native_vector_width
;
85 * Optimization values are:
88 * - 2: Default (-O2, -Os)
89 * - 3: Aggressive (-O3)
91 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
93 enum LLVM_CodeGenOpt_Level
{
102 * Create the LLVM (optimization) pass manager and install
103 * relevant optimization passes.
104 * \return TRUE for success, FALSE for failure
107 create_pass_manager(struct gallivm_state
*gallivm
)
109 assert(!gallivm
->passmgr
);
110 assert(gallivm
->target
);
112 gallivm
->passmgr
= LLVMCreateFunctionPassManagerForModule(gallivm
->module
);
113 if (!gallivm
->passmgr
)
116 * TODO: some per module pass manager with IPO passes might be helpful -
117 * the generated texture functions may benefit from inlining if they are
118 * simple, or constant propagation into them, etc.
121 // Old versions of LLVM get the DataLayout from the pass manager.
122 LLVMAddTargetData(gallivm
->target
, gallivm
->passmgr
);
124 /* Setting the module's DataLayout to an empty string will cause the
125 * ExecutionEngine to copy to the DataLayout string from its target
126 * machine to the module. As of LLVM 3.8 the module and the execution
127 * engine are required to have the same DataLayout.
129 * TODO: This is just a temporary work-around. The correct solution is
130 * for gallivm_init_state() to create a TargetMachine and pull the
131 * DataLayout from there. Currently, the TargetMachine used by llvmpipe
132 * is being implicitly created by the EngineBuilder in
133 * lp_build_create_jit_compiler_for_module()
136 #if HAVE_LLVM < 0x0308
139 // New ones from the Module.
140 td_str
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
141 LLVMSetDataLayout(gallivm
->module
, td_str
);
145 LLVMSetDataLayout(gallivm
->module
, "");
148 if ((gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) == 0) {
149 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
150 * but there are more on SVN.
151 * TODO: Add more passes.
153 LLVMAddScalarReplAggregatesPass(gallivm
->passmgr
);
154 LLVMAddLICMPass(gallivm
->passmgr
);
155 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
156 LLVMAddReassociatePass(gallivm
->passmgr
);
157 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
158 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
159 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
160 LLVMAddGVNPass(gallivm
->passmgr
);
163 /* We need at least this pass to prevent the backends to fail in
166 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
174 * Free gallivm object's LLVM allocations, but not any generated code
175 * nor the gallivm object itself.
178 gallivm_free_ir(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 if (gallivm
->builder
)
200 LLVMDisposeBuilder(gallivm
->builder
);
202 /* The LLVMContext should be owned by the parent of gallivm. */
204 gallivm
->engine
= NULL
;
205 gallivm
->target
= NULL
;
206 gallivm
->module
= NULL
;
207 gallivm
->passmgr
= NULL
;
208 gallivm
->context
= NULL
;
209 gallivm
->builder
= NULL
;
214 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
217 gallivm_free_code(struct gallivm_state
*gallivm
)
219 assert(!gallivm
->module
);
220 assert(!gallivm
->engine
);
221 lp_free_generated_code(gallivm
->code
);
222 gallivm
->code
= NULL
;
223 lp_free_memory_manager(gallivm
->memorymgr
);
224 gallivm
->memorymgr
= NULL
;
229 init_gallivm_engine(struct gallivm_state
*gallivm
)
232 enum LLVM_CodeGenOpt_Level optlevel
;
236 if (gallivm_debug
& GALLIVM_DEBUG_NO_OPT
) {
243 ret
= lp_build_create_jit_compiler_for_module(&gallivm
->engine
,
251 _debug_printf("%s\n", error
);
252 LLVMDisposeMessage(error
);
258 gallivm
->target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
259 if (!gallivm
->target
)
264 * Dump the data layout strings.
267 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
269 char *engine_data_layout
;
271 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
272 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
275 debug_printf("module target data = %s\n", data_layout
);
276 debug_printf("engine target data = %s\n", engine_data_layout
);
280 free(engine_data_layout
);
292 * Allocate gallivm LLVM objects.
293 * \return TRUE for success, FALSE for failure
296 init_gallivm_state(struct gallivm_state
*gallivm
, const char *name
,
297 LLVMContextRef context
)
299 assert(!gallivm
->context
);
300 assert(!gallivm
->module
);
302 if (!lp_build_init())
305 gallivm
->context
= context
;
307 if (!gallivm
->context
)
310 gallivm
->module
= LLVMModuleCreateWithNameInContext(name
,
312 if (!gallivm
->module
)
315 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
316 if (!gallivm
->builder
)
319 gallivm
->memorymgr
= lp_get_default_memory_manager();
320 if (!gallivm
->memorymgr
)
323 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
324 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
328 if (!init_gallivm_engine(gallivm
)) {
333 * MC-JIT engine compiles the module immediately on creation, so we can't
334 * obtain the target data from it. Instead we create a target data layout
337 * The produced layout strings are not precisely the same, but should make
338 * no difference for the kind of optimization passes we run.
340 * For reference this is the layout string on x64:
342 * 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
345 * - http://llvm.org/docs/LangRef.html#datalayout
349 const unsigned pointer_size
= 8 * sizeof(void *);
351 util_snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
352 #ifdef PIPE_ARCH_LITTLE_ENDIAN
353 'e', // little endian
357 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
358 pointer_size
, // aggregate preferred alignment
359 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
361 gallivm
->target
= LLVMCreateTargetData(layout
);
362 if (!gallivm
->target
) {
368 if (!create_pass_manager(gallivm
))
374 gallivm_free_ir(gallivm
);
375 gallivm_free_code(gallivm
);
383 if (gallivm_initialized
)
387 gallivm_debug
= debug_get_option_gallivm_debug();
390 lp_set_target_options();
400 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
401 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
402 * actually more efficient to use 4-wide vectors on this processor.
405 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
407 if (util_cpu_caps
.has_avx
&&
408 util_cpu_caps
.has_intel
) {
409 lp_native_vector_width
= 256;
411 /* Leave it at 128, even when no SIMD extensions are available.
412 * Really needs to be a multiple of 128 so can fit 4 floats.
414 lp_native_vector_width
= 128;
417 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
418 lp_native_vector_width
);
420 if (lp_native_vector_width
<= 128) {
421 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
422 * "util_cpu_caps.has_avx" predicate, and lack the
423 * "lp_native_vector_width > 128" predicate. And also to ensure a more
424 * consistent behavior, allowing one to test SSE2 on AVX machines.
425 * XXX: should not play games with util_cpu_caps directly as it might
426 * get used for other things outside llvm too.
428 util_cpu_caps
.has_avx
= 0;
429 util_cpu_caps
.has_avx2
= 0;
430 util_cpu_caps
.has_f16c
= 0;
433 #ifdef PIPE_ARCH_PPC_64
434 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
435 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
436 * that some rounding and half-float to float handling does not round
438 * XXX: should eventually follow same logic on all platforms.
439 * Right now denorms get explicitly disabled (but elsewhere) for x86,
440 * whereas ppc64 explicitly enables them...
442 if (util_cpu_caps
.has_altivec
) {
443 unsigned short mask
[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
444 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
455 gallivm_initialized
= TRUE
;
458 /* For simulating less capable machines */
459 util_cpu_caps
.has_sse3
= 0;
460 util_cpu_caps
.has_ssse3
= 0;
461 util_cpu_caps
.has_sse4_1
= 0;
462 util_cpu_caps
.has_sse4_2
= 0;
463 util_cpu_caps
.has_avx
= 0;
464 util_cpu_caps
.has_avx2
= 0;
465 util_cpu_caps
.has_f16c
= 0;
474 * Create a new gallivm_state object.
476 struct gallivm_state
*
477 gallivm_create(const char *name
, LLVMContextRef context
)
479 struct gallivm_state
*gallivm
;
481 gallivm
= CALLOC_STRUCT(gallivm_state
);
483 if (!init_gallivm_state(gallivm
, name
, context
)) {
494 * Destroy a gallivm_state object.
497 gallivm_destroy(struct gallivm_state
*gallivm
)
499 gallivm_free_ir(gallivm
);
500 gallivm_free_code(gallivm
);
506 * Validate a function.
507 * Verification is only done with debug builds.
510 gallivm_verify_function(struct gallivm_state
*gallivm
,
513 /* Verify the LLVM IR. If invalid, dump and abort */
515 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
516 lp_debug_dump_value(func
);
522 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
523 /* Print the LLVM IR to stderr */
524 lp_debug_dump_value(func
);
532 * This does IR optimization on all functions in the module.
535 gallivm_compile_module(struct gallivm_state
*gallivm
)
538 int64_t time_begin
= 0;
540 assert(!gallivm
->compiled
);
542 if (gallivm
->builder
) {
543 LLVMDisposeBuilder(gallivm
->builder
);
544 gallivm
->builder
= NULL
;
547 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
548 time_begin
= os_time_get();
550 /* Run optimization passes */
551 LLVMInitializeFunctionPassManager(gallivm
->passmgr
);
552 func
= LLVMGetFirstFunction(gallivm
->module
);
555 debug_printf("optimizing func %s...\n", LLVMGetValueName(func
));
558 /* Disable frame pointer omission on debug/profile builds */
559 /* XXX: And workaround http://llvm.org/PR21435 */
560 #if HAVE_LLVM >= 0x0307 && \
561 (defined(DEBUG) || defined(PROFILE) || \
562 defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64))
563 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim", "true");
564 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim-non-leaf", "true");
567 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
568 func
= LLVMGetNextFunction(func
);
570 LLVMFinalizeFunctionPassManager(gallivm
->passmgr
);
572 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
573 int64_t time_end
= os_time_get();
574 int time_msec
= (int)(time_end
- time_begin
) / 1000;
575 debug_printf("optimizing module %s took %d msec\n",
576 lp_get_module_id(gallivm
->module
), time_msec
);
579 /* Dump byte code to a file */
581 LLVMWriteBitcodeToFile(gallivm
->module
, "llvmpipe.bc");
582 debug_printf("llvmpipe.bc written\n");
583 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
587 assert(!gallivm
->engine
);
588 if (!init_gallivm_engine(gallivm
)) {
592 assert(gallivm
->engine
);
596 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
597 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
601 * Need to filter out functions which don't have an implementation,
602 * such as the intrinsics. May not be sufficient in case of IPO?
603 * LLVMGetPointerToGlobal() will abort otherwise.
605 if (!LLVMIsDeclaration(llvm_func
)) {
606 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
607 lp_disassemble(llvm_func
, func_code
);
609 llvm_func
= LLVMGetNextFunction(llvm_func
);
615 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
618 if (!LLVMIsDeclaration(llvm_func
)) {
619 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
620 lp_profile(llvm_func
, func_code
);
622 llvm_func
= LLVMGetNextFunction(llvm_func
);
631 gallivm_jit_function(struct gallivm_state
*gallivm
,
635 func_pointer jit_func
;
637 assert(gallivm
->compiled
);
638 assert(gallivm
->engine
);
640 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
642 jit_func
= pointer_to_func(code
);