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 #include <llvm-c/Core.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/ExecutionEngine/JITMemoryManager.h>
59 #include <llvm/Support/CommandLine.h>
60 #include <llvm/Support/Host.h>
61 #include <llvm/Support/PrettyStackTrace.h>
63 #include <llvm/Support/TargetSelect.h>
65 #if HAVE_LLVM >= 0x0303
66 #include <llvm/IR/IRBuilder.h>
67 #include <llvm/IR/Module.h>
68 #include <llvm/Support/CBindingWrapping.h>
71 #include "pipe/p_config.h"
72 #include "util/u_debug.h"
73 #include "util/u_cpu_detect.h"
75 #include "lp_bld_misc.h"
79 class LLVMEnsureMultithreaded
{
81 LLVMEnsureMultithreaded()
83 #if HAVE_LLVM < 0x0303
84 if (!llvm::llvm_is_multithreaded()) {
85 llvm::llvm_start_multithreaded();
88 if (!LLVMIsMultithreaded()) {
89 LLVMStartMultithreaded();
95 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded
;
100 lp_set_target_options(void)
102 #if HAVE_LLVM < 0x0304
104 * By default LLVM adds a signal handler to output a pretty stack trace.
105 * This signal handler is never removed, causing problems when unloading the
106 * shared object where the gallium driver resides.
108 llvm::DisablePrettyStackTrace
= true;
111 // If we have a native target, initialize it to ensure it is linked in and
112 // usable by the JIT.
113 llvm::InitializeNativeTarget();
115 llvm::InitializeNativeTargetAsmPrinter();
117 llvm::InitializeNativeTargetDisassembler();
123 lp_build_load_volatile(LLVMBuilderRef B
, LLVMValueRef PointerVal
,
126 return llvm::wrap(llvm::unwrap(B
)->CreateLoad(llvm::unwrap(PointerVal
), true, Name
));
132 lp_set_load_alignment(LLVMValueRef Inst
,
135 llvm::unwrap
<llvm::LoadInst
>(Inst
)->setAlignment(Align
);
140 lp_set_store_alignment(LLVMValueRef Inst
,
143 llvm::unwrap
<llvm::StoreInst
>(Inst
)->setAlignment(Align
);
148 * Delegating is tedious but the default manager class is hidden in an
149 * anonymous namespace in LLVM, so we cannot just derive from it to change
152 class DelegatingJITMemoryManager
: public llvm::JITMemoryManager
{
155 virtual llvm::JITMemoryManager
*mgr() const = 0;
159 * From JITMemoryManager
161 virtual void setMemoryWritable() {
162 mgr()->setMemoryWritable();
164 virtual void setMemoryExecutable() {
165 mgr()->setMemoryExecutable();
167 virtual void setPoisonMemory(bool poison
) {
168 mgr()->setPoisonMemory(poison
);
170 virtual void AllocateGOT() {
171 mgr()->AllocateGOT();
173 * isManagingGOT() is not virtual in base class so we can't delegate.
174 * Instead we mirror the value of HasGOT in our instance.
176 HasGOT
= mgr()->isManagingGOT();
178 virtual uint8_t *getGOTBase() const {
179 return mgr()->getGOTBase();
181 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
182 uintptr_t &ActualSize
) {
183 return mgr()->startFunctionBody(F
, ActualSize
);
185 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
187 unsigned Alignment
) {
188 return mgr()->allocateStub(F
, StubSize
, Alignment
);
190 virtual void endFunctionBody(const llvm::Function
*F
,
191 uint8_t *FunctionStart
,
192 uint8_t *FunctionEnd
) {
193 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
195 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
196 return mgr()->allocateSpace(Size
, Alignment
);
198 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
199 return mgr()->allocateGlobal(Size
, Alignment
);
201 virtual void deallocateFunctionBody(void *Body
) {
202 mgr()->deallocateFunctionBody(Body
);
204 #if HAVE_LLVM < 0x0304
205 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
206 uintptr_t &ActualSize
) {
207 return mgr()->startExceptionTable(F
, ActualSize
);
209 virtual void endExceptionTable(const llvm::Function
*F
,
212 uint8_t *FrameRegister
) {
213 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
216 virtual void deallocateExceptionTable(void *ET
) {
217 mgr()->deallocateExceptionTable(ET
);
220 virtual bool CheckInvariants(std::string
&s
) {
221 return mgr()->CheckInvariants(s
);
223 virtual size_t GetDefaultCodeSlabSize() {
224 return mgr()->GetDefaultCodeSlabSize();
226 virtual size_t GetDefaultDataSlabSize() {
227 return mgr()->GetDefaultDataSlabSize();
229 virtual size_t GetDefaultStubSlabSize() {
230 return mgr()->GetDefaultStubSlabSize();
232 virtual unsigned GetNumCodeSlabs() {
233 return mgr()->GetNumCodeSlabs();
235 virtual unsigned GetNumDataSlabs() {
236 return mgr()->GetNumDataSlabs();
238 virtual unsigned GetNumStubSlabs() {
239 return mgr()->GetNumStubSlabs();
243 * From RTDyldMemoryManager
245 #if HAVE_LLVM >= 0x0304
246 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
249 llvm::StringRef SectionName
) {
250 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
254 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
256 unsigned SectionID
) {
257 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
260 #if HAVE_LLVM >= 0x0303
261 virtual uint8_t *allocateDataSection(uintptr_t Size
,
264 #if HAVE_LLVM >= 0x0304
265 llvm::StringRef SectionName
,
268 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
269 #if HAVE_LLVM >= 0x0304
274 #if HAVE_LLVM >= 0x0304
275 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
276 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
278 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
279 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
282 virtual void registerEHFrames(llvm::StringRef SectionData
) {
283 mgr()->registerEHFrames(SectionData
);
287 virtual uint8_t *allocateDataSection(uintptr_t Size
,
289 unsigned SectionID
) {
290 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
);
293 virtual void *getPointerToNamedFunction(const std::string
&Name
,
294 bool AbortOnFailure
=true) {
295 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
297 #if HAVE_LLVM == 0x0303
298 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
299 return mgr()->applyPermissions(ErrMsg
);
301 #elif HAVE_LLVM > 0x0303
302 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
303 return mgr()->finalizeMemory(ErrMsg
);
310 * Delegate memory management to one shared manager for more efficient use
311 * of memory than creating a separate pool for each LLVM engine.
312 * Keep generated code until freeGeneratedCode() is called, instead of when
313 * memory manager is destroyed, which happens during engine destruction.
314 * This allows additional memory savings as we don't have to keep the engine
315 * around in order to use the code.
316 * All methods are delegated to the shared manager except destruction and
317 * deallocating code. For the latter we just remember what needs to be
318 * deallocated later. The shared manager is deleted once it is empty.
320 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
322 static llvm::JITMemoryManager
*TheMM
;
323 static unsigned NumUsers
;
325 struct GeneratedCode
{
326 typedef std::vector
<void *> Vec
;
327 Vec FunctionBody
, ExceptionTable
;
335 * Deallocate things as previously requested and
336 * free shared manager when no longer used.
341 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
342 TheMM
->deallocateFunctionBody(*i
);
343 #if HAVE_LLVM < 0x0304
344 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
345 TheMM
->deallocateExceptionTable(*i
);
357 llvm::JITMemoryManager
*mgr() const {
359 TheMM
= CreateDefaultMemManager();
366 ShaderMemoryManager() {
367 code
= new GeneratedCode
;
370 virtual ~ShaderMemoryManager() {
372 * 'code' is purposely not deleted. It is the user's responsibility
373 * to call getGeneratedCode() and freeGeneratedCode().
377 struct lp_generated_code
*getGeneratedCode() {
378 return (struct lp_generated_code
*) code
;
381 static void freeGeneratedCode(struct lp_generated_code
*code
) {
382 delete (GeneratedCode
*) code
;
385 #if HAVE_LLVM < 0x0304
386 virtual void deallocateExceptionTable(void *ET
) {
387 // remember for later deallocation
388 code
->ExceptionTable
.push_back(ET
);
392 virtual void deallocateFunctionBody(void *Body
) {
393 // remember for later deallocation
394 code
->FunctionBody
.push_back(Body
);
398 llvm::JITMemoryManager
*ShaderMemoryManager::TheMM
= 0;
399 unsigned ShaderMemoryManager::NumUsers
= 0;
403 * Same as LLVMCreateJITCompilerForModule, but:
404 * - allows using MCJIT and enabling AVX feature where available.
405 * - set target options
408 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
409 * - llvm/tools/lli/lli.cpp
410 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
414 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
415 lp_generated_code
**OutCode
,
421 using namespace llvm
;
424 EngineBuilder
builder(unwrap(M
));
427 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
428 * friends for configuring code generation options, like stack alignment.
430 TargetOptions options
;
431 #if defined(PIPE_ARCH_X86)
432 options
.StackAlignmentOverride
= 4;
433 #if HAVE_LLVM < 0x0304
434 options
.RealignStack
= true;
439 options
.JITEmitDebugInfo
= true;
442 #if defined(DEBUG) || defined(PROFILE)
443 #if HAVE_LLVM < 0x0304
444 options
.NoFramePointerElimNonLeaf
= true;
446 options
.NoFramePointerElim
= true;
449 builder
.setEngineKind(EngineKind::JIT
)
451 .setTargetOptions(options
)
452 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
455 builder
.setUseMCJIT(true);
458 * MCJIT works on Windows, but currently only through ELF object format.
460 std::string targetTriple
= llvm::sys::getProcessTriple();
461 targetTriple
.append("-elf");
462 unwrap(M
)->setTargetTriple(targetTriple
);
466 llvm::SmallVector
<std::string
, 1> MAttrs
;
467 if (util_cpu_caps
.has_avx
) {
469 * AVX feature is not automatically detected from CPUID by the X86 target
470 * yet, because the old (yet default) JIT engine is not capable of
471 * emitting the opcodes. On newer llvm versions it is and at least some
472 * versions (tested with 3.3) will emit avx opcodes without this anyway.
474 MAttrs
.push_back("+avx");
475 if (util_cpu_caps
.has_f16c
) {
476 MAttrs
.push_back("+f16c");
478 builder
.setMAttrs(MAttrs
);
481 #if HAVE_LLVM >= 0x0305
482 StringRef MCPU
= llvm::sys::getHostCPUName();
484 * The cpu bits are no longer set automatically, so need to set mcpu manually.
485 * Note that the MAttrs set above will be sort of ignored (since we should
486 * not set any which would not be set by specifying the cpu anyway).
487 * It ought to be safe though since getHostCPUName() should include bits
488 * not only from the cpu but environment as well (for instance if it's safe
489 * to use avx instructions which need OS support). According to
490 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
491 * right it may be necessary to specify older cpu (or disable mattrs) though
492 * when not using MCJIT so no instructions are generated which the old JIT
493 * can't handle. Not entirely sure if we really need to do anything yet.
495 builder
.setMCPU(MCPU
);
498 ShaderMemoryManager
*MM
= new ShaderMemoryManager();
499 *OutCode
= MM
->getGeneratedCode();
501 builder
.setJITMemoryManager(MM
);
503 ExecutionEngine
*JIT
;
505 #if HAVE_LLVM >= 0x0302
506 JIT
= builder
.create();
509 * Workaround http://llvm.org/PR12833
511 StringRef MArch
= "";
513 Triple
TT(unwrap(M
)->getTargetTriple());
514 JIT
= builder
.create(builder
.selectTarget(TT
, MArch
, MCPU
, MAttrs
));
520 lp_free_generated_code(*OutCode
);
523 *OutError
= strdup(Error
.c_str());
530 lp_free_generated_code(struct lp_generated_code
*code
)
532 ShaderMemoryManager::freeGeneratedCode(code
);