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