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