util: add avx2 and xop detection to cpu detection code
[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 "lp_bld.h"
36 #include "lp_bld_debug.h"
37 #include "lp_bld_misc.h"
38 #include "lp_bld_init.h"
39
40 #include <llvm-c/Analysis.h>
41 #include <llvm-c/Transforms/Scalar.h>
42 #include <llvm-c/BitWriter.h>
43
44
45 /**
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
51 */
52 #if defined(PIPE_ARCH_PPC_64) || defined(PIPE_ARCH_S390) || defined(PIPE_ARCH_ARM) || defined(PIPE_ARCH_AARCH64)
53 # define USE_MCJIT 1
54 # define HAVE_AVX 0
55 #elif HAVE_LLVM >= 0x0302 || (HAVE_LLVM == 0x0301 && defined(HAVE_JIT_AVX_SUPPORT))
56 # define USE_MCJIT 0
57 # define HAVE_AVX 1
58 #elif HAVE_LLVM == 0x0301 && (defined(PIPE_OS_LINUX) || defined(PIPE_OS_APPLE))
59 # define USE_MCJIT 1
60 # define HAVE_AVX 1
61 #else
62 # define USE_MCJIT 0
63 # define HAVE_AVX 0
64 #endif
65
66
67 #if USE_MCJIT
68 void LLVMLinkInMCJIT();
69 #endif
70
71
72 #ifdef DEBUG
73 unsigned gallivm_debug = 0;
74
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 },
85 DEBUG_NAMED_VALUE_END
86 };
87
88 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
89 #endif
90
91
92 static boolean gallivm_initialized = FALSE;
93
94 unsigned lp_native_vector_width;
95
96
97 /*
98 * Optimization values are:
99 * - 0: None (-O0)
100 * - 1: Less (-O1)
101 * - 2: Default (-O2, -Os)
102 * - 3: Aggressive (-O3)
103 *
104 * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
105 */
106 enum LLVM_CodeGenOpt_Level {
107 #if HAVE_LLVM >= 0x207
108 None, // -O0
109 Less, // -O1
110 Default, // -O2, -Os
111 Aggressive // -O3
112 #else
113 Default,
114 None,
115 Aggressive
116 #endif
117 };
118
119
120 #if HAVE_LLVM <= 0x0206
121 /**
122 * LLVM 2.6 permits only one ExecutionEngine to be created. So use the
123 * same gallivm state everywhere.
124 */
125 static struct gallivm_state *GlobalGallivm = NULL;
126 #endif
127
128
129 /**
130 * Create the LLVM (optimization) pass manager and install
131 * relevant optimization passes.
132 * \return TRUE for success, FALSE for failure
133 */
134 static boolean
135 create_pass_manager(struct gallivm_state *gallivm)
136 {
137 assert(!gallivm->passmgr);
138 assert(gallivm->target);
139
140 gallivm->passmgr = LLVMCreateFunctionPassManager(gallivm->provider);
141 if (!gallivm->passmgr)
142 return FALSE;
143
144 LLVMAddTargetData(gallivm->target, gallivm->passmgr);
145
146 if ((gallivm_debug & GALLIVM_DEBUG_NO_OPT) == 0) {
147 /* These are the passes currently listed in llvm-c/Transforms/Scalar.h,
148 * but there are more on SVN.
149 * TODO: Add more passes.
150 */
151 LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
152 LLVMAddLICMPass(gallivm->passmgr);
153 LLVMAddCFGSimplificationPass(gallivm->passmgr);
154 LLVMAddReassociatePass(gallivm->passmgr);
155
156 if (HAVE_LLVM >= 0x207 && sizeof(void*) == 4) {
157 /* For LLVM >= 2.7 and 32-bit build, use this order of passes to
158 * avoid generating bad code.
159 * Test with piglit glsl-vs-sqrt-zero test.
160 */
161 LLVMAddConstantPropagationPass(gallivm->passmgr);
162 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
163 }
164 else {
165 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
166 LLVMAddConstantPropagationPass(gallivm->passmgr);
167 }
168
169 if (util_cpu_caps.has_sse4_1) {
170 /* FIXME: There is a bug in this pass, whereby the combination
171 * of fptosi and sitofp (necessary for trunc/floor/ceil/round
172 * implementation) somehow becomes invalid code.
173 */
174 LLVMAddInstructionCombiningPass(gallivm->passmgr);
175 }
176 LLVMAddGVNPass(gallivm->passmgr);
177 }
178 else {
179 /* We need at least this pass to prevent the backends to fail in
180 * unexpected ways.
181 */
182 LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
183 }
184
185 return TRUE;
186 }
187
188
189 /**
190 * Free gallivm object's LLVM allocations, but not the gallivm object itself.
191 */
192 static void
193 free_gallivm_state(struct gallivm_state *gallivm)
194 {
195 #if HAVE_LLVM >= 0x207 /* XXX or 0x208? */
196 /* This leads to crashes w/ some versions of LLVM */
197 LLVMModuleRef mod;
198 char *error;
199
200 if (gallivm->engine && gallivm->provider)
201 LLVMRemoveModuleProvider(gallivm->engine, gallivm->provider,
202 &mod, &error);
203 #endif
204
205 if (gallivm->passmgr) {
206 LLVMDisposePassManager(gallivm->passmgr);
207 }
208
209 #if 0
210 /* XXX this seems to crash with all versions of LLVM */
211 if (gallivm->provider)
212 LLVMDisposeModuleProvider(gallivm->provider);
213 #endif
214
215 if (HAVE_LLVM >= 0x207 && gallivm->engine) {
216 /* This will already destroy any associated module */
217 LLVMDisposeExecutionEngine(gallivm->engine);
218 } else {
219 LLVMDisposeModule(gallivm->module);
220 }
221
222 #if !USE_MCJIT
223 /* Don't free the TargetData, it's owned by the exec engine */
224 #else
225 if (gallivm->target) {
226 LLVMDisposeTargetData(gallivm->target);
227 }
228 #endif
229
230 /* Never free the LLVM context.
231 */
232 #if 0
233 if (gallivm->context)
234 LLVMContextDispose(gallivm->context);
235 #endif
236
237 if (gallivm->builder)
238 LLVMDisposeBuilder(gallivm->builder);
239
240 gallivm->engine = NULL;
241 gallivm->target = NULL;
242 gallivm->module = NULL;
243 gallivm->provider = NULL;
244 gallivm->passmgr = NULL;
245 gallivm->context = NULL;
246 gallivm->builder = NULL;
247 }
248
249
250 static boolean
251 init_gallivm_engine(struct gallivm_state *gallivm)
252 {
253 if (1) {
254 /* We can only create one LLVMExecutionEngine (w/ LLVM 2.6 anyway) */
255 enum LLVM_CodeGenOpt_Level optlevel;
256 char *error = NULL;
257 int ret;
258
259 if (gallivm_debug & GALLIVM_DEBUG_NO_OPT) {
260 optlevel = None;
261 }
262 else {
263 optlevel = Default;
264 }
265
266 #if HAVE_LLVM >= 0x0301
267 ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
268 gallivm->module,
269 (unsigned) optlevel,
270 USE_MCJIT,
271 &error);
272 #else
273 ret = LLVMCreateJITCompiler(&gallivm->engine, gallivm->provider,
274 (unsigned) optlevel, &error);
275 #endif
276 if (ret) {
277 _debug_printf("%s\n", error);
278 LLVMDisposeMessage(error);
279 goto fail;
280 }
281 }
282
283 LLVMAddModuleProvider(gallivm->engine, gallivm->provider);//new
284
285 #if !USE_MCJIT
286 gallivm->target = LLVMGetExecutionEngineTargetData(gallivm->engine);
287 if (!gallivm->target)
288 goto fail;
289 #else
290 if (0) {
291 /*
292 * Dump the data layout strings.
293 */
294
295 LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
296 char *data_layout;
297 char *engine_data_layout;
298
299 data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
300 engine_data_layout = LLVMCopyStringRepOfTargetData(target);
301
302 if (1) {
303 debug_printf("module target data = %s\n", data_layout);
304 debug_printf("engine target data = %s\n", engine_data_layout);
305 }
306
307 free(data_layout);
308 free(engine_data_layout);
309 }
310 #endif
311
312 return TRUE;
313
314 fail:
315 return FALSE;
316 }
317
318
319 /**
320 * Singleton
321 *
322 * We must never free LLVM contexts, because LLVM has several global caches
323 * which pointing/derived from objects owned by the context, causing false
324 * memory leaks and false cache hits when these objects are destroyed.
325 *
326 * TODO: For thread safety on multi-threaded OpenGL we should use one LLVM
327 * context per thread, and put them in a pool when threads are destroyed.
328 */
329 static LLVMContextRef gallivm_context = NULL;
330
331
332 /**
333 * Allocate gallivm LLVM objects.
334 * \return TRUE for success, FALSE for failure
335 */
336 static boolean
337 init_gallivm_state(struct gallivm_state *gallivm)
338 {
339 assert(!gallivm->context);
340 assert(!gallivm->module);
341 assert(!gallivm->provider);
342
343 lp_build_init();
344
345 if (!gallivm_context) {
346 gallivm_context = LLVMContextCreate();
347 }
348 gallivm->context = gallivm_context;
349 if (!gallivm->context)
350 goto fail;
351
352 gallivm->module = LLVMModuleCreateWithNameInContext("gallivm",
353 gallivm->context);
354 if (!gallivm->module)
355 goto fail;
356
357 gallivm->provider =
358 LLVMCreateModuleProviderForExistingModule(gallivm->module);
359 if (!gallivm->provider)
360 goto fail;
361
362 gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
363 if (!gallivm->builder)
364 goto fail;
365
366 /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
367 * complete when MC-JIT is created. So defer the MC-JIT engine creation for
368 * now.
369 */
370 #if !USE_MCJIT
371 if (!init_gallivm_engine(gallivm)) {
372 goto fail;
373 }
374 #else
375 /*
376 * MC-JIT engine compiles the module immediately on creation, so we can't
377 * obtain the target data from it. Instead we create a target data layout
378 * from a string.
379 *
380 * The produced layout strings are not precisely the same, but should make
381 * no difference for the kind of optimization passes we run.
382 *
383 * For reference this is the layout string on x64:
384 *
385 * 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
386 *
387 * See also:
388 * - http://llvm.org/docs/LangRef.html#datalayout
389 */
390
391 {
392 const unsigned pointer_size = 8 * sizeof(void *);
393 char layout[512];
394 util_snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
395 #ifdef PIPE_ARCH_LITTLE_ENDIAN
396 'e', // little endian
397 #else
398 'E', // big endian
399 #endif
400 pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
401 pointer_size, // aggregate preferred alignment
402 pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
403
404 gallivm->target = LLVMCreateTargetData(layout);
405 if (!gallivm->target) {
406 return FALSE;
407 }
408 }
409 #endif
410
411 if (!create_pass_manager(gallivm))
412 goto fail;
413
414 return TRUE;
415
416 fail:
417 free_gallivm_state(gallivm);
418 return FALSE;
419 }
420
421
422 void
423 lp_build_init(void)
424 {
425 if (gallivm_initialized)
426 return;
427
428 #ifdef DEBUG
429 gallivm_debug = debug_get_option_gallivm_debug();
430 #endif
431
432 lp_set_target_options();
433
434 #if USE_MCJIT
435 LLVMLinkInMCJIT();
436 #else
437 LLVMLinkInJIT();
438 #endif
439
440 util_cpu_detect();
441
442 /* AMD Bulldozer AVX's throughput is the same as SSE2; and because using
443 * 8-wide vector needs more floating ops than 4-wide (due to padding), it is
444 * actually more efficient to use 4-wide vectors on this processor.
445 *
446 * See also:
447 * - http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/2
448 */
449 if (HAVE_AVX &&
450 util_cpu_caps.has_avx &&
451 util_cpu_caps.has_intel) {
452 lp_native_vector_width = 256;
453 } else {
454 /* Leave it at 128, even when no SIMD extensions are available.
455 * Really needs to be a multiple of 128 so can fit 4 floats.
456 */
457 lp_native_vector_width = 128;
458 }
459
460 lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
461 lp_native_vector_width);
462
463 if (lp_native_vector_width <= 128) {
464 /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
465 * "util_cpu_caps.has_avx" predicate, and lack the
466 * "lp_native_vector_width > 128" predicate. And also to ensure a more
467 * consistent behavior, allowing one to test SSE2 on AVX machines.
468 * XXX: should not play games with util_cpu_caps directly as it might
469 * get used for other things outside llvm too.
470 */
471 util_cpu_caps.has_avx = 0;
472 util_cpu_caps.has_avx2 = 0;
473 }
474
475 if (!HAVE_AVX) {
476 /*
477 * note these instructions are VEX-only, so can only emit if we use
478 * avx (don't want to base it on has_avx & has_f16c later as that would
479 * omit it unnecessarily on amd cpus, see above).
480 */
481 util_cpu_caps.has_f16c = 0;
482 util_cpu_caps.has_xop = 0;
483 }
484
485 #ifdef PIPE_ARCH_PPC_64
486 /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
487 * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
488 * that some rounding and half-float to float handling does not round
489 * incorrectly to 0.
490 * XXX: should eventually follow same logic on all platforms.
491 * Right now denorms get explicitly disabled (but elsewhere) for x86,
492 * whereas ppc64 explicitly enables them...
493 */
494 if (util_cpu_caps.has_altivec) {
495 unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
496 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
497 __asm (
498 "mfvscr %%v1\n"
499 "vand %0,%%v1,%0\n"
500 "mtvscr %0"
501 :
502 : "r" (*mask)
503 );
504 }
505 #endif
506
507 gallivm_initialized = TRUE;
508
509 #if 0
510 /* For simulating less capable machines */
511 util_cpu_caps.has_sse3 = 0;
512 util_cpu_caps.has_ssse3 = 0;
513 util_cpu_caps.has_sse4_1 = 0;
514 util_cpu_caps.has_avx = 0;
515 util_cpu_caps.has_f16c = 0;
516 #endif
517 }
518
519
520
521 /**
522 * Create a new gallivm_state object.
523 * Note that we return a singleton.
524 */
525 struct gallivm_state *
526 gallivm_create(void)
527 {
528 struct gallivm_state *gallivm;
529
530 #if HAVE_LLVM <= 0x206
531 if (GlobalGallivm) {
532 return GlobalGallivm;
533 }
534 #endif
535
536 gallivm = CALLOC_STRUCT(gallivm_state);
537 if (gallivm) {
538 if (!init_gallivm_state(gallivm)) {
539 FREE(gallivm);
540 gallivm = NULL;
541 }
542 }
543
544 #if HAVE_LLVM <= 0x206
545 GlobalGallivm = gallivm;
546 #endif
547
548 return gallivm;
549 }
550
551
552 /**
553 * Destroy a gallivm_state object.
554 */
555 void
556 gallivm_destroy(struct gallivm_state *gallivm)
557 {
558 #if HAVE_LLVM <= 0x0206
559 /* No-op: don't destroy the singleton */
560 (void) gallivm;
561 #else
562 free_gallivm_state(gallivm);
563 FREE(gallivm);
564 #endif
565 }
566
567
568 /**
569 * Validate and optimze a function.
570 */
571 static void
572 gallivm_optimize_function(struct gallivm_state *gallivm,
573 LLVMValueRef func)
574 {
575 if (0) {
576 debug_printf("optimizing %s...\n", LLVMGetValueName(func));
577 }
578
579 assert(gallivm->passmgr);
580
581 /* Apply optimizations to LLVM IR */
582 LLVMRunFunctionPassManager(gallivm->passmgr, func);
583
584 if (0) {
585 if (gallivm_debug & GALLIVM_DEBUG_IR) {
586 /* Print the LLVM IR to stderr */
587 lp_debug_dump_value(func);
588 debug_printf("\n");
589 }
590 }
591 }
592
593
594 /**
595 * Validate a function.
596 */
597 void
598 gallivm_verify_function(struct gallivm_state *gallivm,
599 LLVMValueRef func)
600 {
601 /* Verify the LLVM IR. If invalid, dump and abort */
602 #ifdef DEBUG
603 if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
604 lp_debug_dump_value(func);
605 assert(0);
606 return;
607 }
608 #endif
609
610 gallivm_optimize_function(gallivm, func);
611
612 if (gallivm_debug & GALLIVM_DEBUG_IR) {
613 /* Print the LLVM IR to stderr */
614 lp_debug_dump_value(func);
615 debug_printf("\n");
616 }
617 }
618
619
620 void
621 gallivm_compile_module(struct gallivm_state *gallivm)
622 {
623 #if HAVE_LLVM > 0x206
624 assert(!gallivm->compiled);
625 #endif
626
627 /* Dump byte code to a file */
628 if (0) {
629 LLVMWriteBitcodeToFile(gallivm->module, "llvmpipe.bc");
630 debug_printf("llvmpipe.bc written\n");
631 debug_printf("Invoke as \"llc -o - llvmpipe.bc\"\n");
632 }
633
634 #if USE_MCJIT
635 assert(!gallivm->engine);
636 if (!init_gallivm_engine(gallivm)) {
637 assert(0);
638 }
639 #endif
640 assert(gallivm->engine);
641
642 ++gallivm->compiled;
643 }
644
645
646
647 func_pointer
648 gallivm_jit_function(struct gallivm_state *gallivm,
649 LLVMValueRef func)
650 {
651 void *code;
652 func_pointer jit_func;
653
654 assert(gallivm->compiled);
655 assert(gallivm->engine);
656
657 code = LLVMGetPointerToGlobal(gallivm->engine, func);
658 assert(code);
659 jit_func = pointer_to_func(code);
660
661 if (gallivm_debug & GALLIVM_DEBUG_ASM) {
662 lp_disassemble(func, code);
663 }
664
665 #if defined(PROFILE)
666 lp_profile(func, code);
667 #endif
668
669 /* Free the function body to save memory */
670 lp_func_delete_body(func);
671
672 return jit_func;
673 }
674
675
676 /**
677 * Free the function (and its machine code).
678 */
679 void
680 gallivm_free_function(struct gallivm_state *gallivm,
681 LLVMValueRef func,
682 const void *code)
683 {
684 #if !USE_MCJIT
685 if (code) {
686 LLVMFreeMachineCodeForFunction(gallivm->engine, func);
687 }
688
689 LLVMDeleteFunction(func);
690 #endif
691 }