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