blob: bf7274adb5a84a8a51bf4baef06ff70cc69c4f58 [file] [log] [blame]
alan-bakerfec0a472018-11-08 18:09:40 -05001// Copyright 2018 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "clang/Basic/TargetInfo.h"
16#include "clang/CodeGen/CodeGenAction.h"
17#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/FrontendPluginRegistry.h"
19#include "clang/Frontend/TextDiagnosticPrinter.h"
20#include "clang/Lex/PreprocessorOptions.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Verifier.h"
alan-baker0e64a592019-11-18 13:36:25 -050025#include "llvm/InitializePasses.h"
alan-bakerfec0a472018-11-08 18:09:40 -050026#include "llvm/LinkAllPasses.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050027#include "llvm/Support/Allocator.h"
alan-bakerfec0a472018-11-08 18:09:40 -050028#include "llvm/Support/CommandLine.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050029#include "llvm/Support/ErrorOr.h"
alan-bakerfec0a472018-11-08 18:09:40 -050030#include "llvm/Support/MathExtras.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050031#include "llvm/Support/StringSaver.h"
Diego Novillo89500852019-04-15 08:45:10 -040032#include "llvm/Support/ToolOutputFile.h"
alan-bakerfec0a472018-11-08 18:09:40 -050033#include "llvm/Support/raw_ostream.h"
34#include "llvm/Transforms/IPO/PassManagerBuilder.h"
35
Kévin Petit38c52482019-05-07 20:28:00 +080036#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050037#include "clspv/DescriptorMap.h"
alan-bakerfec0a472018-11-08 18:09:40 -050038#include "clspv/Option.h"
39#include "clspv/Passes.h"
40#include "clspv/opencl_builtins_header.h"
41
42#include "FrontendPlugin.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040043#include "Passes.h"
alan-bakerfec0a472018-11-08 18:09:40 -050044
alan-bakerf5e5f692018-11-27 08:33:24 -050045#include <cassert>
alan-bakerfec0a472018-11-08 18:09:40 -050046#include <numeric>
alan-bakerf5e5f692018-11-27 08:33:24 -050047#include <sstream>
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040048#include <string>
alan-bakerfec0a472018-11-08 18:09:40 -050049
50using namespace clang;
51
52namespace {
53// This registration must be located in the same file as the execution of the
54// action.
55static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction>
56 X("extra-validation",
57 "Perform extra validation on OpenCL C when targeting Vulkan");
58
59static llvm::cl::opt<bool> cl_single_precision_constants(
60 "cl-single-precision-constant", llvm::cl::init(false),
61 llvm::cl::desc("Treat double precision floating-point constant as single "
62 "precision constant."));
63
64static llvm::cl::opt<bool> cl_denorms_are_zero(
65 "cl-denorms-are-zero", llvm::cl::init(false),
66 llvm::cl::desc("If specified, denormalized floating point numbers may be "
67 "flushed to zero."));
68
69static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt(
70 "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false),
71 llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and "
72 "sqrt used are correctly rounded."));
73
74static llvm::cl::opt<bool>
75 cl_opt_disable("cl-opt-disable", llvm::cl::init(false),
76 llvm::cl::desc("This option disables all optimizations. The "
77 "default is optimizations are enabled."));
78
79static llvm::cl::opt<bool> cl_mad_enable(
80 "cl-mad-enable", llvm::cl::init(false),
81 llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes "
82 "a * b + c with reduced accuracy."));
83
84static llvm::cl::opt<bool> cl_no_signed_zeros(
85 "cl-no-signed-zeros", llvm::cl::init(false),
86 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
87 "ignore the signedness of zero."));
88
89static llvm::cl::opt<bool> cl_unsafe_math_optimizations(
90 "cl-unsafe-math-optimizations", llvm::cl::init(false),
91 llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) "
92 "assume that arguments and results are valid, (b) may "
93 "violate IEEE 754 standard and (c) may violate the OpenCL "
94 "numerical compliance requirements. This option includes "
95 "the -cl-no-signed-zeros and -cl-mad-enable options."));
96
97static llvm::cl::opt<bool> cl_finite_math_only(
98 "cl-finite-math-only", llvm::cl::init(false),
99 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
100 "assume that arguments and results are not NaNs or INFs."));
101
102static llvm::cl::opt<bool> cl_fast_relaxed_math(
103 "cl-fast-relaxed-math", llvm::cl::init(false),
104 llvm::cl::desc("This option causes the preprocessor macro "
105 "__FAST_RELAXED_MATH__ to be defined. Sets the optimization "
106 "options -cl-finite-math-only and "
107 "-cl-unsafe-math-optimizations."));
108
109static llvm::cl::list<std::string>
110 Includes(llvm::cl::Prefix, "I",
111 llvm::cl::desc("Add a directory to the list of directories "
112 "to be searched for header files."),
113 llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path"));
114
115static llvm::cl::list<std::string>
116 Defines(llvm::cl::Prefix, "D",
117 llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore,
118 llvm::cl::value_desc("define"));
119
120static llvm::cl::opt<std::string>
121 InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"),
122 llvm::cl::init("-"));
123
Kévin Petitddad8f42019-09-30 15:12:08 +0100124static llvm::cl::opt<clang::Language> InputLanguage(
125 "x", llvm::cl::desc("Select input type"),
126 llvm::cl::init(clang::Language::OpenCL),
127 llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"),
128 clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR")));
129
alan-bakerfec0a472018-11-08 18:09:40 -0500130static llvm::cl::opt<std::string>
131 OutputFilename("o", llvm::cl::desc("Override output filename"),
132 llvm::cl::value_desc("filename"));
133
134static llvm::cl::opt<std::string>
135 DescriptorMapFilename("descriptormap",
136 llvm::cl::desc("Output file for descriptor map"),
137 llvm::cl::value_desc("filename"));
138
139static llvm::cl::opt<char>
140 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
141 llvm::cl::desc("Optimization level to use"),
142 llvm::cl::value_desc("level"));
143
alan-bakerfec0a472018-11-08 18:09:40 -0500144static llvm::cl::opt<std::string> OutputFormat(
145 "mfmt", llvm::cl::init(""),
146 llvm::cl::desc(
147 "Specify special output format. 'c' is as a C initializer list"),
148 llvm::cl::value_desc("format"));
149
150static llvm::cl::opt<std::string>
151 SamplerMap("samplermap", llvm::cl::desc("Literal sampler map"),
152 llvm::cl::value_desc("filename"));
153
154static llvm::cl::opt<bool> cluster_non_pointer_kernel_args(
155 "cluster-pod-kernel-args", llvm::cl::init(false),
156 llvm::cl::desc("Collect plain-old-data kernel arguments into a struct in "
157 "a single storage buffer, using a binding number after "
158 "other arguments. Use this to reduce storage buffer "
159 "descriptors."));
160
161static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
162 llvm::cl::desc("Verify diagnostic outputs"));
163
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100164static llvm::cl::opt<bool>
165 IgnoreWarnings("w", llvm::cl::init(false),
166 llvm::cl::desc("Disable all warnings"));
167
168static llvm::cl::opt<bool>
169 WarningsAsErrors("Werror", llvm::cl::init(false),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400170 llvm::cl::desc("Turn warnings into errors"));
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100171
Diego Novillo89500852019-04-15 08:45:10 -0400172static llvm::cl::opt<std::string> IROutputFile(
173 "emit-ir",
174 llvm::cl::desc(
175 "Emit LLVM IR to the given file after parsing and stop compilation."),
176 llvm::cl::value_desc("filename"));
177
alan-bakerfec0a472018-11-08 18:09:40 -0500178// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
179// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500180int ParseSamplerMap(const std::string &sampler_map,
181 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
182 *SamplerMapEntries) {
183 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
184 if (!sampler_map.empty()) {
185 // Parse the sampler map from the provided string.
186 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
187
188 if (!SamplerMap.empty()) {
189 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
190 "provided through a string.\n";
191 }
192 } else if (!SamplerMap.empty()) {
193 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500194 auto errorOrSamplerMapFile =
195 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
196
197 // If there was an error in getting the sampler map file.
198 if (!errorOrSamplerMapFile) {
199 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
200 << " '" << SamplerMap.getValue() << "'\n";
201 return -1;
202 }
203
alan-bakerf5e5f692018-11-27 08:33:24 -0500204 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500205 if (0 == samplerMapBuffer->getBufferSize()) {
206 llvm::errs() << "Error: Sampler map was an empty file!\n";
207 return -1;
208 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500209 }
alan-bakerfec0a472018-11-08 18:09:40 -0500210
alan-bakerf5e5f692018-11-27 08:33:24 -0500211 // No sampler map to parse.
212 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
213 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500214
alan-bakerf5e5f692018-11-27 08:33:24 -0500215 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500216
alan-bakerf5e5f692018-11-27 08:33:24 -0500217 // We need to keep track of the beginning of the current entry.
218 const char *b = samplerMapBuffer->getBufferStart();
219 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
220 // If we have a separator between declarations.
221 if ((*i == '|') || (*i == ',') || (i == e)) {
222 if (i == b) {
223 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
224 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500225 }
226
alan-bakerf5e5f692018-11-27 08:33:24 -0500227 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500228
alan-bakerf5e5f692018-11-27 08:33:24 -0500229 // And set b the next character after i.
230 b = i + 1;
231 }
alan-bakerfec0a472018-11-08 18:09:40 -0500232
alan-bakerf5e5f692018-11-27 08:33:24 -0500233 // If we have a separator between declarations within a single sampler.
234 if ((*i == ',') || (i == e)) {
235 enum NormalizedCoords {
236 CLK_NORMALIZED_COORDS_FALSE = 0x00,
237 CLK_NORMALIZED_COORDS_TRUE = 0x01,
238 CLK_NORMALIZED_COORDS_NOT_SET
239 } NormalizedCoord = CLK_NORMALIZED_COORDS_NOT_SET;
alan-bakerfec0a472018-11-08 18:09:40 -0500240
alan-bakerf5e5f692018-11-27 08:33:24 -0500241 enum AddressingModes {
242 CLK_ADDRESS_NONE = 0x00,
243 CLK_ADDRESS_CLAMP_TO_EDGE = 0x02,
244 CLK_ADDRESS_CLAMP = 0x04,
245 CLK_ADDRESS_MIRRORED_REPEAT = 0x08,
246 CLK_ADDRESS_REPEAT = 0x06,
247 CLK_ADDRESS_NOT_SET
248 } AddressingMode = CLK_ADDRESS_NOT_SET;
249
250 enum FilterModes {
251 CLK_FILTER_NEAREST = 0x10,
252 CLK_FILTER_LINEAR = 0x20,
253 CLK_FILTER_NOT_SET
254 } FilterMode = CLK_FILTER_NOT_SET;
255
256 for (auto str : samplerStrings) {
257 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
258 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
259 llvm::errs() << "Error: Sampler map normalized coordinates was "
260 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500261 return -1;
262 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500263 NormalizedCoord = CLK_NORMALIZED_COORDS_FALSE;
264 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
265 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
266 llvm::errs() << "Error: Sampler map normalized coordinates was "
267 "previously set!\n";
268 return -1;
269 }
270 NormalizedCoord = CLK_NORMALIZED_COORDS_TRUE;
271 } else if ("CLK_ADDRESS_NONE" == str) {
272 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
273 llvm::errs()
274 << "Error: Sampler map addressing mode was previously set!\n";
275 return -1;
276 }
277 AddressingMode = CLK_ADDRESS_NONE;
278 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
279 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
280 llvm::errs()
281 << "Error: Sampler map addressing mode was previously set!\n";
282 return -1;
283 }
284 AddressingMode = CLK_ADDRESS_CLAMP_TO_EDGE;
285 } else if ("CLK_ADDRESS_CLAMP" == str) {
286 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
287 llvm::errs()
288 << "Error: Sampler map addressing mode was previously set!\n";
289 return -1;
290 }
291 AddressingMode = CLK_ADDRESS_CLAMP;
292 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
293 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
294 llvm::errs()
295 << "Error: Sampler map addressing mode was previously set!\n";
296 return -1;
297 }
298 AddressingMode = CLK_ADDRESS_MIRRORED_REPEAT;
299 } else if ("CLK_ADDRESS_REPEAT" == str) {
300 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
301 llvm::errs()
302 << "Error: Sampler map addressing mode was previously set!\n";
303 return -1;
304 }
305 AddressingMode = CLK_ADDRESS_REPEAT;
306 } else if ("CLK_FILTER_NEAREST" == str) {
307 if (CLK_FILTER_NOT_SET != FilterMode) {
308 llvm::errs()
309 << "Error: Sampler map filtering mode was previously set!\n";
310 return -1;
311 }
312 FilterMode = CLK_FILTER_NEAREST;
313 } else if ("CLK_FILTER_LINEAR" == str) {
314 if (CLK_FILTER_NOT_SET != FilterMode) {
315 llvm::errs()
316 << "Error: Sampler map filtering mode was previously set!\n";
317 return -1;
318 }
319 FilterMode = CLK_FILTER_LINEAR;
320 } else {
321 llvm::errs() << "Error: Unknown sampler string '" << str
322 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500323 return -1;
324 }
alan-bakerfec0a472018-11-08 18:09:40 -0500325 }
326
alan-bakerf5e5f692018-11-27 08:33:24 -0500327 if (CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
328 llvm::errs() << "Error: Sampler map entry did not contain normalized "
329 "coordinates entry!\n";
330 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500331 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500332
333 if (CLK_ADDRESS_NOT_SET == AddressingMode) {
334 llvm::errs() << "Error: Sampler map entry did not contain addressing "
335 "mode entry!\n";
336 return -1;
337 }
338
339 if (CLK_FILTER_NOT_SET == FilterMode) {
340 llvm::errs()
341 << "Error: Sampler map entry did not contain filer mode entry!\n";
342 return -1;
343 }
344
345 // Generate an equivalent expression in string form. Sort the
346 // strings to get a canonical ordering.
347 std::sort(samplerStrings.begin(), samplerStrings.end(),
348 std::less<StringRef>());
349 const auto samplerExpr = std::accumulate(
350 samplerStrings.begin(), samplerStrings.end(), std::string(),
351 [](std::string left, std::string right) {
352 return left + std::string(left.empty() ? "" : "|") + right;
353 });
354
355 // SamplerMapEntries->push_back(std::make_pair(
356 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
357 SamplerMapEntries->emplace_back(
358 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
359
360 // And reset the sampler strings for the next sampler in the map.
361 samplerStrings.clear();
362 }
363
364 // And lastly, if we are at the end of the file
365 if (i == e) {
366 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500367 }
368 }
369
370 return 0;
371}
372
373// Sets |instance|'s options for compiling. Returns 0 if successful.
374int SetCompilerInstanceOptions(CompilerInstance &instance,
375 const llvm::StringRef &overiddenInputFilename,
376 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500377 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500378 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500379 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
380 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
381 if (program.empty()) {
382 auto errorOrInputFile =
383 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500384
alan-bakerf5e5f692018-11-27 08:33:24 -0500385 // If there was an error in getting the input file.
386 if (!errorOrInputFile) {
387 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
388 << InputFilename.getValue() << "'\n";
389 return -1;
390 }
391 memory_buffer.reset(errorOrInputFile.get().release());
392 } else {
393 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
394 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500395 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500396
alan-bakerfec0a472018-11-08 18:09:40 -0500397 if (verify) {
398 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400399 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500400 }
401
Kévin Petit0fc88042019-04-09 23:25:02 +0100402 clang::LangStandard::Kind standard;
403 if (clspv::Option::CPlusPlus()) {
404 standard = clang::LangStandard::lang_openclcpp;
405 } else {
406 standard = clang::LangStandard::lang_opencl12;
407 }
alan-bakerfec0a472018-11-08 18:09:40 -0500408
409 // We are targeting OpenCL 1.2 only
410 instance.getLangOpts().OpenCLVersion = 120;
411
412 instance.getLangOpts().C99 = true;
413 instance.getLangOpts().RTTI = false;
414 instance.getLangOpts().RTTIData = false;
415 instance.getLangOpts().MathErrno = false;
416 instance.getLangOpts().Optimize = false;
417 instance.getLangOpts().NoBuiltin = true;
418 instance.getLangOpts().ModulesSearchAll = false;
419 instance.getLangOpts().SinglePrecisionConstants = true;
420 instance.getCodeGenOpts().StackRealignment = true;
421 instance.getCodeGenOpts().SimplifyLibCalls = false;
422 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
423 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100424 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500425
426 instance.getLangOpts().SinglePrecisionConstants =
427 cl_single_precision_constants;
428 // cl_denorms_are_zero ignored for now!
429 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
430 instance.getCodeGenOpts().LessPreciseFPMAD =
431 cl_mad_enable || cl_unsafe_math_optimizations;
432 // cl_no_signed_zeros ignored for now!
433 instance.getCodeGenOpts().UnsafeFPMath =
434 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
435 instance.getLangOpts().FiniteMathOnly =
436 cl_finite_math_only || cl_fast_relaxed_math;
437 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
438
439 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800440 if (!clspv::Option::ImageSupport()) {
441 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
442 }
alan-bakerfec0a472018-11-08 18:09:40 -0500443 if (cl_fast_relaxed_math) {
444 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
445 }
446
447 for (auto define : Defines) {
448 instance.getPreprocessorOpts().addMacroDef(define);
449 }
450
451 // Header search options
452 for (auto include : Includes) {
453 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
454 false, false);
455 }
456
457 // We always compile on opt 0 so we preserve as much debug information about
458 // the source as possible. We'll run optimization later, once we've had a
459 // chance to view the unoptimal code first
460 instance.getCodeGenOpts().OptimizationLevel = 0;
461
462// Debug information is disabled temporarily to call instruction.
463#if 0
464 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
465#endif
466
467 // We use the 32-bit pointer-width SPIR triple
468 llvm::Triple triple("spir-unknown-unknown");
469
470 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400471 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500472 instance.getPreprocessorOpts(), standard);
473
474 // Override the C99 inline semantics to accommodate for more OpenCL C
475 // programs in the wild.
476 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100477
478 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500479 instance.createDiagnostics(
480 new clang::TextDiagnosticPrinter(*diagnosticsStream,
481 &instance.getDiagnosticOpts()),
482 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100483 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
484 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500485
486 instance.getTargetOpts().Triple = triple.str();
487
488 instance.getCodeGenOpts().MainFileName = overiddenInputFilename;
489 instance.getCodeGenOpts().PreserveVec3Type = true;
490 // Disable generation of lifetime intrinsic.
491 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
492 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500493 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
494 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500495
496 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
497 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
498 const char *dataCasted = reinterpret_cast<const char *>(data);
499 init(dataCasted, dataCasted + data_length, true);
500 }
501
502 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
503 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
504 }
505
506 virtual ~OpenCLBuiltinMemoryBuffer() override {}
507 };
508
509 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
510 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
511 opencl_builtins_header_size - 1));
512
513 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
514
alan-bakerf3bce4a2019-06-28 16:01:15 -0400515 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
516 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
517 opencl_base_builtins_header_size - 1));
518
519 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
520
alan-bakerfec0a472018-11-08 18:09:40 -0500521 // Add the VULKAN macro.
522 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
523
524 // Add the __OPENCL_VERSION__ macro.
525 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
526
527 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
528 instance.getDiagnostics(),
529 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
530
531 instance.createFileManager();
532 instance.createSourceManager(instance.getFileManager());
533
534#ifdef _MSC_VER
535 std::string includePrefix("include\\");
536#else
537 std::string includePrefix("include/");
538#endif
539
540 auto entry = instance.getFileManager().getVirtualFile(
541 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
542 0);
543
544 instance.getSourceManager().overrideFileContents(
545 entry, std::move(openCLBuiltinMemoryBuffer));
546
alan-bakerf3bce4a2019-06-28 16:01:15 -0400547 auto base_entry = instance.getFileManager().getVirtualFile(
548 includePrefix + "opencl-c-base.h",
549 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
550
551 instance.getSourceManager().overrideFileContents(
552 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
553
alan-bakerfec0a472018-11-08 18:09:40 -0500554 return 0;
555}
556
alan-bakerf5e5f692018-11-27 08:33:24 -0500557// Populates |pm| with necessary passes to optimize and legalize the IR.
558int PopulatePassManager(
559 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
560 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
561 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
562 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500563 llvm::PassManagerBuilder pmBuilder;
564
565 switch (OptimizationLevel) {
566 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500567 case '1':
568 case '2':
569 case '3':
570 case 's':
571 case 'z':
572 break;
573 default:
574 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
575 << " specified!\n";
576 return -1;
577 }
578
579 switch (OptimizationLevel) {
580 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500581 pmBuilder.OptLevel = 0;
582 break;
583 case '1':
584 pmBuilder.OptLevel = 1;
585 break;
586 case '2':
587 pmBuilder.OptLevel = 2;
588 break;
589 case '3':
590 pmBuilder.OptLevel = 3;
591 break;
592 case 's':
593 pmBuilder.SizeLevel = 1;
594 break;
595 case 'z':
596 pmBuilder.SizeLevel = 2;
597 break;
598 default:
599 break;
600 }
601
602 pm->add(clspv::createZeroInitializeAllocasPass());
603 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
604
605 if (0 < pmBuilder.OptLevel) {
606 pm->add(clspv::createOpenCLInlinerPass());
607 }
608
609 pm->add(clspv::createUndoByvalPass());
610 pm->add(clspv::createUndoSRetPass());
611 if (cluster_non_pointer_kernel_args) {
612 pm->add(clspv::createClusterPodKernelArgumentsPass());
613 }
614 pm->add(clspv::createReplaceOpenCLBuiltinPass());
615
616 // We need to run mem2reg and inst combine early because our
617 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
618 // %1 = alloca i32 1
619 // store <something> %1
620 // %2 = bitcast float* %1
621 // %3 = load float %2
622 pm->add(llvm::createPromoteMemoryToRegisterPass());
623
alan-baker1b13e8f2019-08-08 17:56:51 -0400624 // Try to deal with pointer bitcasts early. This can prevent problems like
625 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
626 // This needs to happen before instcombine and after replacing OpenCL
627 // builtins. This run of the pass will not handle all pointer bitcasts that
628 // could be handled. It should be run again after other optimizations (e.g
629 // InlineFuncWithPointerBitCastArgPass).
630 pm->add(clspv::createSimplifyPointerBitcastPass());
631 pm->add(clspv::createReplacePointerBitcastPass());
632 pm->add(llvm::createDeadCodeEliminationPass());
633
alan-bakerfec0a472018-11-08 18:09:40 -0500634 // Hide loads from __constant address space away from instcombine.
635 // This prevents us from generating select between pointers-to-__constant.
636 // See https://github.com/google/clspv/issues/71
637 pm->add(clspv::createHideConstantLoadsPass());
638
639 pm->add(llvm::createInstructionCombiningPass());
640
641 if (clspv::Option::InlineEntryPoints()) {
642 pm->add(clspv::createInlineEntryPointsPass());
643 } else {
644 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
645 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
646 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
647 }
648
Kévin Petit0fc88042019-04-09 23:25:02 +0100649 if (clspv::Option::CPlusPlus()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800650 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100651 }
652
alan-bakerfec0a472018-11-08 18:09:40 -0500653 if (0 == pmBuilder.OptLevel) {
654 // Mem2Reg pass should be run early because O0 level optimization leaves
655 // redundant alloca, load and store instructions from function arguments.
656 // clspv needs to remove them ahead of transformation.
657 pm->add(llvm::createPromoteMemoryToRegisterPass());
658
659 // SROA pass is run because it will fold structs/unions that are problematic
660 // on Vulkan SPIR-V away.
661 pm->add(llvm::createSROAPass());
662
663 // InstructionCombining pass folds bitcast and gep instructions which are
664 // not supported by Vulkan SPIR-V.
665 pm->add(llvm::createInstructionCombiningPass());
666 }
667
668 // Now we add any of the LLVM optimizations we wanted
669 pmBuilder.populateModulePassManager(*pm);
670
671 // Unhide loads from __constant address space. Undoes the action of
672 // HideConstantLoadsPass.
673 pm->add(clspv::createUnhideConstantLoadsPass());
674
675 pm->add(clspv::createFunctionInternalizerPass());
676 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
677 pm->add(clspv::createUndoBoolPass());
678 pm->add(clspv::createUndoTruncatedSwitchConditionPass());
679 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500680 // Must be run after structurize cfg.
alan-bakerfec0a472018-11-08 18:09:40 -0500681 pm->add(clspv::createReorderBasicBlocksPass());
682 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
683 pm->add(clspv::createSplatArgPass());
684 pm->add(clspv::createSimplifyPointerBitcastPass());
685 pm->add(clspv::createReplacePointerBitcastPass());
686
687 pm->add(clspv::createUndoTranslateSamplerFoldPass());
688
689 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
690 pm->add(clspv::createClusterModuleScopeConstantVars());
691 }
692
693 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakere9308012019-03-15 10:25:13 -0400694 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500695 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
696 pm->add(llvm::createVerifierPass());
697 pm->add(clspv::createDirectResourceAccessPass());
698 // Replacing pointer bitcasts can leave some trivial GEPs
699 // that are easy to remove. Also replace GEPs of GEPS
700 // left by replacing indirect buffer accesses.
701 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500702 // Run after DRA to clean up parameters and help reduce the need for variable
703 // pointers.
704 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500705
706 pm->add(clspv::createSplatSelectConditionPass());
707 pm->add(clspv::createSignedCompareFixupPass());
708 // This pass generates insertions that need to be rewritten.
709 pm->add(clspv::createScalarizePass());
710 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400711 // UBO Transformations
712 if (clspv::Option::ConstantArgsInUniformBuffer() &&
713 !clspv::Option::InlineEntryPoints()) {
714 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
715 // arguments and either multi-version them as necessary or inline them if
716 // multi-versioning cannot be accomplished.
717 pm->add(clspv::createMultiVersionUBOFunctionsPass());
718 // Cleanup passes.
719 // Specialization can blindly generate GEP chains that are easily cleaned up
720 // by SimplifyPointerBitcastPass.
721 pm->add(clspv::createSimplifyPointerBitcastPass());
722 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
723 // problematic to begin with now that they have no uses.
724 pm->add(clspv::createRemoveUnusedArgumentsPass());
725 // DCE cleans up callers of the specialized functions.
726 pm->add(llvm::createDeadCodeEliminationPass());
727 }
alan-bakerfec0a472018-11-08 18:09:40 -0500728 // This pass mucks with types to point where you shouldn't rely on DataLayout
729 // anymore so leave this right before SPIR-V generation.
730 pm->add(clspv::createUBOTypeTransformPass());
alan-baker00e7a582019-06-07 12:54:21 -0400731 pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries,
732 *SamplerMapEntries,
733 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500734
735 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500736}
alan-bakerfec0a472018-11-08 18:09:40 -0500737
Kévin Petitd5db2d22019-04-04 13:55:14 +0100738int ParseOptions(const int argc, const char *const argv[]) {
alan-bakerfec0a472018-11-08 18:09:40 -0500739 // We need to change how one of the called passes works by spoofing
740 // ParseCommandLineOptions with the specific option.
741 const int llvmArgc = 2;
742 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500743 argv[0],
744 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500745 };
746
Kévin Petitd5db2d22019-04-04 13:55:14 +0100747 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500748 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500749 llvm::cl::ParseCommandLineOptions(argc, argv);
750
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400751 if (clspv::Option::CPlusPlus() && !clspv::Option::InlineEntryPoints()) {
Kévin Petit0fc88042019-04-09 23:25:02 +0100752 llvm::errs() << "cannot use -c++ without -inline-entry-points\n";
753 return -1;
754 }
755
Kévin Petitd5db2d22019-04-04 13:55:14 +0100756 return 0;
757}
Diego Novillo89500852019-04-15 08:45:10 -0400758
759int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
760 std::string output) {
761 std::error_code ec;
762 std::unique_ptr<llvm::ToolOutputFile> out(
763 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
764 if (ec) {
765 llvm::errs() << output << ": " << ec.message() << '\n';
766 return -1;
767 }
768 pm->add(llvm::createPrintModulePass(out->os(), "", false));
769 pm->run(module);
770 out->keep();
771 return 0;
772}
773
Kévin Petitd5db2d22019-04-04 13:55:14 +0100774} // namespace
775
776namespace clspv {
777int Compile(const int argc, const char *const argv[]) {
778
779 if (auto error = ParseOptions(argc, argv))
780 return error;
781
alan-bakerfec0a472018-11-08 18:09:40 -0500782 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500783 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500784 return error;
785
786 // if no output file was provided, use a default
787 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
788
789 // If we are reading our input file from stdin.
790 if ("-" == InputFilename) {
791 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100792 switch (InputLanguage) {
793 case clang::Language::OpenCL:
794 overiddenInputFilename = "stdin.cl";
795 break;
796 case clang::Language::LLVM_IR:
797 overiddenInputFilename = "stdin.ll";
798 break;
alan-baker31298a62019-10-07 13:24:30 -0400799 default:
800 // Default to fix compiler warnings/errors. Option parsing will reject a
801 // bad enum value for the option so there is no need for a message.
802 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100803 }
alan-bakerfec0a472018-11-08 18:09:40 -0500804 }
805
806 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100807 clang::FrontendInputFile kernelFile(overiddenInputFilename,
808 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500809 std::string log;
810 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500811 if (auto error = SetCompilerInstanceOptions(
812 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500813 return error;
814
815 // Parse.
816 llvm::LLVMContext context;
817 clang::EmitLLVMOnlyAction action(&context);
818
819 // Prepare the action for processing kernelFile
820 const bool success = action.BeginSourceFile(instance, kernelFile);
821 if (!success) {
822 return -1;
823 }
824
alan-bakerf3bce4a2019-06-28 16:01:15 -0400825 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500826 action.EndSourceFile();
827
828 clang::DiagnosticConsumer *const consumer =
829 instance.getDiagnostics().getClient();
830 consumer->finish();
831
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100832 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500833 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100834 if ((num_errors > 0) || (num_warnings > 0)) {
835 llvm::errs() << log;
836 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400837 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500838 return -1;
839 }
840
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100841 // Don't run the passes or produce any output in verify mode.
842 // Clang doesn't always produce a valid module.
843 if (verify) {
844 return 0;
845 }
846
alan-bakerfec0a472018-11-08 18:09:40 -0500847 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
848 llvm::initializeCore(Registry);
849 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400850 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500851
852 std::unique_ptr<llvm::Module> module(action.takeModule());
853
854 // Optimize.
855 // Create a memory buffer for temporarily writing the result.
856 SmallVector<char, 10000> binary;
857 llvm::raw_svector_ostream binaryStream(binary);
858 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500859 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500860 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
Diego Novillo89500852019-04-15 08:45:10 -0400861
862 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
863 if (!IROutputFile.empty()) {
864 return GenerateIRFile(&pm, *module, IROutputFile);
865 }
866
867 // Otherwise, populate the pass manager and run the regular passes.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400868 if (auto error = PopulatePassManager(
869 &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500870 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500871 pm.run(*module);
872
873 // Write outputs
874
875 // Write the descriptor map, if requested.
876 std::error_code error;
877 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400878 llvm::raw_fd_ostream descriptor_map_out_fd(
879 DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways,
880 llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text);
alan-bakerfec0a472018-11-08 18:09:40 -0500881 if (error) {
882 llvm::errs() << "Unable to open descriptor map file '"
883 << DescriptorMapFilename << "': " << error.message() << '\n';
884 return -1;
885 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500886 std::string descriptor_map_string;
887 std::ostringstream str(descriptor_map_string);
888 for (const auto &entry : descriptor_map_entries) {
889 str << entry << "\n";
890 }
891 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500892 descriptor_map_out_fd.close();
893 }
894
895 // Write the resulting binary.
896 // Wait until now to try writing the file so that we only write it on
897 // successful compilation.
898 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100899 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500900 OutputFilename = "a.spvinc";
901 } else {
902 OutputFilename = "a.spv";
903 }
904 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400905 llvm::raw_fd_ostream outStream(OutputFilename, error,
906 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500907
908 if (error) {
909 llvm::errs() << "Unable to open output file '" << OutputFilename
910 << "': " << error.message() << '\n';
911 return -1;
912 }
913 outStream << binaryStream.str();
914
915 return 0;
916}
alan-bakerf5e5f692018-11-27 08:33:24 -0500917
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400918int CompileFromSourceString(
919 const std::string &program, const std::string &sampler_map,
920 const std::string &options, std::vector<uint32_t> *output_binary,
921 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500922
923 llvm::SmallVector<const char *, 20> argv;
924 llvm::BumpPtrAllocator A;
925 llvm::StringSaver Saver(A);
926 argv.push_back(Saver.save("clspv").data());
927 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
928 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100929
930 if (auto error = ParseOptions(argc, &argv[0]))
931 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500932
933 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
934 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
935 return error;
936
937 InputFilename = "source.cl";
938 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
939
940 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400941 clang::FrontendInputFile kernelFile(
942 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500943 std::string log;
944 llvm::raw_string_ostream diagnosticsStream(log);
945 if (auto error =
946 SetCompilerInstanceOptions(instance, overiddenInputFilename,
947 kernelFile, program, &diagnosticsStream))
948 return error;
949
950 // Parse.
951 llvm::LLVMContext context;
952 clang::EmitLLVMOnlyAction action(&context);
953
954 // Prepare the action for processing kernelFile
955 const bool success = action.BeginSourceFile(instance, kernelFile);
956 if (!success) {
957 return -1;
958 }
959
alan-bakerf3bce4a2019-06-28 16:01:15 -0400960 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -0500961 action.EndSourceFile();
962
963 clang::DiagnosticConsumer *const consumer =
964 instance.getDiagnostics().getClient();
965 consumer->finish();
966
967 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -0400968 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500969 llvm::errs() << log << "\n";
970 return -1;
971 }
972
alan-bakerf5e5f692018-11-27 08:33:24 -0500973 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
974 llvm::initializeCore(Registry);
975 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400976 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -0500977
978 std::unique_ptr<llvm::Module> module(action.takeModule());
979
980 // Optimize.
981 // Create a memory buffer for temporarily writing the result.
982 SmallVector<char, 10000> binary;
983 llvm::raw_svector_ostream binaryStream(binary);
984 std::string descriptor_map;
985 llvm::legacy::PassManager pm;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400986 if (auto error = PopulatePassManager(
987 &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500988 return error;
989 pm.run(*module);
990
991 // Write outputs
992
993 // Write the descriptor map. This is required.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400994 assert(descriptor_map_entries &&
995 "Valid descriptor map container is required.");
alan-bakerf5e5f692018-11-27 08:33:24 -0500996 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400997 llvm::errs() << "Warning: -descriptormap is ignored descriptor map "
998 "container is provided.\n";
alan-bakerf5e5f692018-11-27 08:33:24 -0500999 }
1000
1001 // Write the resulting binary.
1002 // Wait until now to try writing the file so that we only write it on
1003 // successful compilation.
1004 assert(output_binary && "Valid binary container is required.");
1005 if (!OutputFilename.empty()) {
1006 llvm::outs()
1007 << "Warning: -o is ignored when binary container is provided.\n";
1008 }
1009 output_binary->resize(binary.size() / 4);
1010 memcpy(output_binary->data(), binary.data(), binary.size());
1011
1012 return 0;
1013}
alan-bakerfec0a472018-11-08 18:09:40 -05001014} // namespace clspv