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
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:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
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.
27 #include "llvm/codegen.hpp"
28 #include "llvm/compat.hpp"
29 #include "llvm/metadata.hpp"
30 #include "llvm/util.hpp"
31 #include "core/compiler.hpp"
32 #include "util/algorithm.hpp"
34 #include <clang/Frontend/CompilerInstance.h>
35 #include <clang/Frontend/TextDiagnosticBuffer.h>
36 #include <clang/Frontend/TextDiagnosticPrinter.h>
37 #include <clang/CodeGen/CodeGenAction.h>
38 #include <clang/Basic/TargetInfo.h>
39 #include <llvm/Bitcode/BitstreamWriter.h>
40 #include <llvm/Bitcode/ReaderWriter.h>
41 #include <llvm/Linker/Linker.h>
42 #include <llvm/IR/DiagnosticInfo.h>
43 #include <llvm/IR/DiagnosticPrinter.h>
44 #include <llvm/IR/DerivedTypes.h>
45 #include <llvm/IR/LLVMContext.h>
46 #include <llvm/IR/Module.h>
47 #include <llvm/Support/SourceMgr.h>
48 #include <llvm/IRReader/IRReader.h>
49 #include <llvm/Support/CodeGen.h>
50 #include <llvm/Support/TargetSelect.h>
51 #include <llvm/Support/MemoryBuffer.h>
52 #include <llvm/Support/FormattedStream.h>
53 #include <llvm/Support/TargetRegistry.h>
54 #include <llvm/Transforms/IPO.h>
55 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
56 #include <llvm/Transforms/Utils/Cloning.h>
59 #include <llvm/IR/DataLayout.h>
60 #include <llvm/Target/TargetMachine.h>
61 #include <llvm/Target/TargetOptions.h>
63 #include <llvm-c/Target.h>
64 #include <llvm-c/TargetMachine.h>
65 #include <llvm-c/Core.h>
67 #include "pipe/p_state.h"
68 #include "util/u_memory.h"
69 #include "util/u_math.h"
79 using namespace clover
;
80 using namespace clover::llvm
;
83 using ::llvm::dyn_cast
;
84 using ::llvm::Function
;
86 using ::llvm::LLVMContext
;
88 using ::llvm::raw_string_ostream
;
89 using ::llvm::TargetMachine
;
92 // XXX - Temporary hack to avoid breaking the build for the moment, will
93 // get rid of this later.
95 using namespace ::llvm
;
100 static bool targets_initialized
= false;
101 if (!targets_initialized
) {
102 LLVMInitializeAllTargets();
103 LLVMInitializeAllTargetInfos();
104 LLVMInitializeAllTargetMCs();
105 LLVMInitializeAllAsmPrinters();
106 targets_initialized
= true;
111 diagnostic_handler(const ::llvm::DiagnosticInfo
&di
, void *data
) {
112 if (di
.getSeverity() == ::llvm::DS_Error
) {
113 raw_string_ostream os
{ *reinterpret_cast<std::string
*>(data
) };
114 ::llvm::DiagnosticPrinterRawOStream printer
{ os
};
116 throw compile_error();
120 std::unique_ptr
<LLVMContext
>
121 create_context(std::string
&r_log
) {
123 std::unique_ptr
<LLVMContext
> ctx
{ new LLVMContext
};
124 ctx
->setDiagnosticHandler(diagnostic_handler
, &r_log
);
128 std::unique_ptr
<clang::CompilerInstance
>
129 create_compiler_instance(const target
&target
,
130 const std::vector
<std::string
> &opts
,
131 std::string
&r_log
) {
132 std::unique_ptr
<clang::CompilerInstance
> c
{ new clang::CompilerInstance
};
133 clang::DiagnosticsEngine diag
{ new clang::DiagnosticIDs
,
134 new clang::DiagnosticOptions
, new clang::TextDiagnosticBuffer
};
136 // Parse the compiler options. A file name should be present at the end
137 // and must have the .cl extension in order for the CompilerInvocation
138 // class to recognize it as an OpenCL source file.
139 const std::vector
<const char *> copts
=
140 map(std::mem_fn(&std::string::c_str
), opts
);
142 if (!clang::CompilerInvocation::CreateFromArgs(
143 c
->getInvocation(), copts
.data(), copts
.data() + copts
.size(), diag
))
144 throw error(CL_INVALID_COMPILER_OPTIONS
);
146 c
->getTargetOpts().CPU
= target
.cpu
;
147 c
->getTargetOpts().Triple
= target
.triple
;
148 c
->getLangOpts().NoBuiltin
= true;
150 // This is a workaround for a Clang bug which causes the number
151 // of warnings and errors to be printed to stderr.
152 // http://www.llvm.org/bugs/show_bug.cgi?id=19735
153 c
->getDiagnosticOpts().ShowCarets
= false;
155 compat::set_lang_defaults(c
->getInvocation(), c
->getLangOpts(),
156 clang::IK_OpenCL
, ::llvm::Triple(target
.triple
),
157 c
->getPreprocessorOpts(),
158 clang::LangStandard::lang_opencl11
);
160 c
->createDiagnostics(new clang::TextDiagnosticPrinter(
161 *new raw_string_ostream(r_log
),
162 &c
->getDiagnosticOpts(), true));
164 c
->setTarget(clang::TargetInfo::CreateTargetInfo(
165 c
->getDiagnostics(), c
->getInvocation().TargetOpts
));
170 std::unique_ptr
<Module
>
171 compile(LLVMContext
&ctx
, clang::CompilerInstance
&c
,
172 const std::string
&name
, const std::string
&source
,
173 const header_map
&headers
, const std::string
&target
,
174 const std::string
&opts
, std::string
&r_log
) {
175 c
.getFrontendOpts().ProgramAction
= clang::frontend::EmitLLVMOnly
;
176 c
.getHeaderSearchOpts().UseBuiltinIncludes
= true;
177 c
.getHeaderSearchOpts().UseStandardSystemIncludes
= true;
178 c
.getHeaderSearchOpts().ResourceDir
= CLANG_RESOURCE_DIR
;
180 // Add libclc generic search path
181 c
.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR
,
182 clang::frontend::Angled
,
185 // Add libclc include
186 c
.getPreprocessorOpts().Includes
.push_back("clc/clc.h");
188 // clc.h requires that this macro be defined:
189 c
.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
190 c
.getPreprocessorOpts().addRemappedFile(
191 name
, ::llvm::MemoryBuffer::getMemBuffer(source
).release());
193 if (headers
.size()) {
194 const std::string tmp_header_path
= "/tmp/clover/";
196 c
.getHeaderSearchOpts().AddPath(tmp_header_path
,
197 clang::frontend::Angled
,
200 for (const auto &header
: headers
)
201 c
.getPreprocessorOpts().addRemappedFile(
202 tmp_header_path
+ header
.first
,
203 ::llvm::MemoryBuffer::getMemBuffer(header
.second
).release());
206 // Tell clang to link this file before performing any
207 // optimizations. This is required so that we can replace calls
208 // to the OpenCL C barrier() builtin with calls to target
209 // intrinsics that have the noduplicate attribute. This
210 // attribute will prevent Clang from creating illegal uses of
211 // barrier() (e.g. Moving barrier() inside a conditional that is
212 // no executed by all threads) during its optimizaton passes.
213 compat::add_link_bitcode_file(c
.getCodeGenOpts(),
214 LIBCLC_LIBEXECDIR
+ target
+ ".bc");
217 clang::EmitLLVMOnlyAction
act(&ctx
);
218 if (!c
.ExecuteAction(act
))
219 throw compile_error();
221 return act
.takeModule();
225 optimize(Module
&mod
, unsigned optimization_level
) {
226 compat::pass_manager pm
;
228 compat::add_data_layout_pass(pm
);
230 // By default, the function internalizer pass will look for a function
231 // called "main" and then mark all other functions as internal. Marking
232 // functions as internal enables the optimizer to perform optimizations
233 // like function inlining and global dead-code elimination.
235 // When there is no "main" function in a module, the internalize pass will
236 // treat the module like a library, and it won't internalize any functions.
237 // Since there is no "main" function in our kernels, we need to tell
238 // the internalizer pass that this module is not a library by passing a
239 // list of kernel functions to the internalizer. The internalizer will
240 // treat the functions in the list as "main" functions and internalize
241 // all of the other functions.
242 compat::add_internalize_pass(pm
, map(std::mem_fn(&Function::getName
),
245 ::llvm::PassManagerBuilder pmb
;
246 pmb
.OptLevel
= optimization_level
;
247 pmb
.LibraryInfo
= new compat::target_library_info(
248 ::llvm::Triple(mod
.getTargetTriple()));
249 pmb
.populateModulePassManager(pm
);
254 emit_code(::llvm::Module
&mod
, const target
&target
,
255 TargetMachine::CodeGenFileType ft
,
256 std::string
&r_log
) {
258 auto t
= ::llvm::TargetRegistry::lookupTarget(target
.triple
, err
);
260 fail(r_log
, compile_error(), err
);
262 std::unique_ptr
<TargetMachine
> tm
{
263 t
->createTargetMachine(target
.triple
, target
.cpu
, "", {},
264 compat::default_reloc_model
,
265 ::llvm::CodeModel::Default
,
266 ::llvm::CodeGenOpt::Default
) };
268 fail(r_log
, compile_error(),
269 "Could not create TargetMachine: " + target
.triple
);
271 ::llvm::SmallVector
<char, 1024> data
;
274 compat::pass_manager pm
;
275 ::llvm::raw_svector_ostream os
{ data
};
276 compat::raw_ostream_to_emit_file fos
{ os
};
278 mod
.setDataLayout(compat::get_data_layout(*tm
));
279 tm
->Options
.MCOptions
.AsmVerbose
=
280 (ft
== TargetMachine::CGFT_AssemblyFile
);
282 if (tm
->addPassesToEmitFile(pm
, fos
, ft
))
283 fail(r_log
, compile_error(), "TargetMachine can't emit this file");
288 return { data
.begin(), data
.end() };
292 std::unique_ptr
<Elf
, int (*)(Elf
*)>
293 get(const std::vector
<char> &code
) {
294 // One of the libelf implementations
295 // (http://www.mr511.de/software/english.htm) requires calling
296 // elf_version() before elf_memory().
297 elf_version(EV_CURRENT
);
298 return { elf_memory(const_cast<char *>(code
.data()), code
.size()),
303 get_symbol_table(Elf
*elf
) {
304 size_t section_str_index
;
305 elf_getshdrstrndx(elf
, §ion_str_index
);
307 for (Elf_Scn
*s
= elf_nextscn(elf
, NULL
); s
; s
= elf_nextscn(elf
, s
)) {
309 if (gelf_getshdr(s
, &header
) != &header
)
312 if (!std::strcmp(elf_strptr(elf
, section_str_index
, header
.sh_name
),
320 std::map
<std::string
, unsigned>
321 get_symbol_offsets(Elf
*elf
, Elf_Scn
*symtab
) {
322 Elf_Data
*const symtab_data
= elf_getdata(symtab
, NULL
);
324 if (gelf_getshdr(symtab
, &header
) != &header
)
327 std::map
<std::string
, unsigned> symbol_offsets
;
331 while (GElf_Sym
*s
= gelf_getsym(symtab_data
, i
++, &symbol
)) {
332 const char *name
= elf_strptr(elf
, header
.sh_link
, s
->st_name
);
333 symbol_offsets
[name
] = s
->st_value
;
336 return symbol_offsets
;
340 std::map
<std::string
, unsigned>
341 get_symbol_offsets(const std::vector
<char> &code
,
342 std::string
&r_log
) {
343 const auto elf
= elf::get(code
);
344 const auto symtab
= elf::get_symbol_table(elf
.get());
346 fail(r_log
, compile_error(), "Unable to find symbol table.");
348 return elf::get_symbol_offsets(elf
.get(), symtab
);
352 build_module_native(::llvm::Module
&mod
, const target
&target
,
353 const clang::CompilerInstance
&c
,
354 std::string
&r_log
) {
355 const auto code
= emit_code(mod
, target
,
356 TargetMachine::CGFT_ObjectFile
, r_log
);
357 return build_module_common(mod
, code
, get_symbol_offsets(code
, r_log
), c
);
361 print_module_native(const ::llvm::Module
&mod
, const target
&target
) {
364 std::unique_ptr
<llvm::Module
> cmod
{ CloneModule(&mod
) };
365 return as_string(emit_code(*cmod
, target
,
366 TargetMachine::CGFT_AssemblyFile
, log
));
368 return "Couldn't output native disassembly: " + log
;
371 } // End anonymous namespace
374 clover::compile_program_llvm(const std::string
&source
,
375 const header_map
&headers
,
376 enum pipe_shader_ir ir
,
377 const std::string
&target
,
378 const std::string
&opts
,
379 std::string
&r_log
) {
380 if (has_flag(debug::clc
))
381 debug::log(".cl", "// Build options: " + opts
+ '\n' + source
);
383 auto ctx
= create_context(r_log
);
384 // The input file name must have the .cl extension in order for the
385 // CompilerInvocation class to recognize it as an OpenCL source file.
386 const auto c
= create_compiler_instance(target
, tokenize(opts
+ " input.cl"),
388 auto mod
= compile(*ctx
, *c
, "input.cl", source
, headers
, target
, opts
, r_log
);
390 optimize(*mod
, c
->getCodeGenOpts().OptimizationLevel
);
392 if (has_flag(debug::llvm
))
393 debug::log(".ll", print_module_bitcode(*mod
));
396 // Build the clover::module
398 case PIPE_SHADER_IR_NIR
:
399 case PIPE_SHADER_IR_TGSI
:
400 //XXX: Handle TGSI, NIR
404 case PIPE_SHADER_IR_LLVM
:
405 m
= build_module_bitcode(*mod
, *c
);
407 case PIPE_SHADER_IR_NATIVE
:
408 if (has_flag(debug::native
))
409 debug::log(".asm", print_module_native(*mod
, target
));
411 m
= build_module_native(*mod
, target
, *c
, r_log
);