blob: 905b7d126ef9416891a2a1039f6d134fadb03c44 [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>
alan-baker09cb9802019-12-10 13:16:27 -0500151 SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"),
alan-bakerfec0a472018-11-08 18:09:40 -0500152 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
alan-baker09cb9802019-12-10 13:16:27 -0500188 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500189 if (!SamplerMap.empty()) {
190 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
191 "provided through a string.\n";
192 }
193 } else if (!SamplerMap.empty()) {
194 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500195 auto errorOrSamplerMapFile =
196 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
197
198 // If there was an error in getting the sampler map file.
199 if (!errorOrSamplerMapFile) {
200 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
201 << " '" << SamplerMap.getValue() << "'\n";
202 return -1;
203 }
204
alan-baker09cb9802019-12-10 13:16:27 -0500205 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500206 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500207 if (0 == samplerMapBuffer->getBufferSize()) {
208 llvm::errs() << "Error: Sampler map was an empty file!\n";
209 return -1;
210 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500211 }
alan-bakerfec0a472018-11-08 18:09:40 -0500212
alan-baker09cb9802019-12-10 13:16:27 -0500213 if (clspv::Option::UseSamplerMap()) {
214 llvm::outs()
215 << "Warning: use of the sampler map is deprecated and unnecessary\n";
216 }
217
alan-bakerf5e5f692018-11-27 08:33:24 -0500218 // No sampler map to parse.
219 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
220 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500221
alan-bakerf5e5f692018-11-27 08:33:24 -0500222 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500223
alan-bakerf5e5f692018-11-27 08:33:24 -0500224 // We need to keep track of the beginning of the current entry.
225 const char *b = samplerMapBuffer->getBufferStart();
226 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
227 // If we have a separator between declarations.
228 if ((*i == '|') || (*i == ',') || (i == e)) {
229 if (i == b) {
230 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
231 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500232 }
233
alan-bakerf5e5f692018-11-27 08:33:24 -0500234 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500235
alan-bakerf5e5f692018-11-27 08:33:24 -0500236 // And set b the next character after i.
237 b = i + 1;
238 }
alan-bakerfec0a472018-11-08 18:09:40 -0500239
alan-bakerf5e5f692018-11-27 08:33:24 -0500240 // If we have a separator between declarations within a single sampler.
241 if ((*i == ',') || (i == e)) {
242 enum NormalizedCoords {
243 CLK_NORMALIZED_COORDS_FALSE = 0x00,
244 CLK_NORMALIZED_COORDS_TRUE = 0x01,
245 CLK_NORMALIZED_COORDS_NOT_SET
246 } NormalizedCoord = CLK_NORMALIZED_COORDS_NOT_SET;
alan-bakerfec0a472018-11-08 18:09:40 -0500247
alan-bakerf5e5f692018-11-27 08:33:24 -0500248 enum AddressingModes {
249 CLK_ADDRESS_NONE = 0x00,
250 CLK_ADDRESS_CLAMP_TO_EDGE = 0x02,
251 CLK_ADDRESS_CLAMP = 0x04,
252 CLK_ADDRESS_MIRRORED_REPEAT = 0x08,
253 CLK_ADDRESS_REPEAT = 0x06,
254 CLK_ADDRESS_NOT_SET
255 } AddressingMode = CLK_ADDRESS_NOT_SET;
256
257 enum FilterModes {
258 CLK_FILTER_NEAREST = 0x10,
259 CLK_FILTER_LINEAR = 0x20,
260 CLK_FILTER_NOT_SET
261 } FilterMode = CLK_FILTER_NOT_SET;
262
263 for (auto str : samplerStrings) {
264 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
265 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
266 llvm::errs() << "Error: Sampler map normalized coordinates was "
267 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500268 return -1;
269 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500270 NormalizedCoord = CLK_NORMALIZED_COORDS_FALSE;
271 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
272 if (CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
273 llvm::errs() << "Error: Sampler map normalized coordinates was "
274 "previously set!\n";
275 return -1;
276 }
277 NormalizedCoord = CLK_NORMALIZED_COORDS_TRUE;
278 } else if ("CLK_ADDRESS_NONE" == 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_NONE;
285 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == 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_TO_EDGE;
292 } else if ("CLK_ADDRESS_CLAMP" == 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_CLAMP;
299 } else if ("CLK_ADDRESS_MIRRORED_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_MIRRORED_REPEAT;
306 } else if ("CLK_ADDRESS_REPEAT" == str) {
307 if (CLK_ADDRESS_NOT_SET != AddressingMode) {
308 llvm::errs()
309 << "Error: Sampler map addressing mode was previously set!\n";
310 return -1;
311 }
312 AddressingMode = CLK_ADDRESS_REPEAT;
313 } else if ("CLK_FILTER_NEAREST" == 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_NEAREST;
320 } else if ("CLK_FILTER_LINEAR" == str) {
321 if (CLK_FILTER_NOT_SET != FilterMode) {
322 llvm::errs()
323 << "Error: Sampler map filtering mode was previously set!\n";
324 return -1;
325 }
326 FilterMode = CLK_FILTER_LINEAR;
327 } else {
328 llvm::errs() << "Error: Unknown sampler string '" << str
329 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500330 return -1;
331 }
alan-bakerfec0a472018-11-08 18:09:40 -0500332 }
333
alan-bakerf5e5f692018-11-27 08:33:24 -0500334 if (CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
335 llvm::errs() << "Error: Sampler map entry did not contain normalized "
336 "coordinates entry!\n";
337 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500338 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500339
340 if (CLK_ADDRESS_NOT_SET == AddressingMode) {
341 llvm::errs() << "Error: Sampler map entry did not contain addressing "
342 "mode entry!\n";
343 return -1;
344 }
345
346 if (CLK_FILTER_NOT_SET == FilterMode) {
347 llvm::errs()
348 << "Error: Sampler map entry did not contain filer mode entry!\n";
349 return -1;
350 }
351
352 // Generate an equivalent expression in string form. Sort the
353 // strings to get a canonical ordering.
354 std::sort(samplerStrings.begin(), samplerStrings.end(),
355 std::less<StringRef>());
356 const auto samplerExpr = std::accumulate(
357 samplerStrings.begin(), samplerStrings.end(), std::string(),
358 [](std::string left, std::string right) {
359 return left + std::string(left.empty() ? "" : "|") + right;
360 });
361
362 // SamplerMapEntries->push_back(std::make_pair(
363 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
364 SamplerMapEntries->emplace_back(
365 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
366
367 // And reset the sampler strings for the next sampler in the map.
368 samplerStrings.clear();
369 }
370
371 // And lastly, if we are at the end of the file
372 if (i == e) {
373 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500374 }
375 }
376
377 return 0;
378}
379
380// Sets |instance|'s options for compiling. Returns 0 if successful.
381int SetCompilerInstanceOptions(CompilerInstance &instance,
382 const llvm::StringRef &overiddenInputFilename,
383 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500384 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500385 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500386 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
387 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
388 if (program.empty()) {
389 auto errorOrInputFile =
390 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500391
alan-bakerf5e5f692018-11-27 08:33:24 -0500392 // If there was an error in getting the input file.
393 if (!errorOrInputFile) {
394 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
395 << InputFilename.getValue() << "'\n";
396 return -1;
397 }
398 memory_buffer.reset(errorOrInputFile.get().release());
399 } else {
400 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
401 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500402 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500403
alan-bakerfec0a472018-11-08 18:09:40 -0500404 if (verify) {
405 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400406 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500407 }
408
Kévin Petit0fc88042019-04-09 23:25:02 +0100409 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000410 switch (clspv::Option::Language()) {
411 case clspv::Option::SourceLanguage::OpenCL_C_10:
412 standard = clang::LangStandard::lang_opencl10;
413 break;
414 case clspv::Option::SourceLanguage::OpenCL_C_11:
415 standard = clang::LangStandard::lang_opencl11;
416 break;
417 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100418 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000419 break;
420 case clspv::Option::SourceLanguage::OpenCL_C_20:
421 standard = clang::LangStandard::lang_opencl20;
422 break;
423 case clspv::Option::SourceLanguage::OpenCL_CPP:
424 standard = clang::LangStandard::lang_openclcpp;
425 break;
426 default:
427 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100428 }
alan-bakerfec0a472018-11-08 18:09:40 -0500429
alan-bakerfec0a472018-11-08 18:09:40 -0500430 instance.getLangOpts().C99 = true;
431 instance.getLangOpts().RTTI = false;
432 instance.getLangOpts().RTTIData = false;
433 instance.getLangOpts().MathErrno = false;
434 instance.getLangOpts().Optimize = false;
435 instance.getLangOpts().NoBuiltin = true;
436 instance.getLangOpts().ModulesSearchAll = false;
437 instance.getLangOpts().SinglePrecisionConstants = true;
438 instance.getCodeGenOpts().StackRealignment = true;
439 instance.getCodeGenOpts().SimplifyLibCalls = false;
440 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
441 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100442 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500443
444 instance.getLangOpts().SinglePrecisionConstants =
445 cl_single_precision_constants;
446 // cl_denorms_are_zero ignored for now!
447 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
448 instance.getCodeGenOpts().LessPreciseFPMAD =
449 cl_mad_enable || cl_unsafe_math_optimizations;
450 // cl_no_signed_zeros ignored for now!
451 instance.getCodeGenOpts().UnsafeFPMath =
452 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
453 instance.getLangOpts().FiniteMathOnly =
454 cl_finite_math_only || cl_fast_relaxed_math;
455 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
456
457 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800458 if (!clspv::Option::ImageSupport()) {
459 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
460 }
alan-bakerfec0a472018-11-08 18:09:40 -0500461 if (cl_fast_relaxed_math) {
462 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
463 }
464
465 for (auto define : Defines) {
466 instance.getPreprocessorOpts().addMacroDef(define);
467 }
468
469 // Header search options
470 for (auto include : Includes) {
471 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
472 false, false);
473 }
474
475 // We always compile on opt 0 so we preserve as much debug information about
476 // the source as possible. We'll run optimization later, once we've had a
477 // chance to view the unoptimal code first
478 instance.getCodeGenOpts().OptimizationLevel = 0;
479
480// Debug information is disabled temporarily to call instruction.
481#if 0
482 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
483#endif
484
485 // We use the 32-bit pointer-width SPIR triple
486 llvm::Triple triple("spir-unknown-unknown");
487
488 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400489 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500490 instance.getPreprocessorOpts(), standard);
491
492 // Override the C99 inline semantics to accommodate for more OpenCL C
493 // programs in the wild.
494 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100495
496 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500497 instance.createDiagnostics(
498 new clang::TextDiagnosticPrinter(*diagnosticsStream,
499 &instance.getDiagnosticOpts()),
500 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100501 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
502 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500503
504 instance.getTargetOpts().Triple = triple.str();
505
506 instance.getCodeGenOpts().MainFileName = overiddenInputFilename;
507 instance.getCodeGenOpts().PreserveVec3Type = true;
508 // Disable generation of lifetime intrinsic.
509 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
510 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500511 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
512 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500513
514 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
515 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
516 const char *dataCasted = reinterpret_cast<const char *>(data);
517 init(dataCasted, dataCasted + data_length, true);
518 }
519
520 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
521 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
522 }
523
524 virtual ~OpenCLBuiltinMemoryBuffer() override {}
525 };
526
527 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
528 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
529 opencl_builtins_header_size - 1));
530
531 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
532
alan-bakerf3bce4a2019-06-28 16:01:15 -0400533 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
534 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
535 opencl_base_builtins_header_size - 1));
536
537 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
538
alan-bakerfec0a472018-11-08 18:09:40 -0500539 // Add the VULKAN macro.
540 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
541
542 // Add the __OPENCL_VERSION__ macro.
543 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
544
545 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
546 instance.getDiagnostics(),
547 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
548
549 instance.createFileManager();
550 instance.createSourceManager(instance.getFileManager());
551
552#ifdef _MSC_VER
553 std::string includePrefix("include\\");
554#else
555 std::string includePrefix("include/");
556#endif
557
558 auto entry = instance.getFileManager().getVirtualFile(
559 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
560 0);
561
562 instance.getSourceManager().overrideFileContents(
563 entry, std::move(openCLBuiltinMemoryBuffer));
564
alan-bakerf3bce4a2019-06-28 16:01:15 -0400565 auto base_entry = instance.getFileManager().getVirtualFile(
566 includePrefix + "opencl-c-base.h",
567 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
568
569 instance.getSourceManager().overrideFileContents(
570 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
571
alan-bakerfec0a472018-11-08 18:09:40 -0500572 return 0;
573}
574
alan-bakerf5e5f692018-11-27 08:33:24 -0500575// Populates |pm| with necessary passes to optimize and legalize the IR.
576int PopulatePassManager(
577 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
578 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
579 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
580 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500581 llvm::PassManagerBuilder pmBuilder;
582
583 switch (OptimizationLevel) {
584 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500585 case '1':
586 case '2':
587 case '3':
588 case 's':
589 case 'z':
590 break;
591 default:
592 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
593 << " specified!\n";
594 return -1;
595 }
596
597 switch (OptimizationLevel) {
598 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500599 pmBuilder.OptLevel = 0;
600 break;
601 case '1':
602 pmBuilder.OptLevel = 1;
603 break;
604 case '2':
605 pmBuilder.OptLevel = 2;
606 break;
607 case '3':
608 pmBuilder.OptLevel = 3;
609 break;
610 case 's':
611 pmBuilder.SizeLevel = 1;
612 break;
613 case 'z':
614 pmBuilder.SizeLevel = 2;
615 break;
616 default:
617 break;
618 }
619
620 pm->add(clspv::createZeroInitializeAllocasPass());
621 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
622
623 if (0 < pmBuilder.OptLevel) {
624 pm->add(clspv::createOpenCLInlinerPass());
625 }
626
627 pm->add(clspv::createUndoByvalPass());
628 pm->add(clspv::createUndoSRetPass());
629 if (cluster_non_pointer_kernel_args) {
630 pm->add(clspv::createClusterPodKernelArgumentsPass());
631 }
632 pm->add(clspv::createReplaceOpenCLBuiltinPass());
633
634 // We need to run mem2reg and inst combine early because our
635 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
636 // %1 = alloca i32 1
637 // store <something> %1
638 // %2 = bitcast float* %1
639 // %3 = load float %2
640 pm->add(llvm::createPromoteMemoryToRegisterPass());
641
alan-baker1b13e8f2019-08-08 17:56:51 -0400642 // Try to deal with pointer bitcasts early. This can prevent problems like
643 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
644 // This needs to happen before instcombine and after replacing OpenCL
645 // builtins. This run of the pass will not handle all pointer bitcasts that
646 // could be handled. It should be run again after other optimizations (e.g
647 // InlineFuncWithPointerBitCastArgPass).
648 pm->add(clspv::createSimplifyPointerBitcastPass());
649 pm->add(clspv::createReplacePointerBitcastPass());
650 pm->add(llvm::createDeadCodeEliminationPass());
651
alan-bakerfec0a472018-11-08 18:09:40 -0500652 // Hide loads from __constant address space away from instcombine.
653 // This prevents us from generating select between pointers-to-__constant.
654 // See https://github.com/google/clspv/issues/71
655 pm->add(clspv::createHideConstantLoadsPass());
656
657 pm->add(llvm::createInstructionCombiningPass());
658
659 if (clspv::Option::InlineEntryPoints()) {
660 pm->add(clspv::createInlineEntryPointsPass());
661 } else {
662 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
663 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
664 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
665 }
666
Kévin Petitf0515712020-01-07 18:29:20 +0000667 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800668 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100669 }
670
alan-bakerfec0a472018-11-08 18:09:40 -0500671 if (0 == pmBuilder.OptLevel) {
672 // Mem2Reg pass should be run early because O0 level optimization leaves
673 // redundant alloca, load and store instructions from function arguments.
674 // clspv needs to remove them ahead of transformation.
675 pm->add(llvm::createPromoteMemoryToRegisterPass());
676
677 // SROA pass is run because it will fold structs/unions that are problematic
678 // on Vulkan SPIR-V away.
679 pm->add(llvm::createSROAPass());
680
681 // InstructionCombining pass folds bitcast and gep instructions which are
682 // not supported by Vulkan SPIR-V.
683 pm->add(llvm::createInstructionCombiningPass());
684 }
685
686 // Now we add any of the LLVM optimizations we wanted
687 pmBuilder.populateModulePassManager(*pm);
688
689 // Unhide loads from __constant address space. Undoes the action of
690 // HideConstantLoadsPass.
691 pm->add(clspv::createUnhideConstantLoadsPass());
692
693 pm->add(clspv::createFunctionInternalizerPass());
694 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
695 pm->add(clspv::createUndoBoolPass());
696 pm->add(clspv::createUndoTruncatedSwitchConditionPass());
697 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500698 // Must be run after structurize cfg.
alan-bakerfec0a472018-11-08 18:09:40 -0500699 pm->add(clspv::createReorderBasicBlocksPass());
700 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
701 pm->add(clspv::createSplatArgPass());
702 pm->add(clspv::createSimplifyPointerBitcastPass());
703 pm->add(clspv::createReplacePointerBitcastPass());
704
705 pm->add(clspv::createUndoTranslateSamplerFoldPass());
706
707 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
708 pm->add(clspv::createClusterModuleScopeConstantVars());
709 }
710
711 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500712 // Specialize images before assigning descriptors to disambiguate the various
713 // types.
714 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400715 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500716 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
717 pm->add(llvm::createVerifierPass());
718 pm->add(clspv::createDirectResourceAccessPass());
719 // Replacing pointer bitcasts can leave some trivial GEPs
720 // that are easy to remove. Also replace GEPs of GEPS
721 // left by replacing indirect buffer accesses.
722 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500723 // Run after DRA to clean up parameters and help reduce the need for variable
724 // pointers.
725 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500726
727 pm->add(clspv::createSplatSelectConditionPass());
728 pm->add(clspv::createSignedCompareFixupPass());
729 // This pass generates insertions that need to be rewritten.
730 pm->add(clspv::createScalarizePass());
731 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400732 // UBO Transformations
733 if (clspv::Option::ConstantArgsInUniformBuffer() &&
734 !clspv::Option::InlineEntryPoints()) {
735 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
736 // arguments and either multi-version them as necessary or inline them if
737 // multi-versioning cannot be accomplished.
738 pm->add(clspv::createMultiVersionUBOFunctionsPass());
739 // Cleanup passes.
740 // Specialization can blindly generate GEP chains that are easily cleaned up
741 // by SimplifyPointerBitcastPass.
742 pm->add(clspv::createSimplifyPointerBitcastPass());
743 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
744 // problematic to begin with now that they have no uses.
745 pm->add(clspv::createRemoveUnusedArgumentsPass());
746 // DCE cleans up callers of the specialized functions.
747 pm->add(llvm::createDeadCodeEliminationPass());
748 }
alan-bakerfec0a472018-11-08 18:09:40 -0500749 // This pass mucks with types to point where you shouldn't rely on DataLayout
750 // anymore so leave this right before SPIR-V generation.
751 pm->add(clspv::createUBOTypeTransformPass());
alan-baker00e7a582019-06-07 12:54:21 -0400752 pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries,
753 *SamplerMapEntries,
754 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500755
756 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500757}
alan-bakerfec0a472018-11-08 18:09:40 -0500758
Kévin Petitd5db2d22019-04-04 13:55:14 +0100759int ParseOptions(const int argc, const char *const argv[]) {
alan-bakerfec0a472018-11-08 18:09:40 -0500760 // We need to change how one of the called passes works by spoofing
761 // ParseCommandLineOptions with the specific option.
762 const int llvmArgc = 2;
763 const char *llvmArgv[llvmArgc] = {
alan-bakerf5e5f692018-11-27 08:33:24 -0500764 argv[0],
765 "-simplifycfg-sink-common=false",
alan-bakerfec0a472018-11-08 18:09:40 -0500766 };
767
Kévin Petitd5db2d22019-04-04 13:55:14 +0100768 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500769 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500770 llvm::cl::ParseCommandLineOptions(argc, argv);
771
Kévin Petitf0515712020-01-07 18:29:20 +0000772 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
773 !clspv::Option::InlineEntryPoints()) {
774 llvm::errs() << "cannot compile languages that use the generic address "
775 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100776 return -1;
777 }
778
Kévin Petitd5db2d22019-04-04 13:55:14 +0100779 return 0;
780}
Diego Novillo89500852019-04-15 08:45:10 -0400781
782int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
783 std::string output) {
784 std::error_code ec;
785 std::unique_ptr<llvm::ToolOutputFile> out(
786 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
787 if (ec) {
788 llvm::errs() << output << ": " << ec.message() << '\n';
789 return -1;
790 }
791 pm->add(llvm::createPrintModulePass(out->os(), "", false));
792 pm->run(module);
793 out->keep();
794 return 0;
795}
796
Kévin Petitd5db2d22019-04-04 13:55:14 +0100797} // namespace
798
799namespace clspv {
800int Compile(const int argc, const char *const argv[]) {
801
802 if (auto error = ParseOptions(argc, argv))
803 return error;
804
alan-bakerfec0a472018-11-08 18:09:40 -0500805 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500806 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500807 return error;
808
809 // if no output file was provided, use a default
810 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
811
812 // If we are reading our input file from stdin.
813 if ("-" == InputFilename) {
814 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100815 switch (InputLanguage) {
816 case clang::Language::OpenCL:
817 overiddenInputFilename = "stdin.cl";
818 break;
819 case clang::Language::LLVM_IR:
820 overiddenInputFilename = "stdin.ll";
821 break;
alan-baker31298a62019-10-07 13:24:30 -0400822 default:
823 // Default to fix compiler warnings/errors. Option parsing will reject a
824 // bad enum value for the option so there is no need for a message.
825 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100826 }
alan-bakerfec0a472018-11-08 18:09:40 -0500827 }
828
829 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100830 clang::FrontendInputFile kernelFile(overiddenInputFilename,
831 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500832 std::string log;
833 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500834 if (auto error = SetCompilerInstanceOptions(
835 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500836 return error;
837
838 // Parse.
839 llvm::LLVMContext context;
840 clang::EmitLLVMOnlyAction action(&context);
841
842 // Prepare the action for processing kernelFile
843 const bool success = action.BeginSourceFile(instance, kernelFile);
844 if (!success) {
845 return -1;
846 }
847
alan-bakerf3bce4a2019-06-28 16:01:15 -0400848 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500849 action.EndSourceFile();
850
851 clang::DiagnosticConsumer *const consumer =
852 instance.getDiagnostics().getClient();
853 consumer->finish();
854
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100855 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500856 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100857 if ((num_errors > 0) || (num_warnings > 0)) {
858 llvm::errs() << log;
859 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400860 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500861 return -1;
862 }
863
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100864 // Don't run the passes or produce any output in verify mode.
865 // Clang doesn't always produce a valid module.
866 if (verify) {
867 return 0;
868 }
869
alan-bakerfec0a472018-11-08 18:09:40 -0500870 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
871 llvm::initializeCore(Registry);
872 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400873 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500874
875 std::unique_ptr<llvm::Module> module(action.takeModule());
876
877 // Optimize.
878 // Create a memory buffer for temporarily writing the result.
879 SmallVector<char, 10000> binary;
880 llvm::raw_svector_ostream binaryStream(binary);
881 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500882 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500883 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
Diego Novillo89500852019-04-15 08:45:10 -0400884
885 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
886 if (!IROutputFile.empty()) {
887 return GenerateIRFile(&pm, *module, IROutputFile);
888 }
889
890 // Otherwise, populate the pass manager and run the regular passes.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400891 if (auto error = PopulatePassManager(
892 &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500893 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500894 pm.run(*module);
895
896 // Write outputs
897
898 // Write the descriptor map, if requested.
899 std::error_code error;
900 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400901 llvm::raw_fd_ostream descriptor_map_out_fd(
902 DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways,
903 llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text);
alan-bakerfec0a472018-11-08 18:09:40 -0500904 if (error) {
905 llvm::errs() << "Unable to open descriptor map file '"
906 << DescriptorMapFilename << "': " << error.message() << '\n';
907 return -1;
908 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500909 std::string descriptor_map_string;
910 std::ostringstream str(descriptor_map_string);
911 for (const auto &entry : descriptor_map_entries) {
912 str << entry << "\n";
913 }
914 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500915 descriptor_map_out_fd.close();
916 }
917
918 // Write the resulting binary.
919 // Wait until now to try writing the file so that we only write it on
920 // successful compilation.
921 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100922 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500923 OutputFilename = "a.spvinc";
924 } else {
925 OutputFilename = "a.spv";
926 }
927 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400928 llvm::raw_fd_ostream outStream(OutputFilename, error,
929 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500930
931 if (error) {
932 llvm::errs() << "Unable to open output file '" << OutputFilename
933 << "': " << error.message() << '\n';
934 return -1;
935 }
936 outStream << binaryStream.str();
937
938 return 0;
939}
alan-bakerf5e5f692018-11-27 08:33:24 -0500940
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400941int CompileFromSourceString(
942 const std::string &program, const std::string &sampler_map,
943 const std::string &options, std::vector<uint32_t> *output_binary,
944 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500945
946 llvm::SmallVector<const char *, 20> argv;
947 llvm::BumpPtrAllocator A;
948 llvm::StringSaver Saver(A);
949 argv.push_back(Saver.save("clspv").data());
950 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
951 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100952
953 if (auto error = ParseOptions(argc, &argv[0]))
954 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500955
956 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
957 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
958 return error;
959
960 InputFilename = "source.cl";
961 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
962
963 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400964 clang::FrontendInputFile kernelFile(
965 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500966 std::string log;
967 llvm::raw_string_ostream diagnosticsStream(log);
968 if (auto error =
969 SetCompilerInstanceOptions(instance, overiddenInputFilename,
970 kernelFile, program, &diagnosticsStream))
971 return error;
972
973 // Parse.
974 llvm::LLVMContext context;
975 clang::EmitLLVMOnlyAction action(&context);
976
977 // Prepare the action for processing kernelFile
978 const bool success = action.BeginSourceFile(instance, kernelFile);
979 if (!success) {
980 return -1;
981 }
982
alan-bakerf3bce4a2019-06-28 16:01:15 -0400983 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -0500984 action.EndSourceFile();
985
986 clang::DiagnosticConsumer *const consumer =
987 instance.getDiagnostics().getClient();
988 consumer->finish();
989
990 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -0400991 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500992 llvm::errs() << log << "\n";
993 return -1;
994 }
995
alan-bakerf5e5f692018-11-27 08:33:24 -0500996 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
997 llvm::initializeCore(Registry);
998 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400999 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001000
1001 std::unique_ptr<llvm::Module> module(action.takeModule());
1002
1003 // Optimize.
1004 // Create a memory buffer for temporarily writing the result.
1005 SmallVector<char, 10000> binary;
1006 llvm::raw_svector_ostream binaryStream(binary);
1007 std::string descriptor_map;
1008 llvm::legacy::PassManager pm;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001009 if (auto error = PopulatePassManager(
1010 &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001011 return error;
1012 pm.run(*module);
1013
1014 // Write outputs
1015
1016 // Write the descriptor map. This is required.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001017 assert(descriptor_map_entries &&
1018 "Valid descriptor map container is required.");
alan-bakerf5e5f692018-11-27 08:33:24 -05001019 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001020 llvm::errs() << "Warning: -descriptormap is ignored descriptor map "
1021 "container is provided.\n";
alan-bakerf5e5f692018-11-27 08:33:24 -05001022 }
1023
1024 // Write the resulting binary.
1025 // Wait until now to try writing the file so that we only write it on
1026 // successful compilation.
1027 assert(output_binary && "Valid binary container is required.");
1028 if (!OutputFilename.empty()) {
1029 llvm::outs()
1030 << "Warning: -o is ignored when binary container is provided.\n";
1031 }
1032 output_binary->resize(binary.size() / 4);
1033 memcpy(output_binary->data(), binary.data(), binary.size());
1034
1035 return 0;
1036}
alan-bakerfec0a472018-11-08 18:09:40 -05001037} // namespace clspv