OSDN Git Service

c1e262bc1edf6c1a7ab4838ba303f5c41f7cea95
[android-x86/external-mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_misc.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010 VMware, Inc.
4  * All Rights Reserved.
5  *
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:
13  *
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.
21  *
22  * The above copyright notice and this permission notice (including the
23  * next paragraph) shall be included in all copies or substantial portions
24  * of the Software.
25  *
26  **************************************************************************/
27
28
29 /**
30  * The purpose of this module is to expose LLVM functionality not available
31  * through the C++ bindings.
32  */
33
34
35 #ifndef __STDC_LIMIT_MACROS
36 #define __STDC_LIMIT_MACROS
37 #endif
38
39 #ifndef __STDC_CONSTANT_MACROS
40 #define __STDC_CONSTANT_MACROS
41 #endif
42
43 // Undef these vars just to silence warnings
44 #undef PACKAGE_BUGREPORT
45 #undef PACKAGE_NAME
46 #undef PACKAGE_STRING
47 #undef PACKAGE_TARNAME
48 #undef PACKAGE_VERSION
49
50
51 #include <stddef.h>
52
53 // Workaround http://llvm.org/PR23628
54 #if HAVE_LLVM >= 0x0307
55 #  pragma push_macro("DEBUG")
56 #  undef DEBUG
57 #endif
58
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>
66 #else
67 #include <llvm/Target/TargetLibraryInfo.h>
68 #endif
69 #if HAVE_LLVM < 0x0306
70 #include <llvm/ExecutionEngine/JITMemoryManager.h>
71 #else
72 #include <llvm/ExecutionEngine/SectionMemoryManager.h>
73 #endif
74 #include <llvm/Support/CommandLine.h>
75 #include <llvm/Support/Host.h>
76 #include <llvm/Support/PrettyStackTrace.h>
77
78 #include <llvm/Support/TargetSelect.h>
79
80 #include <llvm/IR/IRBuilder.h>
81 #include <llvm/IR/Module.h>
82 #include <llvm/Support/CBindingWrapping.h>
83
84 // Workaround http://llvm.org/PR23628
85 #if HAVE_LLVM >= 0x0307
86 #  pragma pop_macro("DEBUG")
87 #endif
88
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"
94
95 #include "lp_bld_misc.h"
96
97 namespace {
98
99 class LLVMEnsureMultithreaded {
100 public:
101    LLVMEnsureMultithreaded()
102    {
103       if (!LLVMIsMultithreaded()) {
104          LLVMStartMultithreaded();
105       }
106    }
107 };
108
109 static LLVMEnsureMultithreaded lLVMEnsureMultithreaded;
110
111 }
112
113 static once_flag init_native_targets_once_flag;
114
115 static void init_native_targets()
116 {
117    // If we have a native target, initialize it to ensure it is linked in and
118    // usable by the JIT.
119    llvm::InitializeNativeTarget();
120
121    llvm::InitializeNativeTargetAsmPrinter();
122
123    llvm::InitializeNativeTargetDisassembler();
124 }
125
126 /**
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.
130  *
131  * LLVM targets should be initialized before the driver or state-tracker tries
132  * to access the registry.
133  */
134 extern "C" void
135 gallivm_init_llvm_targets(void)
136 {
137    call_once(&init_native_targets_once_flag, init_native_targets);
138 }
139
140 extern "C" void
141 lp_set_target_options(void)
142 {
143 #if HAVE_LLVM < 0x0304
144    /*
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.
148     */
149    llvm::DisablePrettyStackTrace = true;
150 #endif
151
152    gallivm_init_llvm_targets();
153 }
154
155 extern "C"
156 LLVMTargetLibraryInfoRef
157 gallivm_create_target_library_info(const char *triple)
158 {
159    return reinterpret_cast<LLVMTargetLibraryInfoRef>(
160 #if HAVE_LLVM < 0x0307
161    new llvm::TargetLibraryInfo(
162 #else
163    new llvm::TargetLibraryInfoImpl(
164 #endif
165    llvm::Triple(triple)));
166 }
167
168 extern "C"
169 void
170 gallivm_dispose_target_library_info(LLVMTargetLibraryInfoRef library_info)
171 {
172    delete reinterpret_cast<
173 #if HAVE_LLVM < 0x0307
174    llvm::TargetLibraryInfo
175 #else
176    llvm::TargetLibraryInfoImpl
177 #endif
178    *>(library_info);
179 }
180
181
182 #if HAVE_LLVM < 0x0304
183
184 extern "C"
185 void
186 LLVMSetAlignmentBackport(LLVMValueRef V,
187                          unsigned Bytes)
188 {
189    switch (LLVMGetInstructionOpcode(V)) {
190    case LLVMLoad:
191       llvm::unwrap<llvm::LoadInst>(V)->setAlignment(Bytes);
192       break;
193    case LLVMStore:
194       llvm::unwrap<llvm::StoreInst>(V)->setAlignment(Bytes);
195       break;
196    default:
197       assert(0);
198       break;
199    }
200 }
201
202 #endif
203
204
205 #if HAVE_LLVM < 0x0306
206 typedef llvm::JITMemoryManager BaseMemoryManager;
207 #else
208 typedef llvm::RTDyldMemoryManager BaseMemoryManager;
209 #endif
210
211
212 /*
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
215  * its behavior.
216  */
217 class DelegatingJITMemoryManager : public BaseMemoryManager {
218
219    protected:
220       virtual BaseMemoryManager *mgr() const = 0;
221
222    public:
223 #if HAVE_LLVM < 0x0306
224       /*
225        * From JITMemoryManager
226        */
227       virtual void setMemoryWritable() {
228          mgr()->setMemoryWritable();
229       }
230       virtual void setMemoryExecutable() {
231          mgr()->setMemoryExecutable();
232       }
233       virtual void setPoisonMemory(bool poison) {
234          mgr()->setPoisonMemory(poison);
235       }
236       virtual void AllocateGOT() {
237          mgr()->AllocateGOT();
238          /*
239           * isManagingGOT() is not virtual in base class so we can't delegate.
240           * Instead we mirror the value of HasGOT in our instance.
241           */
242          HasGOT = mgr()->isManagingGOT();
243       }
244       virtual uint8_t *getGOTBase() const {
245          return mgr()->getGOTBase();
246       }
247       virtual uint8_t *startFunctionBody(const llvm::Function *F,
248                                          uintptr_t &ActualSize) {
249          return mgr()->startFunctionBody(F, ActualSize);
250       }
251       virtual uint8_t *allocateStub(const llvm::GlobalValue *F,
252                                     unsigned StubSize,
253                                     unsigned Alignment) {
254          return mgr()->allocateStub(F, StubSize, Alignment);
255       }
256       virtual void endFunctionBody(const llvm::Function *F,
257                                    uint8_t *FunctionStart,
258                                    uint8_t *FunctionEnd) {
259          mgr()->endFunctionBody(F, FunctionStart, FunctionEnd);
260       }
261       virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
262          return mgr()->allocateSpace(Size, Alignment);
263       }
264       virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
265          return mgr()->allocateGlobal(Size, Alignment);
266       }
267       virtual void deallocateFunctionBody(void *Body) {
268          mgr()->deallocateFunctionBody(Body);
269       }
270 #if HAVE_LLVM < 0x0304
271       virtual uint8_t *startExceptionTable(const llvm::Function *F,
272                                            uintptr_t &ActualSize) {
273          return mgr()->startExceptionTable(F, ActualSize);
274       }
275       virtual void endExceptionTable(const llvm::Function *F,
276                                      uint8_t *TableStart,
277                                      uint8_t *TableEnd,
278                                      uint8_t *FrameRegister) {
279          mgr()->endExceptionTable(F, TableStart, TableEnd,
280                                   FrameRegister);
281       }
282       virtual void deallocateExceptionTable(void *ET) {
283          mgr()->deallocateExceptionTable(ET);
284       }
285 #endif
286       virtual bool CheckInvariants(std::string &s) {
287          return mgr()->CheckInvariants(s);
288       }
289       virtual size_t GetDefaultCodeSlabSize() {
290          return mgr()->GetDefaultCodeSlabSize();
291       }
292       virtual size_t GetDefaultDataSlabSize() {
293          return mgr()->GetDefaultDataSlabSize();
294       }
295       virtual size_t GetDefaultStubSlabSize() {
296          return mgr()->GetDefaultStubSlabSize();
297       }
298       virtual unsigned GetNumCodeSlabs() {
299          return mgr()->GetNumCodeSlabs();
300       }
301       virtual unsigned GetNumDataSlabs() {
302          return mgr()->GetNumDataSlabs();
303       }
304       virtual unsigned GetNumStubSlabs() {
305          return mgr()->GetNumStubSlabs();
306       }
307 #endif
308
309       /*
310        * From RTDyldMemoryManager
311        */
312 #if HAVE_LLVM >= 0x0304
313       virtual uint8_t *allocateCodeSection(uintptr_t Size,
314                                            unsigned Alignment,
315                                            unsigned SectionID,
316                                            llvm::StringRef SectionName) {
317          return mgr()->allocateCodeSection(Size, Alignment, SectionID,
318                                            SectionName);
319       }
320 #else
321       virtual uint8_t *allocateCodeSection(uintptr_t Size,
322                                            unsigned Alignment,
323                                            unsigned SectionID) {
324          return mgr()->allocateCodeSection(Size, Alignment, SectionID);
325       }
326 #endif
327       virtual uint8_t *allocateDataSection(uintptr_t Size,
328                                            unsigned Alignment,
329                                            unsigned SectionID,
330 #if HAVE_LLVM >= 0x0304
331                                            llvm::StringRef SectionName,
332 #endif
333                                            bool IsReadOnly) {
334          return mgr()->allocateDataSection(Size, Alignment, SectionID,
335 #if HAVE_LLVM >= 0x0304
336                                            SectionName,
337 #endif
338                                            IsReadOnly);
339       }
340 #if HAVE_LLVM >= 0x0304
341       virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
342          mgr()->registerEHFrames(Addr, LoadAddr, Size);
343       }
344       virtual void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) {
345          mgr()->deregisterEHFrames(Addr, LoadAddr, Size);
346       }
347 #else
348       virtual void registerEHFrames(llvm::StringRef SectionData) {
349          mgr()->registerEHFrames(SectionData);
350       }
351 #endif
352       virtual void *getPointerToNamedFunction(const std::string &Name,
353                                               bool AbortOnFailure=true) {
354          return mgr()->getPointerToNamedFunction(Name, AbortOnFailure);
355       }
356 #if HAVE_LLVM <= 0x0303
357       virtual bool applyPermissions(std::string *ErrMsg = 0) {
358          return mgr()->applyPermissions(ErrMsg);
359       }
360 #else
361       virtual bool finalizeMemory(std::string *ErrMsg = 0) {
362          return mgr()->finalizeMemory(ErrMsg);
363       }
364 #endif
365 };
366
367
368 /*
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.
378  */
379 class ShaderMemoryManager : public DelegatingJITMemoryManager {
380
381    BaseMemoryManager *TheMM;
382
383    struct GeneratedCode {
384       typedef std::vector<void *> Vec;
385       Vec FunctionBody, ExceptionTable;
386       BaseMemoryManager *TheMM;
387
388       GeneratedCode(BaseMemoryManager *MM) {
389          TheMM = MM;
390       }
391
392       ~GeneratedCode() {
393          /*
394           * Deallocate things as previously requested and
395           * free shared manager when no longer used.
396           */
397 #if HAVE_LLVM < 0x0306
398          Vec::iterator i;
399
400          assert(TheMM);
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 */
408       }
409    };
410
411    GeneratedCode *code;
412
413    BaseMemoryManager *mgr() const {
414       return TheMM;
415    }
416
417    public:
418
419       ShaderMemoryManager(BaseMemoryManager* MM) {
420          TheMM = MM;
421          code = new GeneratedCode(MM);
422       }
423
424       virtual ~ShaderMemoryManager() {
425          /*
426           * 'code' is purposely not deleted.  It is the user's responsibility
427           * to call getGeneratedCode() and freeGeneratedCode().
428           */
429       }
430
431       struct lp_generated_code *getGeneratedCode() {
432          return (struct lp_generated_code *) code;
433       }
434
435       static void freeGeneratedCode(struct lp_generated_code *code) {
436          delete (GeneratedCode *) code;
437       }
438
439 #if HAVE_LLVM < 0x0304
440       virtual void deallocateExceptionTable(void *ET) {
441          // remember for later deallocation
442          code->ExceptionTable.push_back(ET);
443       }
444 #endif
445
446       virtual void deallocateFunctionBody(void *Body) {
447          // remember for later deallocation
448          code->FunctionBody.push_back(Body);
449       }
450 };
451
452
453 /**
454  * Same as LLVMCreateJITCompilerForModule, but:
455  * - allows using MCJIT and enabling AVX feature where available.
456  * - set target options
457  *
458  * See also:
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
462  */
463 extern "C"
464 LLVMBool
465 lp_build_create_jit_compiler_for_module(LLVMExecutionEngineRef *OutJIT,
466                                         lp_generated_code **OutCode,
467                                         LLVMModuleRef M,
468                                         LLVMMCJITMemoryManagerRef CMM,
469                                         unsigned OptLevel,
470                                         int useMCJIT,
471                                         char **OutError)
472 {
473    using namespace llvm;
474
475    std::string Error;
476 #if HAVE_LLVM >= 0x0306
477    EngineBuilder builder(std::unique_ptr<Module>(unwrap(M)));
478 #else
479    EngineBuilder builder(unwrap(M));
480 #endif
481
482    /**
483     * LLVM 3.1+ haven't more "extern unsigned llvm::StackAlignmentOverride" and
484     * friends for configuring code generation options, like stack alignment.
485     */
486    TargetOptions options;
487 #if defined(PIPE_ARCH_X86)
488    options.StackAlignmentOverride = 4;
489 #if HAVE_LLVM < 0x0304
490    options.RealignStack = true;
491 #endif
492 #endif
493
494 #if defined(DEBUG) && HAVE_LLVM < 0x0307
495    options.JITEmitDebugInfo = true;
496 #endif
497
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;
503 #endif
504 #if HAVE_LLVM < 0x0307
505    options.NoFramePointerElim = true;
506 #endif
507 #endif
508
509    builder.setEngineKind(EngineKind::JIT)
510           .setErrorStr(&Error)
511           .setTargetOptions(options)
512           .setOptLevel((CodeGenOpt::Level)OptLevel);
513
514    if (useMCJIT) {
515 #if HAVE_LLVM < 0x0306
516        builder.setUseMCJIT(true);
517 #endif
518 #ifdef _WIN32
519        /*
520         * MCJIT works on Windows, but currently only through ELF object format.
521         */
522        std::string targetTriple = llvm::sys::getProcessTriple();
523        targetTriple.append("-elf");
524        unwrap(M)->setTargetTriple(targetTriple);
525 #endif
526    }
527
528    llvm::SmallVector<std::string, 16> MAttrs;
529
530 #if defined(PIPE_ARCH_X86) || defined(PIPE_ARCH_X86_64)
531    /*
532     * We need to unset attributes because sometimes LLVM mistakenly assumes
533     * certain features are present given the processor name.
534     *
535     * https://bugs.freedesktop.org/show_bug.cgi?id=92214
536     * http://llvm.org/PR25021
537     * http://llvm.org/PR19429
538     * http://llvm.org/PR16721
539     */
540    MAttrs.push_back(util_cpu_caps.has_sse    ? "+sse"    : "-sse"   );
541    MAttrs.push_back(util_cpu_caps.has_sse2   ? "+sse2"   : "-sse2"  );
542    MAttrs.push_back(util_cpu_caps.has_sse3   ? "+sse3"   : "-sse3"  );
543    MAttrs.push_back(util_cpu_caps.has_ssse3  ? "+ssse3"  : "-ssse3" );
544 #if HAVE_LLVM >= 0x0304
545    MAttrs.push_back(util_cpu_caps.has_sse4_1 ? "+sse4.1" : "-sse4.1");
546 #else
547    MAttrs.push_back(util_cpu_caps.has_sse4_1 ? "+sse41"  : "-sse41" );
548 #endif
549 #if HAVE_LLVM >= 0x0304
550    MAttrs.push_back(util_cpu_caps.has_sse4_2 ? "+sse4.2" : "-sse4.2");
551 #else
552    MAttrs.push_back(util_cpu_caps.has_sse4_2 ? "+sse42"  : "-sse42" );
553 #endif
554    /*
555     * AVX feature is not automatically detected from CPUID by the X86 target
556     * yet, because the old (yet default) JIT engine is not capable of
557     * emitting the opcodes. On newer llvm versions it is and at least some
558     * versions (tested with 3.3) will emit avx opcodes without this anyway.
559     */
560    MAttrs.push_back(util_cpu_caps.has_avx  ? "+avx"  : "-avx");
561    MAttrs.push_back(util_cpu_caps.has_f16c ? "+f16c" : "-f16c");
562    MAttrs.push_back(util_cpu_caps.has_avx2 ? "+avx2" : "-avx2");
563 #endif
564
565 #if defined(PIPE_ARCH_PPC)
566    MAttrs.push_back(util_cpu_caps.has_altivec ? "+altivec" : "-altivec");
567 #if HAVE_LLVM >= 0x0304
568    /*
569     * Make sure VSX instructions are disabled
570     * See LLVM bug https://llvm.org/bugs/show_bug.cgi?id=25503#c7
571     */
572    if (util_cpu_caps.has_altivec) {
573       MAttrs.push_back("-vsx");
574    }
575 #endif
576 #endif
577
578    builder.setMAttrs(MAttrs);
579
580 #if HAVE_LLVM >= 0x0305
581    StringRef MCPU = llvm::sys::getHostCPUName();
582    /*
583     * The cpu bits are no longer set automatically, so need to set mcpu manually.
584     * Note that the MAttrs set above will be sort of ignored (since we should
585     * not set any which would not be set by specifying the cpu anyway).
586     * It ought to be safe though since getHostCPUName() should include bits
587     * not only from the cpu but environment as well (for instance if it's safe
588     * to use avx instructions which need OS support). According to
589     * http://llvm.org/bugs/show_bug.cgi?id=19429 however if I understand this
590     * right it may be necessary to specify older cpu (or disable mattrs) though
591     * when not using MCJIT so no instructions are generated which the old JIT
592     * can't handle. Not entirely sure if we really need to do anything yet.
593     */
594    builder.setMCPU(MCPU);
595 #endif
596
597    ShaderMemoryManager *MM = NULL;
598    if (useMCJIT) {
599 #if HAVE_LLVM > 0x0303
600        BaseMemoryManager* JMM = reinterpret_cast<BaseMemoryManager*>(CMM);
601        MM = new ShaderMemoryManager(JMM);
602        *OutCode = MM->getGeneratedCode();
603
604 #if HAVE_LLVM >= 0x0306
605        builder.setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager>(MM));
606        MM = NULL; // ownership taken by std::unique_ptr
607 #else
608        builder.setMCJITMemoryManager(MM);
609 #endif
610 #endif
611    } else {
612 #if HAVE_LLVM < 0x0306
613        BaseMemoryManager* JMM = reinterpret_cast<BaseMemoryManager*>(CMM);
614        MM = new ShaderMemoryManager(JMM);
615        *OutCode = MM->getGeneratedCode();
616
617        builder.setJITMemoryManager(MM);
618 #else
619        assert(0);
620 #endif
621    }
622
623    ExecutionEngine *JIT;
624
625    JIT = builder.create();
626    if (JIT) {
627       *OutJIT = wrap(JIT);
628       return 0;
629    }
630    lp_free_generated_code(*OutCode);
631    *OutCode = 0;
632    delete MM;
633    *OutError = strdup(Error.c_str());
634    return 1;
635 }
636
637
638 extern "C"
639 void
640 lp_free_generated_code(struct lp_generated_code *code)
641 {
642    ShaderMemoryManager::freeGeneratedCode(code);
643 }
644
645 extern "C"
646 LLVMMCJITMemoryManagerRef
647 lp_get_default_memory_manager()
648 {
649    BaseMemoryManager *mm;
650 #if HAVE_LLVM < 0x0306
651    mm = llvm::JITMemoryManager::CreateDefaultMemManager();
652 #else
653    mm = new llvm::SectionMemoryManager();
654 #endif
655    return reinterpret_cast<LLVMMCJITMemoryManagerRef>(mm);
656 }
657
658 extern "C"
659 void
660 lp_free_memory_manager(LLVMMCJITMemoryManagerRef memorymgr)
661 {
662    delete reinterpret_cast<BaseMemoryManager*>(memorymgr);
663 }