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 #ifndef __STDC_LIMIT_MACROS
36 #define __STDC_LIMIT_MACROS
39 #ifndef __STDC_CONSTANT_MACROS
40 #define __STDC_CONSTANT_MACROS
43 // Undef these vars just to silence warnings
44 #undef PACKAGE_BUGREPORT
47 #undef PACKAGE_TARNAME
48 #undef PACKAGE_VERSION
53 // Workaround http://llvm.org/PR23628
54 #if HAVE_LLVM >= 0x0307
55 # pragma push_macro("DEBUG")
59 #include <llvm-c/Core.h>
60 #include <llvm-c/ExecutionEngine.h>
61 #include <llvm/Target/TargetOptions.h>
62 #include <llvm/ExecutionEngine/ExecutionEngine.h>
63 #include <llvm/ADT/Triple.h>
64 #if HAVE_LLVM >= 0x0307
65 #include <llvm/Analysis/TargetLibraryInfo.h>
67 #include <llvm/Target/TargetLibraryInfo.h>
69 #if HAVE_LLVM < 0x0306
70 #include <llvm/ExecutionEngine/JITMemoryManager.h>
72 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
74 #include <llvm/Support/CommandLine.h>
75 #include <llvm/Support/Host.h>
76 #include <llvm/Support/PrettyStackTrace.h>
78 #include <llvm/Support/TargetSelect.h>
80 #include <llvm/IR/IRBuilder.h>
81 #include <llvm/IR/Module.h>
82 #include <llvm/Support/CBindingWrapping.h>
84 #include <llvm/Config/llvm-config.h>
85 #if LLVM_USE_INTEL_JITEVENTS
86 #include <llvm/ExecutionEngine/JITEventListener.h>
89 // Workaround http://llvm.org/PR23628
90 #if HAVE_LLVM >= 0x0307
91 # pragma pop_macro("DEBUG")
94 #include "c11/threads.h"
95 #include "os/os_thread.h"
96 #include "pipe/p_config.h"
97 #include "util/u_debug.h"
98 #include "util/u_cpu_detect.h"
100 #include "lp_bld_misc.h"
104 class LLVMEnsureMultithreaded
{
106 LLVMEnsureMultithreaded()
108 if (!LLVMIsMultithreaded()) {
109 LLVMStartMultithreaded();
114 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
118 static once_flag init_native_targets_once_flag
= ONCE_FLAG_INIT
;
120 static void init_native_targets()
122 // If we have a native target, initialize it to ensure it is linked in and
123 // usable by the JIT.
124 llvm::InitializeNativeTarget();
126 llvm::InitializeNativeTargetAsmPrinter();
128 llvm::InitializeNativeTargetDisassembler();
132 * The llvm target registry is not thread-safe, so drivers and state-trackers
133 * that want to initialize targets should use the gallivm_init_llvm_targets()
134 * function to safely initialize targets.
136 * LLVM targets should be initialized before the driver or state-tracker tries
137 * to access the registry.
140 gallivm_init_llvm_targets(void)
142 call_once(&init_native_targets_once_flag
, init_native_targets
);
146 lp_set_target_options(void)
148 #if HAVE_LLVM < 0x0304
150 * By default LLVM adds a signal handler to output a pretty stack trace.
151 * This signal handler is never removed, causing problems when unloading the
152 * shared object where the gallium driver resides.
154 llvm::DisablePrettyStackTrace
= true;
157 gallivm_init_llvm_targets();
161 LLVMTargetLibraryInfoRef
162 gallivm_create_target_library_info(const char *triple
)
164 return reinterpret_cast<LLVMTargetLibraryInfoRef
>(
165 #if HAVE_LLVM < 0x0307
166 new llvm::TargetLibraryInfo(
168 new llvm::TargetLibraryInfoImpl(
170 llvm::Triple(triple
)));
175 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info
)
177 delete reinterpret_cast<
178 #if HAVE_LLVM < 0x0307
179 llvm::TargetLibraryInfo
181 llvm::TargetLibraryInfoImpl
187 #if HAVE_LLVM < 0x0304
191 LLVMSetAlignmentBackport(LLVMValueRef V
,
194 switch (LLVMGetInstructionOpcode(V
)) {
196 llvm::unwrap
<llvm::LoadInst
>(V
)->setAlignment(Bytes
);
199 llvm::unwrap
<llvm::StoreInst
>(V
)->setAlignment(Bytes
);
210 #if HAVE_LLVM < 0x0306
211 typedef llvm::JITMemoryManager BaseMemoryManager
;
213 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
218 * Delegating is tedious but the default manager class is hidden in an
219 * anonymous namespace in LLVM, so we cannot just derive from it to change
222 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
225 virtual BaseMemoryManager
*mgr() const = 0;
228 #if HAVE_LLVM < 0x0306
230 * From JITMemoryManager
232 virtual void setMemoryWritable() {
233 mgr()->setMemoryWritable();
235 virtual void setMemoryExecutable() {
236 mgr()->setMemoryExecutable();
238 virtual void setPoisonMemory(bool poison
) {
239 mgr()->setPoisonMemory(poison
);
241 virtual void AllocateGOT() {
242 mgr()->AllocateGOT();
244 * isManagingGOT() is not virtual in base class so we can't delegate.
245 * Instead we mirror the value of HasGOT in our instance.
247 HasGOT
= mgr()->isManagingGOT();
249 virtual uint8_t *getGOTBase() const {
250 return mgr()->getGOTBase();
252 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
253 uintptr_t &ActualSize
) {
254 return mgr()->startFunctionBody(F
, ActualSize
);
256 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
258 unsigned Alignment
) {
259 return mgr()->allocateStub(F
, StubSize
, Alignment
);
261 virtual void endFunctionBody(const llvm::Function
*F
,
262 uint8_t *FunctionStart
,
263 uint8_t *FunctionEnd
) {
264 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
266 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
267 return mgr()->allocateSpace(Size
, Alignment
);
269 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
270 return mgr()->allocateGlobal(Size
, Alignment
);
272 virtual void deallocateFunctionBody(void *Body
) {
273 mgr()->deallocateFunctionBody(Body
);
275 #if HAVE_LLVM < 0x0304
276 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
277 uintptr_t &ActualSize
) {
278 return mgr()->startExceptionTable(F
, ActualSize
);
280 virtual void endExceptionTable(const llvm::Function
*F
,
283 uint8_t *FrameRegister
) {
284 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
287 virtual void deallocateExceptionTable(void *ET
) {
288 mgr()->deallocateExceptionTable(ET
);
291 virtual bool CheckInvariants(std::string
&s
) {
292 return mgr()->CheckInvariants(s
);
294 virtual size_t GetDefaultCodeSlabSize() {
295 return mgr()->GetDefaultCodeSlabSize();
297 virtual size_t GetDefaultDataSlabSize() {
298 return mgr()->GetDefaultDataSlabSize();
300 virtual size_t GetDefaultStubSlabSize() {
301 return mgr()->GetDefaultStubSlabSize();
303 virtual unsigned GetNumCodeSlabs() {
304 return mgr()->GetNumCodeSlabs();
306 virtual unsigned GetNumDataSlabs() {
307 return mgr()->GetNumDataSlabs();
309 virtual unsigned GetNumStubSlabs() {
310 return mgr()->GetNumStubSlabs();
315 * From RTDyldMemoryManager
317 #if HAVE_LLVM >= 0x0304
318 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
321 llvm::StringRef SectionName
) {
322 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
326 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
328 unsigned SectionID
) {
329 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
332 virtual uint8_t *allocateDataSection(uintptr_t Size
,
335 #if HAVE_LLVM >= 0x0304
336 llvm::StringRef SectionName
,
339 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
340 #if HAVE_LLVM >= 0x0304
345 #if HAVE_LLVM >= 0x0304
346 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
347 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
349 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
350 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
353 virtual void registerEHFrames(llvm::StringRef SectionData
) {
354 mgr()->registerEHFrames(SectionData
);
357 virtual void *getPointerToNamedFunction(const std::string
&Name
,
358 bool AbortOnFailure
=true) {
359 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
361 #if HAVE_LLVM <= 0x0303
362 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
363 return mgr()->applyPermissions(ErrMsg
);
366 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
367 return mgr()->finalizeMemory(ErrMsg
);
374 * Delegate memory management to one shared manager for more efficient use
375 * of memory than creating a separate pool for each LLVM engine.
376 * Keep generated code until freeGeneratedCode() is called, instead of when
377 * memory manager is destroyed, which happens during engine destruction.
378 * This allows additional memory savings as we don't have to keep the engine
379 * around in order to use the code.
380 * All methods are delegated to the shared manager except destruction and
381 * deallocating code. For the latter we just remember what needs to be
382 * deallocated later. The shared manager is deleted once it is empty.
384 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
386 BaseMemoryManager
*TheMM
;
388 struct GeneratedCode
{
389 typedef std::vector
<void *> Vec
;
390 Vec FunctionBody
, ExceptionTable
;
391 BaseMemoryManager
*TheMM
;
393 GeneratedCode(BaseMemoryManager
*MM
) {
399 * Deallocate things as previously requested and
400 * free shared manager when no longer used.
402 #if HAVE_LLVM < 0x0306
406 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
407 TheMM
->deallocateFunctionBody(*i
);
408 #if HAVE_LLVM < 0x0304
409 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
410 TheMM
->deallocateExceptionTable(*i
);
411 #endif /* HAVE_LLVM < 0x0304 */
412 #endif /* HAVE_LLVM < 0x0306 */
418 BaseMemoryManager
*mgr() const {
424 ShaderMemoryManager(BaseMemoryManager
* MM
) {
426 code
= new GeneratedCode(MM
);
429 virtual ~ShaderMemoryManager() {
431 * 'code' is purposely not deleted. It is the user's responsibility
432 * to call getGeneratedCode() and freeGeneratedCode().
436 struct lp_generated_code
*getGeneratedCode() {
437 return (struct lp_generated_code
*) code
;
440 static void freeGeneratedCode(struct lp_generated_code
*code
) {
441 delete (GeneratedCode
*) code
;
444 #if HAVE_LLVM < 0x0304
445 virtual void deallocateExceptionTable(void *ET
) {
446 // remember for later deallocation
447 code
->ExceptionTable
.push_back(ET
);
451 virtual void deallocateFunctionBody(void *Body
) {
452 // remember for later deallocation
453 code
->FunctionBody
.push_back(Body
);
459 * Same as LLVMCreateJITCompilerForModule, but:
460 * - allows using MCJIT and enabling AVX feature where available.
461 * - set target options
464 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
465 * - llvm/tools/lli/lli.cpp
466 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
470 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
471 lp_generated_code
**OutCode
,
473 LLVMMCJITMemoryManagerRef CMM
,
478 using namespace llvm
;
481 #if HAVE_LLVM >= 0x0306
482 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
484 EngineBuilder
builder(unwrap(M
));
488 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
489 * friends for configuring code generation options, like stack alignment.
491 TargetOptions options
;
492 #if defined(PIPE_ARCH_X86)
493 options
.StackAlignmentOverride
= 4;
494 #if HAVE_LLVM < 0x0304
495 options
.RealignStack
= true;
499 #if defined(DEBUG) && HAVE_LLVM < 0x0307
500 options
.JITEmitDebugInfo
= true;
503 /* XXX: Workaround http://llvm.org/PR21435 */
504 #if defined(DEBUG) || defined(PROFILE) || \
505 (HAVE_LLVM >= 0x0303 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)))
506 #if HAVE_LLVM < 0x0304
507 options
.NoFramePointerElimNonLeaf
= true;
509 #if HAVE_LLVM < 0x0307
510 options
.NoFramePointerElim
= true;
514 builder
.setEngineKind(EngineKind::JIT
)
516 .setTargetOptions(options
)
517 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
520 #if HAVE_LLVM < 0x0306
521 builder
.setUseMCJIT(true);
525 * MCJIT works on Windows, but currently only through ELF object format.
527 * XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has
528 * different strings for MinGW/MSVC, so better play it safe and be
532 LLVMSetTarget(M
, "x86_64-pc-win32-elf");
534 LLVMSetTarget(M
, "i686-pc-win32-elf");
539 llvm::SmallVector
<std::string
, 16> MAttrs
;
541 #if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
543 * We need to unset attributes because sometimes LLVM mistakenly assumes
544 * certain features are present given the processor name.
546 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
547 * http://llvm.org/PR25021
548 * http://llvm.org/PR19429
549 * http://llvm.org/PR16721
551 MAttrs
.push_back(util_cpu_caps
.has_sse
? "+sse" : "-sse" );
552 MAttrs
.push_back(util_cpu_caps
.has_sse2
? "+sse2" : "-sse2" );
553 MAttrs
.push_back(util_cpu_caps
.has_sse3
? "+sse3" : "-sse3" );
554 MAttrs
.push_back(util_cpu_caps
.has_ssse3
? "+ssse3" : "-ssse3" );
555 #if HAVE_LLVM >= 0x0304
556 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse4.1" : "-sse4.1");
558 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse41" : "-sse41" );
560 #if HAVE_LLVM >= 0x0304
561 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse4.2" : "-sse4.2");
563 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse42" : "-sse42" );
566 * AVX feature is not automatically detected from CPUID by the X86 target
567 * yet, because the old (yet default) JIT engine is not capable of
568 * emitting the opcodes. On newer llvm versions it is and at least some
569 * versions (tested with 3.3) will emit avx opcodes without this anyway.
571 MAttrs
.push_back(util_cpu_caps
.has_avx
? "+avx" : "-avx");
572 MAttrs
.push_back(util_cpu_caps
.has_f16c
? "+f16c" : "-f16c");
573 if (HAVE_LLVM
>= 0x0304 || useMCJIT
) {
574 MAttrs
.push_back(util_cpu_caps
.has_fma
? "+fma" : "-fma");
577 * The old JIT in LLVM 3.3 has a bug encoding llvm.fmuladd.f32 and
578 * llvm.fmuladd.v2f32 intrinsics when FMA is available.
580 MAttrs
.push_back("-fma");
582 MAttrs
.push_back(util_cpu_caps
.has_avx2
? "+avx2" : "-avx2");
583 /* disable avx512 and all subvariants */
584 #if HAVE_LLVM >= 0x0304
585 MAttrs
.push_back("-avx512cd");
586 MAttrs
.push_back("-avx512er");
587 MAttrs
.push_back("-avx512f");
588 MAttrs
.push_back("-avx512pf");
590 #if HAVE_LLVM >= 0x0305
591 MAttrs
.push_back("-avx512bw");
592 MAttrs
.push_back("-avx512dq");
593 MAttrs
.push_back("-avx512vl");
597 #if defined(PIPE_ARCH_PPC)
598 MAttrs
.push_back(util_cpu_caps
.has_altivec
? "+altivec" : "-altivec");
599 #if HAVE_LLVM >= 0x0304
601 * Make sure VSX instructions are disabled
602 * See LLVM bug https://llvm.org/bugs/show_bug.cgi?id=25503#c7
604 if (util_cpu_caps
.has_altivec
) {
605 MAttrs
.push_back("-vsx");
610 builder
.setMAttrs(MAttrs
);
612 #if HAVE_LLVM >= 0x0305
613 StringRef MCPU
= llvm::sys::getHostCPUName();
615 * The cpu bits are no longer set automatically, so need to set mcpu manually.
616 * Note that the MAttrs set above will be sort of ignored (since we should
617 * not set any which would not be set by specifying the cpu anyway).
618 * It ought to be safe though since getHostCPUName() should include bits
619 * not only from the cpu but environment as well (for instance if it's safe
620 * to use avx instructions which need OS support). According to
621 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
622 * right it may be necessary to specify older cpu (or disable mattrs) though
623 * when not using MCJIT so no instructions are generated which the old JIT
624 * can't handle. Not entirely sure if we really need to do anything yet.
626 builder
.setMCPU(MCPU
);
629 ShaderMemoryManager
*MM
= NULL
;
631 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
632 MM
= new ShaderMemoryManager(JMM
);
633 *OutCode
= MM
->getGeneratedCode();
635 #if HAVE_LLVM >= 0x0306
636 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
637 MM
= NULL
; // ownership taken by std::unique_ptr
638 #elif HAVE_LLVM > 0x0303
639 builder
.setMCJITMemoryManager(MM
);
641 builder
.setJITMemoryManager(MM
);
644 #if HAVE_LLVM < 0x0306
645 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
646 MM
= new ShaderMemoryManager(JMM
);
647 *OutCode
= MM
->getGeneratedCode();
649 builder
.setJITMemoryManager(MM
);
655 ExecutionEngine
*JIT
;
657 JIT
= builder
.create();
658 #if LLVM_USE_INTEL_JITEVENTS
659 JITEventListener
*JEL
= JITEventListener::createIntelJITEventListener();
660 JIT
->RegisterJITEventListener(JEL
);
666 lp_free_generated_code(*OutCode
);
669 *OutError
= strdup(Error
.c_str());
676 lp_free_generated_code(struct lp_generated_code
*code
)
678 ShaderMemoryManager::freeGeneratedCode(code
);
682 LLVMMCJITMemoryManagerRef
683 lp_get_default_memory_manager()
685 BaseMemoryManager
*mm
;
686 #if HAVE_LLVM < 0x0306
687 mm
= llvm::JITMemoryManager::CreateDefaultMemManager();
689 mm
= new llvm::SectionMemoryManager();
691 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
696 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
698 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);