• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "util/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/Config/llvm-config.h>
42 #include <llvm-c/Analysis.h>
43 #include <llvm-c/Transforms/Scalar.h>
44 #if LLVM_VERSION_MAJOR >= 7
45 #include <llvm-c/Transforms/Utils.h>
46 #endif
47 #include <llvm-c/BitWriter.h>
48 #if GALLIVM_HAVE_CORO
49 #if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))
50 #include <llvm-c/Transforms/IPO.h>
51 #endif
52 #include <llvm-c/Transforms/Coroutines.h>
53 #endif
54 
55 unsigned gallivm_perf = 0;
56 
57 static const struct debug_named_value lp_bld_perf_flags[] = {
58    { "no_brilinear", GALLIVM_PERF_NO_BRILINEAR, "disable brilinear optimization" },
59    { "no_rho_approx", GALLIVM_PERF_NO_RHO_APPROX, "disable rho_approx optimization" },
60    { "no_quad_lod", GALLIVM_PERF_NO_QUAD_LOD, "disable quad_lod optimization" },
61    { "no_aos_sampling", GALLIVM_PERF_NO_AOS_SAMPLING, "disable aos sampling optimization" },
62    { "nopt",   GALLIVM_PERF_NO_OPT, "disable optimization passes to speed up shader compilation" },
63    { "no_filter_hacks", GALLIVM_PERF_NO_BRILINEAR | GALLIVM_PERF_NO_RHO_APPROX |
64      GALLIVM_PERF_NO_QUAD_LOD, "disable filter optimization hacks" },
65    DEBUG_NAMED_VALUE_END
66 };
67 
68 #ifdef DEBUG
69 unsigned gallivm_debug = 0;
70 
71 static const struct debug_named_value lp_bld_debug_flags[] = {
72    { "tgsi",   GALLIVM_DEBUG_TGSI, NULL },
73    { "ir",     GALLIVM_DEBUG_IR, NULL },
74    { "asm",    GALLIVM_DEBUG_ASM, NULL },
75    { "perf",   GALLIVM_DEBUG_PERF, NULL },
76    { "gc",     GALLIVM_DEBUG_GC, NULL },
77    { "dumpbc", GALLIVM_DEBUG_DUMP_BC, NULL },
78    DEBUG_NAMED_VALUE_END
79 };
80 
81 DEBUG_GET_ONCE_FLAGS_OPTION(gallivm_debug, "GALLIVM_DEBUG", lp_bld_debug_flags, 0)
82 #endif
83 
84 
85 static boolean gallivm_initialized = FALSE;
86 
87 unsigned lp_native_vector_width;
88 
89 
90 /*
91  * Optimization values are:
92  * - 0: None (-O0)
93  * - 1: Less (-O1)
94  * - 2: Default (-O2, -Os)
95  * - 3: Aggressive (-O3)
96  *
97  * See also CodeGenOpt::Level in llvm/Target/TargetMachine.h
98  */
99 enum LLVM_CodeGenOpt_Level {
100    None,        // -O0
101    Less,        // -O1
102    Default,     // -O2, -Os
103    Aggressive   // -O3
104 };
105 
106 
107 /**
108  * Create the LLVM (optimization) pass manager and install
109  * relevant optimization passes.
110  * \return  TRUE for success, FALSE for failure
111  */
112 static boolean
create_pass_manager(struct gallivm_state * gallivm)113 create_pass_manager(struct gallivm_state *gallivm)
114 {
115    assert(!gallivm->passmgr);
116    assert(gallivm->target);
117 
118    gallivm->passmgr = LLVMCreateFunctionPassManagerForModule(gallivm->module);
119    if (!gallivm->passmgr)
120       return FALSE;
121 
122 #if GALLIVM_HAVE_CORO
123    gallivm->cgpassmgr = LLVMCreatePassManager();
124 #endif
125    /*
126     * TODO: some per module pass manager with IPO passes might be helpful -
127     * the generated texture functions may benefit from inlining if they are
128     * simple, or constant propagation into them, etc.
129     */
130 
131    {
132       char *td_str;
133       // New ones from the Module.
134       td_str = LLVMCopyStringRepOfTargetData(gallivm->target);
135       LLVMSetDataLayout(gallivm->module, td_str);
136       free(td_str);
137    }
138 
139 #if GALLIVM_HAVE_CORO
140 #if LLVM_VERSION_MAJOR <= 8 && (defined(PIPE_ARCH_AARCH64) || defined (PIPE_ARCH_ARM) || defined(PIPE_ARCH_S390))
141    LLVMAddArgumentPromotionPass(gallivm->cgpassmgr);
142    LLVMAddFunctionAttrsPass(gallivm->cgpassmgr);
143 #endif
144    LLVMAddCoroEarlyPass(gallivm->cgpassmgr);
145    LLVMAddCoroSplitPass(gallivm->cgpassmgr);
146    LLVMAddCoroElidePass(gallivm->cgpassmgr);
147 #endif
148 
149    if ((gallivm_perf & GALLIVM_PERF_NO_OPT) == 0) {
150       /*
151        * TODO: Evaluate passes some more - keeping in mind
152        * both quality of generated code and compile times.
153        */
154       /*
155        * NOTE: if you change this, don't forget to change the output
156        * with GALLIVM_DEBUG_DUMP_BC in gallivm_compile_module.
157        */
158       LLVMAddScalarReplAggregatesPass(gallivm->passmgr);
159       LLVMAddEarlyCSEPass(gallivm->passmgr);
160       LLVMAddCFGSimplificationPass(gallivm->passmgr);
161       /*
162        * FIXME: LICM is potentially quite useful. However, for some
163        * rather crazy shaders the compile time can reach _hours_ per shader,
164        * due to licm implying lcssa (since llvm 3.5), which can take forever.
165        * Even for sane shaders, the cost of licm is rather high (and not just
166        * due to lcssa, licm itself too), though mostly only in cases when it
167        * can actually move things, so having to disable it is a pity.
168        * LLVMAddLICMPass(gallivm->passmgr);
169        */
170       LLVMAddReassociatePass(gallivm->passmgr);
171       LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
172 #if LLVM_VERSION_MAJOR <= 11
173       LLVMAddConstantPropagationPass(gallivm->passmgr);
174 #else
175       LLVMAddInstructionSimplifyPass(gallivm->passmgr);
176 #endif
177       LLVMAddInstructionCombiningPass(gallivm->passmgr);
178       LLVMAddGVNPass(gallivm->passmgr);
179    }
180    else {
181       /* We need at least this pass to prevent the backends to fail in
182        * unexpected ways.
183        */
184       LLVMAddPromoteMemoryToRegisterPass(gallivm->passmgr);
185    }
186 #if GALLIVM_HAVE_CORO
187    LLVMAddCoroCleanupPass(gallivm->passmgr);
188 #endif
189 
190    return TRUE;
191 }
192 
193 
194 /**
195  * Free gallivm object's LLVM allocations, but not any generated code
196  * nor the gallivm object itself.
197  */
198 void
gallivm_free_ir(struct gallivm_state * gallivm)199 gallivm_free_ir(struct gallivm_state *gallivm)
200 {
201    if (gallivm->passmgr) {
202       LLVMDisposePassManager(gallivm->passmgr);
203    }
204 
205 #if GALLIVM_HAVE_CORO
206    if (gallivm->cgpassmgr) {
207       LLVMDisposePassManager(gallivm->cgpassmgr);
208    }
209 #endif
210 
211    if (gallivm->engine) {
212       /* This will already destroy any associated module */
213       LLVMDisposeExecutionEngine(gallivm->engine);
214    } else if (gallivm->module) {
215       LLVMDisposeModule(gallivm->module);
216    }
217 
218    if (gallivm->cache) {
219       lp_free_objcache(gallivm->cache->jit_obj_cache);
220       free(gallivm->cache->data);
221    }
222    FREE(gallivm->module_name);
223 
224    if (gallivm->target) {
225       LLVMDisposeTargetData(gallivm->target);
226    }
227 
228    if (gallivm->builder)
229       LLVMDisposeBuilder(gallivm->builder);
230 
231    /* The LLVMContext should be owned by the parent of gallivm. */
232 
233    gallivm->engine = NULL;
234    gallivm->target = NULL;
235    gallivm->module = NULL;
236    gallivm->module_name = NULL;
237    gallivm->cgpassmgr = NULL;
238    gallivm->passmgr = NULL;
239    gallivm->context = NULL;
240    gallivm->builder = NULL;
241    gallivm->cache = NULL;
242 }
243 
244 
245 /**
246  * Free LLVM-generated code.  Should be done AFTER gallivm_free_ir().
247  */
248 static void
gallivm_free_code(struct gallivm_state * gallivm)249 gallivm_free_code(struct gallivm_state *gallivm)
250 {
251    assert(!gallivm->module);
252    assert(!gallivm->engine);
253    lp_free_generated_code(gallivm->code);
254    gallivm->code = NULL;
255    lp_free_memory_manager(gallivm->memorymgr);
256    gallivm->memorymgr = NULL;
257 }
258 
259 
260 static boolean
init_gallivm_engine(struct gallivm_state * gallivm)261 init_gallivm_engine(struct gallivm_state *gallivm)
262 {
263    if (1) {
264       enum LLVM_CodeGenOpt_Level optlevel;
265       char *error = NULL;
266       int ret;
267 
268       if (gallivm_perf & GALLIVM_PERF_NO_OPT) {
269          optlevel = None;
270       }
271       else {
272          optlevel = Default;
273       }
274 
275       ret = lp_build_create_jit_compiler_for_module(&gallivm->engine,
276                                                     &gallivm->code,
277                                                     gallivm->cache,
278                                                     gallivm->module,
279                                                     gallivm->memorymgr,
280                                                     (unsigned) optlevel,
281                                                     &error);
282       if (ret) {
283          _debug_printf("%s\n", error);
284          LLVMDisposeMessage(error);
285          goto fail;
286       }
287    }
288 
289    if (0) {
290        /*
291         * Dump the data layout strings.
292         */
293 
294        LLVMTargetDataRef target = LLVMGetExecutionEngineTargetData(gallivm->engine);
295        char *data_layout;
296        char *engine_data_layout;
297 
298        data_layout = LLVMCopyStringRepOfTargetData(gallivm->target);
299        engine_data_layout = LLVMCopyStringRepOfTargetData(target);
300 
301        if (1) {
302           debug_printf("module target data = %s\n", data_layout);
303           debug_printf("engine target data = %s\n", engine_data_layout);
304        }
305 
306        free(data_layout);
307        free(engine_data_layout);
308    }
309 
310    return TRUE;
311 
312 fail:
313    return FALSE;
314 }
315 
316 
317 /**
318  * Allocate gallivm LLVM objects.
319  * \return  TRUE for success, FALSE for failure
320  */
321 static boolean
init_gallivm_state(struct gallivm_state * gallivm,const char * name,LLVMContextRef context,struct lp_cached_code * cache)322 init_gallivm_state(struct gallivm_state *gallivm, const char *name,
323                    LLVMContextRef context, struct lp_cached_code *cache)
324 {
325    assert(!gallivm->context);
326    assert(!gallivm->module);
327 
328    if (!lp_build_init())
329       return FALSE;
330 
331    gallivm->context = context;
332    gallivm->cache = cache;
333    if (!gallivm->context)
334       goto fail;
335 
336    gallivm->module_name = NULL;
337    if (name) {
338       size_t size = strlen(name) + 1;
339       gallivm->module_name = MALLOC(size);
340       if (gallivm->module_name) {
341          memcpy(gallivm->module_name, name, size);
342       }
343    }
344 
345    gallivm->module = LLVMModuleCreateWithNameInContext(name,
346                                                        gallivm->context);
347    if (!gallivm->module)
348       goto fail;
349 
350    gallivm->builder = LLVMCreateBuilderInContext(gallivm->context);
351    if (!gallivm->builder)
352       goto fail;
353 
354    gallivm->memorymgr = lp_get_default_memory_manager();
355    if (!gallivm->memorymgr)
356       goto fail;
357 
358    /* FIXME: MC-JIT only allows compiling one module at a time, and it must be
359     * complete when MC-JIT is created. So defer the MC-JIT engine creation for
360     * now.
361     */
362 
363    /*
364     * MC-JIT engine compiles the module immediately on creation, so we can't
365     * obtain the target data from it.  Instead we create a target data layout
366     * from a string.
367     *
368     * The produced layout strings are not precisely the same, but should make
369     * no difference for the kind of optimization passes we run.
370     *
371     * For reference this is the layout string on x64:
372     *
373     *   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
374     *
375     * See also:
376     * - http://llvm.org/docs/LangRef.html#datalayout
377     */
378 
379    {
380       const unsigned pointer_size = 8 * sizeof(void *);
381       char layout[512];
382       snprintf(layout, sizeof layout, "%c-p:%u:%u:%u-i64:64:64-a0:0:%u-s0:%u:%u",
383 #if UTIL_ARCH_LITTLE_ENDIAN
384                     'e', // little endian
385 #else
386                     'E', // big endian
387 #endif
388                     pointer_size, pointer_size, pointer_size, // pointer size, abi alignment, preferred alignment
389                     pointer_size, // aggregate preferred alignment
390                     pointer_size, pointer_size); // stack objects abi alignment, preferred alignment
391 
392       gallivm->target = LLVMCreateTargetData(layout);
393       if (!gallivm->target) {
394          return FALSE;
395       }
396    }
397 
398    if (!create_pass_manager(gallivm))
399       goto fail;
400 
401    return TRUE;
402 
403 fail:
404    gallivm_free_ir(gallivm);
405    gallivm_free_code(gallivm);
406    return FALSE;
407 }
408 
409 
410 boolean
lp_build_init(void)411 lp_build_init(void)
412 {
413    if (gallivm_initialized)
414       return TRUE;
415 
416 
417    /* LLVMLinkIn* are no-ops at runtime.  They just ensure the respective
418     * component is linked at buildtime, which is sufficient for its static
419     * constructors to be called at load time.
420     */
421    LLVMLinkInMCJIT();
422 
423 #ifdef DEBUG
424    gallivm_debug = debug_get_option_gallivm_debug();
425 #endif
426 
427    gallivm_perf = debug_get_flags_option("GALLIVM_PERF", lp_bld_perf_flags, 0 );
428 
429    lp_set_target_options();
430 
431    util_cpu_detect();
432 
433    /* For simulating less capable machines */
434 #ifdef DEBUG
435    if (debug_get_bool_option("LP_FORCE_SSE2", FALSE)) {
436       assert(util_cpu_caps.has_sse2);
437       util_cpu_caps.has_sse3 = 0;
438       util_cpu_caps.has_ssse3 = 0;
439       util_cpu_caps.has_sse4_1 = 0;
440       util_cpu_caps.has_sse4_2 = 0;
441       util_cpu_caps.has_avx = 0;
442       util_cpu_caps.has_avx2 = 0;
443       util_cpu_caps.has_f16c = 0;
444       util_cpu_caps.has_fma = 0;
445    }
446 #endif
447 
448    if (util_cpu_caps.has_avx2 || util_cpu_caps.has_avx) {
449       lp_native_vector_width = 256;
450    } else {
451       /* Leave it at 128, even when no SIMD extensions are available.
452        * Really needs to be a multiple of 128 so can fit 4 floats.
453        */
454       lp_native_vector_width = 128;
455    }
456 
457    lp_native_vector_width = debug_get_num_option("LP_NATIVE_VECTOR_WIDTH",
458                                                  lp_native_vector_width);
459 
460 #if LLVM_VERSION_MAJOR < 4
461    if (lp_native_vector_width <= 128) {
462       /* Hide AVX support, as often LLVM AVX intrinsics are only guarded by
463        * "util_cpu_caps.has_avx" predicate, and lack the
464        * "lp_native_vector_width > 128" predicate. And also to ensure a more
465        * consistent behavior, allowing one to test SSE2 on AVX machines.
466        * XXX: should not play games with util_cpu_caps directly as it might
467        * get used for other things outside llvm too.
468        */
469       util_cpu_caps.has_avx = 0;
470       util_cpu_caps.has_avx2 = 0;
471       util_cpu_caps.has_f16c = 0;
472       util_cpu_caps.has_fma = 0;
473    }
474 #endif
475 
476 #ifdef PIPE_ARCH_PPC_64
477    /* Set the NJ bit in VSCR to 0 so denormalized values are handled as
478     * specified by IEEE standard (PowerISA 2.06 - Section 6.3). This guarantees
479     * that some rounding and half-float to float handling does not round
480     * incorrectly to 0.
481     * XXX: should eventually follow same logic on all platforms.
482     * Right now denorms get explicitly disabled (but elsewhere) for x86,
483     * whereas ppc64 explicitly enables them...
484     */
485    if (util_cpu_caps.has_altivec) {
486       unsigned short mask[] = { 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
487                                 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFF };
488       __asm (
489         "mfvscr %%v1\n"
490         "vand   %0,%%v1,%0\n"
491         "mtvscr %0"
492         :
493         : "r" (*mask)
494       );
495    }
496 #endif
497 
498    gallivm_initialized = TRUE;
499 
500    return TRUE;
501 }
502 
503 
504 
505 /**
506  * Create a new gallivm_state object.
507  */
508 struct gallivm_state *
gallivm_create(const char * name,LLVMContextRef context,struct lp_cached_code * cache)509 gallivm_create(const char *name, LLVMContextRef context,
510                struct lp_cached_code *cache)
511 {
512    struct gallivm_state *gallivm;
513 
514    gallivm = CALLOC_STRUCT(gallivm_state);
515    if (gallivm) {
516       if (!init_gallivm_state(gallivm, name, context, cache)) {
517          FREE(gallivm);
518          gallivm = NULL;
519       }
520    }
521 
522    assert(gallivm != NULL);
523    return gallivm;
524 }
525 
526 
527 /**
528  * Destroy a gallivm_state object.
529  */
530 void
gallivm_destroy(struct gallivm_state * gallivm)531 gallivm_destroy(struct gallivm_state *gallivm)
532 {
533    gallivm_free_ir(gallivm);
534    gallivm_free_code(gallivm);
535    FREE(gallivm);
536 }
537 
538 
539 /**
540  * Validate a function.
541  * Verification is only done with debug builds.
542  */
543 void
gallivm_verify_function(struct gallivm_state * gallivm,LLVMValueRef func)544 gallivm_verify_function(struct gallivm_state *gallivm,
545                         LLVMValueRef func)
546 {
547    /* Verify the LLVM IR.  If invalid, dump and abort */
548 #ifdef DEBUG
549    if (LLVMVerifyFunction(func, LLVMPrintMessageAction)) {
550       lp_debug_dump_value(func);
551       assert(0);
552       return;
553    }
554 #endif
555 
556    if (gallivm_debug & GALLIVM_DEBUG_IR) {
557       /* Print the LLVM IR to stderr */
558       lp_debug_dump_value(func);
559       debug_printf("\n");
560    }
561 }
562 
563 
564 /**
565  * Compile a module.
566  * This does IR optimization on all functions in the module.
567  */
568 void
gallivm_compile_module(struct gallivm_state * gallivm)569 gallivm_compile_module(struct gallivm_state *gallivm)
570 {
571    LLVMValueRef func;
572    int64_t time_begin = 0;
573 
574    assert(!gallivm->compiled);
575 
576    if (gallivm->builder) {
577       LLVMDisposeBuilder(gallivm->builder);
578       gallivm->builder = NULL;
579    }
580 
581    if (gallivm->cache && gallivm->cache->data_size) {
582       goto skip_cached;
583    }
584 
585    /* Dump bitcode to a file */
586    if (gallivm_debug & GALLIVM_DEBUG_DUMP_BC) {
587       char filename[256];
588       assert(gallivm->module_name);
589       snprintf(filename, sizeof(filename), "ir_%s.bc", gallivm->module_name);
590       LLVMWriteBitcodeToFile(gallivm->module, filename);
591       debug_printf("%s written\n", filename);
592       debug_printf("Invoke as \"opt %s %s | llc -O%d %s%s\"\n",
593                    gallivm_debug & GALLIVM_PERF_NO_OPT ? "-mem2reg" :
594                    "-sroa -early-cse -simplifycfg -reassociate "
595                    "-mem2reg -constprop -instcombine -gvn",
596                    filename, gallivm_debug & GALLIVM_PERF_NO_OPT ? 0 : 2,
597                    "[-mcpu=<-mcpu option>] ",
598                    "[-mattr=<-mattr option(s)>]");
599    }
600 
601    if (gallivm_debug & GALLIVM_DEBUG_PERF)
602       time_begin = os_time_get();
603 
604 #if GALLIVM_HAVE_CORO
605    LLVMRunPassManager(gallivm->cgpassmgr, gallivm->module);
606 #endif
607    /* Run optimization passes */
608    LLVMInitializeFunctionPassManager(gallivm->passmgr);
609    func = LLVMGetFirstFunction(gallivm->module);
610    while (func) {
611       if (0) {
612          debug_printf("optimizing func %s...\n", LLVMGetValueName(func));
613       }
614 
615    /* Disable frame pointer omission on debug/profile builds */
616    /* XXX: And workaround http://llvm.org/PR21435 */
617 #if defined(DEBUG) || defined(PROFILE) || defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
618       LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim", "true");
619       LLVMAddTargetDependentFunctionAttr(func, "no-frame-pointer-elim-non-leaf", "true");
620 #endif
621 
622       LLVMRunFunctionPassManager(gallivm->passmgr, func);
623       func = LLVMGetNextFunction(func);
624    }
625    LLVMFinalizeFunctionPassManager(gallivm->passmgr);
626 
627    if (gallivm_debug & GALLIVM_DEBUG_PERF) {
628       int64_t time_end = os_time_get();
629       int time_msec = (int)((time_end - time_begin) / 1000);
630       assert(gallivm->module_name);
631       debug_printf("optimizing module %s took %d msec\n",
632                    gallivm->module_name, time_msec);
633    }
634 
635    /* Setting the module's DataLayout to an empty string will cause the
636     * ExecutionEngine to copy to the DataLayout string from its target machine
637     * to the module.  As of LLVM 3.8 the module and the execution engine are
638     * required to have the same DataLayout.
639     *
640     * We must make sure we do this after running the optimization passes,
641     * because those passes need a correct datalayout string.  For example, if
642     * those optimization passes see an empty datalayout, they will assume this
643     * is a little endian target and will do optimizations that break big endian
644     * machines.
645     *
646     * TODO: This is just a temporary work-around.  The correct solution is for
647     * gallivm_init_state() to create a TargetMachine and pull the DataLayout
648     * from there.  Currently, the TargetMachine used by llvmpipe is being
649     * implicitly created by the EngineBuilder in
650     * lp_build_create_jit_compiler_for_module()
651     */
652  skip_cached:
653    LLVMSetDataLayout(gallivm->module, "");
654    assert(!gallivm->engine);
655    if (!init_gallivm_engine(gallivm)) {
656       assert(0);
657    }
658    assert(gallivm->engine);
659 
660    ++gallivm->compiled;
661 
662    if (gallivm->debug_printf_hook)
663       LLVMAddGlobalMapping(gallivm->engine, gallivm->debug_printf_hook, debug_printf);
664 
665    if (gallivm_debug & GALLIVM_DEBUG_ASM) {
666       LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
667 
668       while (llvm_func) {
669          /*
670           * Need to filter out functions which don't have an implementation,
671           * such as the intrinsics. May not be sufficient in case of IPO?
672           * LLVMGetPointerToGlobal() will abort otherwise.
673           */
674          if (!LLVMIsDeclaration(llvm_func)) {
675             void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
676             lp_disassemble(llvm_func, func_code);
677          }
678          llvm_func = LLVMGetNextFunction(llvm_func);
679       }
680    }
681 
682 #if defined(PROFILE)
683    {
684       LLVMValueRef llvm_func = LLVMGetFirstFunction(gallivm->module);
685 
686       while (llvm_func) {
687          if (!LLVMIsDeclaration(llvm_func)) {
688             void *func_code = LLVMGetPointerToGlobal(gallivm->engine, llvm_func);
689             lp_profile(llvm_func, func_code);
690          }
691          llvm_func = LLVMGetNextFunction(llvm_func);
692       }
693    }
694 #endif
695 }
696 
697 
698 
699 func_pointer
gallivm_jit_function(struct gallivm_state * gallivm,LLVMValueRef func)700 gallivm_jit_function(struct gallivm_state *gallivm,
701                      LLVMValueRef func)
702 {
703    void *code;
704    func_pointer jit_func;
705    int64_t time_begin = 0;
706 
707    assert(gallivm->compiled);
708    assert(gallivm->engine);
709 
710    if (gallivm_debug & GALLIVM_DEBUG_PERF)
711       time_begin = os_time_get();
712 
713    code = LLVMGetPointerToGlobal(gallivm->engine, func);
714    assert(code);
715    jit_func = pointer_to_func(code);
716 
717    if (gallivm_debug & GALLIVM_DEBUG_PERF) {
718       int64_t time_end = os_time_get();
719       int time_msec = (int)(time_end - time_begin) / 1000;
720       debug_printf("   jitting func %s took %d msec\n",
721                    LLVMGetValueName(func), time_msec);
722    }
723 
724    return jit_func;
725 }
726 
gallivm_get_perf_flags(void)727 unsigned gallivm_get_perf_flags(void)
728 {
729    return gallivm_perf;
730 }
731