Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/gallium/frontends/clover/llvm/invocation.cpp
4573 views
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/Support/raw_ostream.h>
31
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
32
#include <llvm-c/Target.h>
33
#ifdef HAVE_CLOVER_SPIRV
34
#include <LLVMSPIRVLib/LLVMSPIRVLib.h>
35
#endif
36
37
#include <clang/CodeGen/CodeGenAction.h>
38
#include <clang/Lex/PreprocessorOptions.h>
39
#include <clang/Frontend/TextDiagnosticBuffer.h>
40
#include <clang/Frontend/TextDiagnosticPrinter.h>
41
#include <clang/Basic/TargetInfo.h>
42
43
// We need to include internal headers last, because the internal headers
44
// include CL headers which have #define's like:
45
//
46
//#define cl_khr_gl_sharing 1
47
//#define cl_khr_icd 1
48
//
49
// Which will break the compilation of clang/Basic/OpenCLOptions.h
50
51
#include "core/error.hpp"
52
#include "llvm/codegen.hpp"
53
#include "llvm/compat.hpp"
54
#include "llvm/invocation.hpp"
55
#include "llvm/metadata.hpp"
56
#include "llvm/util.hpp"
57
#ifdef HAVE_CLOVER_SPIRV
58
#include "spirv/invocation.hpp"
59
#endif
60
#include "util/algorithm.hpp"
61
62
63
using clover::module;
64
using clover::device;
65
using clover::build_error;
66
using clover::invalid_build_options_error;
67
using clover::map;
68
using clover::header_map;
69
using namespace clover::llvm;
70
71
using ::llvm::Function;
72
using ::llvm::LLVMContext;
73
using ::llvm::Module;
74
using ::llvm::raw_string_ostream;
75
76
namespace {
77
78
static const cl_version ANY_VERSION = CL_MAKE_VERSION(9, 9, 9);
79
const cl_version cl_versions[] = {
80
CL_MAKE_VERSION(1, 1, 0),
81
CL_MAKE_VERSION(1, 2, 0),
82
CL_MAKE_VERSION(2, 0, 0),
83
CL_MAKE_VERSION(2, 1, 0),
84
CL_MAKE_VERSION(2, 2, 0),
85
CL_MAKE_VERSION(3, 0, 0),
86
};
87
88
struct clc_version_lang_std {
89
cl_version version_number; // CLC Version
90
clang::LangStandard::Kind clc_lang_standard;
91
};
92
93
const clc_version_lang_std cl_version_lang_stds[] = {
94
{ CL_MAKE_VERSION(1, 0, 0), clang::LangStandard::lang_opencl10},
95
{ CL_MAKE_VERSION(1, 1, 0), clang::LangStandard::lang_opencl11},
96
{ CL_MAKE_VERSION(1, 2, 0), clang::LangStandard::lang_opencl12},
97
{ CL_MAKE_VERSION(2, 0, 0), clang::LangStandard::lang_opencl20},
98
#if LLVM_VERSION_MAJOR >= 12
99
{ CL_MAKE_VERSION(3, 0, 0), clang::LangStandard::lang_opencl30},
100
#endif
101
};
102
103
bool
104
are_equal(cl_version_khr version1, cl_version_khr version2,
105
bool ignore_patch_version = false) {
106
if (ignore_patch_version) {
107
version1 &= ~CL_VERSION_PATCH_MASK_KHR;
108
version2 &= ~CL_VERSION_PATCH_MASK_KHR;
109
}
110
return version1 == version2;
111
}
112
113
void
114
init_targets() {
115
static bool targets_initialized = false;
116
if (!targets_initialized) {
117
LLVMInitializeAllTargets();
118
LLVMInitializeAllTargetInfos();
119
LLVMInitializeAllTargetMCs();
120
LLVMInitializeAllAsmParsers();
121
LLVMInitializeAllAsmPrinters();
122
targets_initialized = true;
123
}
124
}
125
126
void
127
diagnostic_handler(const ::llvm::DiagnosticInfo &di, void *data) {
128
if (di.getSeverity() == ::llvm::DS_Error) {
129
raw_string_ostream os { *reinterpret_cast<std::string *>(data) };
130
::llvm::DiagnosticPrinterRawOStream printer { os };
131
di.print(printer);
132
throw build_error();
133
}
134
}
135
136
std::unique_ptr<LLVMContext>
137
create_context(std::string &r_log) {
138
init_targets();
139
std::unique_ptr<LLVMContext> ctx { new LLVMContext };
140
141
ctx->setDiagnosticHandlerCallBack(diagnostic_handler, &r_log);
142
return ctx;
143
}
144
145
const struct clc_version_lang_std&
146
get_cl_lang_standard(unsigned requested, unsigned max = ANY_VERSION) {
147
for (const struct clc_version_lang_std &version : cl_version_lang_stds) {
148
if (version.version_number == max ||
149
version.version_number == requested) {
150
return version;
151
}
152
}
153
throw build_error("Unknown/Unsupported language version");
154
}
155
156
const cl_version
157
get_cl_version(cl_version requested,
158
cl_version max = ANY_VERSION) {
159
for (const auto &version : cl_versions) {
160
if (are_equal(version, max, true) ||
161
are_equal(version, requested, true)) {
162
return version;
163
}
164
}
165
throw build_error("Unknown/Unsupported language version");
166
}
167
168
clang::LangStandard::Kind
169
get_lang_standard_from_version(const cl_version input_version,
170
bool is_build_opt = false) {
171
172
//Per CL 2.0 spec, section 5.8.4.5:
173
// If it's an option, use the value directly.
174
// If it's a device version, clamp to max 1.x version, a.k.a. 1.2
175
const cl_version version =
176
get_cl_version(input_version, is_build_opt ? ANY_VERSION : 120);
177
178
const struct clc_version_lang_std standard =
179
get_cl_lang_standard(version);
180
181
return standard.clc_lang_standard;
182
}
183
184
clang::LangStandard::Kind
185
get_language_version(const std::vector<std::string> &opts,
186
const cl_version device_version) {
187
188
const std::string search = "-cl-std=CL";
189
190
for (auto &opt: opts) {
191
auto pos = opt.find(search);
192
if (pos == 0){
193
std::stringstream ver_str(opt.substr(pos + search.size()));
194
unsigned int ver_major = 0;
195
char separator = '\0';
196
unsigned int ver_minor = 0;
197
ver_str >> ver_major >> separator >> ver_minor;
198
if (ver_str.fail() || ver_str.bad() || !ver_str.eof() ||
199
separator != '.') {
200
throw build_error();
201
}
202
const auto ver = CL_MAKE_VERSION_KHR(ver_major, ver_minor, 0);
203
const auto device_ver = get_cl_version(device_version);
204
const auto requested = get_cl_version(ver);
205
if (requested > device_ver) {
206
throw build_error();
207
}
208
return get_lang_standard_from_version(ver, true);
209
}
210
}
211
212
return get_lang_standard_from_version(device_version);
213
}
214
215
std::unique_ptr<clang::CompilerInstance>
216
create_compiler_instance(const device &dev, const std::string& ir_target,
217
const std::vector<std::string> &opts,
218
std::string &r_log) {
219
std::unique_ptr<clang::CompilerInstance> c { new clang::CompilerInstance };
220
clang::TextDiagnosticBuffer *diag_buffer = new clang::TextDiagnosticBuffer;
221
clang::DiagnosticsEngine diag { new clang::DiagnosticIDs,
222
new clang::DiagnosticOptions, diag_buffer };
223
224
// Parse the compiler options. A file name should be present at the end
225
// and must have the .cl extension in order for the CompilerInvocation
226
// class to recognize it as an OpenCL source file.
227
const std::vector<const char *> copts =
228
map(std::mem_fn(&std::string::c_str), opts);
229
230
const target &target = ir_target;
231
const cl_version device_clc_version = dev.device_clc_version();
232
233
if (!compat::create_compiler_invocation_from_args(
234
c->getInvocation(), copts, diag))
235
throw invalid_build_options_error();
236
237
diag_buffer->FlushDiagnostics(diag);
238
if (diag.hasErrorOccurred())
239
throw invalid_build_options_error();
240
241
c->getTargetOpts().CPU = target.cpu;
242
c->getTargetOpts().Triple = target.triple;
243
c->getLangOpts().NoBuiltin = true;
244
245
// This is a workaround for a Clang bug which causes the number
246
// of warnings and errors to be printed to stderr.
247
// http://www.llvm.org/bugs/show_bug.cgi?id=19735
248
c->getDiagnosticOpts().ShowCarets = false;
249
250
compat::compiler_set_lang_defaults(c, compat::ik_opencl,
251
::llvm::Triple(target.triple),
252
get_language_version(opts, device_clc_version));
253
254
c->createDiagnostics(new clang::TextDiagnosticPrinter(
255
*new raw_string_ostream(r_log),
256
&c->getDiagnosticOpts(), true));
257
258
c->setTarget(clang::TargetInfo::CreateTargetInfo(
259
c->getDiagnostics(), c->getInvocation().TargetOpts));
260
261
return c;
262
}
263
264
std::unique_ptr<Module>
265
compile(LLVMContext &ctx, clang::CompilerInstance &c,
266
const std::string &name, const std::string &source,
267
const header_map &headers, const device &dev,
268
const std::string &opts, bool use_libclc, std::string &r_log) {
269
c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
270
c.getHeaderSearchOpts().UseBuiltinIncludes = true;
271
c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
272
c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
273
274
if (use_libclc) {
275
// Add libclc generic search path
276
c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
277
clang::frontend::Angled,
278
false, false);
279
280
// Add libclc include
281
c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
282
} else {
283
// Add opencl-c generic search path
284
c.getHeaderSearchOpts().AddPath(CLANG_RESOURCE_DIR,
285
clang::frontend::Angled,
286
false, false);
287
288
// Add opencl include
289
c.getPreprocessorOpts().Includes.push_back("opencl-c.h");
290
}
291
292
// Add definition for the OpenCL version
293
const auto dev_version = dev.device_version();
294
c.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=" +
295
std::to_string(CL_VERSION_MAJOR_KHR(dev_version)) +
296
std::to_string(CL_VERSION_MINOR_KHR(dev_version)) + "0");
297
298
if (CL_VERSION_MAJOR(dev.version) >= 3) {
299
const auto features = dev.opencl_c_features();
300
for (const auto &feature : features)
301
c.getPreprocessorOpts().addMacroDef(feature.name);
302
}
303
304
// clc.h requires that this macro be defined:
305
c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
306
c.getPreprocessorOpts().addRemappedFile(
307
name, ::llvm::MemoryBuffer::getMemBuffer(source).release());
308
309
if (headers.size()) {
310
const std::string tmp_header_path = "/tmp/clover/";
311
312
c.getHeaderSearchOpts().AddPath(tmp_header_path,
313
clang::frontend::Angled,
314
false, false);
315
316
for (const auto &header : headers)
317
c.getPreprocessorOpts().addRemappedFile(
318
tmp_header_path + header.first,
319
::llvm::MemoryBuffer::getMemBuffer(header.second).release());
320
}
321
322
// Tell clang to link this file before performing any
323
// optimizations. This is required so that we can replace calls
324
// to the OpenCL C barrier() builtin with calls to target
325
// intrinsics that have the noduplicate attribute. This
326
// attribute will prevent Clang from creating illegal uses of
327
// barrier() (e.g. Moving barrier() inside a conditional that is
328
// no executed by all threads) during its optimizaton passes.
329
if (use_libclc) {
330
clang::CodeGenOptions::BitcodeFileToLink F;
331
332
F.Filename = LIBCLC_LIBEXECDIR + dev.ir_target() + ".bc";
333
F.PropagateAttrs = true;
334
F.LinkFlags = ::llvm::Linker::Flags::None;
335
c.getCodeGenOpts().LinkBitcodeFiles.emplace_back(F);
336
}
337
338
// undefine __IMAGE_SUPPORT__ for device without image support
339
if (!dev.image_support())
340
c.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
341
342
// Compile the code
343
clang::EmitLLVMOnlyAction act(&ctx);
344
if (!c.ExecuteAction(act))
345
throw build_error();
346
347
return act.takeModule();
348
}
349
350
#ifdef HAVE_CLOVER_SPIRV
351
SPIRV::TranslatorOpts
352
get_spirv_translator_options(const device &dev) {
353
const auto supported_versions = clover::spirv::supported_versions();
354
const auto max_supported = clover::spirv::to_spirv_version_encoding(supported_versions.back().version);
355
const auto maximum_spirv_version =
356
std::min(static_cast<SPIRV::VersionNumber>(max_supported),
357
SPIRV::VersionNumber::MaximumVersion);
358
359
SPIRV::TranslatorOpts::ExtensionsStatusMap spirv_extensions;
360
for (auto &ext : clover::spirv::supported_extensions()) {
361
#define EXT(X) if (ext == #X) spirv_extensions.insert({ SPIRV::ExtensionID::X, true });
362
#include <LLVMSPIRVLib/LLVMSPIRVExtensions.inc>
363
#undef EXT
364
}
365
366
return SPIRV::TranslatorOpts(maximum_spirv_version, spirv_extensions);
367
}
368
#endif
369
}
370
371
module
372
clover::llvm::compile_program(const std::string &source,
373
const header_map &headers,
374
const device &dev,
375
const std::string &opts,
376
std::string &r_log) {
377
if (has_flag(debug::clc))
378
debug::log(".cl", "// Options: " + opts + '\n' + source);
379
380
auto ctx = create_context(r_log);
381
auto c = create_compiler_instance(dev, dev.ir_target(),
382
tokenize(opts + " input.cl"), r_log);
383
auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, true,
384
r_log);
385
386
if (has_flag(debug::llvm))
387
debug::log(".ll", print_module_bitcode(*mod));
388
389
return build_module_library(*mod, module::section::text_intermediate);
390
}
391
392
namespace {
393
void
394
optimize(Module &mod, unsigned optimization_level,
395
bool internalize_symbols) {
396
::llvm::legacy::PassManager pm;
397
398
// By default, the function internalizer pass will look for a function
399
// called "main" and then mark all other functions as internal. Marking
400
// functions as internal enables the optimizer to perform optimizations
401
// like function inlining and global dead-code elimination.
402
//
403
// When there is no "main" function in a module, the internalize pass will
404
// treat the module like a library, and it won't internalize any functions.
405
// Since there is no "main" function in our kernels, we need to tell
406
// the internalizer pass that this module is not a library by passing a
407
// list of kernel functions to the internalizer. The internalizer will
408
// treat the functions in the list as "main" functions and internalize
409
// all of the other functions.
410
if (internalize_symbols) {
411
std::vector<std::string> names =
412
map(std::mem_fn(&Function::getName), get_kernels(mod));
413
pm.add(::llvm::createInternalizePass(
414
[=](const ::llvm::GlobalValue &gv) {
415
return std::find(names.begin(), names.end(),
416
gv.getName()) != names.end();
417
}));
418
}
419
420
::llvm::PassManagerBuilder pmb;
421
pmb.OptLevel = optimization_level;
422
pmb.LibraryInfo = new ::llvm::TargetLibraryInfoImpl(
423
::llvm::Triple(mod.getTargetTriple()));
424
pmb.populateModulePassManager(pm);
425
pm.run(mod);
426
}
427
428
std::unique_ptr<Module>
429
link(LLVMContext &ctx, const clang::CompilerInstance &c,
430
const std::vector<module> &modules, std::string &r_log) {
431
std::unique_ptr<Module> mod { new Module("link", ctx) };
432
std::unique_ptr< ::llvm::Linker> linker { new ::llvm::Linker(*mod) };
433
434
for (auto &m : modules) {
435
if (linker->linkInModule(parse_module_library(m, ctx, r_log)))
436
throw build_error();
437
}
438
439
return mod;
440
}
441
}
442
443
module
444
clover::llvm::link_program(const std::vector<module> &modules,
445
const device &dev, const std::string &opts,
446
std::string &r_log) {
447
std::vector<std::string> options = tokenize(opts + " input.cl");
448
const bool create_library = count("-create-library", options);
449
erase_if(equals("-create-library"), options);
450
451
auto ctx = create_context(r_log);
452
auto c = create_compiler_instance(dev, dev.ir_target(), options, r_log);
453
auto mod = link(*ctx, *c, modules, r_log);
454
455
optimize(*mod, c->getCodeGenOpts().OptimizationLevel, !create_library);
456
457
static std::atomic_uint seq(0);
458
const std::string id = "." + mod->getModuleIdentifier() + "-" +
459
std::to_string(seq++);
460
461
if (has_flag(debug::llvm))
462
debug::log(id + ".ll", print_module_bitcode(*mod));
463
464
if (create_library) {
465
return build_module_library(*mod, module::section::text_library);
466
467
} else if (dev.ir_format() == PIPE_SHADER_IR_NATIVE) {
468
if (has_flag(debug::native))
469
debug::log(id + ".asm", print_module_native(*mod, dev.ir_target()));
470
471
return build_module_native(*mod, dev.ir_target(), *c, r_log);
472
473
} else {
474
unreachable("Unsupported IR.");
475
}
476
}
477
478
#ifdef HAVE_CLOVER_SPIRV
479
module
480
clover::llvm::compile_to_spirv(const std::string &source,
481
const header_map &headers,
482
const device &dev,
483
const std::string &opts,
484
std::string &r_log) {
485
if (has_flag(debug::clc))
486
debug::log(".cl", "// Options: " + opts + '\n' + source);
487
488
auto ctx = create_context(r_log);
489
const std::string target = dev.address_bits() == 32u ?
490
"-spir-unknown-unknown" :
491
"-spir64-unknown-unknown";
492
auto c = create_compiler_instance(dev, target,
493
tokenize(opts + " -O0 -fgnu89-inline input.cl"), r_log);
494
auto mod = compile(*ctx, *c, "input.cl", source, headers, dev, opts, false,
495
r_log);
496
497
if (has_flag(debug::llvm))
498
debug::log(".ll", print_module_bitcode(*mod));
499
500
const auto spirv_options = get_spirv_translator_options(dev);
501
502
std::string error_msg;
503
std::ostringstream os;
504
if (!::llvm::writeSpirv(mod.get(), spirv_options, os, error_msg)) {
505
r_log += "Translation from LLVM IR to SPIR-V failed: " + error_msg + ".\n";
506
throw error(CL_INVALID_VALUE);
507
}
508
509
const std::string osContent = os.str();
510
std::string binary(osContent.begin(), osContent.end());
511
if (binary.empty()) {
512
r_log += "Failed to retrieve SPIR-V binary.\n";
513
throw error(CL_INVALID_VALUE);
514
}
515
516
if (has_flag(debug::spirv))
517
debug::log(".spvasm", spirv::print_module(binary, dev.device_version()));
518
519
return spirv::compile_program(binary, dev, r_log);
520
}
521
#endif
522
523