1 /**************************************************************************
3 * Copyright 2010 VMware, Inc.
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:
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
17 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 * USE OR OTHER DEALINGS IN THE SOFTWARE.
22 * The above copyright notice and this permission notice (including the
23 * next paragraph) shall be included in all copies or substantial portions
26 **************************************************************************/
30 * The purpose of this module is to expose LLVM functionality not available
31 * through the C++ bindings.
35 // Undef these vars just to silence warnings
36 #undef PACKAGE_BUGREPORT
39 #undef PACKAGE_TARNAME
40 #undef PACKAGE_VERSION
45 #include <llvm/Config/llvm-config.h>
47 // Workaround http://llvm.org/PR23628
48 #pragma push_macro("DEBUG")
51 #include <llvm/Config/llvm-config.h>
52 #include <llvm-c/Core.h>
53 #include <llvm-c/Support.h>
54 #include <llvm-c/ExecutionEngine.h>
55 #include <llvm/Target/TargetOptions.h>
56 #include <llvm/ExecutionEngine/ExecutionEngine.h>
57 #include <llvm/ADT/Triple.h>
58 #include <llvm/Analysis/TargetLibraryInfo.h>
59 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
60 #include <llvm/Support/CommandLine.h>
61 #include <llvm/Support/Host.h>
62 #include <llvm/Support/PrettyStackTrace.h>
64 #include <llvm/Support/TargetSelect.h>
66 #include <llvm/IR/CallSite.h>
67 #include <llvm/IR/IRBuilder.h>
68 #include <llvm/IR/Module.h>
69 #include <llvm/Support/CBindingWrapping.h>
71 #include <llvm/Config/llvm-config.h>
72 #if LLVM_USE_INTEL_JITEVENTS
73 #include <llvm/ExecutionEngine/JITEventListener.h>
76 // Workaround http://llvm.org/PR23628
77 #pragma pop_macro("DEBUG")
79 #include "c11/threads.h"
80 #include "os/os_thread.h"
81 #include "pipe/p_config.h"
82 #include "util/u_debug.h"
83 #include "util/u_cpu_detect.h"
85 #include "lp_bld_misc.h"
86 #include "lp_bld_debug.h"
90 class LLVMEnsureMultithreaded
{
92 LLVMEnsureMultithreaded()
94 if (!LLVMIsMultithreaded()) {
95 LLVMStartMultithreaded();
100 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
104 static once_flag init_native_targets_once_flag
= ONCE_FLAG_INIT
;
106 static void init_native_targets()
108 // If we have a native target, initialize it to ensure it is linked in and
109 // usable by the JIT.
110 llvm::InitializeNativeTarget();
112 llvm::InitializeNativeTargetAsmPrinter();
114 llvm::InitializeNativeTargetDisassembler();
117 char *env_llc_options
= getenv("GALLIVM_LLC_OPTIONS");
118 if (env_llc_options
) {
120 char *options
[64] = {(char *) "llc"}; // Warning without cast
122 for (n
= 0, option
= strtok(env_llc_options
, " "); option
; n
++, option
= strtok(NULL
, " ")) {
123 options
[n
+ 1] = option
;
125 if (gallivm_debug
& (GALLIVM_DEBUG_IR
| GALLIVM_DEBUG_ASM
| GALLIVM_DEBUG_DUMP_BC
)) {
126 debug_printf("llc additional options (%d):\n", n
);
127 for (int i
= 1; i
<= n
; i
++)
128 debug_printf("\t%s\n", options
[i
]);
131 LLVMParseCommandLineOptions(n
+ 1, options
, NULL
);
138 lp_set_target_options(void)
140 /* The llvm target registry is not thread-safe, so drivers and state-trackers
141 * that want to initialize targets should use the lp_set_target_options()
142 * function to safely initialize targets.
144 * LLVM targets should be initialized before the driver or state-tracker tries
145 * to access the registry.
147 call_once(&init_native_targets_once_flag
, init_native_targets
);
151 LLVMTargetLibraryInfoRef
152 gallivm_create_target_library_info(const char *triple
)
154 return reinterpret_cast<LLVMTargetLibraryInfoRef
>(
155 new llvm::TargetLibraryInfoImpl(
156 llvm::Triple(triple
)));
161 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info
)
163 delete reinterpret_cast<
164 llvm::TargetLibraryInfoImpl
169 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
173 * Delegating is tedious but the default manager class is hidden in an
174 * anonymous namespace in LLVM, so we cannot just derive from it to change
177 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
180 virtual BaseMemoryManager
*mgr() const = 0;
184 * From RTDyldMemoryManager
186 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
189 llvm::StringRef SectionName
) {
190 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
193 virtual uint8_t *allocateDataSection(uintptr_t Size
,
196 llvm::StringRef SectionName
,
198 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
202 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
203 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
205 #if LLVM_VERSION_MAJOR >= 5
206 virtual void deregisterEHFrames() {
207 mgr()->deregisterEHFrames();
210 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
211 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
214 virtual void *getPointerToNamedFunction(const std::string
&Name
,
215 bool AbortOnFailure
=true) {
216 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
218 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
219 return mgr()->finalizeMemory(ErrMsg
);
225 * Delegate memory management to one shared manager for more efficient use
226 * of memory than creating a separate pool for each LLVM engine.
227 * Keep generated code until freeGeneratedCode() is called, instead of when
228 * memory manager is destroyed, which happens during engine destruction.
229 * This allows additional memory savings as we don't have to keep the engine
230 * around in order to use the code.
231 * All methods are delegated to the shared manager except destruction and
232 * deallocating code. For the latter we just remember what needs to be
233 * deallocated later. The shared manager is deleted once it is empty.
235 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
237 BaseMemoryManager
*TheMM
;
239 struct GeneratedCode
{
240 typedef std::vector
<void *> Vec
;
241 Vec FunctionBody
, ExceptionTable
;
242 BaseMemoryManager
*TheMM
;
244 GeneratedCode(BaseMemoryManager
*MM
) {
254 BaseMemoryManager
*mgr() const {
260 ShaderMemoryManager(BaseMemoryManager
* MM
) {
262 code
= new GeneratedCode(MM
);
265 virtual ~ShaderMemoryManager() {
267 * 'code' is purposely not deleted. It is the user's responsibility
268 * to call getGeneratedCode() and freeGeneratedCode().
272 struct lp_generated_code
*getGeneratedCode() {
273 return (struct lp_generated_code
*) code
;
276 static void freeGeneratedCode(struct lp_generated_code
*code
) {
277 delete (GeneratedCode
*) code
;
280 virtual void deallocateFunctionBody(void *Body
) {
281 // remember for later deallocation
282 code
->FunctionBody
.push_back(Body
);
288 * Same as LLVMCreateJITCompilerForModule, but:
289 * - allows using MCJIT and enabling AVX feature where available.
290 * - set target options
293 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
294 * - llvm/tools/lli/lli.cpp
295 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
299 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
300 lp_generated_code
**OutCode
,
302 LLVMMCJITMemoryManagerRef CMM
,
306 using namespace llvm
;
309 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
312 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
313 * friends for configuring code generation options, like stack alignment.
315 TargetOptions options
;
316 #if defined(PIPE_ARCH_X86)
317 options
.StackAlignmentOverride
= 4;
320 builder
.setEngineKind(EngineKind::JIT
)
322 .setTargetOptions(options
)
323 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
327 * MCJIT works on Windows, but currently only through ELF object format.
329 * XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has
330 * different strings for MinGW/MSVC, so better play it safe and be
334 LLVMSetTarget(M
, "x86_64-pc-win32-elf");
336 LLVMSetTarget(M
, "i686-pc-win32-elf");
340 llvm::SmallVector
<std::string
, 16> MAttrs
;
342 #if LLVM_VERSION_MAJOR >= 4 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64) || defined(PIPE_ARCH_ARM))
343 /* llvm-3.3+ implements sys::getHostCPUFeatures for Arm
344 * and llvm-3.7+ for x86, which allows us to enable/disable
345 * code generation based on the results of cpuid on these
348 llvm::StringMap
<bool> features
;
349 llvm::sys::getHostCPUFeatures(features
);
351 for (StringMapIterator
<bool> f
= features
.begin();
354 MAttrs
.push_back(((*f
).second
? "+" : "-") + (*f
).first().str());
356 #elif defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
358 * We need to unset attributes because sometimes LLVM mistakenly assumes
359 * certain features are present given the processor name.
361 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
362 * http://llvm.org/PR25021
363 * http://llvm.org/PR19429
364 * http://llvm.org/PR16721
366 MAttrs
.push_back(util_cpu_caps
.has_sse
? "+sse" : "-sse" );
367 MAttrs
.push_back(util_cpu_caps
.has_sse2
? "+sse2" : "-sse2" );
368 MAttrs
.push_back(util_cpu_caps
.has_sse3
? "+sse3" : "-sse3" );
369 MAttrs
.push_back(util_cpu_caps
.has_ssse3
? "+ssse3" : "-ssse3" );
370 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse4.1" : "-sse4.1");
371 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse4.2" : "-sse4.2");
373 * AVX feature is not automatically detected from CPUID by the X86 target
374 * yet, because the old (yet default) JIT engine is not capable of
375 * emitting the opcodes. On newer llvm versions it is and at least some
376 * versions (tested with 3.3) will emit avx opcodes without this anyway.
378 MAttrs
.push_back(util_cpu_caps
.has_avx
? "+avx" : "-avx");
379 MAttrs
.push_back(util_cpu_caps
.has_f16c
? "+f16c" : "-f16c");
380 MAttrs
.push_back(util_cpu_caps
.has_fma
? "+fma" : "-fma");
381 MAttrs
.push_back(util_cpu_caps
.has_avx2
? "+avx2" : "-avx2");
382 /* disable avx512 and all subvariants */
383 MAttrs
.push_back("-avx512cd");
384 MAttrs
.push_back("-avx512er");
385 MAttrs
.push_back("-avx512f");
386 MAttrs
.push_back("-avx512pf");
387 MAttrs
.push_back("-avx512bw");
388 MAttrs
.push_back("-avx512dq");
389 MAttrs
.push_back("-avx512vl");
391 #if defined(PIPE_ARCH_ARM)
392 if (!util_cpu_caps
.has_neon
) {
393 MAttrs
.push_back("-neon");
394 MAttrs
.push_back("-crypto");
395 MAttrs
.push_back("-vfp2");
399 #if defined(PIPE_ARCH_PPC)
400 MAttrs
.push_back(util_cpu_caps
.has_altivec
? "+altivec" : "-altivec");
401 #if (LLVM_VERSION_MAJOR < 4)
403 * Make sure VSX instructions are disabled
405 * https://llvm.org/bugs/show_bug.cgi?id=25503#c7 (fixed in 3.8.1)
406 * https://llvm.org/bugs/show_bug.cgi?id=26775 (fixed in 3.8.1)
407 * https://llvm.org/bugs/show_bug.cgi?id=33531 (fixed in 4.0)
408 * https://llvm.org/bugs/show_bug.cgi?id=34647 (llc performance on certain unusual shader IR; intro'd in 4.0, pending as of 5.0)
410 if (util_cpu_caps
.has_altivec
) {
411 MAttrs
.push_back("-vsx");
416 builder
.setMAttrs(MAttrs
);
418 if (gallivm_debug
& (GALLIVM_DEBUG_IR
| GALLIVM_DEBUG_ASM
| GALLIVM_DEBUG_DUMP_BC
)) {
419 int n
= MAttrs
.size();
421 debug_printf("llc -mattr option(s): ");
422 for (int i
= 0; i
< n
; i
++)
423 debug_printf("%s%s", MAttrs
[i
].c_str(), (i
< n
- 1) ? "," : "");
428 StringRef MCPU
= llvm::sys::getHostCPUName();
430 * The cpu bits are no longer set automatically, so need to set mcpu manually.
431 * Note that the MAttrs set above will be sort of ignored (since we should
432 * not set any which would not be set by specifying the cpu anyway).
433 * It ought to be safe though since getHostCPUName() should include bits
434 * not only from the cpu but environment as well (for instance if it's safe
435 * to use avx instructions which need OS support). According to
436 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
437 * right it may be necessary to specify older cpu (or disable mattrs) though
438 * when not using MCJIT so no instructions are generated which the old JIT
439 * can't handle. Not entirely sure if we really need to do anything yet.
441 #if defined(PIPE_ARCH_LITTLE_ENDIAN) && defined(PIPE_ARCH_PPC_64)
443 * Versions of LLVM prior to 4.0 lacked a table entry for "POWER8NVL",
444 * resulting in (big-endian) "generic" being returned on
445 * little-endian Power8NVL systems. The result was that code that
446 * attempted to load the least significant 32 bits of a 64-bit quantity
447 * from memory loaded the wrong half. This resulted in failures in some
449 * .../arb_gpu_shader_fp64/execution/conversion/frag-conversion-explicit-double-uint
451 if (MCPU
== "generic")
454 builder
.setMCPU(MCPU
);
455 if (gallivm_debug
& (GALLIVM_DEBUG_IR
| GALLIVM_DEBUG_ASM
| GALLIVM_DEBUG_DUMP_BC
)) {
456 debug_printf("llc -mcpu option: %s\n", MCPU
.str().c_str());
459 ShaderMemoryManager
*MM
= NULL
;
460 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
461 MM
= new ShaderMemoryManager(JMM
);
462 *OutCode
= MM
->getGeneratedCode();
464 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
465 MM
= NULL
; // ownership taken by std::unique_ptr
467 ExecutionEngine
*JIT
;
469 JIT
= builder
.create();
470 #if LLVM_USE_INTEL_JITEVENTS
471 JITEventListener
*JEL
= JITEventListener::createIntelJITEventListener();
472 JIT
->RegisterJITEventListener(JEL
);
478 lp_free_generated_code(*OutCode
);
481 *OutError
= strdup(Error
.c_str());
488 lp_free_generated_code(struct lp_generated_code
*code
)
490 ShaderMemoryManager::freeGeneratedCode(code
);
494 LLVMMCJITMemoryManagerRef
495 lp_get_default_memory_manager()
497 BaseMemoryManager
*mm
;
498 mm
= new llvm::SectionMemoryManager();
499 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
504 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
506 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);
509 extern "C" LLVMValueRef
510 lp_get_called_value(LLVMValueRef call
)
512 return LLVMGetCalledValue(call
);
516 lp_is_function(LLVMValueRef v
)
518 return LLVMGetValueKind(v
) == LLVMFunctionValueKind
;