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