st/clover: Adapt to TargetLibraryInfo.h move in LLVM SVN r226078
[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 #if HAVE_LLVM < 0x0305
33 #include <llvm/Linker.h>
34 #else
35 #include <llvm/Linker/Linker.h>
36 #include <llvm/IR/DiagnosticInfo.h>
37 #include <llvm/IR/DiagnosticPrinter.h>
38 #endif
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 < 0x0305
45 #include <llvm/ADT/OwningPtr.h>
46 #endif
47 #include <llvm/PassManager.h>
48 #include <llvm/Support/CodeGen.h>
49 #include <llvm/Support/TargetSelect.h>
50 #include <llvm/Support/MemoryBuffer.h>
51 #include <llvm/Support/FormattedStream.h>
52 #include <llvm/Support/TargetRegistry.h>
53 #include <llvm/Transforms/IPO.h>
54 #include <llvm/Transforms/IPO/PassManagerBuilder.h>
55 #include <llvm/Transforms/Utils/Cloning.h>
56
57
58 #include <llvm/IR/DataLayout.h>
59 #if HAVE_LLVM >= 0x0307
60 #include <llvm/Analysis/TargetLibraryInfo.h>
61 #else
62 #include <llvm/Target/TargetLibraryInfo.h>
63 #endif
64 #include <llvm/Target/TargetMachine.h>
65 #include <llvm/Target/TargetOptions.h>
66
67 #include <llvm-c/Target.h>
68 #include <llvm-c/TargetMachine.h>
69 #include <llvm-c/Core.h>
70
71 #include "pipe/p_state.h"
72 #include "util/u_memory.h"
73 #include "util/u_math.h"
74
75 #include <iostream>
76 #include <iomanip>
77 #include <fstream>
78 #include <cstdio>
79 #include <sstream>
80 #include <libelf.h>
81 #include <gelf.h>
82
83 using namespace clover;
84
85 namespace {
86 #if 0
87 void
88 build_binary(const std::string &source, const std::string &target,
89 const std::string &name) {
90 clang::CompilerInstance c;
91 clang::EmitObjAction act(&llvm::getGlobalContext());
92 std::string log;
93 llvm::raw_string_ostream s_log(log);
94
95 LLVMInitializeTGSITarget();
96 LLVMInitializeTGSITargetInfo();
97 LLVMInitializeTGSITargetMC();
98 LLVMInitializeTGSIAsmPrinter();
99
100 c.getFrontendOpts().Inputs.push_back(
101 std::make_pair(clang::IK_OpenCL, name));
102 c.getHeaderSearchOpts().UseBuiltinIncludes = false;
103 c.getHeaderSearchOpts().UseStandardIncludes = false;
104 c.getLangOpts().NoBuiltin = true;
105 c.getTargetOpts().Triple = target;
106 c.getInvocation().setLangDefaults(clang::IK_OpenCL);
107 c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(
108 s_log, c.getDiagnosticOpts()));
109
110 c.getPreprocessorOpts().addRemappedFile(
111 name, llvm::MemoryBuffer::getMemBuffer(source));
112
113 if (!c.ExecuteAction(act))
114 throw build_error(log);
115 }
116
117 module
118 load_binary(const char *name) {
119 std::ifstream fs((name));
120 std::vector<unsigned char> str((std::istreambuf_iterator<char>(fs)),
121 (std::istreambuf_iterator<char>()));
122 compat::istream cs(str);
123 return module::deserialize(cs);
124 }
125 #endif
126 void debug_log(const std::string &msg, const std::string &suffix) {
127 const char *dbg_file = debug_get_option("CLOVER_DEBUG_FILE", "stderr");
128 if (!strcmp("stderr", dbg_file)) {
129 std::cerr << msg;
130 } else {
131 std::ofstream file(dbg_file + suffix, std::ios::app);
132 file << msg;
133 }
134 }
135
136 llvm::Module *
137 compile_llvm(llvm::LLVMContext &llvm_ctx, const std::string &source,
138 const header_map &headers,
139 const std::string &name, const std::string &triple,
140 const std::string &processor, const std::string &opts,
141 clang::LangAS::Map& address_spaces, unsigned &optimization_level,
142 compat::string &r_log) {
143
144 clang::CompilerInstance c;
145 clang::EmitLLVMOnlyAction act(&llvm_ctx);
146 std::string log;
147 llvm::raw_string_ostream s_log(log);
148 std::string libclc_path = LIBCLC_LIBEXECDIR + processor + "-"
149 + triple + ".bc";
150
151 // Parse the compiler options:
152 std::vector<std::string> opts_array;
153 std::istringstream ss(opts);
154
155 while (!ss.eof()) {
156 std::string opt;
157 getline(ss, opt, ' ');
158 opts_array.push_back(opt);
159 }
160
161 opts_array.push_back(name);
162
163 std::vector<const char *> opts_carray;
164 for (unsigned i = 0; i < opts_array.size(); i++) {
165 opts_carray.push_back(opts_array.at(i).c_str());
166 }
167
168 llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID;
169 llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts;
170 clang::TextDiagnosticBuffer *DiagsBuffer;
171
172 DiagID = new clang::DiagnosticIDs();
173 DiagOpts = new clang::DiagnosticOptions();
174 DiagsBuffer = new clang::TextDiagnosticBuffer();
175
176 clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
177 bool Success;
178
179 Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),
180 opts_carray.data(),
181 opts_carray.data() + opts_carray.size(),
182 Diags);
183 if (!Success) {
184 throw error(CL_INVALID_COMPILER_OPTIONS);
185 }
186 c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;
187 c.getHeaderSearchOpts().UseBuiltinIncludes = true;
188 c.getHeaderSearchOpts().UseStandardSystemIncludes = true;
189 c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;
190
191 // Add libclc generic search path
192 c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,
193 clang::frontend::Angled,
194 false, false
195 );
196
197 // Add libclc include
198 c.getPreprocessorOpts().Includes.push_back("clc/clc.h");
199
200 // clc.h requires that this macro be defined:
201 c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers");
202 c.getPreprocessorOpts().addMacroDef("cl_khr_fp64");
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 clang::LangStandard::lang_opencl11);
214 c.createDiagnostics(
215 new clang::TextDiagnosticPrinter(
216 s_log,
217 &c.getDiagnosticOpts()));
218
219 #if HAVE_LLVM >= 0x0306
220 c.getPreprocessorOpts().addRemappedFile(name,
221 llvm::MemoryBuffer::getMemBuffer(source).release());
222 #else
223 c.getPreprocessorOpts().addRemappedFile(name,
224 llvm::MemoryBuffer::getMemBuffer(source));
225 #endif
226
227 if (headers.size()) {
228 const std::string tmp_header_path = "/tmp/clover/";
229
230 c.getHeaderSearchOpts().AddPath(tmp_header_path,
231 clang::frontend::Angled,
232 false, false
233 );
234
235 for (header_map::const_iterator it = headers.begin();
236 it != headers.end(); ++it) {
237 const std::string path = tmp_header_path + std::string(it->first);
238 c.getPreprocessorOpts().addRemappedFile(path,
239 #if HAVE_LLVM >= 0x0306
240 llvm::MemoryBuffer::getMemBuffer(it->second.c_str()).release());
241 #else
242 llvm::MemoryBuffer::getMemBuffer(it->second.c_str()));
243 #endif
244 }
245 }
246
247 // Setting this attribute tells clang to link this file before
248 // performing any optimizations. This is required so that
249 // we can replace calls to the OpenCL C barrier() builtin
250 // with calls to target intrinsics that have the noduplicate
251 // attribute. This attribute will prevent Clang from creating
252 // illegal uses of barrier() (e.g. Moving barrier() inside a conditional
253 // that is no executed by all threads) during its optimizaton passes.
254 c.getCodeGenOpts().LinkBitcodeFile = libclc_path;
255
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 build_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 void
277 find_kernels(llvm::Module *mod, std::vector<llvm::Function *> &kernels) {
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;
285 }
286
287 for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {
288 #if HAVE_LLVM >= 0x0306
289 kernels.push_back(llvm::mdconst::dyn_extract<llvm::Function>(
290 #else
291 kernels.push_back(llvm::dyn_cast<llvm::Function>(
292 #endif
293 kernel_node->getOperand(i)->getOperand(0)));
294 }
295 }
296
297 void
298 optimize(llvm::Module *mod, unsigned optimization_level,
299 const std::vector<llvm::Function *> &kernels) {
300
301 llvm::PassManager PM;
302 // Add a function internalizer pass.
303 //
304 // By default, the function internalizer pass will look for a function
305 // called "main" and then mark all other functions as internal. Marking
306 // functions as internal enables the optimizer to perform optimizations
307 // like function inlining and global dead-code elimination.
308 //
309 // When there is no "main" function in a module, the internalize pass will
310 // treat the module like a library, and it won't internalize any functions.
311 // Since there is no "main" function in our kernels, we need to tell
312 // the internalizer pass that this module is not a library by passing a
313 // list of kernel functions to the internalizer. The internalizer will
314 // treat the functions in the list as "main" functions and internalize
315 // all of the other functions.
316 std::vector<const char*> export_list;
317 for (std::vector<llvm::Function *>::const_iterator I = kernels.begin(),
318 E = kernels.end();
319 I != E; ++I) {
320 llvm::Function *kernel = *I;
321 export_list.push_back(kernel->getName().data());
322 }
323 #if HAVE_LLVM < 0x0305
324 PM.add(new llvm::DataLayout(mod));
325 #elif HAVE_LLVM < 0x0306
326 PM.add(new llvm::DataLayoutPass(mod));
327 #else
328 PM.add(new llvm::DataLayoutPass());
329 #endif
330 PM.add(llvm::createInternalizePass(export_list));
331
332 llvm::PassManagerBuilder PMB;
333 PMB.OptLevel = optimization_level;
334 PMB.LibraryInfo = new llvm::TargetLibraryInfo(
335 llvm::Triple(mod->getTargetTriple()));
336 PMB.populateModulePassManager(PM);
337 PM.run(*mod);
338 }
339
340 compat::vector<module::argument>
341 get_kernel_args(const llvm::Module *mod, const std::string &kernel_name,
342 const clang::LangAS::Map &address_spaces) {
343
344 compat::vector<module::argument> args;
345 llvm::Function *kernel_func = mod->getFunction(kernel_name);
346
347 #if HAVE_LLVM < 0x0305
348 llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());
349 #else
350 llvm::DataLayout TD(mod);
351 #endif
352
353 for (llvm::Function::const_arg_iterator I = kernel_func->arg_begin(),
354 E = kernel_func->arg_end(); I != E; ++I) {
355 const llvm::Argument &arg = *I;
356
357 llvm::Type *arg_type = arg.getType();
358 const unsigned arg_store_size = TD.getTypeStoreSize(arg_type);
359
360 // OpenCL 1.2 specification, Ch. 6.1.5: "A built-in data
361 // type that is not a power of two bytes in size must be
362 // aligned to the next larger power of two". We need this
363 // alignment for three element vectors, which have
364 // non-power-of-2 store size.
365 const unsigned arg_api_size = util_next_power_of_two(arg_store_size);
366
367 llvm::Type *target_type = arg_type->isIntegerTy() ?
368 TD.getSmallestLegalIntType(mod->getContext(), arg_store_size * 8)
369 : arg_type;
370 unsigned target_size = TD.getTypeStoreSize(target_type);
371 unsigned target_align = TD.getABITypeAlignment(target_type);
372
373 if (llvm::isa<llvm::PointerType>(arg_type) && arg.hasByValAttr()) {
374 arg_type =
375 llvm::dyn_cast<llvm::PointerType>(arg_type)->getElementType();
376 }
377
378 if (arg_type->isPointerTy()) {
379 unsigned address_space = llvm::cast<llvm::PointerType>(arg_type)->getAddressSpace();
380 if (address_space == address_spaces[clang::LangAS::opencl_local
381 - clang::LangAS::Offset]) {
382 args.push_back(module::argument(module::argument::local,
383 arg_api_size, target_size,
384 target_align,
385 module::argument::zero_ext));
386 } else {
387 // XXX: Correctly handle constant address space. There is no
388 // way for r600g to pass a handle for constant buffers back
389 // to clover like it can for global buffers, so
390 // creating constant arguments will break r600g. For now,
391 // continue treating constant buffers as global buffers
392 // until we can come up with a way to create handles for
393 // constant buffers.
394 args.push_back(module::argument(module::argument::global,
395 arg_api_size, target_size,
396 target_align,
397 module::argument::zero_ext));
398 }
399
400 } else {
401 llvm::AttributeSet attrs = kernel_func->getAttributes();
402 enum module::argument::ext_type ext_type =
403 (attrs.hasAttribute(arg.getArgNo() + 1,
404 llvm::Attribute::SExt) ?
405 module::argument::sign_ext :
406 module::argument::zero_ext);
407
408 args.push_back(
409 module::argument(module::argument::scalar, arg_api_size,
410 target_size, target_align, ext_type));
411 }
412 }
413
414 // Append implicit arguments. XXX - The types, ordering and
415 // vector size of the implicit arguments should depend on the
416 // target according to the selected calling convention.
417 llvm::Type *size_type =
418 TD.getSmallestLegalIntType(mod->getContext(), sizeof(cl_uint) * 8);
419
420 args.push_back(
421 module::argument(module::argument::scalar, sizeof(cl_uint),
422 TD.getTypeStoreSize(size_type),
423 TD.getABITypeAlignment(size_type),
424 module::argument::zero_ext,
425 module::argument::grid_dimension));
426
427 args.push_back(
428 module::argument(module::argument::scalar, sizeof(cl_uint),
429 TD.getTypeStoreSize(size_type),
430 TD.getABITypeAlignment(size_type),
431 module::argument::zero_ext,
432 module::argument::grid_offset));
433
434 return args;
435 }
436
437 module
438 build_module_llvm(llvm::Module *mod,
439 const std::vector<llvm::Function *> &kernels,
440 clang::LangAS::Map& address_spaces) {
441
442 module m;
443 struct pipe_llvm_program_header header;
444
445 llvm::SmallVector<char, 1024> llvm_bitcode;
446 llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);
447 llvm::BitstreamWriter writer(llvm_bitcode);
448 llvm::WriteBitcodeToFile(mod, bitcode_ostream);
449 bitcode_ostream.flush();
450
451 for (unsigned i = 0; i < kernels.size(); ++i) {
452 std::string kernel_name = kernels[i]->getName();
453 compat::vector<module::argument> args =
454 get_kernel_args(mod, kernel_name, address_spaces);
455
456 m.syms.push_back(module::symbol(kernel_name, 0, i, args ));
457 }
458
459 header.num_bytes = llvm_bitcode.size();
460 std::string data;
461 data.insert(0, (char*)(&header), sizeof(header));
462 data.insert(data.end(), llvm_bitcode.begin(),
463 llvm_bitcode.end());
464 m.secs.push_back(module::section(0, module::section::text,
465 header.num_bytes, data));
466
467 return m;
468 }
469
470 void
471 emit_code(LLVMTargetMachineRef tm, LLVMModuleRef mod,
472 LLVMCodeGenFileType file_type,
473 LLVMMemoryBufferRef *out_buffer,
474 compat::string &r_log) {
475 LLVMBool err;
476 char *err_message = NULL;
477
478 err = LLVMTargetMachineEmitToMemoryBuffer(tm, mod, file_type,
479 &err_message, out_buffer);
480
481 if (err) {
482 r_log = std::string(err_message);
483 }
484
485 LLVMDisposeMessage(err_message);
486
487 if (err) {
488 throw build_error();
489 }
490 }
491
492 std::vector<char>
493 compile_native(const llvm::Module *mod, const std::string &triple,
494 const std::string &processor, unsigned dump_asm,
495 compat::string &r_log) {
496
497 std::string log;
498 LLVMTargetRef target;
499 char *error_message;
500 LLVMMemoryBufferRef out_buffer;
501 unsigned buffer_size;
502 const char *buffer_data;
503 LLVMModuleRef mod_ref = wrap(mod);
504
505 if (LLVMGetTargetFromTriple(triple.c_str(), &target, &error_message)) {
506 r_log = std::string(error_message);
507 LLVMDisposeMessage(error_message);
508 throw build_error();
509 }
510
511 LLVMTargetMachineRef tm = LLVMCreateTargetMachine(
512 target, triple.c_str(), processor.c_str(), "",
513 LLVMCodeGenLevelDefault, LLVMRelocDefault, LLVMCodeModelDefault);
514
515 if (!tm) {
516 r_log = "Could not create TargetMachine: " + triple;
517 throw build_error();
518 }
519
520 if (dump_asm) {
521 LLVMSetTargetMachineAsmVerbosity(tm, true);
522 LLVMModuleRef debug_mod = wrap(llvm::CloneModule(mod));
523 emit_code(tm, debug_mod, LLVMAssemblyFile, &out_buffer, r_log);
524 buffer_size = LLVMGetBufferSize(out_buffer);
525 buffer_data = LLVMGetBufferStart(out_buffer);
526 debug_log(std::string(buffer_data, buffer_size), ".asm");
527
528 LLVMSetTargetMachineAsmVerbosity(tm, false);
529 LLVMDisposeMemoryBuffer(out_buffer);
530 LLVMDisposeModule(debug_mod);
531 }
532
533 emit_code(tm, mod_ref, LLVMObjectFile, &out_buffer, r_log);
534
535 buffer_size = LLVMGetBufferSize(out_buffer);
536 buffer_data = LLVMGetBufferStart(out_buffer);
537
538 std::vector<char> code(buffer_data, buffer_data + buffer_size);
539
540 LLVMDisposeMemoryBuffer(out_buffer);
541 LLVMDisposeTargetMachine(tm);
542
543 return code;
544 }
545
546 std::map<std::string, unsigned>
547 get_kernel_offsets(std::vector<char> &code,
548 const std::vector<llvm::Function *> &kernels,
549 compat::string &r_log) {
550
551 // One of the libelf implementations
552 // (http://www.mr511.de/software/english.htm) requires calling
553 // elf_version() before elf_memory().
554 //
555 elf_version(EV_CURRENT);
556
557 Elf *elf = elf_memory(&code[0], code.size());
558 size_t section_str_index;
559 elf_getshdrstrndx(elf, &section_str_index);
560 Elf_Scn *section = NULL;
561 Elf_Scn *symtab = NULL;
562 GElf_Shdr symtab_header;
563
564 // Find the symbol table
565 try {
566 while ((section = elf_nextscn(elf, section))) {
567 const char *name;
568 if (gelf_getshdr(section, &symtab_header) != &symtab_header) {
569 r_log = "Failed to read ELF section header.";
570 throw build_error();
571 }
572 name = elf_strptr(elf, section_str_index, symtab_header.sh_name);
573 if (!strcmp(name, ".symtab")) {
574 symtab = section;
575 break;
576 }
577 }
578 if (!symtab) {
579 r_log = "Unable to find symbol table.";
580 throw build_error();
581 }
582 } catch (build_error &e) {
583 elf_end(elf);
584 throw e;
585 }
586
587
588 // Extract symbol information from the table
589 Elf_Data *symtab_data = NULL;
590 GElf_Sym *symbol;
591 GElf_Sym s;
592
593 std::map<std::string, unsigned> kernel_offsets;
594 symtab_data = elf_getdata(symtab, symtab_data);
595
596 // Determine the offsets for each kernel
597 for (int i = 0; (symbol = gelf_getsym(symtab_data, i, &s)); i++) {
598 char *name = elf_strptr(elf, symtab_header.sh_link, symbol->st_name);
599 for (std::vector<llvm::Function*>::const_iterator it = kernels.begin(),
600 e = kernels.end(); it != e; ++it) {
601 llvm::Function *f = *it;
602 if (f->getName() == std::string(name))
603 kernel_offsets[f->getName()] = symbol->st_value;
604 }
605 }
606 elf_end(elf);
607 return kernel_offsets;
608 }
609
610 module
611 build_module_native(std::vector<char> &code,
612 const llvm::Module *mod,
613 const std::vector<llvm::Function *> &kernels,
614 const clang::LangAS::Map &address_spaces,
615 compat::string &r_log) {
616
617 std::map<std::string, unsigned> kernel_offsets =
618 get_kernel_offsets(code, kernels, r_log);
619
620 // Begin building the clover module
621 module m;
622 struct pipe_llvm_program_header header;
623
624 // Store the generated ELF binary in the module's text section.
625 header.num_bytes = code.size();
626 std::string data;
627 data.append((char*)(&header), sizeof(header));
628 data.append(code.begin(), code.end());
629 m.secs.push_back(module::section(0, module::section::text,
630 header.num_bytes, data));
631
632 for (std::map<std::string, unsigned>::iterator i = kernel_offsets.begin(),
633 e = kernel_offsets.end(); i != e; ++i) {
634 compat::vector<module::argument> args =
635 get_kernel_args(mod, i->first, address_spaces);
636 m.syms.push_back(module::symbol(i->first, 0, i->second, args ));
637 }
638
639 return m;
640 }
641
642 #if HAVE_LLVM >= 0x0305
643
644 void
645 diagnostic_handler(const llvm::DiagnosticInfo &di, void *data) {
646 if (di.getSeverity() == llvm::DS_Error) {
647 std::string message = *(compat::string*)data;
648 llvm::raw_string_ostream stream(message);
649 llvm::DiagnosticPrinterRawOStream dp(stream);
650 di.print(dp);
651 stream.flush();
652 *(compat::string*)data = message;
653
654 throw build_error();
655 }
656 }
657
658 #endif
659
660 void
661 init_targets() {
662 static bool targets_initialized = false;
663 if (!targets_initialized) {
664 LLVMInitializeAllTargets();
665 LLVMInitializeAllTargetInfos();
666 LLVMInitializeAllTargetMCs();
667 LLVMInitializeAllAsmPrinters();
668 targets_initialized = true;
669 }
670 }
671 } // End anonymous namespace
672
673 #define DBG_CLC (1 << 0)
674 #define DBG_LLVM (1 << 1)
675 #define DBG_ASM (1 << 2)
676
677 static const struct debug_named_value debug_options[] = {
678 {"clc", DBG_CLC, "Dump the OpenCL C code for all kernels."},
679 {"llvm", DBG_LLVM, "Dump the generated LLVM IR for all kernels."},
680 {"asm", DBG_ASM, "Dump kernel assembly code for targets specifying "
681 "PIPE_SHADER_IR_NATIVE"},
682 DEBUG_NAMED_VALUE_END // must be last
683 };
684
685 module
686 clover::compile_program_llvm(const compat::string &source,
687 const header_map &headers,
688 enum pipe_shader_ir ir,
689 const compat::string &target,
690 const compat::string &opts,
691 compat::string &r_log) {
692
693 init_targets();
694 static unsigned debug_flags = debug_get_flags_option("CLOVER_DEBUG",
695 debug_options, 0);
696
697 std::vector<llvm::Function *> kernels;
698 size_t processor_str_len = std::string(target.begin()).find_first_of("-");
699 std::string processor(target.begin(), 0, processor_str_len);
700 std::string triple(target.begin(), processor_str_len + 1,
701 target.size() - processor_str_len - 1);
702 clang::LangAS::Map address_spaces;
703 llvm::LLVMContext llvm_ctx;
704 unsigned optimization_level;
705
706 #if HAVE_LLVM >= 0x0305
707 llvm_ctx.setDiagnosticHandler(diagnostic_handler, &r_log);
708 #endif
709
710 // The input file name must have the .cl extension in order for the
711 // CompilerInvocation class to recognize it as an OpenCL source file.
712 llvm::Module *mod = compile_llvm(llvm_ctx, source, headers, "input.cl",
713 triple, processor, opts, address_spaces,
714 optimization_level, r_log);
715
716 find_kernels(mod, kernels);
717
718 optimize(mod, optimization_level, kernels);
719
720 if (debug_flags & DBG_CLC)
721 debug_log(source, ".cl");
722
723 if (debug_flags & DBG_LLVM) {
724 std::string log;
725 llvm::raw_string_ostream s_log(log);
726 mod->print(s_log, NULL);
727 s_log.flush();
728 debug_log(log, ".ll");
729 }
730
731 module m;
732 // Build the clover::module
733 switch (ir) {
734 case PIPE_SHADER_IR_TGSI:
735 //XXX: Handle TGSI
736 assert(0);
737 m = module();
738 break;
739 case PIPE_SHADER_IR_LLVM:
740 m = build_module_llvm(mod, kernels, address_spaces);
741 break;
742 case PIPE_SHADER_IR_NATIVE: {
743 std::vector<char> code = compile_native(mod, triple, processor,
744 debug_flags & DBG_ASM, r_log);
745 m = build_module_native(code, mod, kernels, address_spaces, r_log);
746 break;
747 }
748 }
749 #if HAVE_LLVM >= 0x0306
750 // LLVM 3.6 and newer, the user takes ownership of the module.
751 delete mod;
752 #endif
753
754 return m;
755 }