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
);
146 #if HAVE_LLVM < 0x0306
149 * Delegating is tedious but the default manager class is hidden in an
150 * anonymous namespace in LLVM, so we cannot just derive from it to change
153 class DelegatingJITMemoryManager
: public llvm::JITMemoryManager
{
156 virtual llvm::JITMemoryManager
*mgr() const = 0;
160 * From JITMemoryManager
162 virtual void setMemoryWritable() {
163 mgr()->setMemoryWritable();
165 virtual void setMemoryExecutable() {
166 mgr()->setMemoryExecutable();
168 virtual void setPoisonMemory(bool poison
) {
169 mgr()->setPoisonMemory(poison
);
171 virtual void AllocateGOT() {
172 mgr()->AllocateGOT();
174 * isManagingGOT() is not virtual in base class so we can't delegate.
175 * Instead we mirror the value of HasGOT in our instance.
177 HasGOT
= mgr()->isManagingGOT();
179 virtual uint8_t *getGOTBase() const {
180 return mgr()->getGOTBase();
182 virtual uint8_t *startFunctionBody(const llvm::Function
*F
,
183 uintptr_t &ActualSize
) {
184 return mgr()->startFunctionBody(F
, ActualSize
);
186 virtual uint8_t *allocateStub(const llvm::GlobalValue
*F
,
188 unsigned Alignment
) {
189 return mgr()->allocateStub(F
, StubSize
, Alignment
);
191 virtual void endFunctionBody(const llvm::Function
*F
,
192 uint8_t *FunctionStart
,
193 uint8_t *FunctionEnd
) {
194 mgr()->endFunctionBody(F
, FunctionStart
, FunctionEnd
);
196 virtual uint8_t *allocateSpace(intptr_t Size
, unsigned Alignment
) {
197 return mgr()->allocateSpace(Size
, Alignment
);
199 virtual uint8_t *allocateGlobal(uintptr_t Size
, unsigned Alignment
) {
200 return mgr()->allocateGlobal(Size
, Alignment
);
202 virtual void deallocateFunctionBody(void *Body
) {
203 mgr()->deallocateFunctionBody(Body
);
205 #if HAVE_LLVM < 0x0304
206 virtual uint8_t *startExceptionTable(const llvm::Function
*F
,
207 uintptr_t &ActualSize
) {
208 return mgr()->startExceptionTable(F
, ActualSize
);
210 virtual void endExceptionTable(const llvm::Function
*F
,
213 uint8_t *FrameRegister
) {
214 mgr()->endExceptionTable(F
, TableStart
, TableEnd
,
217 virtual void deallocateExceptionTable(void *ET
) {
218 mgr()->deallocateExceptionTable(ET
);
221 virtual bool CheckInvariants(std::string
&s
) {
222 return mgr()->CheckInvariants(s
);
224 virtual size_t GetDefaultCodeSlabSize() {
225 return mgr()->GetDefaultCodeSlabSize();
227 virtual size_t GetDefaultDataSlabSize() {
228 return mgr()->GetDefaultDataSlabSize();
230 virtual size_t GetDefaultStubSlabSize() {
231 return mgr()->GetDefaultStubSlabSize();
233 virtual unsigned GetNumCodeSlabs() {
234 return mgr()->GetNumCodeSlabs();
236 virtual unsigned GetNumDataSlabs() {
237 return mgr()->GetNumDataSlabs();
239 virtual unsigned GetNumStubSlabs() {
240 return mgr()->GetNumStubSlabs();
244 * From RTDyldMemoryManager
246 #if HAVE_LLVM >= 0x0304
247 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
250 llvm::StringRef SectionName
) {
251 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
,
255 virtual uint8_t *allocateCodeSection(uintptr_t Size
,
257 unsigned SectionID
) {
258 return mgr()->allocateCodeSection(Size
, Alignment
, SectionID
);
261 #if HAVE_LLVM >= 0x0303
262 virtual uint8_t *allocateDataSection(uintptr_t Size
,
265 #if HAVE_LLVM >= 0x0304
266 llvm::StringRef SectionName
,
269 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
,
270 #if HAVE_LLVM >= 0x0304
275 #if HAVE_LLVM >= 0x0304
276 virtual void registerEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
277 mgr()->registerEHFrames(Addr
, LoadAddr
, Size
);
279 virtual void deregisterEHFrames(uint8_t *Addr
, uint64_t LoadAddr
, size_t Size
) {
280 mgr()->deregisterEHFrames(Addr
, LoadAddr
, Size
);
283 virtual void registerEHFrames(llvm::StringRef SectionData
) {
284 mgr()->registerEHFrames(SectionData
);
288 virtual uint8_t *allocateDataSection(uintptr_t Size
,
290 unsigned SectionID
) {
291 return mgr()->allocateDataSection(Size
, Alignment
, SectionID
);
294 virtual void *getPointerToNamedFunction(const std::string
&Name
,
295 bool AbortOnFailure
=true) {
296 return mgr()->getPointerToNamedFunction(Name
, AbortOnFailure
);
298 #if HAVE_LLVM == 0x0303
299 virtual bool applyPermissions(std::string
*ErrMsg
= 0) {
300 return mgr()->applyPermissions(ErrMsg
);
302 #elif HAVE_LLVM > 0x0303
303 virtual bool finalizeMemory(std::string
*ErrMsg
= 0) {
304 return mgr()->finalizeMemory(ErrMsg
);
311 * Delegate memory management to one shared manager for more efficient use
312 * of memory than creating a separate pool for each LLVM engine.
313 * Keep generated code until freeGeneratedCode() is called, instead of when
314 * memory manager is destroyed, which happens during engine destruction.
315 * This allows additional memory savings as we don't have to keep the engine
316 * around in order to use the code.
317 * All methods are delegated to the shared manager except destruction and
318 * deallocating code. For the latter we just remember what needs to be
319 * deallocated later. The shared manager is deleted once it is empty.
321 class ShaderMemoryManager
: public DelegatingJITMemoryManager
{
323 static llvm::JITMemoryManager
*TheMM
;
324 static unsigned NumUsers
;
326 struct GeneratedCode
{
327 typedef std::vector
<void *> Vec
;
328 Vec FunctionBody
, ExceptionTable
;
336 * Deallocate things as previously requested and
337 * free shared manager when no longer used.
342 for ( i
= FunctionBody
.begin(); i
!= FunctionBody
.end(); ++i
)
343 TheMM
->deallocateFunctionBody(*i
);
344 #if HAVE_LLVM < 0x0304
345 for ( i
= ExceptionTable
.begin(); i
!= ExceptionTable
.end(); ++i
)
346 TheMM
->deallocateExceptionTable(*i
);
358 llvm::JITMemoryManager
*mgr() const {
360 TheMM
= CreateDefaultMemManager();
367 ShaderMemoryManager() {
368 code
= new GeneratedCode
;
371 virtual ~ShaderMemoryManager() {
373 * 'code' is purposely not deleted. It is the user's responsibility
374 * to call getGeneratedCode() and freeGeneratedCode().
378 struct lp_generated_code
*getGeneratedCode() {
379 return (struct lp_generated_code
*) code
;
382 static void freeGeneratedCode(struct lp_generated_code
*code
) {
383 delete (GeneratedCode
*) code
;
386 #if HAVE_LLVM < 0x0304
387 virtual void deallocateExceptionTable(void *ET
) {
388 // remember for later deallocation
389 code
->ExceptionTable
.push_back(ET
);
393 virtual void deallocateFunctionBody(void *Body
) {
394 // remember for later deallocation
395 code
->FunctionBody
.push_back(Body
);
399 llvm::JITMemoryManager
*ShaderMemoryManager::TheMM
= 0;
400 unsigned ShaderMemoryManager::NumUsers
= 0;
405 * Same as LLVMCreateJITCompilerForModule, but:
406 * - allows using MCJIT and enabling AVX feature where available.
407 * - set target options
410 * - llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp
411 * - llvm/tools/lli/lli.cpp
412 * - http://markmail.org/message/ttkuhvgj4cxxy2on#query:+page:1+mid:aju2dggerju3ivd3+state:results
416 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef
*OutJIT
,
417 lp_generated_code
**OutCode
,
423 using namespace llvm
;
425 #if HAVE_LLVM >= 0x0306
426 *OutError
= strdup("MCJIT not supported");
431 #if HAVE_LLVM >= 0x0306
432 EngineBuilder
builder(std::unique_ptr
<Module
>(unwrap(M
)));
434 EngineBuilder
builder(unwrap(M
));
438 * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
439 * friends for configuring code generation options, like stack alignment.
441 TargetOptions options
;
442 #if defined(PIPE_ARCH_X86)
443 options
.StackAlignmentOverride
= 4;
444 #if HAVE_LLVM < 0x0304
445 options
.RealignStack
= true;
450 options
.JITEmitDebugInfo
= true;
453 #if defined(DEBUG) || defined(PROFILE)
454 #if HAVE_LLVM < 0x0304
455 options
.NoFramePointerElimNonLeaf
= true;
457 options
.NoFramePointerElim
= true;
460 builder
.setEngineKind(EngineKind::JIT
)
462 .setTargetOptions(options
)
463 .setOptLevel((CodeGenOpt::Level
)OptLevel
);
466 #if HAVE_LLVM < 0x0306
467 builder
.setUseMCJIT(true);
471 * MCJIT works on Windows, but currently only through ELF object format.
473 std::string targetTriple
= llvm::sys::getProcessTriple();
474 targetTriple
.append("-elf");
475 unwrap(M
)->setTargetTriple(targetTriple
);
479 llvm::SmallVector
<std::string
, 1> MAttrs
;
480 if (util_cpu_caps
.has_avx
) {
482 * AVX feature is not automatically detected from CPUID by the X86 target
483 * yet, because the old (yet default) JIT engine is not capable of
484 * emitting the opcodes. On newer llvm versions it is and at least some
485 * versions (tested with 3.3) will emit avx opcodes without this anyway.
487 MAttrs
.push_back("+avx");
488 if (util_cpu_caps
.has_f16c
) {
489 MAttrs
.push_back("+f16c");
491 builder
.setMAttrs(MAttrs
);
494 #if HAVE_LLVM >= 0x0305
495 StringRef MCPU
= llvm::sys::getHostCPUName();
497 * The cpu bits are no longer set automatically, so need to set mcpu manually.
498 * Note that the MAttrs set above will be sort of ignored (since we should
499 * not set any which would not be set by specifying the cpu anyway).
500 * It ought to be safe though since getHostCPUName() should include bits
501 * not only from the cpu but environment as well (for instance if it's safe
502 * to use avx instructions which need OS support). According to
503 * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
504 * right it may be necessary to specify older cpu (or disable mattrs) though
505 * when not using MCJIT so no instructions are generated which the old JIT
506 * can't handle. Not entirely sure if we really need to do anything yet.
508 builder
.setMCPU(MCPU
);
511 ShaderMemoryManager
*MM
= new ShaderMemoryManager();
512 *OutCode
= MM
->getGeneratedCode();
514 builder
.setJITMemoryManager(MM
);
516 ExecutionEngine
*JIT
;
518 #if HAVE_LLVM >= 0x0302
519 JIT
= builder
.create();
522 * Workaround http://llvm.org/PR12833
524 StringRef MArch
= "";
526 Triple
TT(unwrap(M
)->getTargetTriple());
527 JIT
= builder
.create(builder
.selectTarget(TT
, MArch
, MCPU
, MAttrs
));
533 lp_free_generated_code(*OutCode
);
536 *OutError
= strdup(Error
.c_str());
544 lp_free_generated_code(struct lp_generated_code
*code
)
546 #if HAVE_LLVM < 0x0306
547 ShaderMemoryManager::freeGeneratedCode(code
);