2 // Copyright 2012 Francisco Jerez
4 // Permission is hereby granted, free of charge, to any person obtaining a
5 // copy of this software and associated documentation files (the "Software"),
6 // to deal in the Software without restriction, including without limitation
7 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 // and/or sell copies of the Software, and to permit persons to whom the
9 // Software is furnished to do so, subject to the following conditions:
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
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 NONINFRINGEMENT. IN NO EVENT SHALL
17 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 // OTHER DEALINGS IN THE SOFTWARE.
23 #include "core/compiler.hpp"
25 #include <clang/Frontend/CompilerInstance.h>
26 #include <clang/Frontend/TextDiagnosticBuffer.h>
27 #include <clang/Frontend/TextDiagnosticPrinter.h>
28 #include <clang/CodeGen/CodeGenAction.h>
29 #include <clang/Basic/TargetInfo.h>
30 #include <llvm/Bitcode/BitstreamWriter.h>
31 #include <llvm/Bitcode/ReaderWriter.h>
32 #include <llvm/Linker/Linker.h>
33 #include <llvm/IR/DiagnosticInfo.h>
34 #include <llvm/IR/DiagnosticPrinter.h>
35 #include <llvm/IR/DerivedTypes.h>
36 #include <llvm/IR/LLVMContext.h>
37 #include <llvm/IR/Module.h>
38 #include <llvm/Support/SourceMgr.h>
39 #include <llvm/IRReader/IRReader.h>
40 #if HAVE_LLVM >= 0x0307
41 #include <llvm/IR/LegacyPassManager.h>
43 #include <llvm/PassManager.h>
45 #include <llvm/Support/CodeGen.h>
46 #include <llvm/Support/TargetSelect.h>
47 #include <llvm/Support/MemoryBuffer.h>
48 #include <llvm/Support/FormattedStream.h>
49 #include <llvm/Support/TargetRegistry.h>
50 #include <llvm/Transforms/IPO.h>
51 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
52 #include <llvm/Transforms/Utils/Cloning.h>
55 #include <llvm/IR/DataLayout.h>
56 #if HAVE_LLVM >= 0x0307
57 #include <llvm/Analysis/TargetLibraryInfo.h>
59 #include <llvm/Target/TargetLibraryInfo.h>
61 #include <llvm/Target/TargetMachine.h>
62 #include <llvm/Target/TargetOptions.h>
64 #include <llvm-c/Target.h>
65 #include <llvm-c/TargetMachine.h>
66 #include <llvm-c/Core.h>
68 #include "pipe/p_state.h"
69 #include "util/u_memory.h"
70 #include "util/u_math.h"
80 using namespace clover
;
85 build_binary(const std::string
&source
, const std::string
&target
,
86 const std::string
&name
) {
87 clang::CompilerInstance c
;
88 clang::EmitObjAction
act(&llvm::getGlobalContext());
90 llvm::raw_string_ostream
s_log(log
);
92 LLVMInitializeTGSITarget();
93 LLVMInitializeTGSITargetInfo();
94 LLVMInitializeTGSITargetMC();
95 LLVMInitializeTGSIAsmPrinter();
97 c
.getFrontendOpts().Inputs
.push_back(
98 std::make_pair(clang::IK_OpenCL
, name
));
99 c
.getHeaderSearchOpts().UseBuiltinIncludes
= false;
100 c
.getHeaderSearchOpts().UseStandardIncludes
= false;
101 c
.getLangOpts().NoBuiltin
= true;
102 c
.getTargetOpts().Triple
= target
;
103 c
.getInvocation().setLangDefaults(clang::IK_OpenCL
);
104 c
.createDiagnostics(0, NULL
, new clang::TextDiagnosticPrinter(
105 s_log
, c
.getDiagnosticOpts()));
107 c
.getPreprocessorOpts().addRemappedFile(
108 name
, llvm::MemoryBuffer::getMemBuffer(source
));
110 if (!c
.ExecuteAction(act
))
111 throw compile_error(log
);
115 load_binary(const char *name
) {
116 std::ifstream
fs((name
));
117 std::vector
<unsigned char> str((std::istreambuf_iterator
<char>(fs
)),
118 (std::istreambuf_iterator
<char>()));
119 compat::istream
cs(str
);
120 return module::deserialize(cs
);
123 void debug_log(const std::string
&msg
, const std::string
&suffix
) {
124 const char *dbg_file
= debug_get_option("CLOVER_DEBUG_FILE", "stderr");
125 if (!strcmp("stderr", dbg_file
)) {
128 std::ofstream
file(dbg_file
+ suffix
, std::ios::app
);
134 compile_llvm(llvm::LLVMContext
&llvm_ctx
, const std::string
&source
,
135 const header_map
&headers
,
136 const std::string
&name
, const std::string
&triple
,
137 const std::string
&processor
, const std::string
&opts
,
138 clang::LangAS::Map
& address_spaces
, unsigned &optimization_level
,
139 std::string
&r_log
) {
141 clang::CompilerInstance c
;
142 clang::EmitLLVMOnlyAction
act(&llvm_ctx
);
144 llvm::raw_string_ostream
s_log(log
);
145 std::string libclc_path
= LIBCLC_LIBEXECDIR
+ processor
+ "-"
148 // Parse the compiler options:
149 std::vector
<std::string
> opts_array
;
150 std::istringstream
ss(opts
);
154 getline(ss
, opt
, ' ');
155 opts_array
.push_back(opt
);
158 opts_array
.push_back(name
);
160 std::vector
<const char *> opts_carray
;
161 for (unsigned i
= 0; i
< opts_array
.size(); i
++) {
162 opts_carray
.push_back(opts_array
.at(i
).c_str());
165 llvm::IntrusiveRefCntPtr
<clang::DiagnosticIDs
> DiagID
;
166 llvm::IntrusiveRefCntPtr
<clang::DiagnosticOptions
> DiagOpts
;
167 clang::TextDiagnosticBuffer
*DiagsBuffer
;
169 DiagID
= new clang::DiagnosticIDs();
170 DiagOpts
= new clang::DiagnosticOptions();
171 DiagsBuffer
= new clang::TextDiagnosticBuffer();
173 clang::DiagnosticsEngine
Diags(DiagID
, &*DiagOpts
, DiagsBuffer
);
176 Success
= clang::CompilerInvocation::CreateFromArgs(c
.getInvocation(),
178 opts_carray
.data() + opts_carray
.size(),
181 throw error(CL_INVALID_COMPILER_OPTIONS
);
183 c
.getFrontendOpts().ProgramAction
= clang::frontend::EmitLLVMOnly
;
184 c
.getHeaderSearchOpts().UseBuiltinIncludes
= true;
185 c
.getHeaderSearchOpts().UseStandardSystemIncludes
= true;
186 c
.getHeaderSearchOpts().ResourceDir
= CLANG_RESOURCE_DIR
;
188 // Add libclc generic search path
189 c
.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR
,
190 clang::frontend::Angled
,
194 // Add libclc include
195 c
.getPreprocessorOpts().Includes
.push_back("clc/clc.h");
197 // clc.h requires that this macro be defined:
198 c
.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
200 c
.getLangOpts().NoBuiltin
= true;
201 c
.getTargetOpts().Triple
= triple
;
202 c
.getTargetOpts().CPU
= processor
;
204 // This is a workaround for a Clang bug which causes the number
205 // of warnings and errors to be printed to stderr.
206 // http://www.llvm.org/bugs/show_bug.cgi?id=19735
207 c
.getDiagnosticOpts().ShowCarets
= false;
208 c
.getInvocation().setLangDefaults(c
.getLangOpts(), clang::IK_OpenCL
,
209 #if HAVE_LLVM >= 0x0309
210 llvm::Triple(triple
),
212 clang::LangStandard::lang_opencl11
);
214 new clang::TextDiagnosticPrinter(
216 &c
.getDiagnosticOpts()));
218 #if HAVE_LLVM >= 0x0306
219 c
.getPreprocessorOpts().addRemappedFile(name
,
220 llvm::MemoryBuffer::getMemBuffer(source
).release());
222 c
.getPreprocessorOpts().addRemappedFile(name
,
223 llvm::MemoryBuffer::getMemBuffer(source
));
226 if (headers
.size()) {
227 const std::string tmp_header_path
= "/tmp/clover/";
229 c
.getHeaderSearchOpts().AddPath(tmp_header_path
,
230 clang::frontend::Angled
,
234 for (header_map::const_iterator it
= headers
.begin();
235 it
!= headers
.end(); ++it
) {
236 const std::string path
= tmp_header_path
+ std::string(it
->first
);
237 c
.getPreprocessorOpts().addRemappedFile(path
,
238 #if HAVE_LLVM >= 0x0306
239 llvm::MemoryBuffer::getMemBuffer(it
->second
.c_str()).release());
241 llvm::MemoryBuffer::getMemBuffer(it
->second
.c_str()));
246 // Setting this attribute tells clang to link this file before
247 // performing any optimizations. This is required so that
248 // we can replace calls to the OpenCL C barrier() builtin
249 // with calls to target intrinsics that have the noduplicate
250 // attribute. This attribute will prevent Clang from creating
251 // illegal uses of barrier() (e.g. Moving barrier() inside a conditional
252 // that is no executed by all threads) during its optimizaton passes.
253 #if HAVE_LLVM >= 0x0308
254 c
.getCodeGenOpts().LinkBitcodeFiles
.emplace_back(llvm::Linker::Flags::None
,
257 c
.getCodeGenOpts().LinkBitcodeFile
= libclc_path
;
259 optimization_level
= c
.getCodeGenOpts().OptimizationLevel
;
262 bool ExecSuccess
= c
.ExecuteAction(act
);
266 throw compile_error();
268 // Get address spaces map to be able to find kernel argument address space
269 memcpy(address_spaces
, c
.getTarget().getAddressSpaceMap(),
270 sizeof(address_spaces
));
272 #if HAVE_LLVM >= 0x0306
273 return act
.takeModule().release();
275 return act
.takeModule();
279 std::vector
<llvm::Function
*>
280 find_kernels(const llvm::Module
*mod
) {
281 const llvm::NamedMDNode
*kernel_node
=
282 mod
->getNamedMetadata("opencl.kernels");
283 // This means there are no kernels in the program. The spec does not
284 // require that we return an error here, but there will be an error if
285 // the user tries to pass this program to a clCreateKernel() call.
287 return std::vector
<llvm::Function
*>();
290 std::vector
<llvm::Function
*> kernels
;
291 kernels
.reserve(kernel_node
->getNumOperands());
292 for (unsigned i
= 0; i
< kernel_node
->getNumOperands(); ++i
) {
293 #if HAVE_LLVM >= 0x0306
294 kernels
.push_back(llvm::mdconst::dyn_extract
<llvm::Function
>(
296 kernels
.push_back(llvm::dyn_cast
<llvm::Function
>(
298 kernel_node
->getOperand(i
)->getOperand(0)));
304 optimize(llvm::Module
*mod
, unsigned optimization_level
) {
306 #if HAVE_LLVM >= 0x0307
307 llvm::legacy::PassManager PM
;
309 llvm::PassManager PM
;
312 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
314 // Add a function internalizer pass.
316 // By default, the function internalizer pass will look for a function
317 // called "main" and then mark all other functions as internal. Marking
318 // functions as internal enables the optimizer to perform optimizations
319 // like function inlining and global dead-code elimination.
321 // When there is no "main" function in a module, the internalize pass will
322 // treat the module like a library, and it won't internalize any functions.
323 // Since there is no "main" function in our kernels, we need to tell
324 // the internalizer pass that this module is not a library by passing a
325 // list of kernel functions to the internalizer. The internalizer will
326 // treat the functions in the list as "main" functions and internalize
327 // all of the other functions.
328 std::vector
<const char*> export_list
;
329 for (std::vector
<llvm::Function
*>::const_iterator I
= kernels
.begin(),
332 llvm::Function
*kernel
= *I
;
333 export_list
.push_back(kernel
->getName().data());
335 #if HAVE_LLVM < 0x0306
336 PM
.add(new llvm::DataLayoutPass(mod
));
337 #elif HAVE_LLVM < 0x0307
338 PM
.add(new llvm::DataLayoutPass());
340 PM
.add(llvm::createInternalizePass(export_list
));
342 llvm::PassManagerBuilder PMB
;
343 PMB
.OptLevel
= optimization_level
;
344 #if HAVE_LLVM < 0x0307
345 PMB
.LibraryInfo
= new llvm::TargetLibraryInfo(
347 PMB
.LibraryInfo
= new llvm::TargetLibraryInfoImpl(
349 llvm::Triple(mod
->getTargetTriple()));
350 PMB
.populateModulePassManager(PM
);
356 struct kernel_arg_md
{
357 llvm::StringRef type_name
;
358 llvm::StringRef access_qual
;
359 kernel_arg_md(llvm::StringRef type_name_
, llvm::StringRef access_qual_
):
360 type_name(type_name_
), access_qual(access_qual_
) {}
363 #if HAVE_LLVM >= 0x0306
366 get_kernel_metadata(const llvm::Function
*kernel_func
) {
367 auto mod
= kernel_func
->getParent();
368 auto kernels_node
= mod
->getNamedMetadata("opencl.kernels");
373 const llvm::MDNode
*kernel_node
= nullptr;
374 for (unsigned i
= 0; i
< kernels_node
->getNumOperands(); ++i
) {
375 auto func
= llvm::mdconst::dyn_extract
<llvm::Function
>(
376 kernels_node
->getOperand(i
)->getOperand(0));
377 if (func
== kernel_func
) {
378 kernel_node
= kernels_node
->getOperand(i
);
387 node_from_op_checked(const llvm::MDOperand
&md_operand
,
388 llvm::StringRef expect_name
,
389 unsigned expect_num_args
)
391 auto node
= llvm::cast
<llvm::MDNode
>(md_operand
);
392 assert(node
->getNumOperands() == expect_num_args
&&
393 "Wrong number of operands.");
395 auto str_node
= llvm::cast
<llvm::MDString
>(node
->getOperand(0));
396 assert(str_node
->getString() == expect_name
&&
397 "Wrong metadata node name.");
402 std::vector
<kernel_arg_md
>
403 get_kernel_arg_md(const llvm::Function
*kernel_func
) {
404 auto num_args
= kernel_func
->getArgumentList().size();
406 auto kernel_node
= get_kernel_metadata(kernel_func
);
407 auto aq
= node_from_op_checked(kernel_node
->getOperand(2),
408 "kernel_arg_access_qual", num_args
+ 1);
409 auto ty
= node_from_op_checked(kernel_node
->getOperand(3),
410 "kernel_arg_type", num_args
+ 1);
412 std::vector
<kernel_arg_md
> res
;
413 res
.reserve(num_args
);
414 for (unsigned i
= 0; i
< num_args
; ++i
) {
415 res
.push_back(kernel_arg_md(
416 llvm::cast
<llvm::MDString
>(ty
->getOperand(i
+1))->getString(),
417 llvm::cast
<llvm::MDString
>(aq
->getOperand(i
+1))->getString()));
425 std::vector
<kernel_arg_md
>
426 get_kernel_arg_md(const llvm::Function
*kernel_func
) {
427 return std::vector
<kernel_arg_md
>(
428 kernel_func
->getArgumentList().size(),
429 kernel_arg_md("", ""));
432 #endif // HAVE_LLVM >= 0x0306
434 std::vector
<module::argument
>
435 get_kernel_args(const llvm::Module
*mod
, const std::string
&kernel_name
,
436 const clang::LangAS::Map
&address_spaces
) {
438 std::vector
<module::argument
> args
;
439 llvm::Function
*kernel_func
= mod
->getFunction(kernel_name
);
440 assert(kernel_func
&& "Kernel name not found in module.");
441 auto arg_md
= get_kernel_arg_md(kernel_func
);
443 llvm::DataLayout
TD(mod
);
444 llvm::Type
*size_type
=
445 TD
.getSmallestLegalIntType(mod
->getContext(), sizeof(cl_uint
) * 8);
447 for (const auto &arg
: kernel_func
->args()) {
449 llvm::Type
*arg_type
= arg
.getType();
450 const unsigned arg_store_size
= TD
.getTypeStoreSize(arg_type
);
452 // OpenCL 1.2 specification, Ch. 6.1.5: "A built-in data
453 // type that is not a power of two bytes in size must be
454 // aligned to the next larger power of two". We need this
455 // alignment for three element vectors, which have
456 // non-power-of-2 store size.
457 const unsigned arg_api_size
= util_next_power_of_two(arg_store_size
);
459 llvm::Type
*target_type
= arg_type
->isIntegerTy() ?
460 TD
.getSmallestLegalIntType(mod
->getContext(), arg_store_size
* 8)
462 unsigned target_size
= TD
.getTypeStoreSize(target_type
);
463 unsigned target_align
= TD
.getABITypeAlignment(target_type
);
465 llvm::StringRef type_name
= arg_md
[arg
.getArgNo()].type_name
;
466 llvm::StringRef access_qual
= arg_md
[arg
.getArgNo()].access_qual
;
469 const bool is_image2d
= type_name
== "image2d_t";
470 const bool is_image3d
= type_name
== "image3d_t";
471 if (is_image2d
|| is_image3d
) {
472 const bool is_write_only
= access_qual
== "write_only";
473 const bool is_read_only
= access_qual
== "read_only";
475 enum module::argument::type marg_type
;
476 if (is_image2d
&& is_read_only
) {
477 marg_type
= module::argument::image2d_rd
;
478 } else if (is_image2d
&& is_write_only
) {
479 marg_type
= module::argument::image2d_wr
;
480 } else if (is_image3d
&& is_read_only
) {
481 marg_type
= module::argument::image3d_rd
;
482 } else if (is_image3d
&& is_write_only
) {
483 marg_type
= module::argument::image3d_wr
;
485 assert(0 && "Wrong image access qualifier");
488 args
.push_back(module::argument(marg_type
,
489 arg_store_size
, target_size
,
491 module::argument::zero_ext
));
495 // Image size implicit argument
496 if (type_name
== "__llvm_image_size") {
497 args
.push_back(module::argument(module::argument::scalar
,
499 TD
.getTypeStoreSize(size_type
),
500 TD
.getABITypeAlignment(size_type
),
501 module::argument::zero_ext
,
502 module::argument::image_size
));
506 // Image format implicit argument
507 if (type_name
== "__llvm_image_format") {
508 args
.push_back(module::argument(module::argument::scalar
,
510 TD
.getTypeStoreSize(size_type
),
511 TD
.getABITypeAlignment(size_type
),
512 module::argument::zero_ext
,
513 module::argument::image_format
));
518 if (llvm::isa
<llvm::PointerType
>(arg_type
) && arg
.hasByValAttr()) {
520 llvm::dyn_cast
<llvm::PointerType
>(arg_type
)->getElementType();
523 if (arg_type
->isPointerTy()) {
524 unsigned address_space
= llvm::cast
<llvm::PointerType
>(arg_type
)->getAddressSpace();
525 if (address_space
== address_spaces
[clang::LangAS::opencl_local
526 - clang::LangAS::Offset
]) {
527 args
.push_back(module::argument(module::argument::local
,
528 arg_api_size
, target_size
,
530 module::argument::zero_ext
));
532 // XXX: Correctly handle constant address space. There is no
533 // way for r600g to pass a handle for constant buffers back
534 // to clover like it can for global buffers, so
535 // creating constant arguments will break r600g. For now,
536 // continue treating constant buffers as global buffers
537 // until we can come up with a way to create handles for
539 args
.push_back(module::argument(module::argument::global
,
540 arg_api_size
, target_size
,
542 module::argument::zero_ext
));
546 llvm::AttributeSet attrs
= kernel_func
->getAttributes();
547 enum module::argument::ext_type ext_type
=
548 (attrs
.hasAttribute(arg
.getArgNo() + 1,
549 llvm::Attribute::SExt
) ?
550 module::argument::sign_ext
:
551 module::argument::zero_ext
);
554 module::argument(module::argument::scalar
, arg_api_size
,
555 target_size
, target_align
, ext_type
));
559 // Append implicit arguments. XXX - The types, ordering and
560 // vector size of the implicit arguments should depend on the
561 // target according to the selected calling convention.
563 module::argument(module::argument::scalar
, sizeof(cl_uint
),
564 TD
.getTypeStoreSize(size_type
),
565 TD
.getABITypeAlignment(size_type
),
566 module::argument::zero_ext
,
567 module::argument::grid_dimension
));
570 module::argument(module::argument::scalar
, sizeof(cl_uint
),
571 TD
.getTypeStoreSize(size_type
),
572 TD
.getABITypeAlignment(size_type
),
573 module::argument::zero_ext
,
574 module::argument::grid_offset
));
580 build_module_llvm(llvm::Module
*mod
,
581 clang::LangAS::Map
& address_spaces
) {
584 struct pipe_llvm_program_header header
;
586 llvm::SmallVector
<char, 1024> llvm_bitcode
;
587 llvm::raw_svector_ostream
bitcode_ostream(llvm_bitcode
);
588 llvm::BitstreamWriter
writer(llvm_bitcode
);
589 llvm::WriteBitcodeToFile(mod
, bitcode_ostream
);
590 #if HAVE_LLVM < 0x0308
591 bitcode_ostream
.flush();
594 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
595 for (unsigned i
= 0; i
< kernels
.size(); ++i
) {
596 std::string kernel_name
= kernels
[i
]->getName();
597 std::vector
<module::argument
> args
=
598 get_kernel_args(mod
, kernel_name
, address_spaces
);
600 m
.syms
.push_back(module::symbol(kernel_name
, 0, i
, args
));
603 header
.num_bytes
= llvm_bitcode
.size();
604 std::vector
<char> data
;
605 data
.insert(data
.end(), (char*)(&header
),
606 (char*)(&header
) + sizeof(header
));
607 data
.insert(data
.end(), llvm_bitcode
.begin(),
609 m
.secs
.push_back(module::section(0, module::section::text
,
610 header
.num_bytes
, data
));
616 emit_code(LLVMTargetMachineRef tm
, LLVMModuleRef mod
,
617 LLVMCodeGenFileType file_type
,
618 LLVMMemoryBufferRef
*out_buffer
,
619 std::string
&r_log
) {
621 char *err_message
= NULL
;
623 err
= LLVMTargetMachineEmitToMemoryBuffer(tm
, mod
, file_type
,
624 &err_message
, out_buffer
);
627 r_log
= std::string(err_message
);
630 LLVMDisposeMessage(err_message
);
633 throw compile_error();
638 compile_native(const llvm::Module
*mod
, const std::string
&triple
,
639 const std::string
&processor
, unsigned dump_asm
,
640 std::string
&r_log
) {
643 LLVMTargetRef target
;
645 LLVMMemoryBufferRef out_buffer
;
646 unsigned buffer_size
;
647 const char *buffer_data
;
648 LLVMModuleRef mod_ref
= wrap(mod
);
650 if (LLVMGetTargetFromTriple(triple
.c_str(), &target
, &error_message
)) {
651 r_log
= std::string(error_message
);
652 LLVMDisposeMessage(error_message
);
653 throw compile_error();
656 LLVMTargetMachineRef tm
= LLVMCreateTargetMachine(
657 target
, triple
.c_str(), processor
.c_str(), "",
658 LLVMCodeGenLevelDefault
, LLVMRelocDefault
, LLVMCodeModelDefault
);
661 r_log
= "Could not create TargetMachine: " + triple
;
662 throw compile_error();
666 LLVMSetTargetMachineAsmVerbosity(tm
, true);
667 #if HAVE_LLVM >= 0x0308
668 LLVMModuleRef debug_mod
= wrap(llvm::CloneModule(mod
).release());
670 LLVMModuleRef debug_mod
= wrap(llvm::CloneModule(mod
));
672 emit_code(tm
, debug_mod
, LLVMAssemblyFile
, &out_buffer
, r_log
);
673 buffer_size
= LLVMGetBufferSize(out_buffer
);
674 buffer_data
= LLVMGetBufferStart(out_buffer
);
675 debug_log(std::string(buffer_data
, buffer_size
), ".asm");
677 LLVMSetTargetMachineAsmVerbosity(tm
, false);
678 LLVMDisposeMemoryBuffer(out_buffer
);
679 LLVMDisposeModule(debug_mod
);
682 emit_code(tm
, mod_ref
, LLVMObjectFile
, &out_buffer
, r_log
);
684 buffer_size
= LLVMGetBufferSize(out_buffer
);
685 buffer_data
= LLVMGetBufferStart(out_buffer
);
687 std::vector
<char> code(buffer_data
, buffer_data
+ buffer_size
);
689 LLVMDisposeMemoryBuffer(out_buffer
);
690 LLVMDisposeTargetMachine(tm
);
695 std::map
<std::string
, unsigned>
696 get_kernel_offsets(std::vector
<char> &code
,
697 const std::vector
<llvm::Function
*> &kernels
,
698 std::string
&r_log
) {
700 // One of the libelf implementations
701 // (http://www.mr511.de/software/english.htm) requires calling
702 // elf_version() before elf_memory().
704 elf_version(EV_CURRENT
);
706 Elf
*elf
= elf_memory(&code
[0], code
.size());
707 size_t section_str_index
;
708 elf_getshdrstrndx(elf
, §ion_str_index
);
709 Elf_Scn
*section
= NULL
;
710 Elf_Scn
*symtab
= NULL
;
711 GElf_Shdr symtab_header
;
713 // Find the symbol table
715 while ((section
= elf_nextscn(elf
, section
))) {
717 if (gelf_getshdr(section
, &symtab_header
) != &symtab_header
) {
718 r_log
= "Failed to read ELF section header.";
719 throw compile_error();
721 name
= elf_strptr(elf
, section_str_index
, symtab_header
.sh_name
);
722 if (!strcmp(name
, ".symtab")) {
728 r_log
= "Unable to find symbol table.";
729 throw compile_error();
731 } catch (compile_error
&e
) {
737 // Extract symbol information from the table
738 Elf_Data
*symtab_data
= NULL
;
742 std::map
<std::string
, unsigned> kernel_offsets
;
743 symtab_data
= elf_getdata(symtab
, symtab_data
);
745 // Determine the offsets for each kernel
746 for (int i
= 0; (symbol
= gelf_getsym(symtab_data
, i
, &s
)); i
++) {
747 char *name
= elf_strptr(elf
, symtab_header
.sh_link
, symbol
->st_name
);
748 for (std::vector
<llvm::Function
*>::const_iterator it
= kernels
.begin(),
749 e
= kernels
.end(); it
!= e
; ++it
) {
750 llvm::Function
*f
= *it
;
751 if (f
->getName() == std::string(name
))
752 kernel_offsets
[f
->getName()] = symbol
->st_value
;
756 return kernel_offsets
;
760 build_module_native(std::vector
<char> &code
,
761 const llvm::Module
*mod
,
762 const clang::LangAS::Map
&address_spaces
,
763 std::string
&r_log
) {
765 const std::vector
<llvm::Function
*> kernels
= find_kernels(mod
);
767 std::map
<std::string
, unsigned> kernel_offsets
=
768 get_kernel_offsets(code
, kernels
, r_log
);
770 // Begin building the clover module
772 struct pipe_llvm_program_header header
;
774 // Store the generated ELF binary in the module's text section.
775 header
.num_bytes
= code
.size();
776 std::vector
<char> data
;
777 data
.insert(data
.end(), (char*)(&header
),
778 (char*)(&header
) + sizeof(header
));
779 data
.insert(data
.end(), code
.begin(), code
.end());
780 m
.secs
.push_back(module::section(0, module::section::text
,
781 header
.num_bytes
, data
));
783 for (std::map
<std::string
, unsigned>::iterator i
= kernel_offsets
.begin(),
784 e
= kernel_offsets
.end(); i
!= e
; ++i
) {
785 std::vector
<module::argument
> args
=
786 get_kernel_args(mod
, i
->first
, address_spaces
);
787 m
.syms
.push_back(module::symbol(i
->first
, 0, i
->second
, args
));
794 diagnostic_handler(const llvm::DiagnosticInfo
&di
, void *data
) {
795 if (di
.getSeverity() == llvm::DS_Error
) {
796 std::string message
= *(std::string
*)data
;
797 llvm::raw_string_ostream
stream(message
);
798 llvm::DiagnosticPrinterRawOStream
dp(stream
);
801 *(std::string
*)data
= message
;
803 throw compile_error();
809 static bool targets_initialized
= false;
810 if (!targets_initialized
) {
811 LLVMInitializeAllTargets();
812 LLVMInitializeAllTargetInfos();
813 LLVMInitializeAllTargetMCs();
814 LLVMInitializeAllAsmPrinters();
815 targets_initialized
= true;
819 #define DBG_CLC (1 << 0)
820 #define DBG_LLVM (1 << 1)
821 #define DBG_ASM (1 << 2)
825 static const struct debug_named_value debug_options
[] = {
826 {"clc", DBG_CLC
, "Dump the OpenCL C code for all kernels."},
827 {"llvm", DBG_LLVM
, "Dump the generated LLVM IR for all kernels."},
828 {"asm", DBG_ASM
, "Dump kernel assembly code for targets specifying "
829 "PIPE_SHADER_IR_NATIVE"},
830 DEBUG_NAMED_VALUE_END
// must be last
832 static const unsigned debug_flags
=
833 debug_get_flags_option("CLOVER_DEBUG", debug_options
, 0);
838 } // End anonymous namespace
841 clover::compile_program_llvm(const std::string
&source
,
842 const header_map
&headers
,
843 enum pipe_shader_ir ir
,
844 const std::string
&target
,
845 const std::string
&opts
,
846 std::string
&r_log
) {
850 size_t processor_str_len
= std::string(target
).find_first_of("-");
851 std::string
processor(target
, 0, processor_str_len
);
852 std::string
triple(target
, processor_str_len
+ 1,
853 target
.size() - processor_str_len
- 1);
854 clang::LangAS::Map address_spaces
;
855 llvm::LLVMContext llvm_ctx
;
856 unsigned optimization_level
;
858 llvm_ctx
.setDiagnosticHandler(diagnostic_handler
, &r_log
);
860 if (get_debug_flags() & DBG_CLC
)
861 debug_log("// Build options: " + opts
+ '\n' + source
, ".cl");
863 // The input file name must have the .cl extension in order for the
864 // CompilerInvocation class to recognize it as an OpenCL source file.
865 llvm::Module
*mod
= compile_llvm(llvm_ctx
, source
, headers
, "input.cl",
866 triple
, processor
, opts
, address_spaces
,
867 optimization_level
, r_log
);
869 optimize(mod
, optimization_level
);
871 if (get_debug_flags() & DBG_LLVM
) {
873 llvm::raw_string_ostream
s_log(log
);
874 mod
->print(s_log
, NULL
);
876 debug_log(log
, ".ll");
880 // Build the clover::module
882 case PIPE_SHADER_IR_TGSI
:
887 case PIPE_SHADER_IR_LLVM
:
888 m
= build_module_llvm(mod
, address_spaces
);
890 case PIPE_SHADER_IR_NATIVE
: {
891 std::vector
<char> code
= compile_native(mod
, triple
, processor
,
892 get_debug_flags() & DBG_ASM
,
894 m
= build_module_native(code
, mod
, address_spaces
, r_log
);
898 #if HAVE_LLVM >= 0x0306
899 // LLVM 3.6 and newer, the user takes ownership of the module.