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 // Workaround http://llvm.org/PR23628
85 #if HAVE_LLVM >= 0x0307
86 # pragma pop_macro("DEBUG")
89 #include "c11/threads.h"
90 #include "os/os_thread.h"
91 #include "pipe/p_config.h"
92 #include "util/u_debug.h"
93 #include "util/u_cpu_detect.h"
95 #include "lp_bld_misc.h"
99 class LLVMEnsureMultithreaded
{
101 LLVMEnsureMultithreaded()
103 if (!LLVMIsMultithreaded()) {
104 LLVMStartMultithreaded();
109 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
113 static once_flag init_native_targets_once_flag
;
115 static void init_native_targets()
117 // If we have a native target, initialize it to ensure it is linked in and
118 // usable by the JIT.
119 llvm::InitializeNativeTarget();
121 llvm::InitializeNativeTargetAsmPrinter();
123 llvm::InitializeNativeTargetDisassembler();
127 * The llvm target registry is not thread-safe, so drivers and state-trackers
128 * that want to initialize targets should use the gallivm_init_llvm_targets()
129 * function to safely initialize targets.
131 * LLVM targets should be initialized before the driver or state-tracker tries
132 * to access the registry.
135 gallivm_init_llvm_targets(void)
137 call_once(&init_native_targets_once_flag
, init_native_targets
);
141 lp_set_target_options(void)
143 #if HAVE_LLVM < 0x0304
145 * By default LLVM adds a signal handler to output a pretty stack trace.
146 * This signal handler is never removed, causing problems when unloading the
147 * shared object where the gallium driver resides.
149 llvm::DisablePrettyStackTrace
= true;
152 gallivm_init_llvm_targets();
156 LLVMTargetLibraryInfoRef
157 gallivm_create_target_library_info(const char *triple
)
159 return reinterpret_cast<LLVMTargetLibraryInfoRef
>(
160 #if HAVE_LLVM < 0x0307
161 new llvm::TargetLibraryInfo(
163 new llvm::TargetLibraryInfoImpl(
165 llvm::Triple(triple
)));
170 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info
)
172 delete reinterpret_cast<
173 #if HAVE_LLVM < 0x0307
174 llvm::TargetLibraryInfo
176 llvm::TargetLibraryInfoImpl
182 #if HAVE_LLVM < 0x0304
186 LLVMSetAlignmentBackport(LLVMValueRef V
,
189 switch (LLVMGetInstructionOpcode(V
)) {
191 llvm::unwrap
<llvm::LoadInst
>(V
)->setAlignment(Bytes
);
194 llvm::unwrap
<llvm::StoreInst
>(V
)->setAlignment(Bytes
);
205 #if HAVE_LLVM < 0x0306
206 typedef llvm::JITMemoryManager BaseMemoryManager
;
208 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
213 * Delegating is tedious but the default manager class is hidden in an
214 * anonymous namespace in LLVM, so we cannot just derive from it to change
217 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
220 virtual BaseMemoryManager
*mgr() const = 0;
223 #if HAVE_LLVM < 0x0306
225 * From JITMemoryManager
227 virtual void setMemoryWritable() {
228 mgr()->setMemoryWritable();
230 virtual void setMemoryExecutable() {
231 mgr()->setMemoryExecutable();
233 virtual void setPoisonMemory(bool poison
) {
234 mgr()->setPoisonMemory(poison
);
236 virtual void AllocateGOT() {
237 mgr()->AllocateGOT();
239 * isManagingGOT() is not virtual in base class so we can't delegate.
240 * Instead we mirror the value of HasGOT in our instance.
242 HasGOT
= mgr()->isManagingGOT();
244 virtual uint8_t *getGOTBase() const {
245 return mgr()->getGOTBase();
247 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
248 uintptr_t &ActualSize
) {
249 return mgr()->startFunctionBody(F
, ActualSize
);
251 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
253 unsigned Alignment
) {
254 return mgr()->allocateStub(F
, StubSize
, Alignment
);
256 virtual void endFunctionBody(const llvm::Function
*F
,
257 uint8_t *FunctionStart
,
258 uint8_t *FunctionEnd
) {
259 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
261 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
262 return mgr()->allocateSpace(Size
, Alignment
);
264 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
265 return mgr()->allocateGlobal(Size
, Alignment
);
267 virtual void deallocateFunctionBody(void *Body
) {
268 mgr()->deallocateFunctionBody(Body
);
270 #if HAVE_LLVM < 0x0304
271 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
272 uintptr_t &ActualSize
) {
273 return mgr()->startExceptionTable(F
, ActualSize
);
275 virtual void endExceptionTable(const llvm::Function
*F
,
278 uint8_t *FrameRegister
) {
279 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
282 virtual void deallocateExceptionTable(void *ET
) {
283 mgr()->deallocateExceptionTable(ET
);
286 virtual bool CheckInvariants(std::string
&s
) {
287 return mgr()->CheckInvariants(s
);
289 virtual size_t GetDefaultCodeSlabSize() {
290 return mgr()->GetDefaultCodeSlabSize();
292 virtual size_t GetDefaultDataSlabSize() {
293 return mgr()->GetDefaultDataSlabSize();
295 virtual size_t GetDefaultStubSlabSize() {
296 return mgr()->GetDefaultStubSlabSize();
298 virtual unsigned GetNumCodeSlabs() {
299 return mgr()->GetNumCodeSlabs();
301 virtual unsigned GetNumDataSlabs() {
302 return mgr()->GetNumDataSlabs();
304 virtual unsigned GetNumStubSlabs() {
305 return mgr()->GetNumStubSlabs();
310 * From RTDyldMemoryManager
312 #if HAVE_LLVM >= 0x0304
313 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
316 llvm::StringRef SectionName
) {
317 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
321 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
323 unsigned SectionID
) {
324 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
327 virtual uint8_t *allocateDataSection(uintptr_t Size
,
330 #if HAVE_LLVM >= 0x0304
331 llvm::StringRef SectionName
,
334 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
335 #if HAVE_LLVM >= 0x0304
340 #if HAVE_LLVM >= 0x0304
341 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
342 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
344 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
345 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
348 virtual void registerEHFrames(llvm::StringRef SectionData
) {
349 mgr()->registerEHFrames(SectionData
);
352 virtual void *getPointerToNamedFunction(const std::string
&Name
,
353 bool AbortOnFailure
=true) {
354 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
356 #if HAVE_LLVM <= 0x0303
357 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
358 return mgr()->applyPermissions(ErrMsg
);
361 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
362 return mgr()->finalizeMemory(ErrMsg
);
369 * Delegate memory management to one shared manager for more efficient use
370 * of memory than creating a separate pool for each LLVM engine.
371 * Keep generated code until freeGeneratedCode() is called, instead of when
372 * memory manager is destroyed, which happens during engine destruction.
373 * This allows additional memory savings as we don't have to keep the engine
374 * around in order to use the code.
375 * All methods are delegated to the shared manager except destruction and
376 * deallocating code. For the latter we just remember what needs to be
377 * deallocated later. The shared manager is deleted once it is empty.
379 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
381 BaseMemoryManager
*TheMM
;
383 struct GeneratedCode
{
384 typedef std::vector
<void *> Vec
;
385 Vec FunctionBody
, ExceptionTable
;
386 BaseMemoryManager
*TheMM
;
388 GeneratedCode(BaseMemoryManager
*MM
) {
394 * Deallocate things as previously requested and
395 * free shared manager when no longer used.
397 #if HAVE_LLVM < 0x0306
401 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
402 TheMM
->deallocateFunctionBody(*i
);
403 #if HAVE_LLVM < 0x0304
404 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
405 TheMM
->deallocateExceptionTable(*i
);
406 #endif /* HAVE_LLVM < 0x0304 */
407 #endif /* HAVE_LLVM < 0x0306 */
413 BaseMemoryManager
*mgr() const {
419 ShaderMemoryManager(BaseMemoryManager
* MM
) {
421 code
= new GeneratedCode(MM
);
424 virtual ~ShaderMemoryManager() {
426 * 'code' is purposely not deleted. It is the user's responsibility
427 * to call getGeneratedCode() and freeGeneratedCode().
431 struct lp_generated_code
*getGeneratedCode() {
432 return (struct lp_generated_code
*) code
;
435 static void freeGeneratedCode(struct lp_generated_code
*code
) {
436 delete (GeneratedCode
*) code
;
439 #if HAVE_LLVM < 0x0304
440 virtual void deallocateExceptionTable(void *ET
) {
441 // remember for later deallocation
442 code
->ExceptionTable
.push_back(ET
);
446 virtual void deallocateFunctionBody(void *Body
) {
447 // remember for later deallocation
448 code
->FunctionBody
.push_back(Body
);
454 * Same as LLVMCreateJITCompilerForModule, but:
455 * - allows using MCJIT and enabling AVX feature where available.
456 * - set target options
459 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
460 * - llvm/tools/lli/lli.cpp
461 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
465 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
466 lp_generated_code
**OutCode
,
468 LLVMMCJITMemoryManagerRef CMM
,
473 using namespace llvm
;
476 #if HAVE_LLVM >= 0x0306
477 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
479 EngineBuilder
builder(unwrap(M
));
483 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
484 * friends for configuring code generation options, like stack alignment.
486 TargetOptions options
;
487 #if defined(PIPE_ARCH_X86)
488 options
.StackAlignmentOverride
= 4;
489 #if HAVE_LLVM < 0x0304
490 options
.RealignStack
= true;
494 #if defined(DEBUG) && HAVE_LLVM < 0x0307
495 options
.JITEmitDebugInfo
= true;
498 /* XXX: Workaround http://llvm.org/PR21435 */
499 #if defined(DEBUG) || defined(PROFILE) || \
500 (HAVE_LLVM >= 0x0303 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)))
501 #if HAVE_LLVM < 0x0304
502 options
.NoFramePointerElimNonLeaf
= true;
504 #if HAVE_LLVM < 0x0307
505 options
.NoFramePointerElim
= true;
509 builder
.setEngineKind(EngineKind::JIT
)
511 .setTargetOptions(options
)
512 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
515 #if HAVE_LLVM < 0x0306
516 builder
.setUseMCJIT(true);
520 * MCJIT works on Windows, but currently only through ELF object format.
522 * XXX: We could use `LLVM_HOST_TRIPLE "-elf"` but LLVM_HOST_TRIPLE has
523 * different strings for MinGW/MSVC, so better play it safe and be
527 LLVMSetTarget(M
, "x86_64-pc-win32-elf");
529 LLVMSetTarget(M
, "i686-pc-win32-elf");
534 llvm::SmallVector
<std::string
, 16> MAttrs
;
536 #if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
538 * We need to unset attributes because sometimes LLVM mistakenly assumes
539 * certain features are present given the processor name.
541 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
542 * http://llvm.org/PR25021
543 * http://llvm.org/PR19429
544 * http://llvm.org/PR16721
546 MAttrs
.push_back(util_cpu_caps
.has_sse
? "+sse" : "-sse" );
547 MAttrs
.push_back(util_cpu_caps
.has_sse2
? "+sse2" : "-sse2" );
548 MAttrs
.push_back(util_cpu_caps
.has_sse3
? "+sse3" : "-sse3" );
549 MAttrs
.push_back(util_cpu_caps
.has_ssse3
? "+ssse3" : "-ssse3" );
550 #if HAVE_LLVM >= 0x0304
551 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse4.1" : "-sse4.1");
553 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse41" : "-sse41" );
555 #if HAVE_LLVM >= 0x0304
556 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse4.2" : "-sse4.2");
558 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse42" : "-sse42" );
561 * AVX feature is not automatically detected from CPUID by the X86 target
562 * yet, because the old (yet default) JIT engine is not capable of
563 * emitting the opcodes. On newer llvm versions it is and at least some
564 * versions (tested with 3.3) will emit avx opcodes without this anyway.
566 MAttrs
.push_back(util_cpu_caps
.has_avx
? "+avx" : "-avx");
567 MAttrs
.push_back(util_cpu_caps
.has_f16c
? "+f16c" : "-f16c");
568 MAttrs
.push_back(util_cpu_caps
.has_avx2
? "+avx2" : "-avx2");
571 #if defined(PIPE_ARCH_PPC)
572 MAttrs
.push_back(util_cpu_caps
.has_altivec
? "+altivec" : "-altivec");
573 #if HAVE_LLVM >= 0x0304
575 * Make sure VSX instructions are disabled
576 * See LLVM bug https://llvm.org/bugs/show_bug.cgi?id=25503#c7
578 if (util_cpu_caps
.has_altivec
) {
579 MAttrs
.push_back("-vsx");
584 builder
.setMAttrs(MAttrs
);
586 #if HAVE_LLVM >= 0x0305
587 StringRef MCPU
= llvm::sys::getHostCPUName();
589 * The cpu bits are no longer set automatically, so need to set mcpu manually.
590 * Note that the MAttrs set above will be sort of ignored (since we should
591 * not set any which would not be set by specifying the cpu anyway).
592 * It ought to be safe though since getHostCPUName() should include bits
593 * not only from the cpu but environment as well (for instance if it's safe
594 * to use avx instructions which need OS support). According to
595 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
596 * right it may be necessary to specify older cpu (or disable mattrs) though
597 * when not using MCJIT so no instructions are generated which the old JIT
598 * can't handle. Not entirely sure if we really need to do anything yet.
600 builder
.setMCPU(MCPU
);
603 ShaderMemoryManager
*MM
= NULL
;
605 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
606 MM
= new ShaderMemoryManager(JMM
);
607 *OutCode
= MM
->getGeneratedCode();
609 #if HAVE_LLVM >= 0x0306
610 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
611 MM
= NULL
; // ownership taken by std::unique_ptr
612 #elif HAVE_LLVM > 0x0303
613 builder
.setMCJITMemoryManager(MM
);
615 builder
.setJITMemoryManager(MM
);
618 #if HAVE_LLVM < 0x0306
619 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
620 MM
= new ShaderMemoryManager(JMM
);
621 *OutCode
= MM
->getGeneratedCode();
623 builder
.setJITMemoryManager(MM
);
629 ExecutionEngine
*JIT
;
631 JIT
= builder
.create();
636 lp_free_generated_code(*OutCode
);
639 *OutError
= strdup(Error
.c_str());
646 lp_free_generated_code(struct lp_generated_code
*code
)
648 ShaderMemoryManager::freeGeneratedCode(code
);
652 LLVMMCJITMemoryManagerRef
653 lp_get_default_memory_manager()
655 BaseMemoryManager
*mm
;
656 #if HAVE_LLVM < 0x0306
657 mm
= llvm::JITMemoryManager::CreateDefaultMemManager();
659 mm
= new llvm::SectionMemoryManager();
661 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
666 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
668 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);