blob: 1ce2fba4798ffae848c193d2e5cb0a9159384273 [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-bakerf67468c2019-11-25 15:51:49 -0500694 // Specialize images before assigning descriptors to disambiguate the various
695 // types.
696 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400697 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500698 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
699 pm->add(llvm::createVerifierPass());
700 pm->add(clspv::createDirectResourceAccessPass());
701 // Replacing pointer bitcasts can leave some trivial GEPs
702 // that are easy to remove. Also replace GEPs of GEPS
703 // left by replacing indirect buffer accesses.
704 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500705 // Run after DRA to clean up parameters and help reduce the need for variable
706 // pointers.
707 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500708
709 pm->add(clspv::createSplatSelectConditionPass());
710 pm->add(clspv::createSignedCompareFixupPass());
711 // This pass generates insertions that need to be rewritten.
712 pm->add(clspv::createScalarizePass());
713 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400714 // UBO Transformations
715 if (clspv::Option::ConstantArgsInUniformBuffer() &&
716 !clspv::Option::InlineEntryPoints()) {
717 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
718 // arguments and either multi-version them as necessary or inline them if
719 // multi-versioning cannot be accomplished.
720 pm->add(clspv::createMultiVersionUBOFunctionsPass());
721 // Cleanup passes.
722 // Specialization can blindly generate GEP chains that are easily cleaned up
723 // by SimplifyPointerBitcastPass.
724 pm->add(clspv::createSimplifyPointerBitcastPass());
725 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
726 // problematic to begin with now that they have no uses.
727 pm->add(clspv::createRemoveUnusedArgumentsPass());
728 // DCE cleans up callers of the specialized functions.
729 pm->add(llvm::createDeadCodeEliminationPass());
730 }
alan-bakerfec0a472018-11-08 18:09:40 -0500731 // This pass mucks with types to point where you shouldn't rely on DataLayout
732 // anymore so leave this right before SPIR-V generation.
733 pm->add(clspv::createUBOTypeTransformPass());
alan-baker00e7a582019-06-07 12:54:21 -0400734 pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries,
735 *SamplerMapEntries,
736 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500737
738 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500739}
alan-bakerfec0a472018-11-08 18:09:40 -0500740
Kévin Petitd5db2d22019-04-04 13:55:14 +0100741int ParseOptions(const int argc, const char *const argv[]) {
alan-bakerfec0a472018-11-08 18:09:40 -0500742 // We need to change how one of the called passes works by spoofing
743 // ParseCommandLineOptions with the specific option.
744 const int llvmArgc = 2;
745 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500746 argv[0],
747 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500748 };
749
Kévin Petitd5db2d22019-04-04 13:55:14 +0100750 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500751 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500752 llvm::cl::ParseCommandLineOptions(argc, argv);
753
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400754 if (clspv::Option::CPlusPlus() && !clspv::Option::InlineEntryPoints()) {
Kévin Petit0fc88042019-04-09 23:25:02 +0100755 llvm::errs() << "cannot use -c++ without -inline-entry-points\n";
756 return -1;
757 }
758
Kévin Petitd5db2d22019-04-04 13:55:14 +0100759 return 0;
760}
Diego Novillo89500852019-04-15 08:45:10 -0400761
762int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
763 std::string output) {
764 std::error_code ec;
765 std::unique_ptr<llvm::ToolOutputFile> out(
766 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
767 if (ec) {
768 llvm::errs() << output << ": " << ec.message() << '\n';
769 return -1;
770 }
771 pm->add(llvm::createPrintModulePass(out->os(), "", false));
772 pm->run(module);
773 out->keep();
774 return 0;
775}
776
Kévin Petitd5db2d22019-04-04 13:55:14 +0100777} // namespace
778
779namespace clspv {
780int Compile(const int argc, const char *const argv[]) {
781
782 if (auto error = ParseOptions(argc, argv))
783 return error;
784
alan-bakerfec0a472018-11-08 18:09:40 -0500785 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500786 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500787 return error;
788
789 // if no output file was provided, use a default
790 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
791
792 // If we are reading our input file from stdin.
793 if ("-" == InputFilename) {
794 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100795 switch (InputLanguage) {
796 case clang::Language::OpenCL:
797 overiddenInputFilename = "stdin.cl";
798 break;
799 case clang::Language::LLVM_IR:
800 overiddenInputFilename = "stdin.ll";
801 break;
alan-baker31298a62019-10-07 13:24:30 -0400802 default:
803 // Default to fix compiler warnings/errors. Option parsing will reject a
804 // bad enum value for the option so there is no need for a message.
805 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100806 }
alan-bakerfec0a472018-11-08 18:09:40 -0500807 }
808
809 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100810 clang::FrontendInputFile kernelFile(overiddenInputFilename,
811 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500812 std::string log;
813 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500814 if (auto error = SetCompilerInstanceOptions(
815 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500816 return error;
817
818 // Parse.
819 llvm::LLVMContext context;
820 clang::EmitLLVMOnlyAction action(&context);
821
822 // Prepare the action for processing kernelFile
823 const bool success = action.BeginSourceFile(instance, kernelFile);
824 if (!success) {
825 return -1;
826 }
827
alan-bakerf3bce4a2019-06-28 16:01:15 -0400828 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500829 action.EndSourceFile();
830
831 clang::DiagnosticConsumer *const consumer =
832 instance.getDiagnostics().getClient();
833 consumer->finish();
834
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100835 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500836 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100837 if ((num_errors > 0) || (num_warnings > 0)) {
838 llvm::errs() << log;
839 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400840 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500841 return -1;
842 }
843
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100844 // Don't run the passes or produce any output in verify mode.
845 // Clang doesn't always produce a valid module.
846 if (verify) {
847 return 0;
848 }
849
alan-bakerfec0a472018-11-08 18:09:40 -0500850 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
851 llvm::initializeCore(Registry);
852 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400853 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500854
855 std::unique_ptr<llvm::Module> module(action.takeModule());
856
857 // Optimize.
858 // Create a memory buffer for temporarily writing the result.
859 SmallVector<char, 10000> binary;
860 llvm::raw_svector_ostream binaryStream(binary);
861 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500862 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500863 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
Diego Novillo89500852019-04-15 08:45:10 -0400864
865 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
866 if (!IROutputFile.empty()) {
867 return GenerateIRFile(&pm, *module, IROutputFile);
868 }
869
870 // Otherwise, populate the pass manager and run the regular passes.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400871 if (auto error = PopulatePassManager(
872 &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500873 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500874 pm.run(*module);
875
876 // Write outputs
877
878 // Write the descriptor map, if requested.
879 std::error_code error;
880 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400881 llvm::raw_fd_ostream descriptor_map_out_fd(
882 DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways,
883 llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text);
alan-bakerfec0a472018-11-08 18:09:40 -0500884 if (error) {
885 llvm::errs() << "Unable to open descriptor map file '"
886 << DescriptorMapFilename << "': " << error.message() << '\n';
887 return -1;
888 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500889 std::string descriptor_map_string;
890 std::ostringstream str(descriptor_map_string);
891 for (const auto &entry : descriptor_map_entries) {
892 str << entry << "\n";
893 }
894 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500895 descriptor_map_out_fd.close();
896 }
897
898 // Write the resulting binary.
899 // Wait until now to try writing the file so that we only write it on
900 // successful compilation.
901 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100902 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500903 OutputFilename = "a.spvinc";
904 } else {
905 OutputFilename = "a.spv";
906 }
907 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400908 llvm::raw_fd_ostream outStream(OutputFilename, error,
909 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500910
911 if (error) {
912 llvm::errs() << "Unable to open output file '" << OutputFilename
913 << "': " << error.message() << '\n';
914 return -1;
915 }
916 outStream << binaryStream.str();
917
918 return 0;
919}
alan-bakerf5e5f692018-11-27 08:33:24 -0500920
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400921int CompileFromSourceString(
922 const std::string &program, const std::string &sampler_map,
923 const std::string &options, std::vector<uint32_t> *output_binary,
924 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500925
926 llvm::SmallVector<const char *, 20> argv;
927 llvm::BumpPtrAllocator A;
928 llvm::StringSaver Saver(A);
929 argv.push_back(Saver.save("clspv").data());
930 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
931 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100932
933 if (auto error = ParseOptions(argc, &argv[0]))
934 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500935
936 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
937 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
938 return error;
939
940 InputFilename = "source.cl";
941 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
942
943 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400944 clang::FrontendInputFile kernelFile(
945 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500946 std::string log;
947 llvm::raw_string_ostream diagnosticsStream(log);
948 if (auto error =
949 SetCompilerInstanceOptions(instance, overiddenInputFilename,
950 kernelFile, program, &diagnosticsStream))
951 return error;
952
953 // Parse.
954 llvm::LLVMContext context;
955 clang::EmitLLVMOnlyAction action(&context);
956
957 // Prepare the action for processing kernelFile
958 const bool success = action.BeginSourceFile(instance, kernelFile);
959 if (!success) {
960 return -1;
961 }
962
alan-bakerf3bce4a2019-06-28 16:01:15 -0400963 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -0500964 action.EndSourceFile();
965
966 clang::DiagnosticConsumer *const consumer =
967 instance.getDiagnostics().getClient();
968 consumer->finish();
969
970 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -0400971 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500972 llvm::errs() << log << "\n";
973 return -1;
974 }
975
alan-bakerf5e5f692018-11-27 08:33:24 -0500976 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
977 llvm::initializeCore(Registry);
978 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400979 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -0500980
981 std::unique_ptr<llvm::Module> module(action.takeModule());
982
983 // Optimize.
984 // Create a memory buffer for temporarily writing the result.
985 SmallVector<char, 10000> binary;
986 llvm::raw_svector_ostream binaryStream(binary);
987 std::string descriptor_map;
988 llvm::legacy::PassManager pm;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400989 if (auto error = PopulatePassManager(
990 &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500991 return error;
992 pm.run(*module);
993
994 // Write outputs
995
996 // Write the descriptor map. This is required.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400997 assert(descriptor_map_entries &&
998 "Valid descriptor map container is required.");
alan-bakerf5e5f692018-11-27 08:33:24 -0500999 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001000 llvm::errs() << "Warning: -descriptormap is ignored descriptor map "
1001 "container is provided.\n";
alan-bakerf5e5f692018-11-27 08:33:24 -05001002 }
1003
1004 // Write the resulting binary.
1005 // Wait until now to try writing the file so that we only write it on
1006 // successful compilation.
1007 assert(output_binary && "Valid binary container is required.");
1008 if (!OutputFilename.empty()) {
1009 llvm::outs()
1010 << "Warning: -o is ignored when binary container is provided.\n";
1011 }
1012 output_binary->resize(binary.size() / 4);
1013 memcpy(output_binary->data(), binary.data(), binary.size());
1014
1015 return 0;
1016}
alan-bakerfec0a472018-11-08 18:09:40 -05001017} // namespace clspv