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