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 "util/os_time.h"
37 #include "lp_bld_debug.h"
38 #include "lp_bld_misc.h"
39 #include "lp_bld_init.h"
41 #include <llvm/Config/llvm-config.h>
42 #include <llvm-c/Analysis.h>
43 #include <llvm-c/Transforms/Scalar.h>
44 #if LLVM_VERSION_MAJOR >= 7
45 #include <llvm-c/Transforms/Utils.h>
47 #include <llvm-c/BitWriter.h>
49 #if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))
50 #include <llvm-c/Transforms/IPO.h>
52 #include <llvm-c/Transforms/Coroutines.h>
55 unsigned gallivm_perf
= 0;
57 static const struct debug_named_value lp_bld_perf_flags
[] = {
58 { "no_brilinear", GALLIVM_PERF_NO_BRILINEAR
, "disable brilinear optimization" },
59 { "no_rho_approx", GALLIVM_PERF_NO_RHO_APPROX
, "disable rho_approx optimization" },
60 { "no_quad_lod", GALLIVM_PERF_NO_QUAD_LOD
, "disable quad_lod optimization" },
61 { "no_aos_sampling", GALLIVM_PERF_NO_AOS_SAMPLING
, "disable aos sampling optimization" },
62 { "nopt", GALLIVM_PERF_NO_OPT
, "disable optimization passes to speed up shader compilation" },
63 { "no_filter_hacks", GALLIVM_PERF_NO_BRILINEAR
| GALLIVM_PERF_NO_RHO_APPROX
|
64 GALLIVM_PERF_NO_QUAD_LOD
, "disable filter optimization hacks" },
69 unsigned gallivm_debug
= 0;
71 static const struct debug_named_value lp_bld_debug_flags
[] = {
72 { "tgsi", GALLIVM_DEBUG_TGSI
, NULL
},
73 { "ir", GALLIVM_DEBUG_IR
, NULL
},
74 { "asm", GALLIVM_DEBUG_ASM
, NULL
},
75 { "perf", GALLIVM_DEBUG_PERF
, NULL
},
76 { "gc", GALLIVM_DEBUG_GC
, NULL
},
77 { "dumpbc", GALLIVM_DEBUG_DUMP_BC
, NULL
},
81 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug
, "GALLIVM_DEBUG", lp_bld_debug_flags
, 0)
85 static boolean gallivm_initialized
= FALSE
;
87 unsigned lp_native_vector_width
;
91 * Optimization values are:
94 * - 2: Default (-O2, -Os)
95 * - 3: Aggressive (-O3)
97 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
99 enum LLVM_CodeGenOpt_Level
{
108 * Create the LLVM (optimization) pass manager and install
109 * relevant optimization passes.
110 * \return TRUE for success, FALSE for failure
113 create_pass_manager(struct gallivm_state
*gallivm
)
115 assert(!gallivm
->passmgr
);
116 assert(gallivm
->target
);
118 gallivm
->passmgr
= LLVMCreateFunctionPassManagerForModule(gallivm
->module
);
119 if (!gallivm
->passmgr
)
122 #if GALLIVM_HAVE_CORO
123 gallivm
->cgpassmgr
= LLVMCreatePassManager();
126 * TODO: some per module pass manager with IPO passes might be helpful -
127 * the generated texture functions may benefit from inlining if they are
128 * simple, or constant propagation into them, etc.
133 // New ones from the Module.
134 td_str
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
135 LLVMSetDataLayout(gallivm
->module
, td_str
);
139 #if GALLIVM_HAVE_CORO
140 #if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))
141 LLVMAddArgumentPromotionPass(gallivm
->cgpassmgr
);
142 LLVMAddFunctionAttrsPass(gallivm
->cgpassmgr
);
144 LLVMAddCoroEarlyPass(gallivm
->cgpassmgr
);
145 LLVMAddCoroSplitPass(gallivm
->cgpassmgr
);
146 LLVMAddCoroElidePass(gallivm
->cgpassmgr
);
149 if ((gallivm_perf
& GALLIVM_PERF_NO_OPT
) == 0) {
151 * TODO: Evaluate passes some more - keeping in mind
152 * both quality of generated code and compile times.
155 * NOTE: if you change this, don't forget to change the output
156 * with GALLIVM_DEBUG_DUMP_BC in gallivm_compile_module.
158 LLVMAddScalarReplAggregatesPass(gallivm
->passmgr
);
159 LLVMAddEarlyCSEPass(gallivm
->passmgr
);
160 LLVMAddCFGSimplificationPass(gallivm
->passmgr
);
162 * FIXME: LICM is potentially quite useful. However, for some
163 * rather crazy shaders the compile time can reach _hours_ per shader,
164 * due to licm implying lcssa (since llvm 3.5), which can take forever.
165 * Even for sane shaders, the cost of licm is rather high (and not just
166 * due to lcssa, licm itself too), though mostly only in cases when it
167 * can actually move things, so having to disable it is a pity.
168 * LLVMAddLICMPass(gallivm->passmgr);
170 LLVMAddReassociatePass(gallivm
->passmgr
);
171 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
172 LLVMAddConstantPropagationPass(gallivm
->passmgr
);
173 LLVMAddInstructionCombiningPass(gallivm
->passmgr
);
174 LLVMAddGVNPass(gallivm
->passmgr
);
175 #if GALLIVM_HAVE_CORO
176 LLVMAddCoroCleanupPass(gallivm
->passmgr
);
180 /* We need at least this pass to prevent the backends to fail in
183 LLVMAddPromoteMemoryToRegisterPass(gallivm
->passmgr
);
191 * Free gallivm object's LLVM allocations, but not any generated code
192 * nor the gallivm object itself.
195 gallivm_free_ir(struct gallivm_state
*gallivm
)
197 if (gallivm
->passmgr
) {
198 LLVMDisposePassManager(gallivm
->passmgr
);
201 #if GALLIVM_HAVE_CORO
202 if (gallivm
->cgpassmgr
) {
203 LLVMDisposePassManager(gallivm
->cgpassmgr
);
207 if (gallivm
->engine
) {
208 /* This will already destroy any associated module */
209 LLVMDisposeExecutionEngine(gallivm
->engine
);
210 } else if (gallivm
->module
) {
211 LLVMDisposeModule(gallivm
->module
);
214 FREE(gallivm
->module_name
);
216 if (gallivm
->target
) {
217 LLVMDisposeTargetData(gallivm
->target
);
220 if (gallivm
->builder
)
221 LLVMDisposeBuilder(gallivm
->builder
);
223 /* The LLVMContext should be owned by the parent of gallivm. */
225 gallivm
->engine
= NULL
;
226 gallivm
->target
= NULL
;
227 gallivm
->module
= NULL
;
228 gallivm
->module_name
= NULL
;
229 gallivm
->cgpassmgr
= NULL
;
230 gallivm
->passmgr
= NULL
;
231 gallivm
->context
= NULL
;
232 gallivm
->builder
= NULL
;
237 * Free LLVM-generated code. Should be done AFTER gallivm_free_ir().
240 gallivm_free_code(struct gallivm_state
*gallivm
)
242 assert(!gallivm
->module
);
243 assert(!gallivm
->engine
);
244 lp_free_generated_code(gallivm
->code
);
245 gallivm
->code
= NULL
;
246 lp_free_memory_manager(gallivm
->memorymgr
);
247 gallivm
->memorymgr
= NULL
;
252 init_gallivm_engine(struct gallivm_state
*gallivm
)
255 enum LLVM_CodeGenOpt_Level optlevel
;
259 if (gallivm_perf
& GALLIVM_PERF_NO_OPT
) {
266 ret
= lp_build_create_jit_compiler_for_module(&gallivm
->engine
,
273 _debug_printf("%s\n", error
);
274 LLVMDisposeMessage(error
);
281 * Dump the data layout strings.
284 LLVMTargetDataRef target
= LLVMGetExecutionEngineTargetData(gallivm
->engine
);
286 char *engine_data_layout
;
288 data_layout
= LLVMCopyStringRepOfTargetData(gallivm
->target
);
289 engine_data_layout
= LLVMCopyStringRepOfTargetData(target
);
292 debug_printf("module target data = %s\n", data_layout
);
293 debug_printf("engine target data = %s\n", engine_data_layout
);
297 free(engine_data_layout
);
308 * Allocate gallivm LLVM objects.
309 * \return TRUE for success, FALSE for failure
312 init_gallivm_state(struct gallivm_state
*gallivm
, const char *name
,
313 LLVMContextRef context
)
315 assert(!gallivm
->context
);
316 assert(!gallivm
->module
);
318 if (!lp_build_init())
321 gallivm
->context
= context
;
323 if (!gallivm
->context
)
326 gallivm
->module_name
= NULL
;
328 size_t size
= strlen(name
) + 1;
329 gallivm
->module_name
= MALLOC(size
);
330 if (gallivm
->module_name
) {
331 memcpy(gallivm
->module_name
, name
, size
);
335 gallivm
->module
= LLVMModuleCreateWithNameInContext(name
,
337 if (!gallivm
->module
)
340 gallivm
->builder
= LLVMCreateBuilderInContext(gallivm
->context
);
341 if (!gallivm
->builder
)
344 gallivm
->memorymgr
= lp_get_default_memory_manager();
345 if (!gallivm
->memorymgr
)
348 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
349 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
354 * MC-JIT engine compiles the module immediately on creation, so we can't
355 * obtain the target data from it. Instead we create a target data layout
358 * The produced layout strings are not precisely the same, but should make
359 * no difference for the kind of optimization passes we run.
361 * For reference this is the layout string on x64:
363 * 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
366 * - http://llvm.org/docs/LangRef.html#datalayout
370 const unsigned pointer_size
= 8 * sizeof(void *);
372 snprintf(layout
, sizeof layout
, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
373 #if UTIL_ARCH_LITTLE_ENDIAN
374 'e', // little endian
378 pointer_size
, pointer_size
, pointer_size
, // pointer size, abi alignment, preferred alignment
379 pointer_size
, // aggregate preferred alignment
380 pointer_size
, pointer_size
); // stack objects abi alignment, preferred alignment
382 gallivm
->target
= LLVMCreateTargetData(layout
);
383 if (!gallivm
->target
) {
388 if (!create_pass_manager(gallivm
))
394 gallivm_free_ir(gallivm
);
395 gallivm_free_code(gallivm
);
403 if (gallivm_initialized
)
407 /* LLVMLinkIn* are no-ops at runtime. They just ensure the respective
408 * component is linked at buildtime, which is sufficient for its static
409 * constructors to be called at load time.
414 gallivm_debug
= debug_get_option_gallivm_debug();
417 gallivm_perf
= debug_get_flags_option("GALLIVM_PERF", lp_bld_perf_flags
, 0 );
419 lp_set_target_options();
423 /* For simulating less capable machines */
425 if (debug_get_bool_option("LP_FORCE_SSE2", FALSE
)) {
426 assert(util_cpu_caps
.has_sse2
);
427 util_cpu_caps
.has_sse3
= 0;
428 util_cpu_caps
.has_ssse3
= 0;
429 util_cpu_caps
.has_sse4_1
= 0;
430 util_cpu_caps
.has_sse4_2
= 0;
431 util_cpu_caps
.has_avx
= 0;
432 util_cpu_caps
.has_avx2
= 0;
433 util_cpu_caps
.has_f16c
= 0;
434 util_cpu_caps
.has_fma
= 0;
438 if (util_cpu_caps
.has_avx2
|| util_cpu_caps
.has_avx
) {
439 lp_native_vector_width
= 256;
441 /* Leave it at 128, even when no SIMD extensions are available.
442 * Really needs to be a multiple of 128 so can fit 4 floats.
444 lp_native_vector_width
= 128;
447 lp_native_vector_width
= debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
448 lp_native_vector_width
);
450 #if LLVM_VERSION_MAJOR < 4
451 if (lp_native_vector_width
<= 128) {
452 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
453 * "util_cpu_caps.has_avx" predicate, and lack the
454 * "lp_native_vector_width > 128" predicate. And also to ensure a more
455 * consistent behavior, allowing one to test SSE2 on AVX machines.
456 * XXX: should not play games with util_cpu_caps directly as it might
457 * get used for other things outside llvm too.
459 util_cpu_caps
.has_avx
= 0;
460 util_cpu_caps
.has_avx2
= 0;
461 util_cpu_caps
.has_f16c
= 0;
462 util_cpu_caps
.has_fma
= 0;
466 #ifdef PIPE_ARCH_PPC_64
467 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
468 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
469 * that some rounding and half-float to float handling does not round
471 * XXX: should eventually follow same logic on all platforms.
472 * Right now denorms get explicitly disabled (but elsewhere) for x86,
473 * whereas ppc64 explicitly enables them...
475 if (util_cpu_caps
.has_altivec
) {
476 unsigned short mask
[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
477 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
488 gallivm_initialized
= TRUE
;
496 * Create a new gallivm_state object.
498 struct gallivm_state
*
499 gallivm_create(const char *name
, LLVMContextRef context
)
501 struct gallivm_state
*gallivm
;
503 gallivm
= CALLOC_STRUCT(gallivm_state
);
505 if (!init_gallivm_state(gallivm
, name
, context
)) {
511 assert(gallivm
!= NULL
);
517 * Destroy a gallivm_state object.
520 gallivm_destroy(struct gallivm_state
*gallivm
)
522 gallivm_free_ir(gallivm
);
523 gallivm_free_code(gallivm
);
529 * Validate a function.
530 * Verification is only done with debug builds.
533 gallivm_verify_function(struct gallivm_state
*gallivm
,
536 /* Verify the LLVM IR. If invalid, dump and abort */
538 if (LLVMVerifyFunction(func
, LLVMPrintMessageAction
)) {
539 lp_debug_dump_value(func
);
545 if (gallivm_debug
& GALLIVM_DEBUG_IR
) {
546 /* Print the LLVM IR to stderr */
547 lp_debug_dump_value(func
);
555 * This does IR optimization on all functions in the module.
558 gallivm_compile_module(struct gallivm_state
*gallivm
)
561 int64_t time_begin
= 0;
563 assert(!gallivm
->compiled
);
565 if (gallivm
->builder
) {
566 LLVMDisposeBuilder(gallivm
->builder
);
567 gallivm
->builder
= NULL
;
570 /* Dump bitcode to a file */
571 if (gallivm_debug
& GALLIVM_DEBUG_DUMP_BC
) {
573 assert(gallivm
->module_name
);
574 snprintf(filename
, sizeof(filename
), "ir_%s.bc", gallivm
->module_name
);
575 LLVMWriteBitcodeToFile(gallivm
->module
, filename
);
576 debug_printf("%s written\n", filename
);
577 debug_printf("Invoke as \"opt %s %s | llc -O%d %s%s\"\n",
578 gallivm_debug
& GALLIVM_PERF_NO_OPT
? "-mem2reg" :
579 "-sroa -early-cse -simplifycfg -reassociate "
580 "-mem2reg -constprop -instcombine -gvn",
581 filename
, gallivm_debug
& GALLIVM_PERF_NO_OPT
? 0 : 2,
582 "[-mcpu=<-mcpu option>] ",
583 "[-mattr=<-mattr option(s)>]");
586 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
587 time_begin
= os_time_get();
589 #if GALLIVM_HAVE_CORO
590 LLVMRunPassManager(gallivm
->cgpassmgr
, gallivm
->module
);
592 /* Run optimization passes */
593 LLVMInitializeFunctionPassManager(gallivm
->passmgr
);
594 func
= LLVMGetFirstFunction(gallivm
->module
);
597 debug_printf("optimizing func %s...\n", LLVMGetValueName(func
));
600 /* Disable frame pointer omission on debug/profile builds */
601 /* XXX: And workaround http://llvm.org/PR21435 */
602 #if defined(DEBUG) || defined(PROFILE) || defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
603 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim", "true");
604 LLVMAddTargetDependentFunctionAttr(func
, "no-frame-pointer-elim-non-leaf", "true");
607 LLVMRunFunctionPassManager(gallivm
->passmgr
, func
);
608 func
= LLVMGetNextFunction(func
);
610 LLVMFinalizeFunctionPassManager(gallivm
->passmgr
);
612 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
613 int64_t time_end
= os_time_get();
614 int time_msec
= (int)((time_end
- time_begin
) / 1000);
615 assert(gallivm
->module_name
);
616 debug_printf("optimizing module %s took %d msec\n",
617 gallivm
->module_name
, time_msec
);
620 /* Setting the module's DataLayout to an empty string will cause the
621 * ExecutionEngine to copy to the DataLayout string from its target machine
622 * to the module. As of LLVM 3.8 the module and the execution engine are
623 * required to have the same DataLayout.
625 * We must make sure we do this after running the optimization passes,
626 * because those passes need a correct datalayout string. For example, if
627 * those optimization passes see an empty datalayout, they will assume this
628 * is a little endian target and will do optimizations that break big endian
631 * TODO: This is just a temporary work-around. The correct solution is for
632 * gallivm_init_state() to create a TargetMachine and pull the DataLayout
633 * from there. Currently, the TargetMachine used by llvmpipe is being
634 * implicitly created by the EngineBuilder in
635 * lp_build_create_jit_compiler_for_module()
637 LLVMSetDataLayout(gallivm
->module
, "");
638 assert(!gallivm
->engine
);
639 if (!init_gallivm_engine(gallivm
)) {
642 assert(gallivm
->engine
);
646 if (gallivm_debug
& GALLIVM_DEBUG_ASM
) {
647 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
651 * Need to filter out functions which don't have an implementation,
652 * such as the intrinsics. May not be sufficient in case of IPO?
653 * LLVMGetPointerToGlobal() will abort otherwise.
655 if (!LLVMIsDeclaration(llvm_func
)) {
656 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
657 lp_disassemble(llvm_func
, func_code
);
659 llvm_func
= LLVMGetNextFunction(llvm_func
);
665 LLVMValueRef llvm_func
= LLVMGetFirstFunction(gallivm
->module
);
668 if (!LLVMIsDeclaration(llvm_func
)) {
669 void *func_code
= LLVMGetPointerToGlobal(gallivm
->engine
, llvm_func
);
670 lp_profile(llvm_func
, func_code
);
672 llvm_func
= LLVMGetNextFunction(llvm_func
);
681 gallivm_jit_function(struct gallivm_state
*gallivm
,
685 func_pointer jit_func
;
686 int64_t time_begin
= 0;
688 assert(gallivm
->compiled
);
689 assert(gallivm
->engine
);
691 if (gallivm_debug
& GALLIVM_DEBUG_PERF
)
692 time_begin
= os_time_get();
694 code
= LLVMGetPointerToGlobal(gallivm
->engine
, func
);
696 jit_func
= pointer_to_func(code
);
698 if (gallivm_debug
& GALLIVM_DEBUG_PERF
) {
699 int64_t time_end
= os_time_get();
700 int time_msec
= (int)(time_end
- time_begin
) / 1000;
701 debug_printf(" jitting func %s took %d msec\n",
702 LLVMGetValueName(func
), time_msec
);