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