clover/llvm: Drop support for LLVM < 3.6.
[mesa.git] / src / gallium / state_trackers / clover / llvm / invocation.cpp
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 "core/compiler.hpp"
28
29 #include <clang/Frontend/CompilerInstance.h>
30 #include <clang/Frontend/TextDiagnosticBuffer.h>
31 #include <clang/Frontend/TextDiagnosticPrinter.h>
32 #include <clang/CodeGen/CodeGenAction.h>
33 #include <clang/Basic/TargetInfo.h>
34 #include <llvm/Bitcode/BitstreamWriter.h>
35 #include <llvm/Bitcode/ReaderWriter.h>
36 #include <llvm/Linker/Linker.h>
37 #include <llvm/IR/DiagnosticInfo.h>
38 #include <llvm/IR/DiagnosticPrinter.h>
39 #include <llvm/IR/DerivedTypes.h>
40 #include <llvm/IR/LLVMContext.h>
41 #include <llvm/IR/Module.h>
42 #include <llvm/Support/SourceMgr.h>
43 #include <llvm/IRReader/IRReader.h>
44 #if HAVE_LLVM >= 0x0307
45 #include <llvm/IR/LegacyPassManager.h>
46 #else
47 #include <llvm/PassManager.h>
48 #endif
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>
57
58
59 #include <llvm/IR/DataLayout.h>
60 #if HAVE_LLVM >= 0x0307
61 #include <llvm/Analysis/TargetLibraryInfo.h>
62 #else
63 #include <llvm/Target/TargetLibraryInfo.h>
64 #endif
65 #include <llvm/Target/TargetMachine.h>
66 #include <llvm/Target/TargetOptions.h>
67
68 #include <llvm-c/Target.h>
69 #include <llvm-c/TargetMachine.h>
70 #include <llvm-c/Core.h>
71
72 #include "pipe/p_state.h"
73 #include "util/u_memory.h"
74 #include "util/u_math.h"
75
76 #include <iostream>
77 #include <iomanip>
78 #include <fstream>
79 #include <cstdio>
80 #include <sstream>
81 #include <libelf.h>
82 #include <gelf.h>
83
84 using namespace clover;
85
86 namespace {
87 #if 0
88 void
89 build_binary(const std::string &source, const std::string &target,
90 const std::string &name) {
91 clang::CompilerInstance c;
92 clang::EmitObjAction act(&llvm::getGlobalContext());
93 std::string log;
94 llvm::raw_string_ostream s_log(log);
95
96 LLVMInitializeTGSITarget();
97 LLVMInitializeTGSITargetInfo();
98 LLVMInitializeTGSITargetMC();
99 LLVMInitializeTGSIAsmPrinter();
100
101 c.getFrontendOpts().Inputs.push_back(
102 std::make_pair(clang::IK_OpenCL, name));
103 c.getHeaderSearchOpts().UseBuiltinIncludes = false;
104 c.getHeaderSearchOpts().UseStandardIncludes = false;
105 c.getLangOpts().NoBuiltin = true;
106 c.getTargetOpts().Triple = target;
107 c.getInvocation().setLangDefaults(clang::IK_OpenCL);
108 c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(
109 s_log, c.getDiagnosticOpts()));
110
111 c.getPreprocessorOpts().addRemappedFile(
112 name, llvm::MemoryBuffer::getMemBuffer(source));
113
114 if (!c.ExecuteAction(act))
115 throw compile_error(log);
116 }
117
118 module
119 load_binary(const char *name) {
120 std::ifstream fs((name));
121 std::vector<unsigned char> str((std::istreambuf_iterator<char>(fs)),
122 (std::istreambuf_iterator<char>()));
123 compat::istream cs(str);
124 return module::deserialize(cs);
125 }
126 #endif
127 void debug_log(const std::string &msg, const std::string &suffix) {
128 const char *dbg_file = debug_get_option("CLOVER_DEBUG_FILE", "stderr");
129 if (!strcmp("stderr", dbg_file)) {
130 std::cerr << msg;
131 } else {
132 std::ofstream file(dbg_file + suffix, std::ios::app);
133 file << msg;
134 }
135 }
136
137 llvm::Module *
138 compile_llvm(llvm::LLVMContext &llvm_ctx, const std::string &source,
139 const header_map &headers,
140 const std::string &name, const std::string &triple,
141 const std::string &processor, const std::string &opts,
142 clang::LangAS::Map& address_spaces, unsigned &optimization_level,
143 std::string &r_log) {
144
145 clang::CompilerInstance c;
146 clang::EmitLLVMOnlyAction act(&llvm_ctx);
147 std::string log;
148 llvm::raw_string_ostream s_log(log);
149 std::string libclc_path = LIBCLC_LIBEXECDIR + processor + "-"
150 + triple + ".bc";
151
152 // Parse the compiler options:
153 std::vector<std::string> opts_array;
154 std::istringstream ss(opts);
155
156 while (!ss.eof()) {
157 std::string opt;
158 getline(ss, opt, ' ');
159 opts_array.push_back(opt);
160 }
161
162 opts_array.push_back(name);
163
164 std::vector<const char *> opts_carray;
165 for (unsigned i = 0; i < opts_array.size(); i++) {
166 opts_carray.push_back(opts_array.at(i).c_str());
167 }
168
169 llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID;
170 llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts;
171 clang::TextDiagnosticBuffer *DiagsBuffer;
172
173 DiagID = new clang::DiagnosticIDs();
174 DiagOpts = new clang::DiagnosticOptions();
175 DiagsBuffer = new clang::TextDiagnosticBuffer();
176
177 clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
178 bool Success;
179
180 Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),
181 opts_carray.data(),
182 opts_carray.data() + opts_carray.size(),
183 Diags);
184 if (!Success) {
185 throw error(CL_INVALID_COMPILER_OPTIONS);
186 }
187 c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
188 c.getHeaderSearchOpts().UseBuiltinIncludes = true;
189 c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
190 c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
191
192 // Add libclc generic search path
193 c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
194 clang::frontend::Angled,
195 false, false
196 );
197
198 // Add libclc include
199 c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
200
201 // clc.h requires that this macro be defined:
202 c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
203
204 c.getLangOpts().NoBuiltin = true;
205 c.getTargetOpts().Triple = triple;
206 c.getTargetOpts().CPU = processor;
207
208 // This is a workaround for a Clang bug which causes the number
209 // of warnings and errors to be printed to stderr.
210 // http://www.llvm.org/bugs/show_bug.cgi?id=19735
211 c.getDiagnosticOpts().ShowCarets = false;
212 c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,
213 #if HAVE_LLVM >= 0x0309
214 llvm::Triple(triple), c.getPreprocessorOpts(),
215 #endif
216 clang::LangStandard::lang_opencl11);
217 c.createDiagnostics(
218 new clang::TextDiagnosticPrinter(
219 s_log,
220 &c.getDiagnosticOpts()));
221
222 c.getPreprocessorOpts().addRemappedFile(name,
223 llvm::MemoryBuffer::getMemBuffer(source).release());
224
225 if (headers.size()) {
226 const std::string tmp_header_path = "/tmp/clover/";
227
228 c.getHeaderSearchOpts().AddPath(tmp_header_path,
229 clang::frontend::Angled,
230 false, false
231 );
232
233 for (header_map::const_iterator it = headers.begin();
234 it != headers.end(); ++it) {
235 const std::string path = tmp_header_path + std::string(it->first);
236 c.getPreprocessorOpts().addRemappedFile(path,
237 llvm::MemoryBuffer::getMemBuffer(it->second.c_str()).release());
238 }
239 }
240
241 // Setting this attribute tells clang to link this file before
242 // performing any optimizations. This is required so that
243 // we can replace calls to the OpenCL C barrier() builtin
244 // with calls to target intrinsics that have the noduplicate
245 // attribute. This attribute will prevent Clang from creating
246 // illegal uses of barrier() (e.g. Moving barrier() inside a conditional
247 // that is no executed by all threads) during its optimizaton passes.
248 #if HAVE_LLVM >= 0x0308
249 c.getCodeGenOpts().LinkBitcodeFiles.emplace_back(llvm::Linker::Flags::None,
250 libclc_path);
251 #else
252 c.getCodeGenOpts().LinkBitcodeFile = libclc_path;
253 #endif
254 optimization_level = c.getCodeGenOpts().OptimizationLevel;
255
256 // Compile the code
257 bool ExecSuccess = c.ExecuteAction(act);
258 r_log = log;
259
260 if (!ExecSuccess)
261 throw compile_error();
262
263 // Get address spaces map to be able to find kernel argument address space
264 memcpy(address_spaces, c.getTarget().getAddressSpaceMap(),
265 sizeof(address_spaces));
266
267 return act.takeModule().release();
268 }
269
270 std::vector<llvm::Function *>
271 find_kernels(llvm::Module *mod) {
272 std::vector<llvm::Function *> kernels;
273 #if HAVE_LLVM >= 0x0309
274 auto &list = mod->getFunctionList();
275 for_each(list.begin(), list.end(), [&](llvm::Function &f){
276 if (f.getMetadata("kernel_arg_type"))
277 kernels.push_back(&f);
278 });
279 return kernels;
280 #endif
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.
286 if (!kernel_node) {
287 return std::vector<llvm::Function *>();
288 }
289
290 kernels.reserve(kernel_node->getNumOperands());
291 for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {
292 kernels.push_back(llvm::mdconst::dyn_extract<llvm::Function>(
293 kernel_node->getOperand(i)->getOperand(0)));
294 }
295 return kernels;
296 }
297
298 void
299 optimize(llvm::Module *mod, unsigned optimization_level) {
300
301 #if HAVE_LLVM >= 0x0307
302 llvm::legacy::PassManager PM;
303 #else
304 llvm::PassManager PM;
305 #endif
306
307 const std::vector<llvm::Function *> kernels = find_kernels(mod);
308
309 // Add a function internalizer pass.
310 //
311 // By default, the function internalizer pass will look for a function
312 // called "main" and then mark all other functions as internal. Marking
313 // functions as internal enables the optimizer to perform optimizations
314 // like function inlining and global dead-code elimination.
315 //
316 // When there is no "main" function in a module, the internalize pass will
317 // treat the module like a library, and it won't internalize any functions.
318 // Since there is no "main" function in our kernels, we need to tell
319 // the internalizer pass that this module is not a library by passing a
320 // list of kernel functions to the internalizer. The internalizer will
321 // treat the functions in the list as "main" functions and internalize
322 // all of the other functions.
323 #if HAVE_LLVM >= 0x0309
324 auto preserve_kernels = [=](const llvm::GlobalValue &GV) {
325 for (const auto &kernel : kernels) {
326 if (GV.getName() == kernel->getName())
327 return true;
328 }
329 return false;
330 };
331 #else
332 std::vector<const char*> export_list;
333 for (std::vector<llvm::Function *>::const_iterator I = kernels.begin(),
334 E = kernels.end();
335 I != E; ++I) {
336 llvm::Function *kernel = *I;
337 export_list.push_back(kernel->getName().data());
338 }
339 #endif
340 #if HAVE_LLVM < 0x0307
341 PM.add(new llvm::DataLayoutPass());
342 #endif
343 #if HAVE_LLVM >= 0x0309
344 PM.add(llvm::createInternalizePass(preserve_kernels));
345 #else
346 PM.add(llvm::createInternalizePass(export_list));
347 #endif
348
349 llvm::PassManagerBuilder PMB;
350 PMB.OptLevel = optimization_level;
351 #if HAVE_LLVM < 0x0307
352 PMB.LibraryInfo = new llvm::TargetLibraryInfo(
353 #else
354 PMB.LibraryInfo = new llvm::TargetLibraryInfoImpl(
355 #endif
356 llvm::Triple(mod->getTargetTriple()));
357 PMB.populateModulePassManager(PM);
358 PM.run(*mod);
359 }
360
361 // Kernel metadata
362
363 struct kernel_arg_md {
364 llvm::StringRef type_name;
365 llvm::StringRef access_qual;
366 kernel_arg_md(llvm::StringRef type_name_, llvm::StringRef access_qual_):
367 type_name(type_name_), access_qual(access_qual_) {}
368 };
369 #if HAVE_LLVM >= 0x0309
370 std::vector<kernel_arg_md>
371 get_kernel_arg_md(const llvm::Function *kernel_func) {
372
373 size_t num_args = kernel_func->getArgumentList().size();
374
375 auto aq = kernel_func->getMetadata("kernel_arg_access_qual");
376 auto ty = kernel_func->getMetadata("kernel_arg_type");
377
378 std::vector<kernel_arg_md> res;
379 res.reserve(num_args);
380 for (size_t i = 0; i < num_args; ++i) {
381 res.push_back(kernel_arg_md(
382 llvm::cast<llvm::MDString>(ty->getOperand(i))->getString(),
383 llvm::cast<llvm::MDString>(aq->getOperand(i))->getString()));
384 }
385
386 return res;
387 }
388
389 #else
390
391 const llvm::MDNode *
392 get_kernel_metadata(const llvm::Function *kernel_func) {
393 auto mod = kernel_func->getParent();
394 auto kernels_node = mod->getNamedMetadata("opencl.kernels");
395 if (!kernels_node) {
396 return nullptr;
397 }
398
399 const llvm::MDNode *kernel_node = nullptr;
400 for (unsigned i = 0; i < kernels_node->getNumOperands(); ++i) {
401 auto func = llvm::mdconst::dyn_extract<llvm::Function>(
402 kernels_node->getOperand(i)->getOperand(0));
403 if (func == kernel_func) {
404 kernel_node = kernels_node->getOperand(i);
405 break;
406 }
407 }
408
409 return kernel_node;
410 }
411
412 llvm::MDNode*
413 node_from_op_checked(const llvm::MDOperand &md_operand,
414 llvm::StringRef expect_name,
415 unsigned expect_num_args)
416 {
417 auto node = llvm::cast<llvm::MDNode>(md_operand);
418 assert(node->getNumOperands() == expect_num_args &&
419 "Wrong number of operands.");
420
421 auto str_node = llvm::cast<llvm::MDString>(node->getOperand(0));
422 assert(str_node->getString() == expect_name &&
423 "Wrong metadata node name.");
424
425 return node;
426 }
427
428 std::vector<kernel_arg_md>
429 get_kernel_arg_md(const llvm::Function *kernel_func) {
430 auto num_args = kernel_func->getArgumentList().size();
431
432 auto kernel_node = get_kernel_metadata(kernel_func);
433 auto aq = node_from_op_checked(kernel_node->getOperand(2),
434 "kernel_arg_access_qual", num_args + 1);
435 auto ty = node_from_op_checked(kernel_node->getOperand(3),
436 "kernel_arg_type", num_args + 1);
437
438 std::vector<kernel_arg_md> res;
439 res.reserve(num_args);
440 for (unsigned i = 0; i < num_args; ++i) {
441 res.push_back(kernel_arg_md(
442 llvm::cast<llvm::MDString>(ty->getOperand(i+1))->getString(),
443 llvm::cast<llvm::MDString>(aq->getOperand(i+1))->getString()));
444 }
445
446 return res;
447 }
448 #endif
449
450 std::vector<module::argument>
451 get_kernel_args(const llvm::Module *mod, const std::string &kernel_name,
452 const clang::LangAS::Map &address_spaces) {
453
454 std::vector<module::argument> args;
455 llvm::Function *kernel_func = mod->getFunction(kernel_name);
456 assert(kernel_func && "Kernel name not found in module.");
457 auto arg_md = get_kernel_arg_md(kernel_func);
458
459 llvm::DataLayout TD(mod);
460 llvm::Type *size_type =
461 TD.getSmallestLegalIntType(mod->getContext(), sizeof(cl_uint) * 8);
462
463 for (const auto &arg: kernel_func->args()) {
464
465 llvm::Type *arg_type = arg.getType();
466 const unsigned arg_store_size = TD.getTypeStoreSize(arg_type);
467
468 // OpenCL 1.2 specification, Ch. 6.1.5: "A built-in data
469 // type that is not a power of two bytes in size must be
470 // aligned to the next larger power of two". We need this
471 // alignment for three element vectors, which have
472 // non-power-of-2 store size.
473 const unsigned arg_api_size = util_next_power_of_two(arg_store_size);
474
475 llvm::Type *target_type = arg_type->isIntegerTy() ?
476 TD.getSmallestLegalIntType(mod->getContext(), arg_store_size * 8)
477 : arg_type;
478 unsigned target_size = TD.getTypeStoreSize(target_type);
479 unsigned target_align = TD.getABITypeAlignment(target_type);
480
481 llvm::StringRef type_name = arg_md[arg.getArgNo()].type_name;
482 llvm::StringRef access_qual = arg_md[arg.getArgNo()].access_qual;
483
484 // Image
485 const bool is_image2d = type_name == "image2d_t";
486 const bool is_image3d = type_name == "image3d_t";
487 if (is_image2d || is_image3d) {
488 const bool is_write_only = access_qual == "write_only";
489 const bool is_read_only = access_qual == "read_only";
490
491 enum module::argument::type marg_type;
492 if (is_image2d && is_read_only) {
493 marg_type = module::argument::image2d_rd;
494 } else if (is_image2d && is_write_only) {
495 marg_type = module::argument::image2d_wr;
496 } else if (is_image3d && is_read_only) {
497 marg_type = module::argument::image3d_rd;
498 } else if (is_image3d && is_write_only) {
499 marg_type = module::argument::image3d_wr;
500 } else {
501 assert(0 && "Wrong image access qualifier");
502 }
503
504 args.push_back(module::argument(marg_type,
505 arg_store_size, target_size,
506 target_align,
507 module::argument::zero_ext));
508 continue;
509 }
510
511 // Image size implicit argument
512 if (type_name == "__llvm_image_size") {
513 args.push_back(module::argument(module::argument::scalar,
514 sizeof(cl_uint),
515 TD.getTypeStoreSize(size_type),
516 TD.getABITypeAlignment(size_type),
517 module::argument::zero_ext,
518 module::argument::image_size));
519 continue;
520 }
521
522 // Image format implicit argument
523 if (type_name == "__llvm_image_format") {
524 args.push_back(module::argument(module::argument::scalar,
525 sizeof(cl_uint),
526 TD.getTypeStoreSize(size_type),
527 TD.getABITypeAlignment(size_type),
528 module::argument::zero_ext,
529 module::argument::image_format));
530 continue;
531 }
532
533 // Other types
534 if (llvm::isa<llvm::PointerType>(arg_type) && arg.hasByValAttr()) {
535 arg_type =
536 llvm::dyn_cast<llvm::PointerType>(arg_type)->getElementType();
537 }
538
539 if (arg_type->isPointerTy()) {
540 unsigned address_space = llvm::cast<llvm::PointerType>(arg_type)->getAddressSpace();
541 if (address_space == address_spaces[clang::LangAS::opencl_local
542 - clang::LangAS::Offset]) {
543 args.push_back(module::argument(module::argument::local,
544 arg_api_size, target_size,
545 target_align,
546 module::argument::zero_ext));
547 } else {
548 // XXX: Correctly handle constant address space. There is no
549 // way for r600g to pass a handle for constant buffers back
550 // to clover like it can for global buffers, so
551 // creating constant arguments will break r600g. For now,
552 // continue treating constant buffers as global buffers
553 // until we can come up with a way to create handles for
554 // constant buffers.
555 args.push_back(module::argument(module::argument::global,
556 arg_api_size, target_size,
557 target_align,
558 module::argument::zero_ext));
559 }
560
561 } else {
562 llvm::AttributeSet attrs = kernel_func->getAttributes();
563 enum module::argument::ext_type ext_type =
564 (attrs.hasAttribute(arg.getArgNo() + 1,
565 llvm::Attribute::SExt) ?
566 module::argument::sign_ext :
567 module::argument::zero_ext);
568
569 args.push_back(
570 module::argument(module::argument::scalar, arg_api_size,
571 target_size, target_align, ext_type));
572 }
573 }
574
575 // Append implicit arguments. XXX - The types, ordering and
576 // vector size of the implicit arguments should depend on the
577 // target according to the selected calling convention.
578 args.push_back(
579 module::argument(module::argument::scalar, sizeof(cl_uint),
580 TD.getTypeStoreSize(size_type),
581 TD.getABITypeAlignment(size_type),
582 module::argument::zero_ext,
583 module::argument::grid_dimension));
584
585 args.push_back(
586 module::argument(module::argument::scalar, sizeof(cl_uint),
587 TD.getTypeStoreSize(size_type),
588 TD.getABITypeAlignment(size_type),
589 module::argument::zero_ext,
590 module::argument::grid_offset));
591
592 return args;
593 }
594
595 module
596 build_module_llvm(llvm::Module *mod,
597 clang::LangAS::Map& address_spaces) {
598
599 module m;
600 struct pipe_llvm_program_header header;
601
602 llvm::SmallVector<char, 1024> llvm_bitcode;
603 llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);
604 llvm::BitstreamWriter writer(llvm_bitcode);
605 llvm::WriteBitcodeToFile(mod, bitcode_ostream);
606 #if HAVE_LLVM < 0x0308
607 bitcode_ostream.flush();
608 #endif
609
610 const std::vector<llvm::Function *> kernels = find_kernels(mod);
611 for (unsigned i = 0; i < kernels.size(); ++i) {
612 std::string kernel_name = kernels[i]->getName();
613 std::vector<module::argument> args =
614 get_kernel_args(mod, kernel_name, address_spaces);
615
616 m.syms.push_back(module::symbol(kernel_name, 0, i, args ));
617 }
618
619 header.num_bytes = llvm_bitcode.size();
620 std::vector<char> data;
621 data.insert(data.end(), (char*)(&header),
622 (char*)(&header) + sizeof(header));
623 data.insert(data.end(), llvm_bitcode.begin(),
624 llvm_bitcode.end());
625 m.secs.push_back(module::section(0, module::section::text,
626 header.num_bytes, data));
627
628 return m;
629 }
630
631 void
632 emit_code(LLVMTargetMachineRef tm, LLVMModuleRef mod,
633 LLVMCodeGenFileType file_type,
634 LLVMMemoryBufferRef *out_buffer,
635 std::string &r_log) {
636 LLVMBool err;
637 char *err_message = NULL;
638
639 err = LLVMTargetMachineEmitToMemoryBuffer(tm, mod, file_type,
640 &err_message, out_buffer);
641
642 if (err) {
643 r_log = std::string(err_message);
644 }
645
646 LLVMDisposeMessage(err_message);
647
648 if (err) {
649 throw compile_error();
650 }
651 }
652
653 std::vector<char>
654 compile_native(const llvm::Module *mod, const std::string &triple,
655 const std::string &processor, unsigned dump_asm,
656 std::string &r_log) {
657
658 std::string log;
659 LLVMTargetRef target;
660 char *error_message;
661 LLVMMemoryBufferRef out_buffer;
662 unsigned buffer_size;
663 const char *buffer_data;
664 LLVMModuleRef mod_ref = wrap(mod);
665
666 if (LLVMGetTargetFromTriple(triple.c_str(), &target, &error_message)) {
667 r_log = std::string(error_message);
668 LLVMDisposeMessage(error_message);
669 throw compile_error();
670 }
671
672 LLVMTargetMachineRef tm = LLVMCreateTargetMachine(
673 target, triple.c_str(), processor.c_str(), "",
674 LLVMCodeGenLevelDefault, LLVMRelocDefault, LLVMCodeModelDefault);
675
676 if (!tm) {
677 r_log = "Could not create TargetMachine: " + triple;
678 throw compile_error();
679 }
680
681 if (dump_asm) {
682 LLVMSetTargetMachineAsmVerbosity(tm, true);
683 #if HAVE_LLVM >= 0x0308
684 LLVMModuleRef debug_mod = wrap(llvm::CloneModule(mod).release());
685 #else
686 LLVMModuleRef debug_mod = wrap(llvm::CloneModule(mod));
687 #endif
688 emit_code(tm, debug_mod, LLVMAssemblyFile, &out_buffer, r_log);
689 buffer_size = LLVMGetBufferSize(out_buffer);
690 buffer_data = LLVMGetBufferStart(out_buffer);
691 debug_log(std::string(buffer_data, buffer_size), ".asm");
692
693 LLVMSetTargetMachineAsmVerbosity(tm, false);
694 LLVMDisposeMemoryBuffer(out_buffer);
695 LLVMDisposeModule(debug_mod);
696 }
697
698 emit_code(tm, mod_ref, LLVMObjectFile, &out_buffer, r_log);
699
700 buffer_size = LLVMGetBufferSize(out_buffer);
701 buffer_data = LLVMGetBufferStart(out_buffer);
702
703 std::vector<char> code(buffer_data, buffer_data + buffer_size);
704
705 LLVMDisposeMemoryBuffer(out_buffer);
706 LLVMDisposeTargetMachine(tm);
707
708 return code;
709 }
710
711 std::map<std::string, unsigned>
712 get_kernel_offsets(std::vector<char> &code,
713 const std::vector<llvm::Function *> &kernels,
714 std::string &r_log) {
715
716 // One of the libelf implementations
717 // (http://www.mr511.de/software/english.htm) requires calling
718 // elf_version() before elf_memory().
719 //
720 elf_version(EV_CURRENT);
721
722 Elf *elf = elf_memory(&code[0], code.size());
723 size_t section_str_index;
724 elf_getshdrstrndx(elf, &section_str_index);
725 Elf_Scn *section = NULL;
726 Elf_Scn *symtab = NULL;
727 GElf_Shdr symtab_header;
728
729 // Find the symbol table
730 try {
731 while ((section = elf_nextscn(elf, section))) {
732 const char *name;
733 if (gelf_getshdr(section, &symtab_header) != &symtab_header) {
734 r_log = "Failed to read ELF section header.";
735 throw compile_error();
736 }
737 name = elf_strptr(elf, section_str_index, symtab_header.sh_name);
738 if (!strcmp(name, ".symtab")) {
739 symtab = section;
740 break;
741 }
742 }
743 if (!symtab) {
744 r_log = "Unable to find symbol table.";
745 throw compile_error();
746 }
747 } catch (compile_error &e) {
748 elf_end(elf);
749 throw e;
750 }
751
752
753 // Extract symbol information from the table
754 Elf_Data *symtab_data = NULL;
755 GElf_Sym *symbol;
756 GElf_Sym s;
757
758 std::map<std::string, unsigned> kernel_offsets;
759 symtab_data = elf_getdata(symtab, symtab_data);
760
761 // Determine the offsets for each kernel
762 for (int i = 0; (symbol = gelf_getsym(symtab_data, i, &s)); i++) {
763 char *name = elf_strptr(elf, symtab_header.sh_link, symbol->st_name);
764 for (std::vector<llvm::Function*>::const_iterator it = kernels.begin(),
765 e = kernels.end(); it != e; ++it) {
766 llvm::Function *f = *it;
767 if (f->getName() == std::string(name))
768 kernel_offsets[f->getName()] = symbol->st_value;
769 }
770 }
771 elf_end(elf);
772 return kernel_offsets;
773 }
774
775 module
776 build_module_native(std::vector<char> &code,
777 llvm::Module *mod,
778 const clang::LangAS::Map &address_spaces,
779 std::string &r_log) {
780
781 const std::vector<llvm::Function *> kernels = find_kernels(mod);
782
783 std::map<std::string, unsigned> kernel_offsets =
784 get_kernel_offsets(code, kernels, r_log);
785
786 // Begin building the clover module
787 module m;
788 struct pipe_llvm_program_header header;
789
790 // Store the generated ELF binary in the module's text section.
791 header.num_bytes = code.size();
792 std::vector<char> data;
793 data.insert(data.end(), (char*)(&header),
794 (char*)(&header) + sizeof(header));
795 data.insert(data.end(), code.begin(), code.end());
796 m.secs.push_back(module::section(0, module::section::text,
797 header.num_bytes, data));
798
799 for (std::map<std::string, unsigned>::iterator i = kernel_offsets.begin(),
800 e = kernel_offsets.end(); i != e; ++i) {
801 std::vector<module::argument> args =
802 get_kernel_args(mod, i->first, address_spaces);
803 m.syms.push_back(module::symbol(i->first, 0, i->second, args ));
804 }
805
806 return m;
807 }
808
809 void
810 diagnostic_handler(const llvm::DiagnosticInfo &di, void *data) {
811 if (di.getSeverity() == llvm::DS_Error) {
812 std::string message = *(std::string*)data;
813 llvm::raw_string_ostream stream(message);
814 llvm::DiagnosticPrinterRawOStream dp(stream);
815 di.print(dp);
816 stream.flush();
817 *(std::string*)data = message;
818
819 throw compile_error();
820 }
821 }
822
823 void
824 init_targets() {
825 static bool targets_initialized = false;
826 if (!targets_initialized) {
827 LLVMInitializeAllTargets();
828 LLVMInitializeAllTargetInfos();
829 LLVMInitializeAllTargetMCs();
830 LLVMInitializeAllAsmPrinters();
831 targets_initialized = true;
832 }
833 }
834
835 #define DBG_CLC (1 << 0)
836 #define DBG_LLVM (1 << 1)
837 #define DBG_ASM (1 << 2)
838
839 unsigned
840 get_debug_flags() {
841 static const struct debug_named_value debug_options[] = {
842 {"clc", DBG_CLC, "Dump the OpenCL C code for all kernels."},
843 {"llvm", DBG_LLVM, "Dump the generated LLVM IR for all kernels."},
844 {"asm", DBG_ASM, "Dump kernel assembly code for targets specifying "
845 "PIPE_SHADER_IR_NATIVE"},
846 DEBUG_NAMED_VALUE_END // must be last
847 };
848 static const unsigned debug_flags =
849 debug_get_flags_option("CLOVER_DEBUG", debug_options, 0);
850
851 return debug_flags;
852 }
853
854 } // End anonymous namespace
855
856 module
857 clover::compile_program_llvm(const std::string &source,
858 const header_map &headers,
859 enum pipe_shader_ir ir,
860 const std::string &target,
861 const std::string &opts,
862 std::string &r_log) {
863
864 init_targets();
865
866 size_t processor_str_len = std::string(target).find_first_of("-");
867 std::string processor(target, 0, processor_str_len);
868 std::string triple(target, processor_str_len + 1,
869 target.size() - processor_str_len - 1);
870 clang::LangAS::Map address_spaces;
871 llvm::LLVMContext llvm_ctx;
872 unsigned optimization_level;
873
874 llvm_ctx.setDiagnosticHandler(diagnostic_handler, &r_log);
875
876 if (get_debug_flags() & DBG_CLC)
877 debug_log("// Build options: " + opts + '\n' + source, ".cl");
878
879 // The input file name must have the .cl extension in order for the
880 // CompilerInvocation class to recognize it as an OpenCL source file.
881 llvm::Module *mod = compile_llvm(llvm_ctx, source, headers, "input.cl",
882 triple, processor, opts, address_spaces,
883 optimization_level, r_log);
884
885 optimize(mod, optimization_level);
886
887 if (get_debug_flags() & DBG_LLVM) {
888 std::string log;
889 llvm::raw_string_ostream s_log(log);
890 mod->print(s_log, NULL);
891 s_log.flush();
892 debug_log(log, ".ll");
893 }
894
895 module m;
896 // Build the clover::module
897 switch (ir) {
898 case PIPE_SHADER_IR_NIR:
899 case PIPE_SHADER_IR_TGSI:
900 //XXX: Handle TGSI, NIR
901 assert(0);
902 m = module();
903 break;
904 case PIPE_SHADER_IR_LLVM:
905 m = build_module_llvm(mod, address_spaces);
906 break;
907 case PIPE_SHADER_IR_NATIVE: {
908 std::vector<char> code = compile_native(mod, triple, processor,
909 get_debug_flags() & DBG_ASM,
910 r_log);
911 m = build_module_native(code, mod, address_spaces, r_log);
912 break;
913 }
914 }
915 // The user takes ownership of the module.
916 delete mod;
917 return m;
918 }