blob: 590fcc0b4df353136dad7f6f0bccc0062bd75689 [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-bakerfec0a472018-11-08 18:09:40 -050038#include "clspv/Option.h"
39#include "clspv/Passes.h"
alan-baker86ce19c2020-08-05 13:09:19 -040040#include "clspv/Sampler.h"
alan-bakerfec0a472018-11-08 18:09:40 -050041#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
alan-bakerfec0a472018-11-08 18:09:40 -0500135static llvm::cl::opt<char>
136 OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'),
137 llvm::cl::desc("Optimization level to use"),
138 llvm::cl::value_desc("level"));
139
alan-bakerfec0a472018-11-08 18:09:40 -0500140static llvm::cl::opt<std::string> OutputFormat(
141 "mfmt", llvm::cl::init(""),
142 llvm::cl::desc(
143 "Specify special output format. 'c' is as a C initializer list"),
144 llvm::cl::value_desc("format"));
145
146static llvm::cl::opt<std::string>
alan-baker09cb9802019-12-10 13:16:27 -0500147 SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"),
alan-bakerfec0a472018-11-08 18:09:40 -0500148 llvm::cl::value_desc("filename"));
149
alan-bakerfec0a472018-11-08 18:09:40 -0500150static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false),
151 llvm::cl::desc("Verify diagnostic outputs"));
152
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100153static llvm::cl::opt<bool>
154 IgnoreWarnings("w", llvm::cl::init(false),
155 llvm::cl::desc("Disable all warnings"));
156
157static llvm::cl::opt<bool>
158 WarningsAsErrors("Werror", llvm::cl::init(false),
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400159 llvm::cl::desc("Turn warnings into errors"));
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100160
Diego Novillo89500852019-04-15 08:45:10 -0400161static llvm::cl::opt<std::string> IROutputFile(
162 "emit-ir",
163 llvm::cl::desc(
164 "Emit LLVM IR to the given file after parsing and stop compilation."),
165 llvm::cl::value_desc("filename"));
166
alan-bakerfec0a472018-11-08 18:09:40 -0500167// Populates |SamplerMapEntries| with data from the input sampler map. Returns 0
168// if successful.
alan-bakerf5e5f692018-11-27 08:33:24 -0500169int ParseSamplerMap(const std::string &sampler_map,
170 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
171 *SamplerMapEntries) {
172 std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr);
173 if (!sampler_map.empty()) {
174 // Parse the sampler map from the provided string.
175 samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map);
176
alan-baker09cb9802019-12-10 13:16:27 -0500177 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500178 if (!SamplerMap.empty()) {
179 llvm::outs() << "Warning: -samplermap is ignored when the sampler map is "
180 "provided through a string.\n";
181 }
182 } else if (!SamplerMap.empty()) {
183 // Parse the sampler map from the option provided file.
alan-bakerfec0a472018-11-08 18:09:40 -0500184 auto errorOrSamplerMapFile =
185 llvm::MemoryBuffer::getFile(SamplerMap.getValue());
186
187 // If there was an error in getting the sampler map file.
188 if (!errorOrSamplerMapFile) {
189 llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message()
190 << " '" << SamplerMap.getValue() << "'\n";
191 return -1;
192 }
193
alan-baker09cb9802019-12-10 13:16:27 -0500194 clspv::Option::SetUseSamplerMap(true);
alan-bakerf5e5f692018-11-27 08:33:24 -0500195 samplerMapBuffer = std::move(errorOrSamplerMapFile.get());
alan-bakerfec0a472018-11-08 18:09:40 -0500196 if (0 == samplerMapBuffer->getBufferSize()) {
197 llvm::errs() << "Error: Sampler map was an empty file!\n";
198 return -1;
199 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500200 }
alan-bakerfec0a472018-11-08 18:09:40 -0500201
alan-baker09cb9802019-12-10 13:16:27 -0500202 if (clspv::Option::UseSamplerMap()) {
203 llvm::outs()
204 << "Warning: use of the sampler map is deprecated and unnecessary\n";
205 }
206
alan-bakerf5e5f692018-11-27 08:33:24 -0500207 // No sampler map to parse.
208 if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize())
209 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500210
alan-bakerf5e5f692018-11-27 08:33:24 -0500211 llvm::SmallVector<llvm::StringRef, 3> samplerStrings;
alan-bakerfec0a472018-11-08 18:09:40 -0500212
alan-bakerf5e5f692018-11-27 08:33:24 -0500213 // We need to keep track of the beginning of the current entry.
214 const char *b = samplerMapBuffer->getBufferStart();
215 for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) {
216 // If we have a separator between declarations.
217 if ((*i == '|') || (*i == ',') || (i == e)) {
218 if (i == b) {
219 llvm::errs() << "Error: Sampler map contained an empty entry!\n";
220 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500221 }
222
alan-bakerf5e5f692018-11-27 08:33:24 -0500223 samplerStrings.push_back(llvm::StringRef(b, i - b).trim());
alan-bakerfec0a472018-11-08 18:09:40 -0500224
alan-bakerf5e5f692018-11-27 08:33:24 -0500225 // And set b the next character after i.
226 b = i + 1;
227 }
alan-bakerfec0a472018-11-08 18:09:40 -0500228
alan-bakerf5e5f692018-11-27 08:33:24 -0500229 // If we have a separator between declarations within a single sampler.
230 if ((*i == ',') || (i == e)) {
alan-bakerfec0a472018-11-08 18:09:40 -0500231
alan-baker86ce19c2020-08-05 13:09:19 -0400232 clspv::SamplerNormalizedCoords NormalizedCoord =
233 clspv::CLK_NORMALIZED_COORDS_NOT_SET;
234 clspv::SamplerAddressingMode AddressingMode = clspv::CLK_ADDRESS_NOT_SET;
235 clspv::SamplerFilterMode FilterMode = clspv::CLK_FILTER_NOT_SET;
alan-bakerf5e5f692018-11-27 08:33:24 -0500236
237 for (auto str : samplerStrings) {
238 if ("CLK_NORMALIZED_COORDS_FALSE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400239 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500240 llvm::errs() << "Error: Sampler map normalized coordinates was "
241 "previously set!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500242 return -1;
243 }
alan-baker86ce19c2020-08-05 13:09:19 -0400244 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_FALSE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500245 } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400246 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500247 llvm::errs() << "Error: Sampler map normalized coordinates was "
248 "previously set!\n";
249 return -1;
250 }
alan-baker86ce19c2020-08-05 13:09:19 -0400251 NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_TRUE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500252 } else if ("CLK_ADDRESS_NONE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400253 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500254 llvm::errs()
255 << "Error: Sampler map addressing mode was previously set!\n";
256 return -1;
257 }
alan-baker86ce19c2020-08-05 13:09:19 -0400258 AddressingMode = clspv::CLK_ADDRESS_NONE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500259 } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400260 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500261 llvm::errs()
262 << "Error: Sampler map addressing mode was previously set!\n";
263 return -1;
264 }
alan-baker86ce19c2020-08-05 13:09:19 -0400265 AddressingMode = clspv::CLK_ADDRESS_CLAMP_TO_EDGE;
alan-bakerf5e5f692018-11-27 08:33:24 -0500266 } else if ("CLK_ADDRESS_CLAMP" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400267 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500268 llvm::errs()
269 << "Error: Sampler map addressing mode was previously set!\n";
270 return -1;
271 }
alan-baker86ce19c2020-08-05 13:09:19 -0400272 AddressingMode = clspv::CLK_ADDRESS_CLAMP;
alan-bakerf5e5f692018-11-27 08:33:24 -0500273 } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400274 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500275 llvm::errs()
276 << "Error: Sampler map addressing mode was previously set!\n";
277 return -1;
278 }
alan-baker86ce19c2020-08-05 13:09:19 -0400279 AddressingMode = clspv::CLK_ADDRESS_MIRRORED_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500280 } else if ("CLK_ADDRESS_REPEAT" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400281 if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500282 llvm::errs()
283 << "Error: Sampler map addressing mode was previously set!\n";
284 return -1;
285 }
alan-baker86ce19c2020-08-05 13:09:19 -0400286 AddressingMode = clspv::CLK_ADDRESS_REPEAT;
alan-bakerf5e5f692018-11-27 08:33:24 -0500287 } else if ("CLK_FILTER_NEAREST" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400288 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500289 llvm::errs()
290 << "Error: Sampler map filtering mode was previously set!\n";
291 return -1;
292 }
alan-baker86ce19c2020-08-05 13:09:19 -0400293 FilterMode = clspv::CLK_FILTER_NEAREST;
alan-bakerf5e5f692018-11-27 08:33:24 -0500294 } else if ("CLK_FILTER_LINEAR" == str) {
alan-baker86ce19c2020-08-05 13:09:19 -0400295 if (clspv::CLK_FILTER_NOT_SET != FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500296 llvm::errs()
297 << "Error: Sampler map filtering mode was previously set!\n";
298 return -1;
299 }
alan-baker86ce19c2020-08-05 13:09:19 -0400300 FilterMode = clspv::CLK_FILTER_LINEAR;
alan-bakerf5e5f692018-11-27 08:33:24 -0500301 } else {
302 llvm::errs() << "Error: Unknown sampler string '" << str
303 << "' found!\n";
alan-bakerfec0a472018-11-08 18:09:40 -0500304 return -1;
305 }
alan-bakerfec0a472018-11-08 18:09:40 -0500306 }
307
alan-baker86ce19c2020-08-05 13:09:19 -0400308 if (clspv::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500309 llvm::errs() << "Error: Sampler map entry did not contain normalized "
310 "coordinates entry!\n";
311 return -1;
alan-bakerfec0a472018-11-08 18:09:40 -0500312 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500313
alan-baker86ce19c2020-08-05 13:09:19 -0400314 if (clspv::CLK_ADDRESS_NOT_SET == AddressingMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500315 llvm::errs() << "Error: Sampler map entry did not contain addressing "
316 "mode entry!\n";
317 return -1;
318 }
319
alan-baker86ce19c2020-08-05 13:09:19 -0400320 if (clspv::CLK_FILTER_NOT_SET == FilterMode) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500321 llvm::errs()
322 << "Error: Sampler map entry did not contain filer mode entry!\n";
323 return -1;
324 }
325
326 // Generate an equivalent expression in string form. Sort the
327 // strings to get a canonical ordering.
328 std::sort(samplerStrings.begin(), samplerStrings.end(),
329 std::less<StringRef>());
330 const auto samplerExpr = std::accumulate(
331 samplerStrings.begin(), samplerStrings.end(), std::string(),
alan-baker21574d32020-01-29 16:00:31 -0500332 [](llvm::StringRef left, llvm::StringRef right) {
333 return left.str() + std::string(left.empty() ? "" : "|") +
334 right.str();
alan-bakerf5e5f692018-11-27 08:33:24 -0500335 });
336
337 // SamplerMapEntries->push_back(std::make_pair(
338 // NormalizedCoord | AddressingMode | FilterMode, samplerExpr));
339 SamplerMapEntries->emplace_back(
340 NormalizedCoord | AddressingMode | FilterMode, samplerExpr);
341
342 // And reset the sampler strings for the next sampler in the map.
343 samplerStrings.clear();
344 }
345
346 // And lastly, if we are at the end of the file
347 if (i == e) {
348 break;
alan-bakerfec0a472018-11-08 18:09:40 -0500349 }
350 }
351
352 return 0;
353}
354
355// Sets |instance|'s options for compiling. Returns 0 if successful.
356int SetCompilerInstanceOptions(CompilerInstance &instance,
357 const llvm::StringRef &overiddenInputFilename,
358 const clang::FrontendInputFile &kernelFile,
alan-bakerf5e5f692018-11-27 08:33:24 -0500359 const std::string &program,
alan-bakerfec0a472018-11-08 18:09:40 -0500360 llvm::raw_string_ostream *diagnosticsStream) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500361 std::unique_ptr<llvm::MemoryBuffer> memory_buffer(nullptr);
362 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr);
363 if (program.empty()) {
364 auto errorOrInputFile =
365 llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue());
alan-bakerfec0a472018-11-08 18:09:40 -0500366
alan-bakerf5e5f692018-11-27 08:33:24 -0500367 // If there was an error in getting the input file.
368 if (!errorOrInputFile) {
369 llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '"
370 << InputFilename.getValue() << "'\n";
371 return -1;
372 }
373 memory_buffer.reset(errorOrInputFile.get().release());
374 } else {
375 memory_buffer = llvm::MemoryBuffer::getMemBuffer(program.c_str(),
376 overiddenInputFilename);
alan-bakerfec0a472018-11-08 18:09:40 -0500377 }
alan-bakerf5e5f692018-11-27 08:33:24 -0500378
alan-bakerfec0a472018-11-08 18:09:40 -0500379 if (verify) {
380 instance.getDiagnosticOpts().VerifyDiagnostics = true;
alan-bakerbccf62c2019-03-29 10:32:41 -0400381 instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected");
alan-bakerfec0a472018-11-08 18:09:40 -0500382 }
383
Kévin Petit0fc88042019-04-09 23:25:02 +0100384 clang::LangStandard::Kind standard;
Kévin Petitf0515712020-01-07 18:29:20 +0000385 switch (clspv::Option::Language()) {
386 case clspv::Option::SourceLanguage::OpenCL_C_10:
387 standard = clang::LangStandard::lang_opencl10;
388 break;
389 case clspv::Option::SourceLanguage::OpenCL_C_11:
390 standard = clang::LangStandard::lang_opencl11;
391 break;
392 case clspv::Option::SourceLanguage::OpenCL_C_12:
Kévin Petit0fc88042019-04-09 23:25:02 +0100393 standard = clang::LangStandard::lang_opencl12;
Kévin Petitf0515712020-01-07 18:29:20 +0000394 break;
395 case clspv::Option::SourceLanguage::OpenCL_C_20:
396 standard = clang::LangStandard::lang_opencl20;
397 break;
Kévin Petit77838ff2020-10-19 18:54:51 +0100398 case clspv::Option::SourceLanguage::OpenCL_C_30:
399 standard = clang::LangStandard::lang_opencl30;
400 break;
Kévin Petitf0515712020-01-07 18:29:20 +0000401 case clspv::Option::SourceLanguage::OpenCL_CPP:
402 standard = clang::LangStandard::lang_openclcpp;
403 break;
404 default:
405 llvm_unreachable("Unknown source language");
Kévin Petit0fc88042019-04-09 23:25:02 +0100406 }
alan-bakerfec0a472018-11-08 18:09:40 -0500407
alan-bakerfec0a472018-11-08 18:09:40 -0500408 instance.getLangOpts().C99 = true;
409 instance.getLangOpts().RTTI = false;
410 instance.getLangOpts().RTTIData = false;
411 instance.getLangOpts().MathErrno = false;
412 instance.getLangOpts().Optimize = false;
413 instance.getLangOpts().NoBuiltin = true;
414 instance.getLangOpts().ModulesSearchAll = false;
415 instance.getLangOpts().SinglePrecisionConstants = true;
416 instance.getCodeGenOpts().StackRealignment = true;
417 instance.getCodeGenOpts().SimplifyLibCalls = false;
418 instance.getCodeGenOpts().EmitOpenCLArgMetadata = false;
419 instance.getCodeGenOpts().DisableO0ImplyOptNone = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100420 instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings;
alan-bakerfec0a472018-11-08 18:09:40 -0500421
422 instance.getLangOpts().SinglePrecisionConstants =
423 cl_single_precision_constants;
424 // cl_denorms_are_zero ignored for now!
425 // cl_fp32_correctly_rounded_divide_sqrt ignored for now!
426 instance.getCodeGenOpts().LessPreciseFPMAD =
427 cl_mad_enable || cl_unsafe_math_optimizations;
428 // cl_no_signed_zeros ignored for now!
alan-baker0f814cd2020-06-02 15:35:14 -0400429 instance.getLangOpts().UnsafeFPMath =
alan-bakerfec0a472018-11-08 18:09:40 -0500430 cl_unsafe_math_optimizations || cl_fast_relaxed_math;
431 instance.getLangOpts().FiniteMathOnly =
432 cl_finite_math_only || cl_fast_relaxed_math;
433 instance.getLangOpts().FastRelaxedMath = cl_fast_relaxed_math;
434
435 // Preprocessor options
Kévin Petita624c0c2019-05-07 20:27:43 +0800436 if (!clspv::Option::ImageSupport()) {
437 instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__");
438 }
alan-bakerfec0a472018-11-08 18:09:40 -0500439 if (cl_fast_relaxed_math) {
440 instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__");
441 }
442
443 for (auto define : Defines) {
444 instance.getPreprocessorOpts().addMacroDef(define);
445 }
446
447 // Header search options
448 for (auto include : Includes) {
449 instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After,
450 false, false);
451 }
452
453 // We always compile on opt 0 so we preserve as much debug information about
454 // the source as possible. We'll run optimization later, once we've had a
455 // chance to view the unoptimal code first
456 instance.getCodeGenOpts().OptimizationLevel = 0;
457
458// Debug information is disabled temporarily to call instruction.
459#if 0
460 instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo);
461#endif
462
463 // We use the 32-bit pointer-width SPIR triple
464 llvm::Triple triple("spir-unknown-unknown");
465
466 instance.getInvocation().setLangDefaults(
alan-bakerd354f1a2019-08-06 15:41:55 -0400467 instance.getLangOpts(), clang::InputKind(clang::Language::OpenCL), triple,
alan-bakerfec0a472018-11-08 18:09:40 -0500468 instance.getPreprocessorOpts(), standard);
469
470 // Override the C99 inline semantics to accommodate for more OpenCL C
471 // programs in the wild.
472 instance.getLangOpts().GNUInline = true;
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100473
474 // Set up diagnostics
alan-bakerfec0a472018-11-08 18:09:40 -0500475 instance.createDiagnostics(
476 new clang::TextDiagnosticPrinter(*diagnosticsStream,
477 &instance.getDiagnosticOpts()),
478 true);
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100479 instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors);
480 instance.getDiagnostics().setEnableAllWarnings(true);
alan-bakerfec0a472018-11-08 18:09:40 -0500481
482 instance.getTargetOpts().Triple = triple.str();
483
alan-baker21574d32020-01-29 16:00:31 -0500484 instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str();
alan-bakerfec0a472018-11-08 18:09:40 -0500485 instance.getCodeGenOpts().PreserveVec3Type = true;
486 // Disable generation of lifetime intrinsic.
487 instance.getCodeGenOpts().DisableLifetimeMarkers = true;
488 instance.getFrontendOpts().Inputs.push_back(kernelFile);
alan-bakerf5e5f692018-11-27 08:33:24 -0500489 instance.getPreprocessorOpts().addRemappedFile(overiddenInputFilename,
490 memory_buffer.release());
alan-bakerfec0a472018-11-08 18:09:40 -0500491
492 struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer {
493 OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) {
494 const char *dataCasted = reinterpret_cast<const char *>(data);
495 init(dataCasted, dataCasted + data_length, true);
496 }
497
498 virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override {
499 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
500 }
501
502 virtual ~OpenCLBuiltinMemoryBuffer() override {}
503 };
504
505 std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer(
506 new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data,
507 opencl_builtins_header_size - 1));
508
509 instance.getPreprocessorOpts().Includes.push_back("openclc.h");
510
alan-bakerf3bce4a2019-06-28 16:01:15 -0400511 std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer(
512 new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data,
513 opencl_base_builtins_header_size - 1));
514
515 instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h");
516
alan-bakerfec0a472018-11-08 18:09:40 -0500517 // Add the VULKAN macro.
518 instance.getPreprocessorOpts().addMacroDef("VULKAN=100");
519
520 // Add the __OPENCL_VERSION__ macro.
521 instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120");
522
523 instance.setTarget(clang::TargetInfo::CreateTargetInfo(
524 instance.getDiagnostics(),
525 std::make_shared<clang::TargetOptions>(instance.getTargetOpts())));
526
527 instance.createFileManager();
528 instance.createSourceManager(instance.getFileManager());
529
530#ifdef _MSC_VER
531 std::string includePrefix("include\\");
532#else
533 std::string includePrefix("include/");
534#endif
535
536 auto entry = instance.getFileManager().getVirtualFile(
537 includePrefix + "openclc.h", openCLBuiltinMemoryBuffer->getBufferSize(),
538 0);
539
540 instance.getSourceManager().overrideFileContents(
541 entry, std::move(openCLBuiltinMemoryBuffer));
542
alan-bakerf3bce4a2019-06-28 16:01:15 -0400543 auto base_entry = instance.getFileManager().getVirtualFile(
544 includePrefix + "opencl-c-base.h",
545 openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0);
546
547 instance.getSourceManager().overrideFileContents(
548 base_entry, std::move(openCLBaseBuiltinMemoryBuffer));
549
alan-bakerfec0a472018-11-08 18:09:40 -0500550 return 0;
551}
552
alan-bakerf5e5f692018-11-27 08:33:24 -0500553// Populates |pm| with necessary passes to optimize and legalize the IR.
554int PopulatePassManager(
555 llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream,
alan-bakerf5e5f692018-11-27 08:33:24 -0500556 llvm::SmallVectorImpl<std::pair<unsigned, std::string>>
557 *SamplerMapEntries) {
alan-bakerfec0a472018-11-08 18:09:40 -0500558 llvm::PassManagerBuilder pmBuilder;
559
560 switch (OptimizationLevel) {
561 case '0':
alan-bakerf5e5f692018-11-27 08:33:24 -0500562 case '1':
563 case '2':
564 case '3':
565 case 's':
566 case 'z':
567 break;
568 default:
569 llvm::errs() << "Unknown optimization level -O" << OptimizationLevel
570 << " specified!\n";
571 return -1;
572 }
573
574 switch (OptimizationLevel) {
575 case '0':
alan-bakerfec0a472018-11-08 18:09:40 -0500576 pmBuilder.OptLevel = 0;
577 break;
578 case '1':
579 pmBuilder.OptLevel = 1;
580 break;
581 case '2':
582 pmBuilder.OptLevel = 2;
583 break;
584 case '3':
585 pmBuilder.OptLevel = 3;
586 break;
587 case 's':
588 pmBuilder.SizeLevel = 1;
589 break;
590 case 'z':
591 pmBuilder.SizeLevel = 2;
592 break;
593 default:
594 break;
595 }
596
597 pm->add(clspv::createZeroInitializeAllocasPass());
alan-baker04f3a952020-03-24 10:39:53 -0400598 pm->add(clspv::createAddFunctionAttributesPass());
alan-bakerc4579bb2020-04-29 14:15:50 -0400599 pm->add(clspv::createAutoPodArgsPass());
Kévin Petitbbbda972020-03-03 19:16:31 +0000600 pm->add(clspv::createDeclarePushConstantsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500601 pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass());
602
603 if (0 < pmBuilder.OptLevel) {
604 pm->add(clspv::createOpenCLInlinerPass());
605 }
606
607 pm->add(clspv::createUndoByvalPass());
608 pm->add(clspv::createUndoSRetPass());
alan-baker9b0ec3c2020-04-06 14:45:34 -0400609 if (clspv::Option::ClusterPodKernelArgs()) {
alan-bakerfec0a472018-11-08 18:09:40 -0500610 pm->add(clspv::createClusterPodKernelArgumentsPass());
611 }
612 pm->add(clspv::createReplaceOpenCLBuiltinPass());
613
Marco Antognini535998c2020-09-16 18:48:51 +0100614 // Lower longer vectors when requested. Note that this pass depends on
615 // ReplaceOpenCLBuiltinPass and expects DeadCodeEliminationPass to be run
616 // afterwards.
617 if (clspv::Option::LongVectorSupport()) {
618 pm->add(clspv::createLongVectorLoweringPass());
619 }
620
alan-bakerfec0a472018-11-08 18:09:40 -0500621 // 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());
alan-bakerad1a12f2020-08-25 09:18:38 -0400686 // Replace LLVM intrinsics can leave dead code around.
687 pm->add(llvm::createDeadCodeEliminationPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500688 pm->add(clspv::createUndoBoolPass());
alan-bakere711c762020-05-20 17:56:59 -0400689 pm->add(clspv::createUndoTruncateToOddIntegerPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500690 pm->add(llvm::createStructurizeCFGPass(false));
alan-baker3fa76d92018-11-12 14:54:40 -0500691 // Must be run after structurize cfg.
alan-baker9580aef2020-01-07 22:31:48 -0500692 pm->add(clspv::createFixupStructuredCFGPass());
693 // Must be run after structured cfg fixup.
alan-bakerfec0a472018-11-08 18:09:40 -0500694 pm->add(clspv::createReorderBasicBlocksPass());
695 pm->add(clspv::createUndoGetElementPtrConstantExprPass());
696 pm->add(clspv::createSplatArgPass());
697 pm->add(clspv::createSimplifyPointerBitcastPass());
698 pm->add(clspv::createReplacePointerBitcastPass());
699
700 pm->add(clspv::createUndoTranslateSamplerFoldPass());
701
702 if (clspv::Option::ModuleConstantsInStorageBuffer()) {
703 pm->add(clspv::createClusterModuleScopeConstantVars());
704 }
705
706 pm->add(clspv::createShareModuleScopeVariablesPass());
alan-bakerf67468c2019-11-25 15:51:49 -0500707 // Specialize images before assigning descriptors to disambiguate the various
708 // types.
709 pm->add(clspv::createSpecializeImageTypesPass());
alan-bakere9308012019-03-15 10:25:13 -0400710 // This should be run after LLVM and OpenCL intrinsics are replaced.
alan-bakerfec0a472018-11-08 18:09:40 -0500711 pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries));
712 pm->add(llvm::createVerifierPass());
713 pm->add(clspv::createDirectResourceAccessPass());
714 // Replacing pointer bitcasts can leave some trivial GEPs
715 // that are easy to remove. Also replace GEPs of GEPS
716 // left by replacing indirect buffer accesses.
717 pm->add(clspv::createSimplifyPointerBitcastPass());
alan-baker4217b322019-03-06 08:56:12 -0500718 // Run after DRA to clean up parameters and help reduce the need for variable
719 // pointers.
720 pm->add(clspv::createRemoveUnusedArgumentsPass());
alan-bakerfec0a472018-11-08 18:09:40 -0500721
722 pm->add(clspv::createSplatSelectConditionPass());
723 pm->add(clspv::createSignedCompareFixupPass());
724 // This pass generates insertions that need to be rewritten.
725 pm->add(clspv::createScalarizePass());
726 pm->add(clspv::createRewriteInsertsPass());
alan-bakera71f1932019-04-11 11:04:34 -0400727 // UBO Transformations
728 if (clspv::Option::ConstantArgsInUniformBuffer() &&
729 !clspv::Option::InlineEntryPoints()) {
730 // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO
731 // arguments and either multi-version them as necessary or inline them if
732 // multi-versioning cannot be accomplished.
733 pm->add(clspv::createMultiVersionUBOFunctionsPass());
734 // Cleanup passes.
735 // Specialization can blindly generate GEP chains that are easily cleaned up
736 // by SimplifyPointerBitcastPass.
737 pm->add(clspv::createSimplifyPointerBitcastPass());
738 // RemoveUnusedArgumentsPass removes the actual UBO arguments that were
739 // problematic to begin with now that they have no uses.
740 pm->add(clspv::createRemoveUnusedArgumentsPass());
741 // DCE cleans up callers of the specialized functions.
742 pm->add(llvm::createDeadCodeEliminationPass());
743 }
alan-bakerfec0a472018-11-08 18:09:40 -0500744 // This pass mucks with types to point where you shouldn't rely on DataLayout
745 // anymore so leave this right before SPIR-V generation.
746 pm->add(clspv::createUBOTypeTransformPass());
alan-baker86ce19c2020-08-05 13:09:19 -0400747 pm->add(clspv::createSPIRVProducerPass(*binaryStream, *SamplerMapEntries,
alan-baker00e7a582019-06-07 12:54:21 -0400748 OutputFormat == "c"));
alan-bakerf5e5f692018-11-27 08:33:24 -0500749
750 return 0;
alan-bakerfec0a472018-11-08 18:09:40 -0500751}
alan-bakerfec0a472018-11-08 18:09:40 -0500752
Kévin Petitd5db2d22019-04-04 13:55:14 +0100753int ParseOptions(const int argc, const char *const argv[]) {
alan-baker227e9782020-06-02 15:35:37 -0400754 // We need to change how some of the called passes works by spoofing
755 // ParseCommandLineOptions with the specific options.
756 bool has_pre = false;
757 bool has_load_pre = false;
758 const std::string pre = "-enable-pre";
759 const std::string load_pre = "-enable-load-pre";
760 for (int i = 1; i < argc; ++i) {
761 std::string option(argv[i]);
762 auto pre_pos = option.find(pre);
763 auto load_pos = option.find(load_pre);
764 if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) {
765 has_pre = true;
766 } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) {
767 has_load_pre = true;
768 }
769 }
770
771 int llvmArgc = 2;
772 const char *llvmArgv[4];
773 llvmArgv[0] = argv[0];
774 llvmArgv[1] = "-simplifycfg-sink-common=false";
775 if (!has_pre) {
776 llvmArgv[llvmArgc++] = "-enable-pre=0";
777 }
778 if (!has_load_pre) {
779 llvmArgv[llvmArgc++] = "-enable-load-pre=0";
780 }
alan-bakerfec0a472018-11-08 18:09:40 -0500781
Kévin Petitd5db2d22019-04-04 13:55:14 +0100782 llvm::cl::ResetAllOptionOccurrences();
alan-bakerfec0a472018-11-08 18:09:40 -0500783 llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv);
alan-bakerfec0a472018-11-08 18:09:40 -0500784 llvm::cl::ParseCommandLineOptions(argc, argv);
785
Kévin Petitf0515712020-01-07 18:29:20 +0000786 if (clspv::Option::LanguageUsesGenericAddressSpace() &&
787 !clspv::Option::InlineEntryPoints()) {
788 llvm::errs() << "cannot compile languages that use the generic address "
789 "space (e.g. CLC++, CL2.0) without -inline-entry-points\n";
Kévin Petit0fc88042019-04-09 23:25:02 +0100790 return -1;
791 }
792
Kévin Petitbbbda972020-03-03 19:16:31 +0000793 if (clspv::Option::ScalarBlockLayout()) {
794 llvm::errs() << "scalar block layout support unimplemented\n";
795 return -1;
796 }
797
alan-baker9b0ec3c2020-04-06 14:45:34 -0400798 // Push constant option validation.
799 if (clspv::Option::PodArgsInPushConstants()) {
800 if (clspv::Option::PodArgsInUniformBuffer()) {
801 llvm::errs() << "POD arguments can only be in either uniform buffers or "
802 "push constants\n";
803 return -1;
804 }
805
806 if (!clspv::Option::ClusterPodKernelArgs()) {
807 llvm::errs()
808 << "POD arguments must be clustered to be passed as push constants\n";
809 return -1;
810 }
811
812 // Conservatively error if a module scope push constant could be used.
James Price708cf362020-05-06 19:33:45 -0400813 if (clspv::Option::GlobalOffsetPushConstant() ||
alan-baker9b0ec3c2020-04-06 14:45:34 -0400814 clspv::Option::Language() ==
815 clspv::Option::SourceLanguage::OpenCL_C_20 ||
816 clspv::Option::Language() ==
817 clspv::Option::SourceLanguage::OpenCL_CPP) {
818 llvm::errs() << "POD arguments as push constants are not compatible with "
819 "module scope push constants\n";
820 return -1;
821 }
822 }
823
Kévin Petitd5db2d22019-04-04 13:55:14 +0100824 return 0;
825}
Diego Novillo89500852019-04-15 08:45:10 -0400826
827int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module,
828 std::string output) {
829 std::error_code ec;
830 std::unique_ptr<llvm::ToolOutputFile> out(
831 new llvm::ToolOutputFile(output, ec, llvm::sys::fs::F_None));
832 if (ec) {
833 llvm::errs() << output << ": " << ec.message() << '\n';
834 return -1;
835 }
836 pm->add(llvm::createPrintModulePass(out->os(), "", false));
837 pm->run(module);
838 out->keep();
839 return 0;
840}
841
Kévin Petitd5db2d22019-04-04 13:55:14 +0100842} // namespace
843
844namespace clspv {
845int Compile(const int argc, const char *const argv[]) {
846
847 if (auto error = ParseOptions(argc, argv))
848 return error;
849
alan-bakerfec0a472018-11-08 18:09:40 -0500850 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
alan-bakerf5e5f692018-11-27 08:33:24 -0500851 if (auto error = ParseSamplerMap("", &SamplerMapEntries))
alan-bakerfec0a472018-11-08 18:09:40 -0500852 return error;
853
854 // if no output file was provided, use a default
855 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
856
857 // If we are reading our input file from stdin.
858 if ("-" == InputFilename) {
859 // We need to overwrite the file name we use.
Kévin Petitddad8f42019-09-30 15:12:08 +0100860 switch (InputLanguage) {
861 case clang::Language::OpenCL:
862 overiddenInputFilename = "stdin.cl";
863 break;
864 case clang::Language::LLVM_IR:
865 overiddenInputFilename = "stdin.ll";
866 break;
alan-baker31298a62019-10-07 13:24:30 -0400867 default:
868 // Default to fix compiler warnings/errors. Option parsing will reject a
869 // bad enum value for the option so there is no need for a message.
870 return -1;
Kévin Petitddad8f42019-09-30 15:12:08 +0100871 }
alan-bakerfec0a472018-11-08 18:09:40 -0500872 }
873
874 clang::CompilerInstance instance;
Kévin Petitddad8f42019-09-30 15:12:08 +0100875 clang::FrontendInputFile kernelFile(overiddenInputFilename,
876 clang::InputKind(InputLanguage));
alan-bakerfec0a472018-11-08 18:09:40 -0500877 std::string log;
878 llvm::raw_string_ostream diagnosticsStream(log);
alan-bakerf5e5f692018-11-27 08:33:24 -0500879 if (auto error = SetCompilerInstanceOptions(
880 instance, overiddenInputFilename, kernelFile, "", &diagnosticsStream))
alan-bakerfec0a472018-11-08 18:09:40 -0500881 return error;
882
883 // Parse.
884 llvm::LLVMContext context;
885 clang::EmitLLVMOnlyAction action(&context);
886
887 // Prepare the action for processing kernelFile
888 const bool success = action.BeginSourceFile(instance, kernelFile);
889 if (!success) {
890 return -1;
891 }
892
alan-bakerf3bce4a2019-06-28 16:01:15 -0400893 auto result = action.Execute();
alan-bakerfec0a472018-11-08 18:09:40 -0500894 action.EndSourceFile();
895
896 clang::DiagnosticConsumer *const consumer =
897 instance.getDiagnostics().getClient();
898 consumer->finish();
899
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100900 auto num_warnings = consumer->getNumWarnings();
alan-bakerfec0a472018-11-08 18:09:40 -0500901 auto num_errors = consumer->getNumErrors();
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100902 if ((num_errors > 0) || (num_warnings > 0)) {
903 llvm::errs() << log;
904 }
alan-bakerf3bce4a2019-06-28 16:01:15 -0400905 if (result || num_errors > 0) {
alan-bakerfec0a472018-11-08 18:09:40 -0500906 return -1;
907 }
908
Kévin Petit6b07cbe2019-04-02 21:52:16 +0100909 // Don't run the passes or produce any output in verify mode.
910 // Clang doesn't always produce a valid module.
911 if (verify) {
912 return 0;
913 }
914
alan-bakerfec0a472018-11-08 18:09:40 -0500915 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
916 llvm::initializeCore(Registry);
917 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -0400918 llvm::initializeClspvPasses(Registry);
alan-bakerfec0a472018-11-08 18:09:40 -0500919
920 std::unique_ptr<llvm::Module> module(action.takeModule());
921
922 // Optimize.
923 // Create a memory buffer for temporarily writing the result.
924 SmallVector<char, 10000> binary;
925 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerfec0a472018-11-08 18:09:40 -0500926 llvm::legacy::PassManager pm;
Diego Novillo89500852019-04-15 08:45:10 -0400927
928 // If --emit-ir was requested, emit the initial LLVM IR and stop compilation.
929 if (!IROutputFile.empty()) {
930 return GenerateIRFile(&pm, *module, IROutputFile);
931 }
932
933 // Otherwise, populate the pass manager and run the regular passes.
alan-baker86ce19c2020-08-05 13:09:19 -0400934 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -0500935 return error;
alan-bakerfec0a472018-11-08 18:09:40 -0500936 pm.run(*module);
937
938 // Write outputs
alan-bakerfec0a472018-11-08 18:09:40 -0500939 std::error_code error;
alan-bakerfec0a472018-11-08 18:09:40 -0500940
941 // Write the resulting binary.
942 // Wait until now to try writing the file so that we only write it on
943 // successful compilation.
944 if (OutputFilename.empty()) {
Kévin Petite4786902019-04-02 21:51:47 +0100945 if (OutputFormat == "c") {
alan-bakerfec0a472018-11-08 18:09:40 -0500946 OutputFilename = "a.spvinc";
947 } else {
948 OutputFilename = "a.spv";
949 }
950 }
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400951 llvm::raw_fd_ostream outStream(OutputFilename, error,
952 llvm::sys::fs::FA_Write);
alan-bakerfec0a472018-11-08 18:09:40 -0500953
954 if (error) {
955 llvm::errs() << "Unable to open output file '" << OutputFilename
956 << "': " << error.message() << '\n';
957 return -1;
958 }
959 outStream << binaryStream.str();
960
961 return 0;
962}
alan-bakerf5e5f692018-11-27 08:33:24 -0500963
alan-baker86ce19c2020-08-05 13:09:19 -0400964int CompileFromSourceString(const std::string &program,
965 const std::string &sampler_map,
966 const std::string &options,
Kévin Petit899162d2020-09-08 19:16:08 +0100967 std::vector<uint32_t> *output_binary,
968 std::string *output_log) {
alan-bakerf5e5f692018-11-27 08:33:24 -0500969
970 llvm::SmallVector<const char *, 20> argv;
971 llvm::BumpPtrAllocator A;
972 llvm::StringSaver Saver(A);
973 argv.push_back(Saver.save("clspv").data());
974 llvm::cl::TokenizeGNUCommandLine(options, Saver, argv);
975 int argc = static_cast<int>(argv.size());
Kévin Petitd5db2d22019-04-04 13:55:14 +0100976
977 if (auto error = ParseOptions(argc, &argv[0]))
978 return error;
alan-bakerf5e5f692018-11-27 08:33:24 -0500979
980 llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries;
981 if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries))
982 return error;
983
984 InputFilename = "source.cl";
985 llvm::StringRef overiddenInputFilename = InputFilename.getValue();
986
987 clang::CompilerInstance instance;
alan-bakerd354f1a2019-08-06 15:41:55 -0400988 clang::FrontendInputFile kernelFile(
989 overiddenInputFilename, clang::InputKind(clang::Language::OpenCL));
alan-bakerf5e5f692018-11-27 08:33:24 -0500990 std::string log;
991 llvm::raw_string_ostream diagnosticsStream(log);
992 if (auto error =
993 SetCompilerInstanceOptions(instance, overiddenInputFilename,
994 kernelFile, program, &diagnosticsStream))
995 return error;
996
997 // Parse.
998 llvm::LLVMContext context;
999 clang::EmitLLVMOnlyAction action(&context);
1000
1001 // Prepare the action for processing kernelFile
1002 const bool success = action.BeginSourceFile(instance, kernelFile);
1003 if (!success) {
1004 return -1;
1005 }
1006
alan-bakerf3bce4a2019-06-28 16:01:15 -04001007 auto result = action.Execute();
alan-bakerf5e5f692018-11-27 08:33:24 -05001008 action.EndSourceFile();
1009
1010 clang::DiagnosticConsumer *const consumer =
1011 instance.getDiagnostics().getClient();
1012 consumer->finish();
1013
Kévin Petit899162d2020-09-08 19:16:08 +01001014 if (output_log != nullptr) {
1015 *output_log = log;
1016 }
1017
alan-bakerf5e5f692018-11-27 08:33:24 -05001018 auto num_errors = consumer->getNumErrors();
alan-bakerf3bce4a2019-06-28 16:01:15 -04001019 if (result || num_errors > 0) {
alan-bakerf5e5f692018-11-27 08:33:24 -05001020 return -1;
1021 }
1022
alan-bakerf5e5f692018-11-27 08:33:24 -05001023 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
1024 llvm::initializeCore(Registry);
1025 llvm::initializeScalarOpts(Registry);
Diego Novillo1fcff722019-05-07 13:45:53 -04001026 llvm::initializeClspvPasses(Registry);
alan-bakerf5e5f692018-11-27 08:33:24 -05001027
1028 std::unique_ptr<llvm::Module> module(action.takeModule());
1029
1030 // Optimize.
1031 // Create a memory buffer for temporarily writing the result.
1032 SmallVector<char, 10000> binary;
1033 llvm::raw_svector_ostream binaryStream(binary);
alan-bakerf5e5f692018-11-27 08:33:24 -05001034 llvm::legacy::PassManager pm;
alan-baker86ce19c2020-08-05 13:09:19 -04001035 if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries))
alan-bakerf5e5f692018-11-27 08:33:24 -05001036 return error;
1037 pm.run(*module);
1038
alan-bakerf5e5f692018-11-27 08:33:24 -05001039 // Write the resulting binary.
1040 // Wait until now to try writing the file so that we only write it on
1041 // successful compilation.
1042 assert(output_binary && "Valid binary container is required.");
1043 if (!OutputFilename.empty()) {
1044 llvm::outs()
1045 << "Warning: -o is ignored when binary container is provided.\n";
1046 }
1047 output_binary->resize(binary.size() / 4);
1048 memcpy(output_binary->data(), binary.data(), binary.size());
1049
1050 return 0;
1051}
alan-bakerfec0a472018-11-08 18:09:40 -05001052} // namespace clspv