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 | |
alan-baker | 0d095d6 | 2020-03-12 14:59:47 -0400 | [diff] [blame] | 15 | #include "clang/Basic/FileManager.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 16 | #include "clang/Basic/TargetInfo.h" |
| 17 | #include "clang/CodeGen/CodeGenAction.h" |
| 18 | #include "clang/Frontend/CompilerInstance.h" |
| 19 | #include "clang/Frontend/FrontendPluginRegistry.h" |
| 20 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
| 21 | #include "clang/Lex/PreprocessorOptions.h" |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 22 | #include "llvm/IR/GlobalValue.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 23 | #include "llvm/IR/LLVMContext.h" |
| 24 | #include "llvm/IR/LegacyPassManager.h" |
| 25 | #include "llvm/IR/Module.h" |
| 26 | #include "llvm/IR/Verifier.h" |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 27 | #include "llvm/IRReader/IRReader.h" |
alan-baker | 0e64a59 | 2019-11-18 13:36:25 -0500 | [diff] [blame] | 28 | #include "llvm/InitializePasses.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 29 | #include "llvm/LinkAllPasses.h" |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 30 | #include "llvm/Linker/Linker.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 31 | #include "llvm/Support/Allocator.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 32 | #include "llvm/Support/CommandLine.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 33 | #include "llvm/Support/ErrorOr.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 34 | #include "llvm/Support/MathExtras.h" |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 35 | #include "llvm/Support/StringSaver.h" |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 36 | #include "llvm/Support/ToolOutputFile.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 37 | #include "llvm/Support/raw_ostream.h" |
| 38 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" |
| 39 | |
Kévin Petit | 38c5248 | 2019-05-07 20:28:00 +0800 | [diff] [blame] | 40 | #include "clspv/AddressSpace.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 41 | #include "clspv/Option.h" |
| 42 | #include "clspv/Passes.h" |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 43 | #include "clspv/Sampler.h" |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 44 | #include "clspv/clspv_builtin_library.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 45 | #include "clspv/opencl_builtins_header.h" |
| 46 | |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 47 | #include "Builtins.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 48 | #include "FrontendPlugin.h" |
Diego Novillo | a4c44fa | 2019-04-11 10:56:15 -0400 | [diff] [blame] | 49 | #include "Passes.h" |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 50 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 51 | #include <cassert> |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 52 | #include <numeric> |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 53 | #include <sstream> |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 54 | #include <string> |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 55 | |
| 56 | using namespace clang; |
| 57 | |
| 58 | namespace { |
| 59 | // This registration must be located in the same file as the execution of the |
| 60 | // action. |
| 61 | static FrontendPluginRegistry::Add<clspv::ExtraValidationASTAction> |
| 62 | X("extra-validation", |
| 63 | "Perform extra validation on OpenCL C when targeting Vulkan"); |
| 64 | |
| 65 | static llvm::cl::opt<bool> cl_single_precision_constants( |
| 66 | "cl-single-precision-constant", llvm::cl::init(false), |
| 67 | llvm::cl::desc("Treat double precision floating-point constant as single " |
| 68 | "precision constant.")); |
| 69 | |
| 70 | static llvm::cl::opt<bool> cl_denorms_are_zero( |
| 71 | "cl-denorms-are-zero", llvm::cl::init(false), |
| 72 | llvm::cl::desc("If specified, denormalized floating point numbers may be " |
| 73 | "flushed to zero.")); |
| 74 | |
| 75 | static llvm::cl::opt<bool> cl_fp32_correctly_rounded_divide_sqrt( |
| 76 | "cl-fp32-correctly-rounded-divide-sqrt", llvm::cl::init(false), |
| 77 | llvm::cl::desc("Single precision floating-point divide (x/y and 1/x) and " |
| 78 | "sqrt used are correctly rounded.")); |
| 79 | |
| 80 | static llvm::cl::opt<bool> |
| 81 | cl_opt_disable("cl-opt-disable", llvm::cl::init(false), |
| 82 | llvm::cl::desc("This option disables all optimizations. The " |
| 83 | "default is optimizations are enabled.")); |
| 84 | |
| 85 | static llvm::cl::opt<bool> cl_mad_enable( |
| 86 | "cl-mad-enable", llvm::cl::init(false), |
| 87 | llvm::cl::desc("Allow a * b + c to be replaced by a mad. The mad computes " |
| 88 | "a * b + c with reduced accuracy.")); |
| 89 | |
| 90 | static llvm::cl::opt<bool> cl_no_signed_zeros( |
| 91 | "cl-no-signed-zeros", llvm::cl::init(false), |
| 92 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that " |
| 93 | "ignore the signedness of zero.")); |
| 94 | |
| 95 | static llvm::cl::opt<bool> cl_unsafe_math_optimizations( |
| 96 | "cl-unsafe-math-optimizations", llvm::cl::init(false), |
| 97 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that (a) " |
| 98 | "assume that arguments and results are valid, (b) may " |
| 99 | "violate IEEE 754 standard and (c) may violate the OpenCL " |
| 100 | "numerical compliance requirements. This option includes " |
| 101 | "the -cl-no-signed-zeros and -cl-mad-enable options.")); |
| 102 | |
| 103 | static llvm::cl::opt<bool> cl_finite_math_only( |
| 104 | "cl-finite-math-only", llvm::cl::init(false), |
| 105 | llvm::cl::desc("Allow optimizations for floating-point arithmetic that " |
| 106 | "assume that arguments and results are not NaNs or INFs.")); |
| 107 | |
| 108 | static llvm::cl::opt<bool> cl_fast_relaxed_math( |
| 109 | "cl-fast-relaxed-math", llvm::cl::init(false), |
| 110 | llvm::cl::desc("This option causes the preprocessor macro " |
| 111 | "__FAST_RELAXED_MATH__ to be defined. Sets the optimization " |
| 112 | "options -cl-finite-math-only and " |
| 113 | "-cl-unsafe-math-optimizations.")); |
| 114 | |
| 115 | static llvm::cl::list<std::string> |
| 116 | Includes(llvm::cl::Prefix, "I", |
| 117 | llvm::cl::desc("Add a directory to the list of directories " |
| 118 | "to be searched for header files."), |
| 119 | llvm::cl::ZeroOrMore, llvm::cl::value_desc("include path")); |
| 120 | |
| 121 | static llvm::cl::list<std::string> |
| 122 | Defines(llvm::cl::Prefix, "D", |
| 123 | llvm::cl::desc("Define a #define directive."), llvm::cl::ZeroOrMore, |
| 124 | llvm::cl::value_desc("define")); |
| 125 | |
| 126 | static llvm::cl::opt<std::string> |
| 127 | InputFilename(llvm::cl::Positional, llvm::cl::desc("<input .cl file>"), |
| 128 | llvm::cl::init("-")); |
| 129 | |
Kévin Petit | ddad8f4 | 2019-09-30 15:12:08 +0100 | [diff] [blame] | 130 | static llvm::cl::opt<clang::Language> InputLanguage( |
| 131 | "x", llvm::cl::desc("Select input type"), |
| 132 | llvm::cl::init(clang::Language::OpenCL), |
| 133 | llvm::cl::values(clEnumValN(clang::Language::OpenCL, "cl", "OpenCL source"), |
| 134 | clEnumValN(clang::Language::LLVM_IR, "ir", "LLVM IR"))); |
| 135 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 136 | static llvm::cl::opt<std::string> |
| 137 | OutputFilename("o", llvm::cl::desc("Override output filename"), |
| 138 | llvm::cl::value_desc("filename")); |
| 139 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 140 | static llvm::cl::opt<char> |
| 141 | OptimizationLevel(llvm::cl::Prefix, "O", llvm::cl::init('2'), |
| 142 | llvm::cl::desc("Optimization level to use"), |
| 143 | llvm::cl::value_desc("level")); |
| 144 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 145 | static llvm::cl::opt<std::string> OutputFormat( |
| 146 | "mfmt", llvm::cl::init(""), |
| 147 | llvm::cl::desc( |
| 148 | "Specify special output format. 'c' is as a C initializer list"), |
| 149 | llvm::cl::value_desc("format")); |
| 150 | |
| 151 | static llvm::cl::opt<std::string> |
alan-baker | 09cb980 | 2019-12-10 13:16:27 -0500 | [diff] [blame] | 152 | SamplerMap("samplermap", llvm::cl::desc("DEPRECATED - Literal sampler map"), |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 153 | llvm::cl::value_desc("filename")); |
| 154 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 155 | static llvm::cl::opt<bool> verify("verify", llvm::cl::init(false), |
| 156 | llvm::cl::desc("Verify diagnostic outputs")); |
| 157 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 158 | static llvm::cl::opt<bool> |
| 159 | IgnoreWarnings("w", llvm::cl::init(false), |
| 160 | llvm::cl::desc("Disable all warnings")); |
| 161 | |
| 162 | static llvm::cl::opt<bool> |
| 163 | WarningsAsErrors("Werror", llvm::cl::init(false), |
Diego Novillo | 3cc8d7a | 2019-04-10 13:30:34 -0400 | [diff] [blame] | 164 | llvm::cl::desc("Turn warnings into errors")); |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 165 | |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 166 | static llvm::cl::opt<std::string> IROutputFile( |
| 167 | "emit-ir", |
| 168 | llvm::cl::desc( |
| 169 | "Emit LLVM IR to the given file after parsing and stop compilation."), |
| 170 | llvm::cl::value_desc("filename")); |
| 171 | |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 172 | namespace { |
| 173 | struct OpenCLBuiltinMemoryBuffer final : public llvm::MemoryBuffer { |
| 174 | OpenCLBuiltinMemoryBuffer(const void *data, uint64_t data_length) { |
| 175 | const char *dataCasted = reinterpret_cast<const char *>(data); |
| 176 | init(dataCasted, dataCasted + data_length, true); |
| 177 | } |
| 178 | |
| 179 | virtual llvm::MemoryBuffer::BufferKind getBufferKind() const override { |
| 180 | return llvm::MemoryBuffer::MemoryBuffer_Malloc; |
| 181 | } |
| 182 | |
| 183 | virtual ~OpenCLBuiltinMemoryBuffer() override {} |
| 184 | }; |
| 185 | } // namespace |
| 186 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 187 | // Populates |SamplerMapEntries| with data from the input sampler map. Returns 0 |
| 188 | // if successful. |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 189 | int ParseSamplerMap(const std::string &sampler_map, |
| 190 | llvm::SmallVectorImpl<std::pair<unsigned, std::string>> |
| 191 | *SamplerMapEntries) { |
| 192 | std::unique_ptr<llvm::MemoryBuffer> samplerMapBuffer(nullptr); |
| 193 | if (!sampler_map.empty()) { |
| 194 | // Parse the sampler map from the provided string. |
| 195 | samplerMapBuffer = llvm::MemoryBuffer::getMemBuffer(sampler_map); |
| 196 | |
alan-baker | 09cb980 | 2019-12-10 13:16:27 -0500 | [diff] [blame] | 197 | clspv::Option::SetUseSamplerMap(true); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 198 | if (!SamplerMap.empty()) { |
| 199 | llvm::outs() << "Warning: -samplermap is ignored when the sampler map is " |
| 200 | "provided through a string.\n"; |
| 201 | } |
| 202 | } else if (!SamplerMap.empty()) { |
| 203 | // Parse the sampler map from the option provided file. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 204 | auto errorOrSamplerMapFile = |
| 205 | llvm::MemoryBuffer::getFile(SamplerMap.getValue()); |
| 206 | |
| 207 | // If there was an error in getting the sampler map file. |
| 208 | if (!errorOrSamplerMapFile) { |
| 209 | llvm::errs() << "Error: " << errorOrSamplerMapFile.getError().message() |
| 210 | << " '" << SamplerMap.getValue() << "'\n"; |
| 211 | return -1; |
| 212 | } |
| 213 | |
alan-baker | 09cb980 | 2019-12-10 13:16:27 -0500 | [diff] [blame] | 214 | clspv::Option::SetUseSamplerMap(true); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 215 | samplerMapBuffer = std::move(errorOrSamplerMapFile.get()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 216 | if (0 == samplerMapBuffer->getBufferSize()) { |
| 217 | llvm::errs() << "Error: Sampler map was an empty file!\n"; |
| 218 | return -1; |
| 219 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 220 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 221 | |
alan-baker | 09cb980 | 2019-12-10 13:16:27 -0500 | [diff] [blame] | 222 | if (clspv::Option::UseSamplerMap()) { |
| 223 | llvm::outs() |
| 224 | << "Warning: use of the sampler map is deprecated and unnecessary\n"; |
| 225 | } |
| 226 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 227 | // No sampler map to parse. |
| 228 | if (!samplerMapBuffer || 0 == samplerMapBuffer->getBufferSize()) |
| 229 | return 0; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 230 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 231 | llvm::SmallVector<llvm::StringRef, 3> samplerStrings; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 232 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 233 | // We need to keep track of the beginning of the current entry. |
| 234 | const char *b = samplerMapBuffer->getBufferStart(); |
| 235 | for (const char *i = b, *e = samplerMapBuffer->getBufferEnd();; i++) { |
| 236 | // If we have a separator between declarations. |
| 237 | if ((*i == '|') || (*i == ',') || (i == e)) { |
| 238 | if (i == b) { |
| 239 | llvm::errs() << "Error: Sampler map contained an empty entry!\n"; |
| 240 | return -1; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 241 | } |
| 242 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 243 | samplerStrings.push_back(llvm::StringRef(b, i - b).trim()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 244 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 245 | // And set b the next character after i. |
| 246 | b = i + 1; |
| 247 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 248 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 249 | // If we have a separator between declarations within a single sampler. |
| 250 | if ((*i == ',') || (i == e)) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 251 | |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 252 | clspv::SamplerNormalizedCoords NormalizedCoord = |
| 253 | clspv::CLK_NORMALIZED_COORDS_NOT_SET; |
| 254 | clspv::SamplerAddressingMode AddressingMode = clspv::CLK_ADDRESS_NOT_SET; |
| 255 | clspv::SamplerFilterMode FilterMode = clspv::CLK_FILTER_NOT_SET; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 256 | |
| 257 | for (auto str : samplerStrings) { |
| 258 | if ("CLK_NORMALIZED_COORDS_FALSE" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 259 | if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 260 | llvm::errs() << "Error: Sampler map normalized coordinates was " |
| 261 | "previously set!\n"; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 262 | return -1; |
| 263 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 264 | NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_FALSE; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 265 | } else if ("CLK_NORMALIZED_COORDS_TRUE" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 266 | if (clspv::CLK_NORMALIZED_COORDS_NOT_SET != NormalizedCoord) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 267 | llvm::errs() << "Error: Sampler map normalized coordinates was " |
| 268 | "previously set!\n"; |
| 269 | return -1; |
| 270 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 271 | NormalizedCoord = clspv::CLK_NORMALIZED_COORDS_TRUE; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 272 | } else if ("CLK_ADDRESS_NONE" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 273 | if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 274 | llvm::errs() |
| 275 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 276 | return -1; |
| 277 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 278 | AddressingMode = clspv::CLK_ADDRESS_NONE; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 279 | } else if ("CLK_ADDRESS_CLAMP_TO_EDGE" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 280 | if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 281 | llvm::errs() |
| 282 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 283 | return -1; |
| 284 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 285 | AddressingMode = clspv::CLK_ADDRESS_CLAMP_TO_EDGE; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 286 | } else if ("CLK_ADDRESS_CLAMP" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 287 | if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 288 | llvm::errs() |
| 289 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 290 | return -1; |
| 291 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 292 | AddressingMode = clspv::CLK_ADDRESS_CLAMP; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 293 | } else if ("CLK_ADDRESS_MIRRORED_REPEAT" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 294 | if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 295 | llvm::errs() |
| 296 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 297 | return -1; |
| 298 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 299 | AddressingMode = clspv::CLK_ADDRESS_MIRRORED_REPEAT; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 300 | } else if ("CLK_ADDRESS_REPEAT" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 301 | if (clspv::CLK_ADDRESS_NOT_SET != AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 302 | llvm::errs() |
| 303 | << "Error: Sampler map addressing mode was previously set!\n"; |
| 304 | return -1; |
| 305 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 306 | AddressingMode = clspv::CLK_ADDRESS_REPEAT; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 307 | } else if ("CLK_FILTER_NEAREST" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 308 | if (clspv::CLK_FILTER_NOT_SET != FilterMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 309 | llvm::errs() |
| 310 | << "Error: Sampler map filtering mode was previously set!\n"; |
| 311 | return -1; |
| 312 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 313 | FilterMode = clspv::CLK_FILTER_NEAREST; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 314 | } else if ("CLK_FILTER_LINEAR" == str) { |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 315 | if (clspv::CLK_FILTER_NOT_SET != FilterMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 316 | llvm::errs() |
| 317 | << "Error: Sampler map filtering mode was previously set!\n"; |
| 318 | return -1; |
| 319 | } |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 320 | FilterMode = clspv::CLK_FILTER_LINEAR; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 321 | } else { |
| 322 | llvm::errs() << "Error: Unknown sampler string '" << str |
| 323 | << "' found!\n"; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 324 | return -1; |
| 325 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 326 | } |
| 327 | |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 328 | if (clspv::CLK_NORMALIZED_COORDS_NOT_SET == NormalizedCoord) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 329 | llvm::errs() << "Error: Sampler map entry did not contain normalized " |
| 330 | "coordinates entry!\n"; |
| 331 | return -1; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 332 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 333 | |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 334 | if (clspv::CLK_ADDRESS_NOT_SET == AddressingMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 335 | llvm::errs() << "Error: Sampler map entry did not contain addressing " |
| 336 | "mode entry!\n"; |
| 337 | return -1; |
| 338 | } |
| 339 | |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 340 | if (clspv::CLK_FILTER_NOT_SET == FilterMode) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 341 | llvm::errs() |
| 342 | << "Error: Sampler map entry did not contain filer mode entry!\n"; |
| 343 | return -1; |
| 344 | } |
| 345 | |
| 346 | // Generate an equivalent expression in string form. Sort the |
| 347 | // strings to get a canonical ordering. |
| 348 | std::sort(samplerStrings.begin(), samplerStrings.end(), |
| 349 | std::less<StringRef>()); |
| 350 | const auto samplerExpr = std::accumulate( |
| 351 | samplerStrings.begin(), samplerStrings.end(), std::string(), |
alan-baker | 21574d3 | 2020-01-29 16:00:31 -0500 | [diff] [blame] | 352 | [](llvm::StringRef left, llvm::StringRef right) { |
| 353 | return left.str() + std::string(left.empty() ? "" : "|") + |
| 354 | right.str(); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 355 | }); |
| 356 | |
| 357 | // SamplerMapEntries->push_back(std::make_pair( |
| 358 | // NormalizedCoord | AddressingMode | FilterMode, samplerExpr)); |
| 359 | SamplerMapEntries->emplace_back( |
| 360 | NormalizedCoord | AddressingMode | FilterMode, samplerExpr); |
| 361 | |
| 362 | // And reset the sampler strings for the next sampler in the map. |
| 363 | samplerStrings.clear(); |
| 364 | } |
| 365 | |
| 366 | // And lastly, if we are at the end of the file |
| 367 | if (i == e) { |
| 368 | break; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 369 | } |
| 370 | } |
| 371 | |
| 372 | return 0; |
| 373 | } |
| 374 | |
Kévin Petit | aab5bb8 | 2021-03-30 16:26:11 +0100 | [diff] [blame] | 375 | clang::TargetInfo *PrepareTargetInfo(CompilerInstance &instance) { |
| 376 | // Create target info |
| 377 | auto TargetInfo = clang::TargetInfo::CreateTargetInfo( |
| 378 | instance.getDiagnostics(), |
| 379 | std::make_shared<clang::TargetOptions>(instance.getTargetOpts())); |
| 380 | |
| 381 | // The SPIR target enables all possible options, disable the ones we don't |
| 382 | // want |
| 383 | auto &Opts = TargetInfo->getSupportedOpenCLOpts(); |
| 384 | |
| 385 | // Conditionally disable extensions based on support |
| 386 | if (!clspv::Option::FP16()) { |
| 387 | Opts["cl_khr_fp16"] = false; |
| 388 | } |
| 389 | if (!clspv::Option::FP64()) { |
| 390 | Opts["cl_khr_fp64"] = false; |
| 391 | } |
| 392 | |
| 393 | // Disable CL3.0 feature macros for unsupported features |
| 394 | if (instance.getLangOpts().LangStd == clang::LangStandard::lang_opencl30) { |
| 395 | |
Kévin Petit | aab5bb8 | 2021-03-30 16:26:11 +0100 | [diff] [blame] | 396 | // The following features are never supported |
| 397 | Opts["__opencl_c_pipes"] = false; |
| 398 | Opts["__opencl_c_generic_address_space"] = false; |
Kévin Petit | aab5bb8 | 2021-03-30 16:26:11 +0100 | [diff] [blame] | 399 | Opts["__opencl_c_device_enqueue"] = false; |
| 400 | Opts["__opencl_c_program_scope_global_variables"] = false; |
| 401 | |
| 402 | if (!clspv::Option::ImageSupport()) { |
| 403 | Opts["__opencl_c_images"] = false; |
| 404 | } |
| 405 | |
| 406 | if (!clspv::Option::FP64()) { |
| 407 | Opts["__opencl_c_fp64"] = false; |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | return TargetInfo; |
| 412 | } |
| 413 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 414 | // Sets |instance|'s options for compiling. Returns 0 if successful. |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 415 | int SetCompilerInstanceOptions( |
| 416 | CompilerInstance &instance, const llvm::StringRef &overiddenInputFilename, |
| 417 | clang::FrontendInputFile &kernelFile, const std::string &program, |
| 418 | std::unique_ptr<llvm::MemoryBuffer> &file_memory_buffer, |
| 419 | llvm::raw_string_ostream *diagnosticsStream) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 420 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> errorOrInputFile(nullptr); |
| 421 | if (program.empty()) { |
| 422 | auto errorOrInputFile = |
| 423 | llvm::MemoryBuffer::getFileOrSTDIN(InputFilename.getValue()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 424 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 425 | // If there was an error in getting the input file. |
| 426 | if (!errorOrInputFile) { |
| 427 | llvm::errs() << "Error: " << errorOrInputFile.getError().message() << " '" |
| 428 | << InputFilename.getValue() << "'\n"; |
| 429 | return -1; |
| 430 | } |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 431 | file_memory_buffer = std::move(errorOrInputFile.get()); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 432 | } else { |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 433 | file_memory_buffer = |
| 434 | llvm::MemoryBuffer::getMemBuffer(program, overiddenInputFilename); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 435 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 436 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 437 | if (verify) { |
| 438 | instance.getDiagnosticOpts().VerifyDiagnostics = true; |
alan-baker | bccf62c | 2019-03-29 10:32:41 -0400 | [diff] [blame] | 439 | instance.getDiagnosticOpts().VerifyPrefixes.push_back("expected"); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 440 | } |
| 441 | |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 442 | clang::LangStandard::Kind standard; |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 443 | switch (clspv::Option::Language()) { |
| 444 | case clspv::Option::SourceLanguage::OpenCL_C_10: |
| 445 | standard = clang::LangStandard::lang_opencl10; |
| 446 | break; |
| 447 | case clspv::Option::SourceLanguage::OpenCL_C_11: |
| 448 | standard = clang::LangStandard::lang_opencl11; |
| 449 | break; |
| 450 | case clspv::Option::SourceLanguage::OpenCL_C_12: |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 451 | standard = clang::LangStandard::lang_opencl12; |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 452 | break; |
| 453 | case clspv::Option::SourceLanguage::OpenCL_C_20: |
| 454 | standard = clang::LangStandard::lang_opencl20; |
| 455 | break; |
Kévin Petit | 77838ff | 2020-10-19 18:54:51 +0100 | [diff] [blame] | 456 | case clspv::Option::SourceLanguage::OpenCL_C_30: |
| 457 | standard = clang::LangStandard::lang_opencl30; |
| 458 | break; |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 459 | case clspv::Option::SourceLanguage::OpenCL_CPP: |
alan-baker | 3970681 | 2021-08-03 13:21:39 -0400 | [diff] [blame] | 460 | standard = clang::LangStandard::lang_openclcpp10; |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 461 | break; |
| 462 | default: |
| 463 | llvm_unreachable("Unknown source language"); |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 464 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 465 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 466 | instance.getLangOpts().C99 = true; |
| 467 | instance.getLangOpts().RTTI = false; |
| 468 | instance.getLangOpts().RTTIData = false; |
| 469 | instance.getLangOpts().MathErrno = false; |
| 470 | instance.getLangOpts().Optimize = false; |
| 471 | instance.getLangOpts().NoBuiltin = true; |
| 472 | instance.getLangOpts().ModulesSearchAll = false; |
| 473 | instance.getLangOpts().SinglePrecisionConstants = true; |
| 474 | instance.getCodeGenOpts().StackRealignment = true; |
| 475 | instance.getCodeGenOpts().SimplifyLibCalls = false; |
| 476 | instance.getCodeGenOpts().EmitOpenCLArgMetadata = false; |
| 477 | instance.getCodeGenOpts().DisableO0ImplyOptNone = true; |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 478 | instance.getDiagnosticOpts().IgnoreWarnings = IgnoreWarnings; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 479 | |
| 480 | instance.getLangOpts().SinglePrecisionConstants = |
| 481 | cl_single_precision_constants; |
| 482 | // cl_denorms_are_zero ignored for now! |
| 483 | // cl_fp32_correctly_rounded_divide_sqrt ignored for now! |
| 484 | instance.getCodeGenOpts().LessPreciseFPMAD = |
| 485 | cl_mad_enable || cl_unsafe_math_optimizations; |
| 486 | // cl_no_signed_zeros ignored for now! |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 487 | instance.getLangOpts().UnsafeFPMath = cl_unsafe_math_optimizations || |
| 488 | cl_fast_relaxed_math || |
| 489 | clspv::Option::NativeMath(); |
| 490 | instance.getLangOpts().FiniteMathOnly = cl_finite_math_only || |
| 491 | cl_fast_relaxed_math || |
| 492 | clspv::Option::NativeMath(); |
| 493 | instance.getLangOpts().FastRelaxedMath = |
| 494 | cl_fast_relaxed_math || clspv::Option::NativeMath(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 495 | |
| 496 | // Preprocessor options |
Kévin Petit | a624c0c | 2019-05-07 20:27:43 +0800 | [diff] [blame] | 497 | if (!clspv::Option::ImageSupport()) { |
| 498 | instance.getPreprocessorOpts().addMacroUndef("__IMAGE_SUPPORT__"); |
| 499 | } |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 500 | if (cl_fast_relaxed_math || clspv::Option::NativeMath()) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 501 | instance.getPreprocessorOpts().addMacroDef("__FAST_RELAXED_MATH__"); |
| 502 | } |
| 503 | |
| 504 | for (auto define : Defines) { |
| 505 | instance.getPreprocessorOpts().addMacroDef(define); |
| 506 | } |
| 507 | |
| 508 | // Header search options |
| 509 | for (auto include : Includes) { |
| 510 | instance.getHeaderSearchOpts().AddPath(include, clang::frontend::After, |
| 511 | false, false); |
| 512 | } |
| 513 | |
| 514 | // We always compile on opt 0 so we preserve as much debug information about |
| 515 | // the source as possible. We'll run optimization later, once we've had a |
| 516 | // chance to view the unoptimal code first |
| 517 | instance.getCodeGenOpts().OptimizationLevel = 0; |
| 518 | |
| 519 | // Debug information is disabled temporarily to call instruction. |
| 520 | #if 0 |
| 521 | instance.getCodeGenOpts().setDebugInfo(clang::codegenoptions::FullDebugInfo); |
| 522 | #endif |
| 523 | |
| 524 | // We use the 32-bit pointer-width SPIR triple |
| 525 | llvm::Triple triple("spir-unknown-unknown"); |
| 526 | |
James Price | 40efe7f | 2021-01-18 09:19:31 -0500 | [diff] [blame] | 527 | // We manually include the OpenCL headers below, so this vector is unused. |
| 528 | std::vector<std::string> includes; |
| 529 | |
alan-baker | 1e20bf2 | 2022-04-13 16:05:14 -0400 | [diff] [blame^] | 530 | LangOptions::setLangDefaults(instance.getLangOpts(), clang::Language::OpenCL, |
| 531 | triple, includes, standard); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 532 | |
| 533 | // Override the C99 inline semantics to accommodate for more OpenCL C |
| 534 | // programs in the wild. |
| 535 | instance.getLangOpts().GNUInline = true; |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 536 | |
| 537 | // Set up diagnostics |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 538 | instance.createDiagnostics( |
| 539 | new clang::TextDiagnosticPrinter(*diagnosticsStream, |
| 540 | &instance.getDiagnosticOpts()), |
| 541 | true); |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 542 | instance.getDiagnostics().setWarningsAsErrors(WarningsAsErrors); |
| 543 | instance.getDiagnostics().setEnableAllWarnings(true); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 544 | |
| 545 | instance.getTargetOpts().Triple = triple.str(); |
| 546 | |
alan-baker | 21574d3 | 2020-01-29 16:00:31 -0500 | [diff] [blame] | 547 | instance.getCodeGenOpts().MainFileName = overiddenInputFilename.str(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 548 | instance.getCodeGenOpts().PreserveVec3Type = true; |
| 549 | // Disable generation of lifetime intrinsic. |
| 550 | instance.getCodeGenOpts().DisableLifetimeMarkers = true; |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 551 | if (InputLanguage == clang::Language::OpenCL) { |
| 552 | instance.getPreprocessorOpts().addRemappedFile( |
| 553 | overiddenInputFilename, file_memory_buffer.release()); |
| 554 | } else if (!program.empty()) { |
| 555 | // Can't use preprocessor to do file remapping for LLVM_IR |
| 556 | kernelFile = clang::FrontendInputFile(*file_memory_buffer, |
| 557 | clang::InputKind(InputLanguage)); |
| 558 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 559 | instance.getFrontendOpts().Inputs.push_back(kernelFile); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 560 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 561 | std::unique_ptr<llvm::MemoryBuffer> openCLBuiltinMemoryBuffer( |
| 562 | new OpenCLBuiltinMemoryBuffer(opencl_builtins_header_data, |
| 563 | opencl_builtins_header_size - 1)); |
| 564 | |
James Price | 40efe7f | 2021-01-18 09:19:31 -0500 | [diff] [blame] | 565 | instance.getPreprocessorOpts().Includes.push_back("opencl-c.h"); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 566 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 567 | std::unique_ptr<llvm::MemoryBuffer> openCLBaseBuiltinMemoryBuffer( |
| 568 | new OpenCLBuiltinMemoryBuffer(opencl_base_builtins_header_data, |
| 569 | opencl_base_builtins_header_size - 1)); |
| 570 | |
| 571 | instance.getPreprocessorOpts().Includes.push_back("opencl-c-base.h"); |
| 572 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 573 | // Add the VULKAN macro. |
| 574 | instance.getPreprocessorOpts().addMacroDef("VULKAN=100"); |
| 575 | |
| 576 | // Add the __OPENCL_VERSION__ macro. |
| 577 | instance.getPreprocessorOpts().addMacroDef("__OPENCL_VERSION__=120"); |
| 578 | |
Kévin Petit | aab5bb8 | 2021-03-30 16:26:11 +0100 | [diff] [blame] | 579 | instance.setTarget(PrepareTargetInfo(instance)); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 580 | |
| 581 | instance.createFileManager(); |
| 582 | instance.createSourceManager(instance.getFileManager()); |
| 583 | |
| 584 | #ifdef _MSC_VER |
| 585 | std::string includePrefix("include\\"); |
| 586 | #else |
| 587 | std::string includePrefix("include/"); |
| 588 | #endif |
| 589 | |
| 590 | auto entry = instance.getFileManager().getVirtualFile( |
James Price | 40efe7f | 2021-01-18 09:19:31 -0500 | [diff] [blame] | 591 | includePrefix + "opencl-c.h", openCLBuiltinMemoryBuffer->getBufferSize(), |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 592 | 0); |
| 593 | |
| 594 | instance.getSourceManager().overrideFileContents( |
| 595 | entry, std::move(openCLBuiltinMemoryBuffer)); |
| 596 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 597 | auto base_entry = instance.getFileManager().getVirtualFile( |
| 598 | includePrefix + "opencl-c-base.h", |
| 599 | openCLBaseBuiltinMemoryBuffer->getBufferSize(), 0); |
| 600 | |
| 601 | instance.getSourceManager().overrideFileContents( |
| 602 | base_entry, std::move(openCLBaseBuiltinMemoryBuffer)); |
| 603 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 604 | return 0; |
| 605 | } |
| 606 | |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 607 | // Populates |pm| with necessary passes to optimize and legalize the IR. |
| 608 | int PopulatePassManager( |
| 609 | llvm::legacy::PassManager *pm, llvm::raw_svector_ostream *binaryStream, |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 610 | llvm::SmallVectorImpl<std::pair<unsigned, std::string>> |
| 611 | *SamplerMapEntries) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 612 | llvm::PassManagerBuilder pmBuilder; |
| 613 | |
| 614 | switch (OptimizationLevel) { |
| 615 | case '0': |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 616 | case '1': |
| 617 | case '2': |
| 618 | case '3': |
| 619 | case 's': |
| 620 | case 'z': |
| 621 | break; |
| 622 | default: |
| 623 | llvm::errs() << "Unknown optimization level -O" << OptimizationLevel |
| 624 | << " specified!\n"; |
| 625 | return -1; |
| 626 | } |
| 627 | |
| 628 | switch (OptimizationLevel) { |
| 629 | case '0': |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 630 | pmBuilder.OptLevel = 0; |
| 631 | break; |
| 632 | case '1': |
| 633 | pmBuilder.OptLevel = 1; |
| 634 | break; |
| 635 | case '2': |
| 636 | pmBuilder.OptLevel = 2; |
| 637 | break; |
| 638 | case '3': |
| 639 | pmBuilder.OptLevel = 3; |
| 640 | break; |
| 641 | case 's': |
| 642 | pmBuilder.SizeLevel = 1; |
| 643 | break; |
| 644 | case 'z': |
| 645 | pmBuilder.SizeLevel = 2; |
| 646 | break; |
| 647 | default: |
| 648 | break; |
| 649 | } |
| 650 | |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 651 | pm->add(clspv::createNativeMathPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 652 | pm->add(clspv::createZeroInitializeAllocasPass()); |
alan-baker | 04f3a95 | 2020-03-24 10:39:53 -0400 | [diff] [blame] | 653 | pm->add(clspv::createAddFunctionAttributesPass()); |
alan-baker | c4579bb | 2020-04-29 14:15:50 -0400 | [diff] [blame] | 654 | pm->add(clspv::createAutoPodArgsPass()); |
Kévin Petit | bbbda97 | 2020-03-03 19:16:31 +0000 | [diff] [blame] | 655 | pm->add(clspv::createDeclarePushConstantsPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 656 | pm->add(clspv::createDefineOpenCLWorkItemBuiltinsPass()); |
| 657 | |
| 658 | if (0 < pmBuilder.OptLevel) { |
| 659 | pm->add(clspv::createOpenCLInlinerPass()); |
| 660 | } |
| 661 | |
| 662 | pm->add(clspv::createUndoByvalPass()); |
| 663 | pm->add(clspv::createUndoSRetPass()); |
alan-baker | 9b0ec3c | 2020-04-06 14:45:34 -0400 | [diff] [blame] | 664 | if (clspv::Option::ClusterPodKernelArgs()) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 665 | pm->add(clspv::createClusterPodKernelArgumentsPass()); |
| 666 | } |
| 667 | pm->add(clspv::createReplaceOpenCLBuiltinPass()); |
| 668 | |
Romaric Jodin | 322e9ba | 2021-12-08 16:00:06 +0100 | [diff] [blame] | 669 | pm->add(clspv::createThreeElementVectorLoweringPass()); |
| 670 | |
Marco Antognini | 535998c | 2020-09-16 18:48:51 +0100 | [diff] [blame] | 671 | // Lower longer vectors when requested. Note that this pass depends on |
| 672 | // ReplaceOpenCLBuiltinPass and expects DeadCodeEliminationPass to be run |
| 673 | // afterwards. |
| 674 | if (clspv::Option::LongVectorSupport()) { |
| 675 | pm->add(clspv::createLongVectorLoweringPass()); |
| 676 | } |
| 677 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 678 | // We need to run mem2reg and inst combine early because our |
| 679 | // createInlineFuncWithPointerBitCastArgPass pass cannot handle the pattern |
| 680 | // %1 = alloca i32 1 |
| 681 | // store <something> %1 |
| 682 | // %2 = bitcast float* %1 |
| 683 | // %3 = load float %2 |
| 684 | pm->add(llvm::createPromoteMemoryToRegisterPass()); |
| 685 | |
alan-baker | 1b13e8f | 2019-08-08 17:56:51 -0400 | [diff] [blame] | 686 | // Try to deal with pointer bitcasts early. This can prevent problems like |
| 687 | // issue #409 where LLVM is looser about access chain addressing than SPIR-V. |
| 688 | // This needs to happen before instcombine and after replacing OpenCL |
| 689 | // builtins. This run of the pass will not handle all pointer bitcasts that |
| 690 | // could be handled. It should be run again after other optimizations (e.g |
| 691 | // InlineFuncWithPointerBitCastArgPass). |
| 692 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 693 | pm->add(clspv::createReplacePointerBitcastPass()); |
| 694 | pm->add(llvm::createDeadCodeEliminationPass()); |
| 695 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 696 | // Hide loads from __constant address space away from instcombine. |
| 697 | // This prevents us from generating select between pointers-to-__constant. |
| 698 | // See https://github.com/google/clspv/issues/71 |
| 699 | pm->add(clspv::createHideConstantLoadsPass()); |
| 700 | |
| 701 | pm->add(llvm::createInstructionCombiningPass()); |
| 702 | |
| 703 | if (clspv::Option::InlineEntryPoints()) { |
| 704 | pm->add(clspv::createInlineEntryPointsPass()); |
| 705 | } else { |
| 706 | pm->add(clspv::createInlineFuncWithPointerBitCastArgPass()); |
| 707 | pm->add(clspv::createInlineFuncWithPointerToFunctionArgPass()); |
| 708 | pm->add(clspv::createInlineFuncWithSingleCallSitePass()); |
| 709 | } |
| 710 | |
Shangwu Yao | 4197100 | 2022-04-04 23:01:50 -0400 | [diff] [blame] | 711 | // Mem2Reg pass should be run early because O0 level optimization leaves |
| 712 | // redundant alloca, load and store instructions from function arguments. |
| 713 | // clspv needs to remove them ahead of transformation. |
| 714 | pm->add(llvm::createPromoteMemoryToRegisterPass()); |
| 715 | |
| 716 | // SROA pass is run because it will fold structs/unions that are problematic |
| 717 | // on Vulkan SPIR-V away. |
| 718 | pm->add(llvm::createSROAPass()); |
| 719 | |
| 720 | // InstructionCombining pass folds bitcast and gep instructions which are |
| 721 | // not supported by Vulkan SPIR-V. |
| 722 | pm->add(llvm::createInstructionCombiningPass()); |
| 723 | |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 724 | if (clspv::Option::LanguageUsesGenericAddressSpace()) { |
Kévin Petit | 38c5248 | 2019-05-07 20:28:00 +0800 | [diff] [blame] | 725 | pm->add(llvm::createInferAddressSpacesPass(clspv::AddressSpace::Generic)); |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 726 | } |
| 727 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 728 | // Now we add any of the LLVM optimizations we wanted |
| 729 | pmBuilder.populateModulePassManager(*pm); |
| 730 | |
alan-baker | b5e74d6 | 2020-04-07 20:38:05 -0400 | [diff] [blame] | 731 | // No point attempting to handle freeze currently so strip them from the IR. |
| 732 | pm->add(clspv::createStripFreezePass()); |
| 733 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 734 | // Unhide loads from __constant address space. Undoes the action of |
| 735 | // HideConstantLoadsPass. |
| 736 | pm->add(clspv::createUnhideConstantLoadsPass()); |
| 737 | |
alan-baker | 1356838 | 2020-04-02 17:29:27 -0400 | [diff] [blame] | 738 | pm->add(clspv::createUndoInstCombinePass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 739 | pm->add(clspv::createFunctionInternalizerPass()); |
| 740 | pm->add(clspv::createReplaceLLVMIntrinsicsPass()); |
alan-baker | ad1a12f | 2020-08-25 09:18:38 -0400 | [diff] [blame] | 741 | // Replace LLVM intrinsics can leave dead code around. |
| 742 | pm->add(llvm::createDeadCodeEliminationPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 743 | pm->add(clspv::createUndoBoolPass()); |
alan-baker | e711c76 | 2020-05-20 17:56:59 -0400 | [diff] [blame] | 744 | pm->add(clspv::createUndoTruncateToOddIntegerPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 745 | pm->add(llvm::createStructurizeCFGPass(false)); |
alan-baker | 3fa76d9 | 2018-11-12 14:54:40 -0500 | [diff] [blame] | 746 | // Must be run after structurize cfg. |
alan-baker | 9580aef | 2020-01-07 22:31:48 -0500 | [diff] [blame] | 747 | pm->add(clspv::createFixupStructuredCFGPass()); |
| 748 | // Must be run after structured cfg fixup. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 749 | pm->add(clspv::createReorderBasicBlocksPass()); |
| 750 | pm->add(clspv::createUndoGetElementPtrConstantExprPass()); |
| 751 | pm->add(clspv::createSplatArgPass()); |
| 752 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 753 | pm->add(clspv::createReplacePointerBitcastPass()); |
David Neto | c04f8d3 | 2021-09-29 13:02:25 -0400 | [diff] [blame] | 754 | pm->add(llvm::createDeadCodeEliminationPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 755 | |
| 756 | pm->add(clspv::createUndoTranslateSamplerFoldPass()); |
| 757 | |
| 758 | if (clspv::Option::ModuleConstantsInStorageBuffer()) { |
| 759 | pm->add(clspv::createClusterModuleScopeConstantVars()); |
| 760 | } |
| 761 | |
| 762 | pm->add(clspv::createShareModuleScopeVariablesPass()); |
alan-baker | f67468c | 2019-11-25 15:51:49 -0500 | [diff] [blame] | 763 | // Specialize images before assigning descriptors to disambiguate the various |
| 764 | // types. |
| 765 | pm->add(clspv::createSpecializeImageTypesPass()); |
alan-baker | e930801 | 2019-03-15 10:25:13 -0400 | [diff] [blame] | 766 | // This should be run after LLVM and OpenCL intrinsics are replaced. |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 767 | pm->add(clspv::createAllocateDescriptorsPass(*SamplerMapEntries)); |
| 768 | pm->add(llvm::createVerifierPass()); |
| 769 | pm->add(clspv::createDirectResourceAccessPass()); |
| 770 | // Replacing pointer bitcasts can leave some trivial GEPs |
| 771 | // that are easy to remove. Also replace GEPs of GEPS |
| 772 | // left by replacing indirect buffer accesses. |
| 773 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
alan-baker | 4217b32 | 2019-03-06 08:56:12 -0500 | [diff] [blame] | 774 | // Run after DRA to clean up parameters and help reduce the need for variable |
| 775 | // pointers. |
| 776 | pm->add(clspv::createRemoveUnusedArgumentsPass()); |
David Neto | c04f8d3 | 2021-09-29 13:02:25 -0400 | [diff] [blame] | 777 | pm->add(llvm::createDeadCodeEliminationPass()); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 778 | |
alan-baker | 3f772c0 | 2021-06-15 22:18:11 -0400 | [diff] [blame] | 779 | // SPIR-V 1.4 and higher do not need to splat scalar conditions for vector |
| 780 | // data. |
| 781 | if (clspv::Option::SpvVersion() < clspv::Option::SPIRVVersion::SPIRV_1_4) { |
| 782 | pm->add(clspv::createSplatSelectConditionPass()); |
| 783 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 784 | pm->add(clspv::createSignedCompareFixupPass()); |
| 785 | // This pass generates insertions that need to be rewritten. |
| 786 | pm->add(clspv::createScalarizePass()); |
| 787 | pm->add(clspv::createRewriteInsertsPass()); |
alan-baker | a71f193 | 2019-04-11 11:04:34 -0400 | [diff] [blame] | 788 | // UBO Transformations |
| 789 | if (clspv::Option::ConstantArgsInUniformBuffer() && |
| 790 | !clspv::Option::InlineEntryPoints()) { |
| 791 | // MultiVersionUBOFunctionsPass will examine non-kernel functions with UBO |
| 792 | // arguments and either multi-version them as necessary or inline them if |
| 793 | // multi-versioning cannot be accomplished. |
| 794 | pm->add(clspv::createMultiVersionUBOFunctionsPass()); |
| 795 | // Cleanup passes. |
| 796 | // Specialization can blindly generate GEP chains that are easily cleaned up |
| 797 | // by SimplifyPointerBitcastPass. |
| 798 | pm->add(clspv::createSimplifyPointerBitcastPass()); |
| 799 | // RemoveUnusedArgumentsPass removes the actual UBO arguments that were |
| 800 | // problematic to begin with now that they have no uses. |
| 801 | pm->add(clspv::createRemoveUnusedArgumentsPass()); |
| 802 | // DCE cleans up callers of the specialized functions. |
| 803 | pm->add(llvm::createDeadCodeEliminationPass()); |
| 804 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 805 | // This pass mucks with types to point where you shouldn't rely on DataLayout |
| 806 | // anymore so leave this right before SPIR-V generation. |
| 807 | pm->add(clspv::createUBOTypeTransformPass()); |
alan-baker | 3f772c0 | 2021-06-15 22:18:11 -0400 | [diff] [blame] | 808 | pm->add(clspv::createSPIRVProducerPass(binaryStream, SamplerMapEntries, |
alan-baker | 00e7a58 | 2019-06-07 12:54:21 -0400 | [diff] [blame] | 809 | OutputFormat == "c")); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 810 | |
| 811 | return 0; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 812 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 813 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 814 | int ParseOptions(const int argc, const char *const argv[]) { |
alan-baker | 227e978 | 2020-06-02 15:35:37 -0400 | [diff] [blame] | 815 | // We need to change how some of the called passes works by spoofing |
| 816 | // ParseCommandLineOptions with the specific options. |
| 817 | bool has_pre = false; |
| 818 | bool has_load_pre = false; |
| 819 | const std::string pre = "-enable-pre"; |
| 820 | const std::string load_pre = "-enable-load-pre"; |
| 821 | for (int i = 1; i < argc; ++i) { |
| 822 | std::string option(argv[i]); |
| 823 | auto pre_pos = option.find(pre); |
| 824 | auto load_pos = option.find(load_pre); |
| 825 | if (pre_pos == 0 || (pre_pos == 1 && option[0] == '-')) { |
| 826 | has_pre = true; |
| 827 | } else if (load_pos == 0 || (load_pos == 1 && option[0] == '-')) { |
| 828 | has_load_pre = true; |
| 829 | } |
| 830 | } |
| 831 | |
alan-baker | 1b333b6 | 2021-05-31 14:55:32 -0400 | [diff] [blame] | 832 | int llvmArgc = 3; |
| 833 | const char *llvmArgv[5]; |
alan-baker | 227e978 | 2020-06-02 15:35:37 -0400 | [diff] [blame] | 834 | llvmArgv[0] = argv[0]; |
| 835 | llvmArgv[1] = "-simplifycfg-sink-common=false"; |
alan-baker | 1b333b6 | 2021-05-31 14:55:32 -0400 | [diff] [blame] | 836 | // TODO(#738): find a better solution to this. |
| 837 | llvmArgv[2] = "-disable-vector-combine"; |
alan-baker | 227e978 | 2020-06-02 15:35:37 -0400 | [diff] [blame] | 838 | if (!has_pre) { |
| 839 | llvmArgv[llvmArgc++] = "-enable-pre=0"; |
| 840 | } |
| 841 | if (!has_load_pre) { |
| 842 | llvmArgv[llvmArgc++] = "-enable-load-pre=0"; |
| 843 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 844 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 845 | llvm::cl::ResetAllOptionOccurrences(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 846 | llvm::cl::ParseCommandLineOptions(llvmArgc, llvmArgv); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 847 | llvm::cl::ParseCommandLineOptions(argc, argv); |
| 848 | |
Kévin Petit | f051571 | 2020-01-07 18:29:20 +0000 | [diff] [blame] | 849 | if (clspv::Option::LanguageUsesGenericAddressSpace() && |
| 850 | !clspv::Option::InlineEntryPoints()) { |
| 851 | llvm::errs() << "cannot compile languages that use the generic address " |
| 852 | "space (e.g. CLC++, CL2.0) without -inline-entry-points\n"; |
Kévin Petit | 0fc8804 | 2019-04-09 23:25:02 +0100 | [diff] [blame] | 853 | return -1; |
| 854 | } |
| 855 | |
Kévin Petit | bbbda97 | 2020-03-03 19:16:31 +0000 | [diff] [blame] | 856 | if (clspv::Option::ScalarBlockLayout()) { |
| 857 | llvm::errs() << "scalar block layout support unimplemented\n"; |
| 858 | return -1; |
| 859 | } |
| 860 | |
alan-baker | 9b0ec3c | 2020-04-06 14:45:34 -0400 | [diff] [blame] | 861 | // Push constant option validation. |
| 862 | if (clspv::Option::PodArgsInPushConstants()) { |
| 863 | if (clspv::Option::PodArgsInUniformBuffer()) { |
| 864 | llvm::errs() << "POD arguments can only be in either uniform buffers or " |
| 865 | "push constants\n"; |
| 866 | return -1; |
| 867 | } |
| 868 | |
| 869 | if (!clspv::Option::ClusterPodKernelArgs()) { |
| 870 | llvm::errs() |
| 871 | << "POD arguments must be clustered to be passed as push constants\n"; |
| 872 | return -1; |
| 873 | } |
| 874 | |
| 875 | // Conservatively error if a module scope push constant could be used. |
James Price | 708cf36 | 2020-05-06 19:33:45 -0400 | [diff] [blame] | 876 | if (clspv::Option::GlobalOffsetPushConstant() || |
alan-baker | 9b0ec3c | 2020-04-06 14:45:34 -0400 | [diff] [blame] | 877 | clspv::Option::Language() == |
| 878 | clspv::Option::SourceLanguage::OpenCL_C_20 || |
| 879 | clspv::Option::Language() == |
| 880 | clspv::Option::SourceLanguage::OpenCL_CPP) { |
| 881 | llvm::errs() << "POD arguments as push constants are not compatible with " |
| 882 | "module scope push constants\n"; |
| 883 | return -1; |
| 884 | } |
| 885 | } |
| 886 | |
Mehmet Oguz Derin | 047cc87 | 2021-04-15 19:56:41 +0300 | [diff] [blame] | 887 | if (clspv::Option::ArmNonUniformWorkGroupSize() && |
| 888 | clspv::Option::UniformWorkgroupSize()) { |
| 889 | llvm::errs() << "cannot enable Arm non-uniform workgroup extension support " |
| 890 | "and assume uniform workgroup sizes\n"; |
| 891 | return -1; |
| 892 | } |
| 893 | |
Romaric Jodin | e40f67d | 2022-01-18 16:45:08 +0100 | [diff] [blame] | 894 | if (clspv::Option::Vec3ToVec4() == |
| 895 | clspv::Option::Vec3ToVec4SupportClass::vec3ToVec4SupportError) { |
| 896 | llvm::errs() << "error: -vec3-to-vec4 and -no-vec3-to-vec4 are exclusive " |
| 897 | "so they cannot be used together!\n"; |
| 898 | return -1; |
| 899 | } |
| 900 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 901 | return 0; |
| 902 | } |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 903 | |
| 904 | int GenerateIRFile(llvm::legacy::PassManager *pm, llvm::Module &module, |
| 905 | std::string output) { |
| 906 | std::error_code ec; |
| 907 | std::unique_ptr<llvm::ToolOutputFile> out( |
Natalie Chouinard | 058da87 | 2021-06-17 12:32:47 -0400 | [diff] [blame] | 908 | new llvm::ToolOutputFile(output, ec, llvm::sys::fs::OF_None)); |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 909 | if (ec) { |
| 910 | llvm::errs() << output << ": " << ec.message() << '\n'; |
| 911 | return -1; |
| 912 | } |
| 913 | pm->add(llvm::createPrintModulePass(out->os(), "", false)); |
| 914 | pm->run(module); |
| 915 | out->keep(); |
| 916 | return 0; |
| 917 | } |
| 918 | |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 919 | bool LinkBuiltinLibrary(llvm::Module *module) { |
| 920 | std::unique_ptr<llvm::MemoryBuffer> buffer(new OpenCLBuiltinMemoryBuffer( |
| 921 | clspv_builtin_library_data, clspv_builtin_library_size - 1)); |
| 922 | |
| 923 | llvm::SMDiagnostic Err; |
| 924 | auto library = llvm::parseIR(*buffer, Err, module->getContext()); |
| 925 | if (!library) { |
| 926 | llvm::errs() << "Failed to parse builtins library\n"; |
| 927 | return false; |
| 928 | } |
| 929 | |
| 930 | // TODO: when clang generates builtins using the generic address space, |
| 931 | // different builtins are used for pointer-based builtins. Need to do some |
| 932 | // work to ensure they are kept around. |
| 933 | // Affects: modf, remquo, lgamma_r, frexp |
| 934 | |
| 935 | llvm::Linker L(*module); |
| 936 | L.linkInModule(std::move(library), 0); |
| 937 | |
| 938 | return true; |
| 939 | } |
| 940 | |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 941 | } // namespace |
| 942 | |
| 943 | namespace clspv { |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 944 | int Compile(const llvm::StringRef &input_filename, const std::string &program, |
| 945 | const std::string &sampler_map, |
| 946 | std::vector<uint32_t> *output_binary, std::string *output_log) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 947 | llvm::SmallVector<std::pair<unsigned, std::string>, 8> SamplerMapEntries; |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 948 | if (auto error = ParseSamplerMap(sampler_map, &SamplerMapEntries)) |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 949 | return error; |
| 950 | |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 951 | llvm::StringRef overiddenInputFilename = input_filename; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 952 | |
| 953 | clang::CompilerInstance instance; |
Kévin Petit | ddad8f4 | 2019-09-30 15:12:08 +0100 | [diff] [blame] | 954 | clang::FrontendInputFile kernelFile(overiddenInputFilename, |
| 955 | clang::InputKind(InputLanguage)); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 956 | std::string log; |
| 957 | llvm::raw_string_ostream diagnosticsStream(log); |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 958 | std::unique_ptr<llvm::MemoryBuffer> file_memory_buffer; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 959 | if (auto error = SetCompilerInstanceOptions( |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 960 | instance, overiddenInputFilename, kernelFile, program, |
| 961 | file_memory_buffer, &diagnosticsStream)) |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 962 | return error; |
| 963 | |
| 964 | // Parse. |
| 965 | llvm::LLVMContext context; |
| 966 | clang::EmitLLVMOnlyAction action(&context); |
| 967 | |
| 968 | // Prepare the action for processing kernelFile |
| 969 | const bool success = action.BeginSourceFile(instance, kernelFile); |
| 970 | if (!success) { |
| 971 | return -1; |
| 972 | } |
| 973 | |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 974 | auto result = action.Execute(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 975 | action.EndSourceFile(); |
| 976 | |
| 977 | clang::DiagnosticConsumer *const consumer = |
| 978 | instance.getDiagnostics().getClient(); |
| 979 | consumer->finish(); |
| 980 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 981 | auto num_warnings = consumer->getNumWarnings(); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 982 | auto num_errors = consumer->getNumErrors(); |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 983 | if (output_log != nullptr) { |
| 984 | *output_log = log; |
| 985 | } else if ((num_errors > 0) || (num_warnings > 0)) { |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 986 | llvm::errs() << log; |
| 987 | } |
alan-baker | f3bce4a | 2019-06-28 16:01:15 -0400 | [diff] [blame] | 988 | if (result || num_errors > 0) { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 989 | return -1; |
| 990 | } |
| 991 | |
Kévin Petit | 6b07cbe | 2019-04-02 21:52:16 +0100 | [diff] [blame] | 992 | // Don't run the passes or produce any output in verify mode. |
| 993 | // Clang doesn't always produce a valid module. |
| 994 | if (verify) { |
| 995 | return 0; |
| 996 | } |
| 997 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 998 | llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); |
| 999 | llvm::initializeCore(Registry); |
| 1000 | llvm::initializeScalarOpts(Registry); |
Diego Novillo | 1fcff72 | 2019-05-07 13:45:53 -0400 | [diff] [blame] | 1001 | llvm::initializeClspvPasses(Registry); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1002 | |
| 1003 | std::unique_ptr<llvm::Module> module(action.takeModule()); |
| 1004 | |
| 1005 | // Optimize. |
| 1006 | // Create a memory buffer for temporarily writing the result. |
| 1007 | SmallVector<char, 10000> binary; |
| 1008 | llvm::raw_svector_ostream binaryStream(binary); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1009 | llvm::legacy::PassManager pm; |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 1010 | |
| 1011 | // If --emit-ir was requested, emit the initial LLVM IR and stop compilation. |
| 1012 | if (!IROutputFile.empty()) { |
| 1013 | return GenerateIRFile(&pm, *module, IROutputFile); |
| 1014 | } |
| 1015 | |
alan-baker | 869cd68 | 2021-03-05 11:21:19 -0500 | [diff] [blame] | 1016 | if (!LinkBuiltinLibrary(module.get())) { |
| 1017 | return -1; |
| 1018 | } |
| 1019 | |
Diego Novillo | 8950085 | 2019-04-15 08:45:10 -0400 | [diff] [blame] | 1020 | // Otherwise, populate the pass manager and run the regular passes. |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 1021 | if (auto error = PopulatePassManager(&pm, &binaryStream, &SamplerMapEntries)) |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 1022 | return error; |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1023 | pm.run(*module); |
| 1024 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1025 | // Write the resulting binary. |
| 1026 | // Wait until now to try writing the file so that we only write it on |
| 1027 | // successful compilation. |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 1028 | if (output_binary) { |
| 1029 | output_binary->resize(binary.size() / 4); |
| 1030 | memcpy(output_binary->data(), binary.data(), binary.size()); |
| 1031 | } |
| 1032 | |
| 1033 | if (!OutputFilename.empty()) { |
| 1034 | std::error_code error; |
| 1035 | llvm::raw_fd_ostream outStream(OutputFilename, error, |
| 1036 | llvm::sys::fs::FA_Write); |
| 1037 | |
| 1038 | if (error) { |
| 1039 | llvm::errs() << "Unable to open output file '" << OutputFilename |
| 1040 | << "': " << error.message() << '\n'; |
| 1041 | return -1; |
| 1042 | } |
| 1043 | outStream << binaryStream.str(); |
| 1044 | } |
| 1045 | |
| 1046 | return 0; |
| 1047 | } |
| 1048 | |
| 1049 | int Compile(const int argc, const char *const argv[]) { |
| 1050 | if (auto error = ParseOptions(argc, argv)) |
| 1051 | return error; |
| 1052 | |
| 1053 | // if no input file was provided, use a default |
| 1054 | llvm::StringRef overiddenInputFilename = InputFilename.getValue(); |
| 1055 | |
| 1056 | // If we are reading our input file from stdin. |
| 1057 | if ("-" == InputFilename) { |
| 1058 | // We need to overwrite the file name we use. |
| 1059 | switch (InputLanguage) { |
| 1060 | case clang::Language::OpenCL: |
| 1061 | overiddenInputFilename = "stdin.cl"; |
| 1062 | break; |
| 1063 | case clang::Language::LLVM_IR: |
| 1064 | overiddenInputFilename = "stdin.ll"; |
| 1065 | break; |
| 1066 | default: |
| 1067 | // Default to fix compiler warnings/errors. Option parsing will reject a |
| 1068 | // bad enum value for the option so there is no need for a message. |
| 1069 | return -1; |
| 1070 | } |
| 1071 | } |
| 1072 | |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1073 | if (OutputFilename.empty()) { |
Kévin Petit | e478690 | 2019-04-02 21:51:47 +0100 | [diff] [blame] | 1074 | if (OutputFormat == "c") { |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1075 | OutputFilename = "a.spvinc"; |
| 1076 | } else { |
| 1077 | OutputFilename = "a.spv"; |
| 1078 | } |
| 1079 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1080 | |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 1081 | return Compile(overiddenInputFilename, "", "", nullptr, nullptr); |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1082 | } |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 1083 | |
alan-baker | 86ce19c | 2020-08-05 13:09:19 -0400 | [diff] [blame] | 1084 | int CompileFromSourceString(const std::string &program, |
| 1085 | const std::string &sampler_map, |
| 1086 | const std::string &options, |
Kévin Petit | 899162d | 2020-09-08 19:16:08 +0100 | [diff] [blame] | 1087 | std::vector<uint32_t> *output_binary, |
| 1088 | std::string *output_log) { |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 1089 | |
| 1090 | llvm::SmallVector<const char *, 20> argv; |
| 1091 | llvm::BumpPtrAllocator A; |
| 1092 | llvm::StringSaver Saver(A); |
| 1093 | argv.push_back(Saver.save("clspv").data()); |
| 1094 | llvm::cl::TokenizeGNUCommandLine(options, Saver, argv); |
| 1095 | int argc = static_cast<int>(argv.size()); |
Kévin Petit | d5db2d2 | 2019-04-04 13:55:14 +0100 | [diff] [blame] | 1096 | |
| 1097 | if (auto error = ParseOptions(argc, &argv[0])) |
| 1098 | return error; |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 1099 | |
Ryan Senanayake | 6917fb1 | 2022-02-28 18:17:02 -0500 | [diff] [blame] | 1100 | return Compile("source", program, sampler_map, output_binary, output_log); |
alan-baker | f5e5f69 | 2018-11-27 08:33:24 -0500 | [diff] [blame] | 1101 | } |
alan-baker | fec0a47 | 2018-11-08 18:09:40 -0500 | [diff] [blame] | 1102 | } // namespace clspv |