blob: 1235e0ba5e77feb09f22fcb4ca66f9dcbdd06114 [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
alan-baker0d095d62020-03-12 14:59:47 -040015#include "clang/Basic/FileManager.h"
alan-bakerfec0a472018-11-08 18:09:40 -050016#include "clang/Basic/TargetInfo.h"
17#include "clang/CodeGen/CodeGenAction.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/FrontendPluginRegistry.h"
20#include "clang/Frontend/TextDiagnosticPrinter.h"
21#include "clang/Lex/PreprocessorOptions.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/LegacyPassManager.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Verifier.h"
alan-baker0e64a592019-11-18 13:36:25 -050026#include "llvm/InitializePasses.h"
alan-bakerfec0a472018-11-08 18:09:40 -050027#include "llvm/LinkAllPasses.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050028#include "llvm/Support/Allocator.h"
alan-bakerfec0a472018-11-08 18:09:40 -050029#include "llvm/Support/CommandLine.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050030#include "llvm/Support/ErrorOr.h"
alan-bakerfec0a472018-11-08 18:09:40 -050031#include "llvm/Support/MathExtras.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050032#include "llvm/Support/StringSaver.h"
Diego Novillo89500852019-04-15 08:45:10 -040033#include "llvm/Support/ToolOutputFile.h"
alan-bakerfec0a472018-11-08 18:09:40 -050034#include "llvm/Support/raw_ostream.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
36
Kévin Petit38c52482019-05-07 20:28:00 +080037#include "clspv/AddressSpace.h"
alan-bakerf5e5f692018-11-27 08:33:24 -050038#include "clspv/DescriptorMap.h"
alan-bakerfec0a472018-11-08 18:09:40 -050039#include "clspv/Option.h"
40#include "clspv/Passes.h"
41#include "clspv/opencl_builtins_header.h"
42
43#include "FrontendPlugin.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040044#include "Passes.h"
alan-bakerfec0a472018-11-08 18:09:40 -050045
alan-bakerf5e5f692018-11-27 08:33:24 -050046#include <cassert>
alan-bakerfec0a472018-11-08 18:09:40 -050047#include <numeric>
alan-bakerf5e5f692018-11-27 08:33:24 -050048#include <sstream>
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040049#include <string>
alan-bakerfec0a472018-11-08 18:09:40 -050050
51using namespace clang;
52
53namespace {
54// This registration must be located in the same file as the execution of the
55// action.
56static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction>
57 X("extra-validation",
58 "Perform extra validation on OpenCL C when targeting Vulkan");
59
60static llvm::cl::opt<bool> cl_single_precision_constants(
61 "cl-single-precision-constant", llvm::cl::init(false),
62 llvm::cl::desc("Treat double precision floating-point constant as single "
63 "precision constant."));
64
65static llvm::cl::opt<bool> cl_denorms_are_zero(
66 "cl-denorms-are-zero", llvm::cl::init(false),
67 llvm::cl::desc("If specified, denormalized floating point numbers may be "
68 "flushed to zero."));
69
70static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt(
71 "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false),
72 llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and "
73 "sqrt used are correctly rounded."));
74
75static llvm::cl::opt<bool>
76 cl_opt_disable("cl-opt-disable", llvm::cl::init(false),
77 llvm::cl::desc("This option disables all optimizations. The "
78 "default is optimizations are enabled."));
79
80static llvm::cl::opt<bool> cl_mad_enable(
81 "cl-mad-enable", llvm::cl::init(false),
82 llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes "
83 "a * b + c with reduced accuracy."));
84
85static llvm::cl::opt<bool> cl_no_signed_zeros(
86 "cl-no-signed-zeros", llvm::cl::init(false),
87 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
88 "ignore the signedness of zero."));
89
90static llvm::cl::opt<bool> cl_unsafe_math_optimizations(
91 "cl-unsafe-math-optimizations", llvm::cl::init(false),
92 llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) "
93 "assume that arguments and results are valid, (b) may "
94 "violate IEEE 754 standard and (c) may violate the OpenCL "
95 "numerical compliance requirements. This option includes "
96 "the -cl-no-signed-zeros and -cl-mad-enable options."));
97
98static llvm::cl::opt<bool> cl_finite_math_only(
99 "cl-finite-math-only", llvm::cl::init(false),
100 llvm::cl::desc("Allow optimizations for floating-point arithmetic that "
101 "assume that arguments and results are not NaNs or INFs."));
102
103static llvm::cl::opt<bool> cl_fast_relaxed_math(
104 "cl-fast-relaxed-math", llvm::cl::init(false),
105 llvm::cl::desc("This option causes the preprocessor macro "
106 "__FAST_RELAXED_MATH__ to be defined. Sets the optimization "
107 "options -cl-finite-math-only and "
108 "-cl-unsafe-math-optimizations."));
109
110static llvm::cl::list<std::string>
111 Includes(llvm::cl::Prefix, "I",
112 llvm::cl::desc("Add a directory to the list of directories "
113 "to be searched for header files."),
114 llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path"));
115
116static llvm::cl::list<std::string>
117 Defines(llvm::cl::Prefix, "D",
118 llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore,
119 llvm::cl::value_desc("define"));
120
121static llvm::cl::opt<std::string>
122 InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"),
123 llvm::cl::init("-"));
124
Kévin Petitddad8f42019-09-30 15:12:08 +0100125static llvm::cl::opt<clang::Language> InputLanguage(
126 "x", llvm::cl::desc("Select input type"),
127 llvm::cl::init(clang::Language::OpenCL),
128 llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"),
129 clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR")));
130
alan-bakerfec0a472018-11-08 18:09:40 -0500131static llvm::cl::opt<std::string>
132 OutputFilename("o", llvm::cl::desc("Override output filename"),
133 llvm::cl::value_desc("filename"));
134
135static llvm::cl::opt<std::string>
136 DescriptorMapFilename("descriptormap",
137 llvm::cl::desc("Output file for descriptor map"),
138 llvm::cl::value_desc("filename"));
139
140static llvm::cl::opt<char>
141 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
142 llvm::cl::desc("Optimization level to use"),
143 llvm::cl::value_desc("level"));
144
alan-bakerfec0a472018-11-08 18:09:40 -0500145static llvm::cl::opt<std::string> OutputFormat(
146 "mfmt", llvm::cl::init(""),
147 llvm::cl::desc(
148 "Specify special output format. 'c' is as a C initializer list"),
149 llvm::cl::value_desc("format"));
150
151static llvm::cl::opt<std::string>
alan-baker09cb9802019-12-10 13:16:27 -0500152 SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"),
alan-bakerfec0a472018-11-08 18:09:40 -0500153 llvm::cl::value_desc("filename"));
154
alan-bakerfec0a472018-11-08 18:09:40 -0500155static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
156 llvm::cl::desc("Verify diagnostic outputs"));
157
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100158static llvm::cl::opt<bool>
159 IgnoreWarnings("w", llvm::cl::init(false),
160 llvm::cl::desc("Disable all warnings"));
161
162static llvm::cl::opt<bool>
163 WarningsAsErrors("Werror", llvm::cl::init(false),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400164 llvm::cl::desc("Turn warnings into errors"));
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100165
Diego Novillo89500852019-04-15 08:45:10 -0400166static llvm::cl::opt<std::string> IROutputFile(
167 "emit-ir",
168 llvm::cl::desc(
169 "Emit LLVM IR to the given file after parsing and stop compilation."),
170 llvm::cl::value_desc("filename"));
171
alan-bakerfec0a472018-11-08 18:09:40 -0500172// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
173// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500174int ParseSamplerMap(const std::string &sampler_map,
175 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
176 *SamplerMapEntries) {
177 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
178 if (!sampler_map.empty()) {
179 // Parse the sampler map from the provided string.
180 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
181
alan-baker09cb9802019-12-10 13:16:27 -0500182 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500183 if (!SamplerMap.empty()) {
184 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
185 "provided through a string.\n";
186 }
187 } else if (!SamplerMap.empty()) {
188 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500189 auto errorOrSamplerMapFile =
190 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
191
192 // If there was an error in getting the sampler map file.
193 if (!errorOrSamplerMapFile) {
194 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
195 << " '" << SamplerMap.getValue() << "'\n";
196 return -1;
197 }
198
alan-baker09cb9802019-12-10 13:16:27 -0500199 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500200 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500201 if (0 == samplerMapBuffer->getBufferSize()) {
202 llvm::errs() << "Error: Sampler map was an empty file!\n";
203 return -1;
204 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500205 }
alan-bakerfec0a472018-11-08 18:09:40 -0500206
alan-baker09cb9802019-12-10 13:16:27 -0500207 if (clspv::Option::UseSamplerMap()) {
208 llvm::outs()
209 << "Warning: use of the sampler map is deprecated and unnecessary\n";
210 }
211
alan-bakerf5e5f692018-11-27 08:33:24 -0500212 // No sampler map to parse.
213 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
214 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500215
alan-bakerf5e5f692018-11-27 08:33:24 -0500216 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500217
alan-bakerf5e5f692018-11-27 08:33:24 -0500218 // We need to keep track of the beginning of the current entry.
219 const char *b = samplerMapBuffer->getBufferStart();
220 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
221 // If we have a separator between declarations.
222 if ((*i == '|') || (*i == ',') || (i == e)) {
223 if (i == b) {
224 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
225 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500226 }
227
alan-bakerf5e5f692018-11-27 08:33:24 -0500228 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500229
alan-bakerf5e5f692018-11-27 08:33:24 -0500230 // And set b the next character after i.
231 b = i + 1;
232 }
alan-bakerfec0a472018-11-08 18:09:40 -0500233
alan-bakerf5e5f692018-11-27 08:33:24 -0500234 // If we have a separator between declarations within a single sampler.
235 if ((*i == ',') || (i == e)) {
alan-bakerfec0a472018-11-08 18:09:40 -0500236
James Pricec05f6052020-01-14 13:37:20 -0500237 clspv::version0::SamplerNormalizedCoords NormalizedCoord =
238 clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET;
239 clspv::version0::SamplerAddressingMode AddressingMode =
240 clspv::version0::CLK_ADDRESS_NOT_SET;
241 clspv::version0::SamplerFilterMode FilterMode =
242 clspv::version0::CLK_FILTER_NOT_SET;
alan-bakerf5e5f692018-11-27 08:33:24 -0500243
244 for (auto str : samplerStrings) {
245 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500246 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET !=
247 NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500248 llvm::errs() << "Error: Sampler map normalized coordinates was "
249 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500250 return -1;
251 }
James Pricec05f6052020-01-14 13:37:20 -0500252 NormalizedCoord = clspv::version0::CLK_NORMALIZED_COORDS_FALSE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500253 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500254 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET !=
255 NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500256 llvm::errs() << "Error: Sampler map normalized coordinates was "
257 "previously set!\n";
258 return -1;
259 }
James Pricec05f6052020-01-14 13:37:20 -0500260 NormalizedCoord = clspv::version0::CLK_NORMALIZED_COORDS_TRUE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500261 } else if ("CLK_ADDRESS_NONE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500262 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500263 llvm::errs()
264 << "Error: Sampler map addressing mode was previously set!\n";
265 return -1;
266 }
James Pricec05f6052020-01-14 13:37:20 -0500267 AddressingMode = clspv::version0::CLK_ADDRESS_NONE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500268 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500269 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500270 llvm::errs()
271 << "Error: Sampler map addressing mode was previously set!\n";
272 return -1;
273 }
James Pricec05f6052020-01-14 13:37:20 -0500274 AddressingMode = clspv::version0::CLK_ADDRESS_CLAMP_TO_EDGE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500275 } else if ("CLK_ADDRESS_CLAMP" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500276 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500277 llvm::errs()
278 << "Error: Sampler map addressing mode was previously set!\n";
279 return -1;
280 }
James Pricec05f6052020-01-14 13:37:20 -0500281 AddressingMode = clspv::version0::CLK_ADDRESS_CLAMP;
alan-bakerf5e5f692018-11-27 08:33:24 -0500282 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500283 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500284 llvm::errs()
285 << "Error: Sampler map addressing mode was previously set!\n";
286 return -1;
287 }
James Pricec05f6052020-01-14 13:37:20 -0500288 AddressingMode = clspv::version0::CLK_ADDRESS_MIRRORED_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500289 } else if ("CLK_ADDRESS_REPEAT" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500290 if (clspv::version0::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500291 llvm::errs()
292 << "Error: Sampler map addressing mode was previously set!\n";
293 return -1;
294 }
James Pricec05f6052020-01-14 13:37:20 -0500295 AddressingMode = clspv::version0::CLK_ADDRESS_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500296 } else if ("CLK_FILTER_NEAREST" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500297 if (clspv::version0::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500298 llvm::errs()
299 << "Error: Sampler map filtering mode was previously set!\n";
300 return -1;
301 }
James Pricec05f6052020-01-14 13:37:20 -0500302 FilterMode = clspv::version0::CLK_FILTER_NEAREST;
alan-bakerf5e5f692018-11-27 08:33:24 -0500303 } else if ("CLK_FILTER_LINEAR" == str) {
James Pricec05f6052020-01-14 13:37:20 -0500304 if (clspv::version0::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500305 llvm::errs()
306 << "Error: Sampler map filtering mode was previously set!\n";
307 return -1;
308 }
James Pricec05f6052020-01-14 13:37:20 -0500309 FilterMode = clspv::version0::CLK_FILTER_LINEAR;
alan-bakerf5e5f692018-11-27 08:33:24 -0500310 } else {
311 llvm::errs() << "Error: Unknown sampler string '" << str
312 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500313 return -1;
314 }
alan-bakerfec0a472018-11-08 18:09:40 -0500315 }
316
James Pricec05f6052020-01-14 13:37:20 -0500317 if (clspv::version0::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500318 llvm::errs() << "Error: Sampler map entry did not contain normalized "
319 "coordinates entry!\n";
320 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500321 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500322
James Pricec05f6052020-01-14 13:37:20 -0500323 if (clspv::version0::CLK_ADDRESS_NOT_SET == AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500324 llvm::errs() << "Error: Sampler map entry did not contain addressing "
325 "mode entry!\n";
326 return -1;
327 }
328
James Pricec05f6052020-01-14 13:37:20 -0500329 if (clspv::version0::CLK_FILTER_NOT_SET == FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500330 llvm::errs()
331 << "Error: Sampler map entry did not contain filer mode entry!\n";
332 return -1;
333 }
334
335 // Generate an equivalent expression in string form. Sort the
336 // strings to get a canonical ordering.
337 std::sort(samplerStrings.begin(), samplerStrings.end(),
338 std::less<StringRef>());
339 const auto samplerExpr = std::accumulate(
340 samplerStrings.begin(), samplerStrings.end(), std::string(),
alan-baker21574d32020-01-29 16:00:31 -0500341 [](llvm::StringRef left, llvm::StringRef right) {
342 return left.str() + std::string(left.empty() ? "" : "|") +
343 right.str();
alan-bakerf5e5f692018-11-27 08:33:24 -0500344 });
345
346 // SamplerMapEntries->push_back(std::make_pair(
347 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
348 SamplerMapEntries->emplace_back(
349 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
350
351 // And reset the sampler strings for the next sampler in the map.
352 samplerStrings.clear();
353 }
354
355 // And lastly, if we are at the end of the file
356 if (i == e) {
357 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500358 }
359 }
360
361 return 0;
362}
363
364// Sets |instance|'s options for compiling. Returns 0 if successful.
365int SetCompilerInstanceOptions(CompilerInstance &instance,
366 const llvm::StringRef &overiddenInputFilename,
367 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500368 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500369 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500370 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
371 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
372 if (program.empty()) {
373 auto errorOrInputFile =
374 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500375
alan-bakerf5e5f692018-11-27 08:33:24 -0500376 // If there was an error in getting the input file.
377 if (!errorOrInputFile) {
378 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
379 << InputFilename.getValue() << "'\n";
380 return -1;
381 }
382 memory_buffer.reset(errorOrInputFile.get().release());
383 } else {
384 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
385 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500386 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500387
alan-bakerfec0a472018-11-08 18:09:40 -0500388 if (verify) {
389 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400390 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500391 }
392
Kévin Petit0fc88042019-04-09 23:25:02 +0100393 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000394 switch (clspv::Option::Language()) {
395 case clspv::Option::SourceLanguage::OpenCL_C_10:
396 standard = clang::LangStandard::lang_opencl10;
397 break;
398 case clspv::Option::SourceLanguage::OpenCL_C_11:
399 standard = clang::LangStandard::lang_opencl11;
400 break;
401 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100402 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000403 break;
404 case clspv::Option::SourceLanguage::OpenCL_C_20:
405 standard = clang::LangStandard::lang_opencl20;
406 break;
407 case clspv::Option::SourceLanguage::OpenCL_CPP:
408 standard = clang::LangStandard::lang_openclcpp;
409 break;
410 default:
411 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100412 }
alan-bakerfec0a472018-11-08 18:09:40 -0500413
alan-bakerfec0a472018-11-08 18:09:40 -0500414 instance.getLangOpts().C99 = true;
415 instance.getLangOpts().RTTI = false;
416 instance.getLangOpts().RTTIData = false;
417 instance.getLangOpts().MathErrno = false;
418 instance.getLangOpts().Optimize = false;
419 instance.getLangOpts().NoBuiltin = true;
420 instance.getLangOpts().ModulesSearchAll = false;
421 instance.getLangOpts().SinglePrecisionConstants = true;
422 instance.getCodeGenOpts().StackRealignment = true;
423 instance.getCodeGenOpts().SimplifyLibCalls = false;
424 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
425 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100426 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500427
428 instance.getLangOpts().SinglePrecisionConstants =
429 cl_single_precision_constants;
430 // cl_denorms_are_zero ignored for now!
431 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
432 instance.getCodeGenOpts().LessPreciseFPMAD =
433 cl_mad_enable || cl_unsafe_math_optimizations;
434 // cl_no_signed_zeros ignored for now!
alan-baker0f814cd2020-06-02 15:35:14 -0400435 instance.getLangOpts().UnsafeFPMath =
alan-bakerfec0a472018-11-08 18:09:40 -0500436 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
437 instance.getLangOpts().FiniteMathOnly =
438 cl_finite_math_only || cl_fast_relaxed_math;
439 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
440
441 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800442 if (!clspv::Option::ImageSupport()) {
443 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
444 }
alan-bakerfec0a472018-11-08 18:09:40 -0500445 if (cl_fast_relaxed_math) {
446 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
447 }
448
449 for (auto define : Defines) {
450 instance.getPreprocessorOpts().addMacroDef(define);
451 }
452
453 // Header search options
454 for (auto include : Includes) {
455 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
456 false, false);
457 }
458
459 // We always compile on opt 0 so we preserve as much debug information about
460 // the source as possible. We'll run optimization later, once we've had a
461 // chance to view the unoptimal code first
462 instance.getCodeGenOpts().OptimizationLevel = 0;
463
464// Debug information is disabled temporarily to call instruction.
465#if 0
466 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
467#endif
468
469 // We use the 32-bit pointer-width SPIR triple
470 llvm::Triple triple("spir-unknown-unknown");
471
472 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400473 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500474 instance.getPreprocessorOpts(), standard);
475
476 // Override the C99 inline semantics to accommodate for more OpenCL C
477 // programs in the wild.
478 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100479
480 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500481 instance.createDiagnostics(
482 new clang::TextDiagnosticPrinter(*diagnosticsStream,
483 &instance.getDiagnosticOpts()),
484 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100485 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
486 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500487
488 instance.getTargetOpts().Triple = triple.str();
489
alan-baker21574d32020-01-29 16:00:31 -0500490 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500491 instance.getCodeGenOpts().PreserveVec3Type = true;
492 // Disable generation of lifetime intrinsic.
493 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
494 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500495 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
496 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500497
498 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
499 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
500 const char *dataCasted = reinterpret_cast<const char *>(data);
501 init(dataCasted, dataCasted + data_length, true);
502 }
503
504 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
505 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
506 }
507
508 virtual ~OpenCLBuiltinMemoryBuffer() override {}
509 };
510
511 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
512 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
513 opencl_builtins_header_size - 1));
514
515 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
516
alan-bakerf3bce4a2019-06-28 16:01:15 -0400517 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
518 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
519 opencl_base_builtins_header_size - 1));
520
521 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
522
alan-bakerfec0a472018-11-08 18:09:40 -0500523 // Add the VULKAN macro.
524 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
525
526 // Add the __OPENCL_VERSION__ macro.
527 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
528
529 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
530 instance.getDiagnostics(),
531 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
532
533 instance.createFileManager();
534 instance.createSourceManager(instance.getFileManager());
535
536#ifdef _MSC_VER
537 std::string includePrefix("include\\");
538#else
539 std::string includePrefix("include/");
540#endif
541
542 auto entry = instance.getFileManager().getVirtualFile(
543 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
544 0);
545
546 instance.getSourceManager().overrideFileContents(
547 entry, std::move(openCLBuiltinMemoryBuffer));
548
alan-bakerf3bce4a2019-06-28 16:01:15 -0400549 auto base_entry = instance.getFileManager().getVirtualFile(
550 includePrefix + "opencl-c-base.h",
551 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
552
553 instance.getSourceManager().overrideFileContents(
554 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
555
alan-bakerfec0a472018-11-08 18:09:40 -0500556 return 0;
557}
558
alan-bakerf5e5f692018-11-27 08:33:24 -0500559// Populates |pm| with necessary passes to optimize and legalize the IR.
560int PopulatePassManager(
561 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
562 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries,
563 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
564 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500565 llvm::PassManagerBuilder pmBuilder;
566
567 switch (OptimizationLevel) {
568 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500569 case '1':
570 case '2':
571 case '3':
572 case 's':
573 case 'z':
574 break;
575 default:
576 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
577 << " specified!\n";
578 return -1;
579 }
580
581 switch (OptimizationLevel) {
582 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500583 pmBuilder.OptLevel = 0;
584 break;
585 case '1':
586 pmBuilder.OptLevel = 1;
587 break;
588 case '2':
589 pmBuilder.OptLevel = 2;
590 break;
591 case '3':
592 pmBuilder.OptLevel = 3;
593 break;
594 case 's':
595 pmBuilder.SizeLevel = 1;
596 break;
597 case 'z':
598 pmBuilder.SizeLevel = 2;
599 break;
600 default:
601 break;
602 }
603
604 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400605 pm->add(clspv::createAddFunctionAttributesPass());
alan-bakerc4579bb2020-04-29 14:15:50 -0400606 pm->add(clspv::createAutoPodArgsPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000607 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500608 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
609
610 if (0 < pmBuilder.OptLevel) {
611 pm->add(clspv::createOpenCLInlinerPass());
612 }
613
614 pm->add(clspv::createUndoByvalPass());
615 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400616 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500617 pm->add(clspv::createClusterPodKernelArgumentsPass());
618 }
619 pm->add(clspv::createReplaceOpenCLBuiltinPass());
620
621 // We need to run mem2reg and inst combine early because our
622 // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern
623 // %1 = alloca i32 1
624 // store <something> %1
625 // %2 = bitcast float* %1
626 // %3 = load float %2
627 pm->add(llvm::createPromoteMemoryToRegisterPass());
628
alan-baker1b13e8f2019-08-08 17:56:51 -0400629 // Try to deal with pointer bitcasts early. This can prevent problems like
630 // issue #409 where LLVM is looser about access chain addressing than SPIR-V.
631 // This needs to happen before instcombine and after replacing OpenCL
632 // builtins. This run of the pass will not handle all pointer bitcasts that
633 // could be handled. It should be run again after other optimizations (e.g
634 // InlineFuncWithPointerBitCastArgPass).
635 pm->add(clspv::createSimplifyPointerBitcastPass());
636 pm->add(clspv::createReplacePointerBitcastPass());
637 pm->add(llvm::createDeadCodeEliminationPass());
638
alan-bakerfec0a472018-11-08 18:09:40 -0500639 // Hide loads from __constant address space away from instcombine.
640 // This prevents us from generating select between pointers-to-__constant.
641 // See https://github.com/google/clspv/issues/71
642 pm->add(clspv::createHideConstantLoadsPass());
643
644 pm->add(llvm::createInstructionCombiningPass());
645
646 if (clspv::Option::InlineEntryPoints()) {
647 pm->add(clspv::createInlineEntryPointsPass());
648 } else {
649 pm->add(clspv::createInlineFuncWithPointerBitCastArgPass());
650 pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass());
651 pm->add(clspv::createInlineFuncWithSingleCallSitePass());
652 }
653
Kévin Petitf0515712020-01-07 18:29:20 +0000654 if (clspv::Option::LanguageUsesGenericAddressSpace()) {
Kévin Petit38c52482019-05-07 20:28:00 +0800655 pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic));
Kévin Petit0fc88042019-04-09 23:25:02 +0100656 }
657
alan-bakerfec0a472018-11-08 18:09:40 -0500658 if (0 == pmBuilder.OptLevel) {
659 // Mem2Reg pass should be run early because O0 level optimization leaves
660 // redundant alloca, load and store instructions from function arguments.
661 // clspv needs to remove them ahead of transformation.
662 pm->add(llvm::createPromoteMemoryToRegisterPass());
663
664 // SROA pass is run because it will fold structs/unions that are problematic
665 // on Vulkan SPIR-V away.
666 pm->add(llvm::createSROAPass());
667
668 // InstructionCombining pass folds bitcast and gep instructions which are
669 // not supported by Vulkan SPIR-V.
670 pm->add(llvm::createInstructionCombiningPass());
671 }
672
673 // Now we add any of the LLVM optimizations we wanted
674 pmBuilder.populateModulePassManager(*pm);
675
alan-bakerb5e74d62020-04-07 20:38:05 -0400676 // No point attempting to handle freeze currently so strip them from the IR.
677 pm->add(clspv::createStripFreezePass());
678
alan-bakerfec0a472018-11-08 18:09:40 -0500679 // Unhide loads from __constant address space. Undoes the action of
680 // HideConstantLoadsPass.
681 pm->add(clspv::createUnhideConstantLoadsPass());
682
alan-baker13568382020-04-02 17:29:27 -0400683 pm->add(clspv::createUndoInstCombinePass());
alan-bakerfec0a472018-11-08 18:09:40 -0500684 pm->add(clspv::createFunctionInternalizerPass());
685 pm->add(clspv::createReplaceLLVMIntrinsicsPass());
686 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400687 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500688 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500689 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500690 pm->add(clspv::createFixupStructuredCFGPass());
691 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500692 pm->add(clspv::createReorderBasicBlocksPass());
693 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
694 pm->add(clspv::createSplatArgPass());
695 pm->add(clspv::createSimplifyPointerBitcastPass());
696 pm->add(clspv::createReplacePointerBitcastPass());
697
698 pm->add(clspv::createUndoTranslateSamplerFoldPass());
699
700 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
701 pm->add(clspv::createClusterModuleScopeConstantVars());
702 }
703
704 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500705 // Specialize images before assigning descriptors to disambiguate the various
706 // types.
707 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400708 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500709 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
710 pm->add(llvm::createVerifierPass());
711 pm->add(clspv::createDirectResourceAccessPass());
712 // Replacing pointer bitcasts can leave some trivial GEPs
713 // that are easy to remove. Also replace GEPs of GEPS
714 // left by replacing indirect buffer accesses.
715 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500716 // Run after DRA to clean up parameters and help reduce the need for variable
717 // pointers.
718 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500719
720 pm->add(clspv::createSplatSelectConditionPass());
721 pm->add(clspv::createSignedCompareFixupPass());
722 // This pass generates insertions that need to be rewritten.
723 pm->add(clspv::createScalarizePass());
724 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400725 // UBO Transformations
726 if (clspv::Option::ConstantArgsInUniformBuffer() &&
727 !clspv::Option::InlineEntryPoints()) {
728 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
729 // arguments and either multi-version them as necessary or inline them if
730 // multi-versioning cannot be accomplished.
731 pm->add(clspv::createMultiVersionUBOFunctionsPass());
732 // Cleanup passes.
733 // Specialization can blindly generate GEP chains that are easily cleaned up
734 // by SimplifyPointerBitcastPass.
735 pm->add(clspv::createSimplifyPointerBitcastPass());
736 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
737 // problematic to begin with now that they have no uses.
738 pm->add(clspv::createRemoveUnusedArgumentsPass());
739 // DCE cleans up callers of the specialized functions.
740 pm->add(llvm::createDeadCodeEliminationPass());
741 }
alan-bakerfec0a472018-11-08 18:09:40 -0500742 // This pass mucks with types to point where you shouldn't rely on DataLayout
743 // anymore so leave this right before SPIR-V generation.
744 pm->add(clspv::createUBOTypeTransformPass());
alan-baker00e7a582019-06-07 12:54:21 -0400745 pm->add(clspv::createSPIRVProducerPass(*binaryStream, descriptor_map_entries,
746 *SamplerMapEntries,
747 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500748
749 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500750}
alan-bakerfec0a472018-11-08 18:09:40 -0500751
Kévin Petitd5db2d22019-04-04 13:55:14 +0100752int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400753 // We need to change how some of the called passes works by spoofing
754 // ParseCommandLineOptions with the specific options.
755 bool has_pre = false;
756 bool has_load_pre = false;
757 const std::string pre = "-enable-pre";
758 const std::string load_pre = "-enable-load-pre";
759 for (int i = 1; i < argc; ++i) {
760 std::string option(argv[i]);
761 auto pre_pos = option.find(pre);
762 auto load_pos = option.find(load_pre);
763 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
764 has_pre = true;
765 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
766 has_load_pre = true;
767 }
768 }
769
770 int llvmArgc = 2;
771 const char *llvmArgv[4];
772 llvmArgv[0] = argv[0];
773 llvmArgv[1] = "-simplifycfg-sink-common=false";
774 if (!has_pre) {
775 llvmArgv[llvmArgc++] = "-enable-pre=0";
776 }
777 if (!has_load_pre) {
778 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
779 }
alan-bakerfec0a472018-11-08 18:09:40 -0500780
Kévin Petitd5db2d22019-04-04 13:55:14 +0100781 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500782 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500783 llvm::cl::ParseCommandLineOptions(argc, argv);
784
Kévin Petitf0515712020-01-07 18:29:20 +0000785 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
786 !clspv::Option::InlineEntryPoints()) {
787 llvm::errs() << "cannot compile languages that use the generic address "
788 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100789 return -1;
790 }
791
Kévin Petitbbbda972020-03-03 19:16:31 +0000792 if (clspv::Option::ScalarBlockLayout()) {
793 llvm::errs() << "scalar block layout support unimplemented\n";
794 return -1;
795 }
796
alan-baker9b0ec3c2020-04-06 14:45:34 -0400797 // Push constant option validation.
798 if (clspv::Option::PodArgsInPushConstants()) {
799 if (clspv::Option::PodArgsInUniformBuffer()) {
800 llvm::errs() << "POD arguments can only be in either uniform buffers or "
801 "push constants\n";
802 return -1;
803 }
804
805 if (!clspv::Option::ClusterPodKernelArgs()) {
806 llvm::errs()
807 << "POD arguments must be clustered to be passed as push constants\n";
808 return -1;
809 }
810
811 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400812 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400813 clspv::Option::Language() ==
814 clspv::Option::SourceLanguage::OpenCL_C_20 ||
815 clspv::Option::Language() ==
816 clspv::Option::SourceLanguage::OpenCL_CPP) {
817 llvm::errs() << "POD arguments as push constants are not compatible with "
818 "module scope push constants\n";
819 return -1;
820 }
821 }
822
Kévin Petitd5db2d22019-04-04 13:55:14 +0100823 return 0;
824}
Diego Novillo89500852019-04-15 08:45:10 -0400825
826int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
827 std::string output) {
828 std::error_code ec;
829 std::unique_ptr<llvm::ToolOutputFile> out(
830 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
831 if (ec) {
832 llvm::errs() << output << ": " << ec.message() << '\n';
833 return -1;
834 }
835 pm->add(llvm::createPrintModulePass(out->os(), "", false));
836 pm->run(module);
837 out->keep();
838 return 0;
839}
840
Kévin Petitd5db2d22019-04-04 13:55:14 +0100841} // namespace
842
843namespace clspv {
844int Compile(const int argc, const char *const argv[]) {
845
846 if (auto error = ParseOptions(argc, argv))
847 return error;
848
alan-bakerfec0a472018-11-08 18:09:40 -0500849 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500850 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500851 return error;
852
853 // if no output file was provided, use a default
854 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
855
856 // If we are reading our input file from stdin.
857 if ("-" == InputFilename) {
858 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100859 switch (InputLanguage) {
860 case clang::Language::OpenCL:
861 overiddenInputFilename = "stdin.cl";
862 break;
863 case clang::Language::LLVM_IR:
864 overiddenInputFilename = "stdin.ll";
865 break;
alan-baker31298a62019-10-07 13:24:30 -0400866 default:
867 // Default to fix compiler warnings/errors. Option parsing will reject a
868 // bad enum value for the option so there is no need for a message.
869 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100870 }
alan-bakerfec0a472018-11-08 18:09:40 -0500871 }
872
873 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100874 clang::FrontendInputFile kernelFile(overiddenInputFilename,
875 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500876 std::string log;
877 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500878 if (auto error = SetCompilerInstanceOptions(
879 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500880 return error;
881
882 // Parse.
883 llvm::LLVMContext context;
884 clang::EmitLLVMOnlyAction action(&context);
885
886 // Prepare the action for processing kernelFile
887 const bool success = action.BeginSourceFile(instance, kernelFile);
888 if (!success) {
889 return -1;
890 }
891
alan-bakerf3bce4a2019-06-28 16:01:15 -0400892 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500893 action.EndSourceFile();
894
895 clang::DiagnosticConsumer *const consumer =
896 instance.getDiagnostics().getClient();
897 consumer->finish();
898
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100899 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500900 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100901 if ((num_errors > 0) || (num_warnings > 0)) {
902 llvm::errs() << log;
903 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400904 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500905 return -1;
906 }
907
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100908 // Don't run the passes or produce any output in verify mode.
909 // Clang doesn't always produce a valid module.
910 if (verify) {
911 return 0;
912 }
913
alan-bakerfec0a472018-11-08 18:09:40 -0500914 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
915 llvm::initializeCore(Registry);
916 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400917 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500918
919 std::unique_ptr<llvm::Module> module(action.takeModule());
920
921 // Optimize.
922 // Create a memory buffer for temporarily writing the result.
923 SmallVector<char, 10000> binary;
924 llvm::raw_svector_ostream binaryStream(binary);
925 std::string descriptor_map;
alan-bakerfec0a472018-11-08 18:09:40 -0500926 llvm::legacy::PassManager pm;
alan-bakerf5e5f692018-11-27 08:33:24 -0500927 std::vector<version0::DescriptorMapEntry> descriptor_map_entries;
Diego Novillo89500852019-04-15 08:45:10 -0400928
929 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
930 if (!IROutputFile.empty()) {
931 return GenerateIRFile(&pm, *module, IROutputFile);
932 }
933
934 // Otherwise, populate the pass manager and run the regular passes.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400935 if (auto error = PopulatePassManager(
936 &pm, &binaryStream, &descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500937 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500938 pm.run(*module);
939
940 // Write outputs
941
942 // Write the descriptor map, if requested.
943 std::error_code error;
944 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400945 llvm::raw_fd_ostream descriptor_map_out_fd(
946 DescriptorMapFilename, error, llvm::sys::fs::CD_CreateAlways,
947 llvm::sys::fs::FA_Write, llvm::sys::fs::F_Text);
alan-bakerfec0a472018-11-08 18:09:40 -0500948 if (error) {
949 llvm::errs() << "Unable to open descriptor map file '"
950 << DescriptorMapFilename << "': " << error.message() << '\n';
951 return -1;
952 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500953 std::string descriptor_map_string;
954 std::ostringstream str(descriptor_map_string);
955 for (const auto &entry : descriptor_map_entries) {
956 str << entry << "\n";
957 }
958 descriptor_map_out_fd << str.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500959 descriptor_map_out_fd.close();
960 }
961
962 // Write the resulting binary.
963 // Wait until now to try writing the file so that we only write it on
964 // successful compilation.
965 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100966 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500967 OutputFilename = "a.spvinc";
968 } else {
969 OutputFilename = "a.spv";
970 }
971 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400972 llvm::raw_fd_ostream outStream(OutputFilename, error,
973 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500974
975 if (error) {
976 llvm::errs() << "Unable to open output file '" << OutputFilename
977 << "': " << error.message() << '\n';
978 return -1;
979 }
980 outStream << binaryStream.str();
981
982 return 0;
983}
alan-bakerf5e5f692018-11-27 08:33:24 -0500984
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400985int CompileFromSourceString(
986 const std::string &program, const std::string &sampler_map,
987 const std::string &options, std::vector<uint32_t> *output_binary,
988 std::vector<clspv::version0::DescriptorMapEntry> *descriptor_map_entries) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500989
990 llvm::SmallVector<const char *, 20> argv;
991 llvm::BumpPtrAllocator A;
992 llvm::StringSaver Saver(A);
993 argv.push_back(Saver.save("clspv").data());
994 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
995 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100996
997 if (auto error = ParseOptions(argc, &argv[0]))
998 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500999
1000 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
1001 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
1002 return error;
1003
1004 InputFilename = "source.cl";
1005 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
1006
1007 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -04001008 clang::FrontendInputFile kernelFile(
1009 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -05001010 std::string log;
1011 llvm::raw_string_ostream diagnosticsStream(log);
1012 if (auto error =
1013 SetCompilerInstanceOptions(instance, overiddenInputFilename,
1014 kernelFile, program, &diagnosticsStream))
1015 return error;
1016
1017 // Parse.
1018 llvm::LLVMContext context;
1019 clang::EmitLLVMOnlyAction action(&context);
1020
1021 // Prepare the action for processing kernelFile
1022 const bool success = action.BeginSourceFile(instance, kernelFile);
1023 if (!success) {
1024 return -1;
1025 }
1026
alan-bakerf3bce4a2019-06-28 16:01:15 -04001027 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001028 action.EndSourceFile();
1029
1030 clang::DiagnosticConsumer *const consumer =
1031 instance.getDiagnostics().getClient();
1032 consumer->finish();
1033
1034 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001035 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001036 llvm::errs() << log << "\n";
1037 return -1;
1038 }
1039
alan-bakerf5e5f692018-11-27 08:33:24 -05001040 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1041 llvm::initializeCore(Registry);
1042 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001043 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001044
1045 std::unique_ptr<llvm::Module> module(action.takeModule());
1046
1047 // Optimize.
1048 // Create a memory buffer for temporarily writing the result.
1049 SmallVector<char, 10000> binary;
1050 llvm::raw_svector_ostream binaryStream(binary);
1051 std::string descriptor_map;
1052 llvm::legacy::PassManager pm;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001053 if (auto error = PopulatePassManager(
1054 &pm, &binaryStream, descriptor_map_entries, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001055 return error;
1056 pm.run(*module);
1057
1058 // Write outputs
1059
1060 // Write the descriptor map. This is required.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001061 assert(descriptor_map_entries &&
1062 "Valid descriptor map container is required.");
alan-bakerf5e5f692018-11-27 08:33:24 -05001063 if (!DescriptorMapFilename.empty()) {
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001064 llvm::errs() << "Warning: -descriptormap is ignored descriptor map "
1065 "container is provided.\n";
alan-bakerf5e5f692018-11-27 08:33:24 -05001066 }
1067
1068 // Write the resulting binary.
1069 // Wait until now to try writing the file so that we only write it on
1070 // successful compilation.
1071 assert(output_binary && "Valid binary container is required.");
1072 if (!OutputFilename.empty()) {
1073 llvm::outs()
1074 << "Warning: -o is ignored when binary container is provided.\n";
1075 }
1076 output_binary->resize(binary.size() / 4);
1077 memcpy(output_binary->data(), binary.data(), binary.size());
1078
1079 return 0;
1080}
alan-bakerfec0a472018-11-08 18:09:40 -05001081} // namespace clspv