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