• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2012-2016 Francisco Jerez
3 // Copyright 2012-2016 Advanced Micro Devices, Inc.
4 // Copyright 2014-2016 Jan Vesely
5 // Copyright 2014-2015 Serge Martin
6 // Copyright 2015 Zoltan Gilian
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 // OTHER DEALINGS IN THE SOFTWARE.
25 //
26 
27 #include <llvm/IR/DiagnosticPrinter.h>
28 #include <llvm/IR/DiagnosticInfo.h>
29 #include <llvm/IR/LLVMContext.h>
30 #include <llvm/IR/Module.h>
31 #include <llvm/Support/raw_ostream.h>
32 #include <llvm/Transforms/IPO/Internalize.h>
33 #include <llvm-c/Target.h>
34 #ifdef HAVE_CLOVER_SPIRV
35 #include <LLVMSPIRVLib/LLVMSPIRVLib.h>
36 #endif
37 
38 #include <llvm-c/TargetMachine.h>
39 #include <llvm-c/Transforms/PassBuilder.h>
40 #include <llvm/Support/CBindingWrapping.h>
41 #include <clang/CodeGen/CodeGenAction.h>
42 #include <clang/Lex/PreprocessorOptions.h>
43 #include <clang/Frontend/TextDiagnosticBuffer.h>
44 #include <clang/Frontend/TextDiagnosticPrinter.h>
45 #include <clang/Basic/TargetInfo.h>
46 
47 // We need to include internal headers last, because the internal headers
48 // include CL headers which have #define's like:
49 //
50 //#define cl_khr_gl_sharing 1
51 //#define cl_khr_icd 1
52 //
53 // Which will break the compilation of clang/Basic/OpenCLOptions.h
54 
55 #include "core/error.hpp"
56 #include "llvm/codegen.hpp"
57 #include "llvm/compat.hpp"
58 #include "llvm/invocation.hpp"
59 #include "llvm/metadata.hpp"
60 #include "llvm/util.hpp"
61 #ifdef HAVE_CLOVER_SPIRV
62 #include "spirv/invocation.hpp"
63 #endif
64 #include "util/algorithm.hpp"
65 
66 
67 using clover::binary;
68 using clover::device;
69 using clover::build_error;
70 using clover::invalid_build_options_error;
71 using clover::map;
72 using clover::header_map;
73 using namespace clover::llvm;
74 
75 using ::llvm::Function;
76 using ::llvm::LLVMContext;
77 using ::llvm::Module;
78 using ::llvm::raw_string_ostream;
79 
80 namespace {
81 
82    static const cl_version ANY_VERSION = CL_MAKE_VERSION(9, 9, 9);
83    const cl_version cl_versions[] = {
84       CL_MAKE_VERSION(1, 1, 0),
85       CL_MAKE_VERSION(1, 2, 0),
86       CL_MAKE_VERSION(2, 0, 0),
87       CL_MAKE_VERSION(2, 1, 0),
88       CL_MAKE_VERSION(2, 2, 0),
89       CL_MAKE_VERSION(3, 0, 0),
90    };
91 
92     struct clc_version_lang_std {
93         cl_version version_number; // CLC Version
94         clang::LangStandard::Kind clc_lang_standard;
95     };
96 
97     const clc_version_lang_std cl_version_lang_stds[] = {
98        { CL_MAKE_VERSION(1, 0, 0), clang::LangStandard::lang_opencl10},
99        { CL_MAKE_VERSION(1, 1, 0), clang::LangStandard::lang_opencl11},
100        { CL_MAKE_VERSION(1, 2, 0), clang::LangStandard::lang_opencl12},
101        { CL_MAKE_VERSION(2, 0, 0), clang::LangStandard::lang_opencl20},
102 #if LLVM_VERSION_MAJOR >= 12
103        { CL_MAKE_VERSION(3, 0, 0), clang::LangStandard::lang_opencl30},
104 #endif
105     };
106 
107    bool
are_equal(cl_version_khr version1,cl_version_khr version2,bool ignore_patch_version=false)108    are_equal(cl_version_khr version1, cl_version_khr version2,
109              bool ignore_patch_version = false) {
110       if (ignore_patch_version) {
111          version1 &= ~CL_VERSION_PATCH_MASK_KHR;
112          version2 &= ~CL_VERSION_PATCH_MASK_KHR;
113       }
114       return version1 == version2;
115    }
116 
117    void
init_targets()118    init_targets() {
119       static bool targets_initialized = false;
120       if (!targets_initialized) {
121          LLVMInitializeAllTargets();
122          LLVMInitializeAllTargetInfos();
123          LLVMInitializeAllTargetMCs();
124          LLVMInitializeAllAsmParsers();
125          LLVMInitializeAllAsmPrinters();
126          targets_initialized = true;
127       }
128    }
129 
130    void
diagnostic_handler(const::llvm::DiagnosticInfo & di,void * data)131    diagnostic_handler(const ::llvm::DiagnosticInfo &di, void *data) {
132       if (di.getSeverity() == ::llvm::DS_Error) {
133          raw_string_ostream os { *reinterpret_cast<std::string *>(data) };
134          ::llvm::DiagnosticPrinterRawOStream printer { os };
135          di.print(printer);
136          throw build_error();
137       }
138    }
139 
140    std::unique_ptr<LLVMContext>
create_context(std::string & r_log)141    create_context(std::string &r_log) {
142       init_targets();
143       std::unique_ptr<LLVMContext> ctx { new LLVMContext };
144 
145       ctx->setDiagnosticHandlerCallBack(diagnostic_handler, &r_log);
146       return ctx;
147    }
148 
149    const struct clc_version_lang_std&
get_cl_lang_standard(unsigned requested,unsigned max=ANY_VERSION)150    get_cl_lang_standard(unsigned requested, unsigned max = ANY_VERSION) {
151        for (const struct clc_version_lang_std &version : cl_version_lang_stds) {
152            if (version.version_number == max ||
153                    version.version_number == requested) {
154                return version;
155            }
156        }
157        throw build_error("Unknown/Unsupported language version");
158    }
159 
160    const cl_version
get_cl_version(cl_version requested,cl_version max=ANY_VERSION)161    get_cl_version(cl_version requested,
162                   cl_version max = ANY_VERSION) {
163       for (const auto &version : cl_versions) {
164          if (are_equal(version, max, true) ||
165              are_equal(version, requested, true)) {
166             return version;
167          }
168       }
169       throw build_error("Unknown/Unsupported language version");
170    }
171 
172    clang::LangStandard::Kind
get_lang_standard_from_version(const cl_version input_version,bool is_build_opt=false)173    get_lang_standard_from_version(const cl_version input_version,
174                                   bool is_build_opt = false) {
175 
176        //Per CL 2.0 spec, section 5.8.4.5:
177        //  If it's an option, use the value directly.
178        //  If it's a device version, clamp to max 1.x version, a.k.a. 1.2
179       const cl_version version =
180          get_cl_version(input_version, is_build_opt ? ANY_VERSION : 120);
181 
182       const struct clc_version_lang_std standard =
183          get_cl_lang_standard(version);
184 
185       return standard.clc_lang_standard;
186    }
187 
188    clang::LangStandard::Kind
get_language_version(const std::vector<std::string> & opts,const cl_version device_version)189    get_language_version(const std::vector<std::string> &opts,
190                         const cl_version device_version) {
191 
192       const std::string search = "-cl-std=CL";
193 
194       for (auto &opt: opts) {
195          auto pos = opt.find(search);
196          if (pos == 0){
197             std::stringstream ver_str(opt.substr(pos + search.size()));
198             unsigned int ver_major = 0;
199             char separator = '\0';
200             unsigned int ver_minor = 0;
201             ver_str >> ver_major >> separator >> ver_minor;
202             if (ver_str.fail() || ver_str.bad() || !ver_str.eof() ||
203                  separator != '.') {
204                throw build_error();
205             }
206             const auto ver = CL_MAKE_VERSION_KHR(ver_major, ver_minor, 0);
207             const auto device_ver = get_cl_version(device_version);
208             const auto requested = get_cl_version(ver);
209             if (requested > device_ver) {
210                throw build_error();
211             }
212             return get_lang_standard_from_version(ver, true);
213          }
214       }
215 
216       return get_lang_standard_from_version(device_version);
217    }
218 
219    std::unique_ptr<clang::CompilerInstance>
create_compiler_instance(const device & dev,const std::string & ir_target,const std::vector<std::string> & opts,std::string & r_log)220    create_compiler_instance(const device &dev, const std::string& ir_target,
221                             const std::vector<std::string> &opts,
222                             std::string &r_log) {
223       std::unique_ptr<clang::CompilerInstance> c { new clang::CompilerInstance };
224       clang::TextDiagnosticBuffer *diag_buffer = new clang::TextDiagnosticBuffer;
225       clang::DiagnosticsEngine diag { new clang::DiagnosticIDs,
226             new clang::DiagnosticOptions, diag_buffer };
227 
228       // Parse the compiler options.  A file name should be present at the end
229       // and must have the .cl extension in order for the CompilerInvocation
230       // class to recognize it as an OpenCL source file.
231 #if LLVM_VERSION_MAJOR >= 12
232       std::vector<const char *> copts;
233 #if LLVM_VERSION_MAJOR == 15 || LLVM_VERSION_MAJOR == 16
234       // Before LLVM commit 702d5de4 opaque pointers were supported but not enabled
235       // by default when building LLVM. They were made default in commit 702d5de4.
236       // LLVM commit d69e9f9d introduced -opaque-pointers/-no-opaque-pointers cc1
237       // options to enable or disable them whatever the LLVM default is.
238 
239       // Those two commits follow llvmorg-15-init and precede llvmorg-15.0.0-rc1 tags.
240 
241       // Since LLVM commit d785a8ea, the CLANG_ENABLE_OPAQUE_POINTERS build option of
242       // LLVM is removed, meaning there is no way to build LLVM with opaque pointers
243       // enabled by default.
244       // It was said at the time it was still possible to explicitly disable opaque
245       // pointers via cc1 -no-opaque-pointers option, but it is known a later commit
246       // broke backward compatibility provided by -no-opaque-pointers as verified with
247       // arbitrary commit d7d586e5, so there is no way to use opaque pointers starting
248       // with LLVM 16.
249 
250       // Those two commits follow llvmorg-16-init and precede llvmorg-16.0.0-rc1 tags.
251 
252       // Since Mesa commit 977dbfc9 opaque pointers are properly implemented in Clover
253       // and used.
254 
255       // If we don't pass -opaque-pointers to Clang on LLVM versions supporting opaque
256       // pointers but disabling them by default, there will be an API mismatch between
257       // Mesa and LLVM and Clover will not work.
258       copts.push_back("-opaque-pointers");
259 #endif
260       for (auto &opt : opts) {
261          if (opt == "-cl-denorms-are-zero")
262             copts.push_back("-fdenormal-fp-math=positive-zero");
263          else
264             copts.push_back(opt.c_str());
265       }
266 #else
267       const std::vector<const char *> copts =
268          map(std::mem_fn(&std::string::c_str), opts);
269 #endif
270 
271       const target &target = ir_target;
272       const cl_version device_clc_version = dev.device_clc_version();
273 
274       if (!compat::create_compiler_invocation_from_args(
275              c->getInvocation(), copts, diag))
276          throw invalid_build_options_error();
277 
278       diag_buffer->FlushDiagnostics(diag);
279       if (diag.hasErrorOccurred())
280          throw invalid_build_options_error();
281 
282       c->getTargetOpts().CPU = target.cpu;
283       c->getTargetOpts().Triple = target.triple;
284       c->getLangOpts().NoBuiltin = true;
285 
286 #if LLVM_VERSION_MAJOR >= 13
287       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_generic_address_space");
288       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_pipes");
289       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_device_enqueue");
290       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_program_scope_global_variables");
291       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_subgroups");
292       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_work_group_collective_functions");
293       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_atomic_scope_device");
294       c->getTargetOpts().OpenCLExtensionsAsWritten.push_back("-__opencl_c_atomic_order_seq_cst");
295 #endif
296 
297       // This is a workaround for a Clang bug which causes the number
298       // of warnings and errors to be printed to stderr.
299       // http://www.llvm.org/bugs/show_bug.cgi?id=19735
300       c->getDiagnosticOpts().ShowCarets = false;
301 
302       compat::compiler_set_lang_defaults(c, compat::ik_opencl,
303                                 ::llvm::Triple(target.triple),
304                                 get_language_version(opts, device_clc_version));
305 
306       c->createDiagnostics(new clang::TextDiagnosticPrinter(
307                               *new raw_string_ostream(r_log),
308                               &c->getDiagnosticOpts(), true));
309 
310       c->setTarget(clang::TargetInfo::CreateTargetInfo(
311                            c->getDiagnostics(), c->getInvocation().TargetOpts));
312 
313       return c;
314    }
315 
316    std::unique_ptr<Module>
compile(LLVMContext & ctx,clang::CompilerInstance & c,const std::string & name,const std::string & source,const header_map & headers,const device & dev,const std::string & opts,bool use_libclc,std::string & r_log)317    compile(LLVMContext &ctx, clang::CompilerInstance &c,
318            const std::string &name, const std::string &source,
319            const header_map &headers, const device &dev,
320            const std::string &opts, bool use_libclc, std::string &r_log) {
321       c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
322       c.getHeaderSearchOpts().UseBuiltinIncludes = true;
323       c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
324       c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
325 
326       if (use_libclc) {
327          // Add libclc generic search path
328          c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
329                                          clang::frontend::Angled,
330                                          false, false);
331 
332          // Add libclc include
333          c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
334       } else {
335          // Add opencl-c generic search path
336          c.getHeaderSearchOpts().AddPath(CLANG_RESOURCE_DIR,
337                                          clang::frontend::Angled,
338                                          false, false);
339 
340          // Add opencl include
341          c.getPreprocessorOpts().Includes.push_back("opencl-c.h");
342       }
343 
344       // Add definition for the OpenCL version
345       const auto dev_version = dev.device_version();
346       c.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=" +
347                                           std::to_string(CL_VERSION_MAJOR_KHR(dev_version)) +
348                                           std::to_string(CL_VERSION_MINOR_KHR(dev_version)) + "0");
349 
350       if (CL_VERSION_MAJOR(dev.version) >= 3) {
351          const auto features = dev.opencl_c_features();
352          for (const auto &feature : features)
353             c.getPreprocessorOpts().addMacroDef(feature.name);
354       }
355 
356       // clc.h requires that this macro be defined:
357       c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
358       c.getPreprocessorOpts().addRemappedFile(
359               name, ::llvm::MemoryBuffer::getMemBuffer(source).release());
360 
361       if (headers.size()) {
362          const std::string tmp_header_path = "/tmp/clover/";
363 
364          c.getHeaderSearchOpts().AddPath(tmp_header_path,
365                                          clang::frontend::Angled,
366                                          false, false);
367 
368          for (const auto &header : headers)
369             c.getPreprocessorOpts().addRemappedFile(
370                tmp_header_path + header.first,
371                ::llvm::MemoryBuffer::getMemBuffer(header.second).release());
372       }
373 
374       // Tell clang to link this file before performing any
375       // optimizations.  This is required so that we can replace calls
376       // to the OpenCL C barrier() builtin with calls to target
377       // intrinsics that have the noduplicate attribute.  This
378       // attribute will prevent Clang from creating illegal uses of
379       // barrier() (e.g. Moving barrier() inside a conditional that is
380       // no executed by all threads) during its optimizaton passes.
381       if (use_libclc) {
382          clang::CodeGenOptions::BitcodeFileToLink F;
383 
384          F.Filename = LIBCLC_LIBEXECDIR + dev.ir_target() + ".bc";
385          F.PropagateAttrs = true;
386          F.LinkFlags = ::llvm::Linker::Flags::None;
387          c.getCodeGenOpts().LinkBitcodeFiles.emplace_back(F);
388       }
389 
390       // undefine __IMAGE_SUPPORT__ for device without image support
391       if (!dev.image_support())
392          c.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
393 
394       // Compile the code
395       clang::EmitLLVMOnlyAction act(&ctx);
396       if (!c.ExecuteAction(act))
397          throw build_error();
398 
399       return act.takeModule();
400    }
401 
402 #ifdef HAVE_CLOVER_SPIRV
403    SPIRV::TranslatorOpts
get_spirv_translator_options(const device & dev)404    get_spirv_translator_options(const device &dev) {
405       const auto supported_versions = clover::spirv::supported_versions();
406       const auto max_supported = clover::spirv::to_spirv_version_encoding(supported_versions.back().version);
407       const auto maximum_spirv_version =
408          std::min(static_cast<SPIRV::VersionNumber>(max_supported),
409                   SPIRV::VersionNumber::MaximumVersion);
410 
411       SPIRV::TranslatorOpts::ExtensionsStatusMap spirv_extensions;
412       for (auto &ext : clover::spirv::supported_extensions()) {
413          #define EXT(X) if (ext == #X) spirv_extensions.insert({ SPIRV::ExtensionID::X, true });
414          #include <LLVMSPIRVLib/LLVMSPIRVExtensions.inc>
415          #undef EXT
416       }
417 
418       auto translator_opts = SPIRV::TranslatorOpts(maximum_spirv_version, spirv_extensions);
419 #if LLVM_VERSION_MAJOR >= 13
420       translator_opts.setPreserveOCLKernelArgTypeMetadataThroughString(true);
421 #endif
422       return translator_opts;
423    }
424 #endif
425 }
426 
427 binary
compile_program(const std::string & source,const header_map & headers,const device & dev,const std::string & opts,std::string & r_log)428 clover::llvm::compile_program(const std::string &source,
429                               const header_map &headers,
430                               const device &dev,
431                               const std::string &opts,
432                               std::string &r_log) {
433    if (has_flag(debug::clc))
434       debug::log(".cl", "// Options: " + opts + '\n' + source);
435 
436    auto ctx = create_context(r_log);
437    auto c = create_compiler_instance(dev, dev.ir_target(),
438                                      tokenize(opts + " input.cl"), r_log);
439    auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, true,
440                       r_log);
441 
442    if (has_flag(debug::llvm))
443       debug::log(".ll", print_module_bitcode(*mod));
444 
445    return build_module_library(*mod, binary::section::text_intermediate);
446 }
447 
448 namespace {
449    void
optimize(Module & mod,const std::string & ir_target,unsigned optimization_level,bool internalize_symbols)450    optimize(Module &mod,
451             const std::string& ir_target,
452             unsigned optimization_level,
453             bool internalize_symbols) {
454       // By default, the function internalizer pass will look for a function
455       // called "main" and then mark all other functions as internal.  Marking
456       // functions as internal enables the optimizer to perform optimizations
457       // like function inlining and global dead-code elimination.
458       //
459       // When there is no "main" function in a binary, the internalize pass will
460       // treat the binary like a library, and it won't internalize any functions.
461       // Since there is no "main" function in our kernels, we need to tell
462       // the internalizer pass that this binary is not a library by passing a
463       // list of kernel functions to the internalizer.  The internalizer will
464       // treat the functions in the list as "main" functions and internalize
465       // all of the other functions.
466       if (internalize_symbols) {
467          std::vector<std::string> names =
468             map(std::mem_fn(&Function::getName), get_kernels(mod));
469          internalizeModule(mod,
470                       [=](const ::llvm::GlobalValue &gv) {
471                          return std::find(names.begin(), names.end(),
472                                           gv.getName()) != names.end();
473                       });
474       }
475 
476 
477       const char *opt_str = NULL;
478       LLVMCodeGenOptLevel level;
479       switch (optimization_level) {
480       case 0:
481       default:
482          opt_str = "default<O0>";
483          level = LLVMCodeGenLevelNone;
484          break;
485       case 1:
486          opt_str = "default<O1>";
487          level = LLVMCodeGenLevelLess;
488          break;
489       case 2:
490          opt_str = "default<O2>";
491          level = LLVMCodeGenLevelDefault;
492          break;
493       case 3:
494          opt_str = "default<O3>";
495          level = LLVMCodeGenLevelAggressive;
496          break;
497       }
498 
499       const target &target = ir_target;
500       LLVMTargetRef targ;
501       char *err_message;
502 
503       if (LLVMGetTargetFromTriple(target.triple.c_str(), &targ, &err_message))
504          return;
505       LLVMTargetMachineRef tm =
506          LLVMCreateTargetMachine(targ, target.triple.c_str(),
507                                  target.cpu.c_str(), "", level,
508                                  LLVMRelocDefault, LLVMCodeModelDefault);
509 
510       if (!tm)
511          return;
512       LLVMPassBuilderOptionsRef opts = LLVMCreatePassBuilderOptions();
513       LLVMRunPasses(wrap(&mod), opt_str, tm, opts);
514 
515       LLVMDisposeTargetMachine(tm);
516    }
517 
518    std::unique_ptr<Module>
link(LLVMContext & ctx,const clang::CompilerInstance & c,const std::vector<binary> & binaries,std::string & r_log)519    link(LLVMContext &ctx, const clang::CompilerInstance &c,
520         const std::vector<binary> &binaries, std::string &r_log) {
521       std::unique_ptr<Module> mod { new Module("link", ctx) };
522       std::unique_ptr< ::llvm::Linker> linker { new ::llvm::Linker(*mod) };
523 
524       for (auto &b : binaries) {
525          if (linker->linkInModule(parse_module_library(b, ctx, r_log)))
526             throw build_error();
527       }
528 
529       return mod;
530    }
531 }
532 
533 binary
link_program(const std::vector<binary> & binaries,const device & dev,const std::string & opts,std::string & r_log)534 clover::llvm::link_program(const std::vector<binary> &binaries,
535                            const device &dev, const std::string &opts,
536                            std::string &r_log) {
537    std::vector<std::string> options = tokenize(opts + " input.cl");
538    const bool create_library = count("-create-library", options);
539    erase_if(equals("-create-library"), options);
540 
541    auto ctx = create_context(r_log);
542    auto c = create_compiler_instance(dev, dev.ir_target(), options, r_log);
543    auto mod = link(*ctx, *c, binaries, r_log);
544 
545    optimize(*mod, dev.ir_target(), c->getCodeGenOpts().OptimizationLevel, !create_library);
546 
547    static std::atomic_uint seq(0);
548    const std::string id = "." + mod->getModuleIdentifier() + "-" +
549       std::to_string(seq++);
550 
551    if (has_flag(debug::llvm))
552       debug::log(id + ".ll", print_module_bitcode(*mod));
553 
554    if (create_library) {
555       return build_module_library(*mod, binary::section::text_library);
556 
557    } else if (dev.ir_format() == PIPE_SHADER_IR_NATIVE) {
558       if (has_flag(debug::native))
559          debug::log(id +  ".asm", print_module_native(*mod, dev.ir_target()));
560 
561       return build_module_native(*mod, dev.ir_target(), *c, r_log);
562 
563    } else {
564       unreachable("Unsupported IR.");
565    }
566 }
567 
568 #ifdef HAVE_CLOVER_SPIRV
569 binary
compile_to_spirv(const std::string & source,const header_map & headers,const device & dev,const std::string & opts,std::string & r_log)570 clover::llvm::compile_to_spirv(const std::string &source,
571                                const header_map &headers,
572                                const device &dev,
573                                const std::string &opts,
574                                std::string &r_log) {
575    if (has_flag(debug::clc))
576       debug::log(".cl", "// Options: " + opts + '\n' + source);
577 
578    auto ctx = create_context(r_log);
579    const std::string target = dev.address_bits() == 32u ?
580       "-spir-unknown-unknown" :
581       "-spir64-unknown-unknown";
582    auto c = create_compiler_instance(dev, target,
583                                      tokenize(opts + " -O0 -fgnu89-inline input.cl"), r_log);
584    auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, false,
585                       r_log);
586 
587    if (has_flag(debug::llvm))
588       debug::log(".ll", print_module_bitcode(*mod));
589 
590    const auto spirv_options = get_spirv_translator_options(dev);
591 
592    std::string error_msg;
593    std::ostringstream os;
594    if (!::llvm::writeSpirv(mod.get(), spirv_options, os, error_msg)) {
595       r_log += "Translation from LLVM IR to SPIR-V failed: " + error_msg + ".\n";
596       throw error(CL_INVALID_VALUE);
597    }
598 
599    const std::string osContent = os.str();
600    std::string binary(osContent.begin(), osContent.end());
601    if (binary.empty()) {
602       r_log += "Failed to retrieve SPIR-V binary.\n";
603       throw error(CL_INVALID_VALUE);
604    }
605 
606    if (has_flag(debug::spirv))
607       debug::log(".spvasm", spirv::print_module(binary, dev.device_version()));
608 
609    return spirv::compile_program(binary, dev, r_log);
610 }
611 #endif
612