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 < 0x0306
65 #include <llvm/ExecutionEngine/JITMemoryManager.h>
67 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
69 #include <llvm/Support/CommandLine.h>
70 #include <llvm/Support/Host.h>
71 #include <llvm/Support/PrettyStackTrace.h>
73 #include <llvm/Support/TargetSelect.h>
75 #include <llvm/IR/IRBuilder.h>
76 #include <llvm/IR/Module.h>
77 #include <llvm/Support/CBindingWrapping.h>
79 // Workaround http://llvm.org/PR23628
80 #if HAVE_LLVM >= 0x0307
81 # pragma pop_macro("DEBUG")
84 #include "c11/threads.h"
85 #include "os/os_thread.h"
86 #include "pipe/p_config.h"
87 #include "util/u_debug.h"
88 #include "util/u_cpu_detect.h"
90 #include "lp_bld_misc.h"
94 class LLVMEnsureMultithreaded
{
96 LLVMEnsureMultithreaded()
98 if (!LLVMIsMultithreaded()) {
99 LLVMStartMultithreaded();
104 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
108 static once_flag init_native_targets_once_flag
;
110 static void init_native_targets()
112 // If we have a native target, initialize it to ensure it is linked in and
113 // usable by the JIT.
114 llvm::InitializeNativeTarget();
116 llvm::InitializeNativeTargetAsmPrinter();
118 llvm::InitializeNativeTargetDisassembler();
122 * The llvm target registry is not thread-safe, so drivers and state-trackers
123 * that want to initialize targets should use the gallivm_init_llvm_targets()
124 * function to safely initialize targets.
126 * LLVM targets should be initialized before the driver or state-tracker tries
127 * to access the registry.
130 gallivm_init_llvm_targets(void)
132 call_once(&init_native_targets_once_flag
, init_native_targets
);
136 lp_set_target_options(void)
138 #if HAVE_LLVM < 0x0304
140 * By default LLVM adds a signal handler to output a pretty stack trace.
141 * This signal handler is never removed, causing problems when unloading the
142 * shared object where the gallium driver resides.
144 llvm::DisablePrettyStackTrace
= true;
147 gallivm_init_llvm_targets();
153 lp_build_load_volatile(LLVMBuilderRef B
, LLVMValueRef PointerVal
,
156 return llvm::wrap(llvm::unwrap(B
)->CreateLoad(llvm::unwrap(PointerVal
), true, Name
));
162 lp_set_load_alignment(LLVMValueRef Inst
,
165 llvm::unwrap
<llvm::LoadInst
>(Inst
)->setAlignment(Align
);
170 lp_set_store_alignment(LLVMValueRef Inst
,
173 llvm::unwrap
<llvm::StoreInst
>(Inst
)->setAlignment(Align
);
177 #if HAVE_LLVM < 0x0306
178 typedef llvm::JITMemoryManager BaseMemoryManager
;
180 typedef llvm::RTDyldMemoryManager BaseMemoryManager
;
185 * Delegating is tedious but the default manager class is hidden in an
186 * anonymous namespace in LLVM, so we cannot just derive from it to change
189 class DelegatingJITMemoryManager
: public BaseMemoryManager
{
192 virtual BaseMemoryManager
*mgr() const = 0;
195 #if HAVE_LLVM < 0x0306
197 * From JITMemoryManager
199 virtual void setMemoryWritable() {
200 mgr()->setMemoryWritable();
202 virtual void setMemoryExecutable() {
203 mgr()->setMemoryExecutable();
205 virtual void setPoisonMemory(bool poison
) {
206 mgr()->setPoisonMemory(poison
);
208 virtual void AllocateGOT() {
209 mgr()->AllocateGOT();
211 * isManagingGOT() is not virtual in base class so we can't delegate.
212 * Instead we mirror the value of HasGOT in our instance.
214 HasGOT
= mgr()->isManagingGOT();
216 virtual uint8_t *getGOTBase() const {
217 return mgr()->getGOTBase();
219 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
220 uintptr_t &ActualSize
) {
221 return mgr()->startFunctionBody(F
, ActualSize
);
223 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
225 unsigned Alignment
) {
226 return mgr()->allocateStub(F
, StubSize
, Alignment
);
228 virtual void endFunctionBody(const llvm::Function
*F
,
229 uint8_t *FunctionStart
,
230 uint8_t *FunctionEnd
) {
231 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
233 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
234 return mgr()->allocateSpace(Size
, Alignment
);
236 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
237 return mgr()->allocateGlobal(Size
, Alignment
);
239 virtual void deallocateFunctionBody(void *Body
) {
240 mgr()->deallocateFunctionBody(Body
);
242 #if HAVE_LLVM < 0x0304
243 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
244 uintptr_t &ActualSize
) {
245 return mgr()->startExceptionTable(F
, ActualSize
);
247 virtual void endExceptionTable(const llvm::Function
*F
,
250 uint8_t *FrameRegister
) {
251 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
254 virtual void deallocateExceptionTable(void *ET
) {
255 mgr()->deallocateExceptionTable(ET
);
258 virtual bool CheckInvariants(std::string
&s
) {
259 return mgr()->CheckInvariants(s
);
261 virtual size_t GetDefaultCodeSlabSize() {
262 return mgr()->GetDefaultCodeSlabSize();
264 virtual size_t GetDefaultDataSlabSize() {
265 return mgr()->GetDefaultDataSlabSize();
267 virtual size_t GetDefaultStubSlabSize() {
268 return mgr()->GetDefaultStubSlabSize();
270 virtual unsigned GetNumCodeSlabs() {
271 return mgr()->GetNumCodeSlabs();
273 virtual unsigned GetNumDataSlabs() {
274 return mgr()->GetNumDataSlabs();
276 virtual unsigned GetNumStubSlabs() {
277 return mgr()->GetNumStubSlabs();
282 * From RTDyldMemoryManager
284 #if HAVE_LLVM >= 0x0304
285 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
288 llvm::StringRef SectionName
) {
289 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
293 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
295 unsigned SectionID
) {
296 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
299 virtual uint8_t *allocateDataSection(uintptr_t Size
,
302 #if HAVE_LLVM >= 0x0304
303 llvm::StringRef SectionName
,
306 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
307 #if HAVE_LLVM >= 0x0304
312 #if HAVE_LLVM >= 0x0304
313 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
314 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
316 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
317 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
320 virtual void registerEHFrames(llvm::StringRef SectionData
) {
321 mgr()->registerEHFrames(SectionData
);
324 virtual void *getPointerToNamedFunction(const std::string
&Name
,
325 bool AbortOnFailure
=true) {
326 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
328 #if HAVE_LLVM <= 0x0303
329 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
330 return mgr()->applyPermissions(ErrMsg
);
333 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
334 return mgr()->finalizeMemory(ErrMsg
);
341 * Delegate memory management to one shared manager for more efficient use
342 * of memory than creating a separate pool for each LLVM engine.
343 * Keep generated code until freeGeneratedCode() is called, instead of when
344 * memory manager is destroyed, which happens during engine destruction.
345 * This allows additional memory savings as we don't have to keep the engine
346 * around in order to use the code.
347 * All methods are delegated to the shared manager except destruction and
348 * deallocating code. For the latter we just remember what needs to be
349 * deallocated later. The shared manager is deleted once it is empty.
351 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
353 BaseMemoryManager
*TheMM
;
355 struct GeneratedCode
{
356 typedef std::vector
<void *> Vec
;
357 Vec FunctionBody
, ExceptionTable
;
358 BaseMemoryManager
*TheMM
;
360 GeneratedCode(BaseMemoryManager
*MM
) {
366 * Deallocate things as previously requested and
367 * free shared manager when no longer used.
369 #if HAVE_LLVM < 0x0306
373 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
374 TheMM
->deallocateFunctionBody(*i
);
375 #if HAVE_LLVM < 0x0304
376 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
377 TheMM
->deallocateExceptionTable(*i
);
378 #endif /* HAVE_LLVM < 0x0304 */
379 #endif /* HAVE_LLVM < 0x0306 */
385 BaseMemoryManager
*mgr() const {
391 ShaderMemoryManager(BaseMemoryManager
* MM
) {
393 code
= new GeneratedCode(MM
);
396 virtual ~ShaderMemoryManager() {
398 * 'code' is purposely not deleted. It is the user's responsibility
399 * to call getGeneratedCode() and freeGeneratedCode().
403 struct lp_generated_code
*getGeneratedCode() {
404 return (struct lp_generated_code
*) code
;
407 static void freeGeneratedCode(struct lp_generated_code
*code
) {
408 delete (GeneratedCode
*) code
;
411 #if HAVE_LLVM < 0x0304
412 virtual void deallocateExceptionTable(void *ET
) {
413 // remember for later deallocation
414 code
->ExceptionTable
.push_back(ET
);
418 virtual void deallocateFunctionBody(void *Body
) {
419 // remember for later deallocation
420 code
->FunctionBody
.push_back(Body
);
426 * Same as LLVMCreateJITCompilerForModule, but:
427 * - allows using MCJIT and enabling AVX feature where available.
428 * - set target options
431 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
432 * - llvm/tools/lli/lli.cpp
433 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
437 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
438 lp_generated_code
**OutCode
,
440 LLVMMCJITMemoryManagerRef CMM
,
445 using namespace llvm
;
448 #if HAVE_LLVM >= 0x0306
449 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
451 EngineBuilder
builder(unwrap(M
));
455 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
456 * friends for configuring code generation options, like stack alignment.
458 TargetOptions options
;
459 #if defined(PIPE_ARCH_X86)
460 options
.StackAlignmentOverride
= 4;
461 #if HAVE_LLVM < 0x0304
462 options
.RealignStack
= true;
466 #if defined(DEBUG) && HAVE_LLVM < 0x0307
467 options
.JITEmitDebugInfo
= true;
470 /* XXX: Workaround http://llvm.org/PR21435 */
471 #if defined(DEBUG) || defined(PROFILE) || \
472 (HAVE_LLVM >= 0x0303 && (defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)))
473 #if HAVE_LLVM < 0x0304
474 options
.NoFramePointerElimNonLeaf
= true;
476 #if HAVE_LLVM < 0x0307
477 options
.NoFramePointerElim
= true;
481 builder
.setEngineKind(EngineKind::JIT
)
483 .setTargetOptions(options
)
484 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
487 #if HAVE_LLVM < 0x0306
488 builder
.setUseMCJIT(true);
492 * MCJIT works on Windows, but currently only through ELF object format.
494 std::string targetTriple
= llvm::sys::getProcessTriple();
495 targetTriple
.append("-elf");
496 unwrap(M
)->setTargetTriple(targetTriple
);
500 llvm::SmallVector
<std::string
, 16> MAttrs
;
502 #if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
504 * We need to unset attributes because sometimes LLVM mistakenly assumes
505 * certain features are present given the processor name.
507 * https://bugs.freedesktop.org/show_bug.cgi?id=92214
508 * http://llvm.org/PR25021
509 * http://llvm.org/PR19429
510 * http://llvm.org/PR16721
512 MAttrs
.push_back(util_cpu_caps
.has_sse
? "+sse" : "-sse" );
513 MAttrs
.push_back(util_cpu_caps
.has_sse2
? "+sse2" : "-sse2" );
514 MAttrs
.push_back(util_cpu_caps
.has_sse3
? "+sse3" : "-sse3" );
515 MAttrs
.push_back(util_cpu_caps
.has_ssse3
? "+ssse3" : "-ssse3" );
516 #if HAVE_LLVM >= 0x0304
517 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse4.1" : "-sse4.1");
519 MAttrs
.push_back(util_cpu_caps
.has_sse4_1
? "+sse41" : "-sse41" );
521 #if HAVE_LLVM >= 0x0304
522 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse4.2" : "-sse4.2");
524 MAttrs
.push_back(util_cpu_caps
.has_sse4_2
? "+sse42" : "-sse42" );
527 * AVX feature is not automatically detected from CPUID by the X86 target
528 * yet, because the old (yet default) JIT engine is not capable of
529 * emitting the opcodes. On newer llvm versions it is and at least some
530 * versions (tested with 3.3) will emit avx opcodes without this anyway.
532 MAttrs
.push_back(util_cpu_caps
.has_avx
? "+avx" : "-avx");
533 MAttrs
.push_back(util_cpu_caps
.has_f16c
? "+f16c" : "-f16c");
534 MAttrs
.push_back(util_cpu_caps
.has_avx2
? "+avx2" : "-avx2");
537 #if defined(PIPE_ARCH_PPC)
538 MAttrs
.push_back(util_cpu_caps
.has_altivec
? "+altivec" : "-altivec");
539 #if HAVE_LLVM >= 0x0304
541 * Make sure VSX instructions are disabled
542 * See LLVM bug https://llvm.org/bugs/show_bug.cgi?id=25503#c7
544 if (util_cpu_caps
.has_altivec
) {
545 MAttrs
.push_back("-vsx");
550 builder
.setMAttrs(MAttrs
);
552 #if HAVE_LLVM >= 0x0305
553 StringRef MCPU
= llvm::sys::getHostCPUName();
555 * The cpu bits are no longer set automatically, so need to set mcpu manually.
556 * Note that the MAttrs set above will be sort of ignored (since we should
557 * not set any which would not be set by specifying the cpu anyway).
558 * It ought to be safe though since getHostCPUName() should include bits
559 * not only from the cpu but environment as well (for instance if it's safe
560 * to use avx instructions which need OS support). According to
561 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
562 * right it may be necessary to specify older cpu (or disable mattrs) though
563 * when not using MCJIT so no instructions are generated which the old JIT
564 * can't handle. Not entirely sure if we really need to do anything yet.
566 builder
.setMCPU(MCPU
);
569 ShaderMemoryManager
*MM
= NULL
;
571 #if HAVE_LLVM > 0x0303
572 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
573 MM
= new ShaderMemoryManager(JMM
);
574 *OutCode
= MM
->getGeneratedCode();
576 #if HAVE_LLVM >= 0x0306
577 builder
.setMCJITMemoryManager(std::unique_ptr
<RTDyldMemoryManager
>(MM
));
578 MM
= NULL
; // ownership taken by std::unique_ptr
580 builder
.setMCJITMemoryManager(MM
);
584 #if HAVE_LLVM < 0x0306
585 BaseMemoryManager
* JMM
= reinterpret_cast<BaseMemoryManager
*>(CMM
);
586 MM
= new ShaderMemoryManager(JMM
);
587 *OutCode
= MM
->getGeneratedCode();
589 builder
.setJITMemoryManager(MM
);
595 ExecutionEngine
*JIT
;
597 JIT
= builder
.create();
602 lp_free_generated_code(*OutCode
);
605 *OutError
= strdup(Error
.c_str());
612 lp_free_generated_code(struct lp_generated_code
*code
)
614 ShaderMemoryManager::freeGeneratedCode(code
);
618 LLVMMCJITMemoryManagerRef
619 lp_get_default_memory_manager()
621 BaseMemoryManager
*mm
;
622 #if HAVE_LLVM < 0x0306
623 mm
= llvm::JITMemoryManager::CreateDefaultMemManager();
625 mm
= new llvm::SectionMemoryManager();
627 return reinterpret_cast<LLVMMCJITMemoryManagerRef
>(mm
);
632 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr
)
634 delete reinterpret_cast<BaseMemoryManager
*>(memorymgr
);