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