blob: 5e4ae33f946b2c4152a8b1c26a1ecf0f1c756238 [file] [log] [blame]
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001/// Copyright 2020 The Tint Authors.
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 "src/tint/writer/hlsl/generator_impl.h"
16
17#include <algorithm>
18#include <cmath>
19#include <functional>
20#include <iomanip>
21#include <set>
22#include <utility>
23#include <vector>
24
25#include "src/tint/ast/call_statement.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000026#include "src/tint/ast/id_attribute.h"
27#include "src/tint/ast/internal_attribute.h"
28#include "src/tint/ast/interpolate_attribute.h"
29#include "src/tint/ast/variable_decl_statement.h"
dan sinclairb53b8cf2022-12-15 16:25:31 +000030#include "src/tint/constant/value.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000031#include "src/tint/debug.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000032#include "src/tint/sem/block_statement.h"
33#include "src/tint/sem/call.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000034#include "src/tint/sem/function.h"
35#include "src/tint/sem/member_accessor_expression.h"
36#include "src/tint/sem/module.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000037#include "src/tint/sem/statement.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000038#include "src/tint/sem/struct.h"
dan sinclaird32fbe02022-10-19 00:43:41 +000039#include "src/tint/sem/switch_statement.h"
Ben Clayton54a104e2023-02-22 20:04:40 +000040#include "src/tint/sem/value_constructor.h"
41#include "src/tint/sem/value_conversion.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000042#include "src/tint/sem/variable.h"
Ben Clayton23946b32023-03-09 16:50:19 +000043#include "src/tint/switch.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000044#include "src/tint/transform/add_empty_entry_point.h"
45#include "src/tint/transform/array_length_from_uniform.h"
dan sinclair39d40652023-03-15 13:41:46 +000046#include "src/tint/transform/binding_remapper.h"
Ben Clayton27aa57c2022-02-22 23:13:39 +000047#include "src/tint/transform/builtin_polyfill.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000048#include "src/tint/transform/calculate_array_length.h"
49#include "src/tint/transform/canonicalize_entry_point_io.h"
50#include "src/tint/transform/decompose_memory_access.h"
James Price744d0eb2022-11-09 19:58:59 +000051#include "src/tint/transform/demote_to_helper.h"
Ben Clayton6992f512022-12-01 18:49:09 +000052#include "src/tint/transform/direct_variable_access.h"
James Price791b4352022-05-11 13:50:33 +000053#include "src/tint/transform/disable_uniformity_analysis.h"
James Price508a9662022-03-31 22:30:10 +000054#include "src/tint/transform/expand_compound_assignment.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000055#include "src/tint/transform/localize_struct_array_assignment.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000056#include "src/tint/transform/manager.h"
dan sinclair6521a352023-03-14 16:18:24 +000057#include "src/tint/transform/multiplanar_external_texture.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000058#include "src/tint/transform/num_workgroups_from_uniform.h"
Ben Clayton7ebcfc72022-06-27 20:20:25 +000059#include "src/tint/transform/promote_initializers_to_let.h"
Antonio Maiorano93baaae2022-03-15 15:35:13 +000060#include "src/tint/transform/promote_side_effects_to_decl.h"
Antonio Maioranob3497102022-03-31 15:02:25 +000061#include "src/tint/transform/remove_continue_in_switch.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000062#include "src/tint/transform/remove_phonies.h"
Ben Clayton03de0e82023-03-02 20:48:48 +000063#include "src/tint/transform/robustness.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000064#include "src/tint/transform/simplify_pointers.h"
shrekshaof9c66332022-11-22 21:36:27 +000065#include "src/tint/transform/truncate_interstage_variables.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000066#include "src/tint/transform/unshadow.h"
dan sinclair6e77b472022-10-20 13:38:28 +000067#include "src/tint/transform/vectorize_scalar_matrix_initializers.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000068#include "src/tint/transform/zero_init_workgroup_memory.h"
dan sinclair946858a2022-12-08 22:21:24 +000069#include "src/tint/type/array.h"
dan sinclaird8a08452022-12-08 22:21:24 +000070#include "src/tint/type/atomic.h"
dan sinclair4595fb72022-12-08 14:14:10 +000071#include "src/tint/type/depth_multisampled_texture.h"
72#include "src/tint/type/depth_texture.h"
73#include "src/tint/type/multisampled_texture.h"
74#include "src/tint/type/sampled_texture.h"
75#include "src/tint/type/storage_texture.h"
dan sinclair3cbf3fc2023-01-21 19:16:15 +000076#include "src/tint/type/texture_dimension.h"
Ben Clayton884f9522023-01-12 22:52:57 +000077#include "src/tint/utils/compiler_macros.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000078#include "src/tint/utils/defer.h"
79#include "src/tint/utils/map.h"
80#include "src/tint/utils/scoped_assignment.h"
dan sinclair4abf28e2022-08-02 15:55:35 +000081#include "src/tint/utils/string.h"
dan sinclair2b9d5b32023-02-28 14:49:25 +000082#include "src/tint/utils/string_stream.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000083#include "src/tint/writer/append_vector.h"
Ben Clayton1a567782022-10-14 13:38:27 +000084#include "src/tint/writer/check_supported_extensions.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000085#include "src/tint/writer/float_to_string.h"
86
Ben Clayton0ce9ab02022-05-05 20:23:40 +000087using namespace tint::number_suffixes; // NOLINT
88
dan sinclair6a5bef12022-04-07 14:30:24 +000089namespace tint::writer::hlsl {
Ryan Harrisondbc13af2022-02-21 15:19:07 +000090namespace {
91
92const char kTempNamePrefix[] = "tint_tmp";
Ryan Harrisondbc13af2022-02-21 15:19:07 +000093
dan sinclairba082fd2023-02-19 04:14:19 +000094const char* image_format_to_rwtexture_type(builtin::TexelFormat image_format) {
dan sinclair41e4d9a2022-05-01 14:40:55 +000095 switch (image_format) {
dan sinclairba082fd2023-02-19 04:14:19 +000096 case builtin::TexelFormat::kBgra8Unorm:
97 case builtin::TexelFormat::kRgba8Unorm:
98 case builtin::TexelFormat::kRgba8Snorm:
99 case builtin::TexelFormat::kRgba16Float:
100 case builtin::TexelFormat::kR32Float:
101 case builtin::TexelFormat::kRg32Float:
102 case builtin::TexelFormat::kRgba32Float:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000103 return "float4";
dan sinclairba082fd2023-02-19 04:14:19 +0000104 case builtin::TexelFormat::kRgba8Uint:
105 case builtin::TexelFormat::kRgba16Uint:
106 case builtin::TexelFormat::kR32Uint:
107 case builtin::TexelFormat::kRg32Uint:
108 case builtin::TexelFormat::kRgba32Uint:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000109 return "uint4";
dan sinclairba082fd2023-02-19 04:14:19 +0000110 case builtin::TexelFormat::kRgba8Sint:
111 case builtin::TexelFormat::kRgba16Sint:
112 case builtin::TexelFormat::kR32Sint:
113 case builtin::TexelFormat::kRg32Sint:
114 case builtin::TexelFormat::kRgba32Sint:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000115 return "int4";
116 default:
117 return nullptr;
118 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000119}
120
dan sinclair2b9d5b32023-02-28 14:49:25 +0000121void PrintF32(utils::StringStream& out, float value) {
Ben Claytone9f8b092022-06-01 13:14:39 +0000122 if (std::isinf(value)) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000123 out << "0.0f " << (value >= 0 ? "/* inf */" : "/* -inf */");
Ben Claytone9f8b092022-06-01 13:14:39 +0000124 } else if (std::isnan(value)) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000125 out << "0.0f /* nan */";
Ben Claytone9f8b092022-06-01 13:14:39 +0000126 } else {
127 out << FloatToString(value) << "f";
128 }
129}
130
dan sinclair2b9d5b32023-02-28 14:49:25 +0000131void PrintF16(utils::StringStream& out, float value) {
Antonio Maiorano679cf4f2022-09-03 21:43:01 +0000132 if (std::isinf(value)) {
133 out << "0.0h " << (value >= 0 ? "/* inf */" : "/* -inf */");
134 } else if (std::isnan(value)) {
135 out << "0.0h /* nan */";
Zhaoming Jianga5988a32022-07-11 15:43:38 +0000136 } else {
137 out << FloatToString(value) << "h";
Zhaoming Jianga5988a32022-07-11 15:43:38 +0000138 }
139}
140
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000141// Helper for writing " : register(RX, spaceY)", where R is the register, X is
142// the binding point binding value, and Y is the binding point group value.
143struct RegisterAndSpace {
dan sinclairacdf6e12022-08-24 15:47:25 +0000144 RegisterAndSpace(char r, sem::BindingPoint bp) : reg(r), binding_point(bp) {}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000145
dan sinclair41e4d9a2022-05-01 14:40:55 +0000146 const char reg;
dan sinclairacdf6e12022-08-24 15:47:25 +0000147 sem::BindingPoint const binding_point;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000148};
149
dan sinclair2b9d5b32023-02-28 14:49:25 +0000150utils::StringStream& operator<<(utils::StringStream& s, const RegisterAndSpace& rs) {
Peng Huangc00ff7f2023-03-31 17:55:19 +0000151 s << " : register(" << rs.reg << rs.binding_point.binding;
152 // Omit the space if it's 0, as it's the default.
153 // SM 5.0 doesn't support spaces, so we don't emit them if group is 0 for better compatibility.
154 if (rs.binding_point.group == 0) {
155 s << ")";
156 } else {
157 s << ", space" << rs.binding_point.group << ")";
158 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000159 return s;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000160}
161
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000162} // namespace
163
164SanitizedResult::SanitizedResult() = default;
165SanitizedResult::~SanitizedResult() = default;
166SanitizedResult::SanitizedResult(SanitizedResult&&) = default;
167
Antonio Maiorano7eaab382022-04-11 16:33:30 +0000168SanitizedResult Sanitize(const Program* in, const Options& options) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000169 transform::Manager manager;
170 transform::DataMap data;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000171
James Price791b4352022-05-11 13:50:33 +0000172 manager.Add<transform::DisableUniformityAnalysis>();
173
Ben Clayton46ee6392022-11-09 22:04:11 +0000174 // ExpandCompoundAssignment must come before BuiltinPolyfill
175 manager.Add<transform::ExpandCompoundAssignment>();
176
Ben Clayton03de0e82023-03-02 20:48:48 +0000177 manager.Add<transform::Unshadow>(); // Must come before DirectVariableAccess
178
179 manager.Add<transform::DirectVariableAccess>();
180
181 // LocalizeStructArrayAssignment must come after:
182 // * SimplifyPointers, because it assumes assignment to arrays in structs are
183 // done directly, not indirectly.
184 // TODO(crbug.com/tint/1340): See if we can get rid of the duplicate
185 // SimplifyPointers transform. Can't do it right now because
186 // LocalizeStructArrayAssignment introduces pointers.
187 manager.Add<transform::SimplifyPointers>();
188 manager.Add<transform::LocalizeStructArrayAssignment>();
189
190 manager.Add<transform::PromoteSideEffectsToDecl>();
191
192 if (!options.disable_robustness) {
Ben Clayton8525ff22023-03-06 21:05:01 +0000193 // Robustness must come after PromoteSideEffectsToDecl
194 // Robustness must come before BuiltinPolyfill and CanonicalizeEntryPointIO
Ben Clayton03de0e82023-03-02 20:48:48 +0000195 manager.Add<transform::Robustness>();
196 }
197
dan sinclair04d61c82023-04-11 23:02:45 +0000198 // Note: it is more efficient for MultiplanarExternalTexture to come after Robustness
199 data.Add<transform::MultiplanarExternalTexture::NewBindingPoints>(
200 options.external_texture_options.bindings_map);
201 manager.Add<transform::MultiplanarExternalTexture>();
Ben Clayton03de0e82023-03-02 20:48:48 +0000202
dan sinclair39d40652023-03-15 13:41:46 +0000203 // BindingRemapper must come after MultiplanarExternalTexture
204 manager.Add<transform::BindingRemapper>();
205 data.Add<transform::BindingRemapper::Remappings>(
206 options.binding_remapper_options.binding_points,
207 options.binding_remapper_options.access_controls,
208 options.binding_remapper_options.allow_collisions);
209
dan sinclair41e4d9a2022-05-01 14:40:55 +0000210 { // Builtin polyfills
211 transform::BuiltinPolyfill::Builtins polyfills;
dan sinclaird23f2962022-06-28 15:27:44 +0000212 polyfills.acosh = transform::BuiltinPolyfill::Level::kFull;
213 polyfills.asinh = true;
214 polyfills.atanh = transform::BuiltinPolyfill::Level::kFull;
Ben Clayton02f04d92022-11-03 19:15:17 +0000215 polyfills.bitshift_modulo = true;
Ben Clayton6dbb4632022-10-31 17:54:49 +0000216 polyfills.clamp_int = true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000217 // TODO(crbug.com/tint/1449): Some of these can map to HLSL's `firstbitlow`
218 // and `firstbithigh`.
Ben Claytoncc3f8512023-03-09 21:26:12 +0000219 polyfills.conv_f32_to_iu32 = true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000220 polyfills.count_leading_zeros = true;
221 polyfills.count_trailing_zeros = true;
222 polyfills.extract_bits = transform::BuiltinPolyfill::Level::kFull;
223 polyfills.first_leading_bit = true;
224 polyfills.first_trailing_bit = true;
225 polyfills.insert_bits = transform::BuiltinPolyfill::Level::kFull;
Ben Clayton46ee6392022-11-09 22:04:11 +0000226 polyfills.int_div_mod = true;
Antonio Maioranoee665a42023-02-14 16:12:59 +0000227 polyfills.precise_float_mod = true;
Zhaoming Jiang04529be2023-02-27 02:59:50 +0000228 polyfills.reflect_vec2_f32 = options.polyfill_reflect_vec2_f32;
Ben Claytonc4ebf2c2022-09-22 22:59:16 +0000229 polyfills.texture_sample_base_clamp_to_edge_2d_f32 = true;
James Price128980f2023-01-06 02:25:06 +0000230 polyfills.workgroup_uniform_load = true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000231 data.Add<transform::BuiltinPolyfill::Config>(polyfills);
232 manager.Add<transform::BuiltinPolyfill>();
233 }
Ben Clayton27aa57c2022-02-22 23:13:39 +0000234
dan sinclair41e4d9a2022-05-01 14:40:55 +0000235 if (!options.disable_workgroup_init) {
236 // ZeroInitWorkgroupMemory must come before CanonicalizeEntryPointIO as
237 // ZeroInitWorkgroupMemory may inject new builtin parameters.
238 manager.Add<transform::ZeroInitWorkgroupMemory>();
239 }
Ben Clayton03de0e82023-03-02 20:48:48 +0000240
241 // CanonicalizeEntryPointIO must come after Robustness
dan sinclair41e4d9a2022-05-01 14:40:55 +0000242 manager.Add<transform::CanonicalizeEntryPointIO>();
shrekshaof9c66332022-11-22 21:36:27 +0000243
shrekshao8f0607a2023-04-18 01:34:41 +0000244 if (options.truncate_interstage_variables) {
shrekshaof9c66332022-11-22 21:36:27 +0000245 // When interstage_locations is empty, it means there's no user-defined interstage variables
shrekshao8f0607a2023-04-18 01:34:41 +0000246 // being used in the next stage. Still, HLSL compiler register mismatch could happen, if
247 // there's builtin inputs used in the next stage. So we still run
248 // TruncateInterstageVariables transform.
shrekshaof9c66332022-11-22 21:36:27 +0000249
250 // TruncateInterstageVariables itself will skip when interstage_locations matches exactly
251 // with the current stage output.
252
253 // Build the config for internal TruncateInterstageVariables transform.
254 transform::TruncateInterstageVariables::Config truncate_interstage_variables_cfg;
255 truncate_interstage_variables_cfg.interstage_locations =
256 std::move(options.interstage_locations);
257 manager.Add<transform::TruncateInterstageVariables>();
258 data.Add<transform::TruncateInterstageVariables::Config>(
259 std::move(truncate_interstage_variables_cfg));
260 }
261
dan sinclair41e4d9a2022-05-01 14:40:55 +0000262 // NumWorkgroupsFromUniform must come after CanonicalizeEntryPointIO, as it
263 // assumes that num_workgroups builtins only appear as struct members and are
264 // only accessed directly via member accessors.
265 manager.Add<transform::NumWorkgroupsFromUniform>();
dan sinclair6e77b472022-10-20 13:38:28 +0000266 manager.Add<transform::VectorizeScalarMatrixInitializers>();
dan sinclair41e4d9a2022-05-01 14:40:55 +0000267 manager.Add<transform::SimplifyPointers>();
268 manager.Add<transform::RemovePhonies>();
James Price744d0eb2022-11-09 19:58:59 +0000269
Ben Clayton03de0e82023-03-02 20:48:48 +0000270 // Build the config for the internal ArrayLengthFromUniform transform.
271 auto& array_length_from_uniform = options.array_length_from_uniform;
272 transform::ArrayLengthFromUniform::Config array_length_from_uniform_cfg(
273 array_length_from_uniform.ubo_binding);
274 array_length_from_uniform_cfg.bindpoint_to_size_index =
275 array_length_from_uniform.bindpoint_to_size_index;
276
James Price744d0eb2022-11-09 19:58:59 +0000277 // DemoteToHelper must come after CanonicalizeEntryPointIO, PromoteSideEffectsToDecl, and
278 // ExpandCompoundAssignment.
279 // TODO(crbug.com/tint/1752): This is only necessary when FXC is being used.
280 manager.Add<transform::DemoteToHelper>();
281
Ben Clayton559e5a22023-04-17 14:24:58 +0000282 // ArrayLengthFromUniform must come after SimplifyPointers as it assumes that the form of the
283 // array length argument is &var.array.
dan sinclair41e4d9a2022-05-01 14:40:55 +0000284 manager.Add<transform::ArrayLengthFromUniform>();
285 data.Add<transform::ArrayLengthFromUniform::Config>(std::move(array_length_from_uniform_cfg));
286 // DecomposeMemoryAccess must come after:
Ben Clayton559e5a22023-04-17 14:24:58 +0000287 // * SimplifyPointers, as we cannot take the address of calls to
288 // DecomposeMemoryAccess::Intrinsic and we need to fold away the address-of and dereferences
289 // of `*(&(intrinsic_load()))` expressions.
dan sinclair41e4d9a2022-05-01 14:40:55 +0000290 // * RemovePhonies, as phonies can be assigned a pointer to a
291 // non-constructible buffer, or dynamic array, which DMA cannot cope with.
292 manager.Add<transform::DecomposeMemoryAccess>();
293 // CalculateArrayLength must come after DecomposeMemoryAccess, as
294 // DecomposeMemoryAccess special-cases the arrayLength() intrinsic, which
295 // will be transformed by CalculateArrayLength
296 manager.Add<transform::CalculateArrayLength>();
Ben Clayton7ebcfc72022-06-27 20:20:25 +0000297 manager.Add<transform::PromoteInitializersToLet>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000298
dan sinclair41e4d9a2022-05-01 14:40:55 +0000299 manager.Add<transform::RemoveContinueInSwitch>();
Antonio Maioranob3497102022-03-31 15:02:25 +0000300
dan sinclair41e4d9a2022-05-01 14:40:55 +0000301 manager.Add<transform::AddEmptyEntryPoint>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000302
dan sinclair41e4d9a2022-05-01 14:40:55 +0000303 data.Add<transform::CanonicalizeEntryPointIO::Config>(
304 transform::CanonicalizeEntryPointIO::ShaderStyle::kHlsl);
305 data.Add<transform::NumWorkgroupsFromUniform::Config>(options.root_constant_binding_point);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000306
dan sinclair41e4d9a2022-05-01 14:40:55 +0000307 auto out = manager.Run(in, data);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000308
dan sinclair41e4d9a2022-05-01 14:40:55 +0000309 SanitizedResult result;
310 result.program = std::move(out.program);
311 if (auto* res = out.data.Get<transform::ArrayLengthFromUniform::Result>()) {
312 result.used_array_length_from_uniform_indices = std::move(res->used_size_indices);
313 }
314 return result;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000315}
316
317GeneratorImpl::GeneratorImpl(const Program* program) : TextGenerator(program) {}
318
319GeneratorImpl::~GeneratorImpl() = default;
320
321bool GeneratorImpl::Generate() {
Ben Clayton1a567782022-10-14 13:38:27 +0000322 if (!CheckSupportedExtensions("HLSL", program_->AST(), diagnostics_,
323 utils::Vector{
dan sinclaire4039c72023-02-17 21:58:59 +0000324 builtin::Extension::kChromiumDisableUniformityAnalysis,
325 builtin::Extension::kChromiumExperimentalDp4A,
326 builtin::Extension::kChromiumExperimentalFullPtrParameters,
327 builtin::Extension::kChromiumExperimentalPushConstant,
328 builtin::Extension::kF16,
Ben Clayton1a567782022-10-14 13:38:27 +0000329 })) {
330 return false;
331 }
332
dan sinclair41e4d9a2022-05-01 14:40:55 +0000333 const TypeInfo* last_kind = nullptr;
334 size_t last_padding_line = 0;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000335
dan sinclair41e4d9a2022-05-01 14:40:55 +0000336 auto* mod = builder_.Sem().Module();
337 for (auto* decl : mod->DependencyOrderedDeclarations()) {
James Price98dc5a82023-02-04 12:20:55 +0000338 if (decl->IsAnyOf<ast::Alias, ast::DiagnosticDirective, ast::Enable, ast::ConstAssert>()) {
Ben Claytonb4744ac2022-08-03 07:01:08 +0000339 continue; // These are not emitted.
James Price791b4352022-05-11 13:50:33 +0000340 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000341
dan sinclair41e4d9a2022-05-01 14:40:55 +0000342 // Emit a new line between declarations if the type of declaration has
343 // changed, or we're about to emit a function
344 auto* kind = &decl->TypeInfo();
345 if (current_buffer_->lines.size() != last_padding_line) {
346 if (last_kind && (last_kind != kind || decl->Is<ast::Function>())) {
347 line();
348 last_padding_line = current_buffer_->lines.size();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000349 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000350 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000351 last_kind = kind;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000352
dan sinclair41e4d9a2022-05-01 14:40:55 +0000353 bool ok = Switch(
354 decl,
355 [&](const ast::Variable* global) { //
356 return EmitGlobalVariable(global);
357 },
358 [&](const ast::Struct* str) {
359 auto* ty = builder_.Sem().Get(str);
dan sinclairff7cf212022-10-03 14:05:23 +0000360 auto address_space_uses = ty->AddressSpaceUsage();
361 if (address_space_uses.size() !=
dan sinclair2a651632023-02-19 04:03:55 +0000362 (address_space_uses.count(builtin::AddressSpace::kStorage) +
363 address_space_uses.count(builtin::AddressSpace::kUniform))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000364 // The structure is used as something other than a storage buffer or
365 // uniform buffer, so it needs to be emitted.
366 // Storage buffer are read and written to via a ByteAddressBuffer
367 // instead of true structure.
368 // Structures used as uniform buffer are read from an array of
369 // vectors instead of true structure.
370 return EmitStructType(current_buffer_, ty);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000371 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000372 return true;
373 },
374 [&](const ast::Function* func) {
375 if (func->IsEntryPoint()) {
376 return EmitEntryPointFunction(func);
377 }
378 return EmitFunction(func);
379 },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000380 [&](Default) {
381 TINT_ICE(Writer, diagnostics_)
382 << "unhandled module-scope declaration: " << decl->TypeInfo().name;
383 return false;
384 });
385
386 if (!ok) {
387 return false;
388 }
389 }
390
391 if (!helpers_.lines.empty()) {
392 current_buffer_->Insert(helpers_, 0, 0);
393 }
394
395 return true;
396}
397
398bool GeneratorImpl::EmitDynamicVectorAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000399 const type::Vector* vec) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000400 auto name = utils::GetOrCreate(dynamic_vector_write_, vec, [&]() -> std::string {
401 std::string fn;
402 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000403 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000404 if (!EmitType(ss, vec, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000405 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000406 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000407 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000408 fn = UniqueIdentifier("set_" + ss.str());
409 }
410 {
411 auto out = line(&helpers_);
412 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000413 if (!EmitTypeAndName(out, vec, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000414 builtin::Access::kUndefined, "vec")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000415 return "";
416 }
417 out << ", int idx, ";
dan sinclair2a651632023-02-19 04:03:55 +0000418 if (!EmitTypeAndName(out, vec->type(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000419 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000420 return "";
421 }
422 out << ") {";
423 }
424 {
425 ScopedIndent si(&helpers_);
426 auto out = line(&helpers_);
427 switch (vec->Width()) {
428 case 2:
429 out << "vec = (idx.xx == int2(0, 1)) ? val.xx : vec;";
430 break;
431 case 3:
432 out << "vec = (idx.xxx == int3(0, 1, 2)) ? val.xxx : vec;";
433 break;
434 case 4:
435 out << "vec = (idx.xxxx == int4(0, 1, 2, 3)) ? val.xxxx : vec;";
436 break;
437 default:
Ben Claytondcdf66e2022-06-17 12:48:51 +0000438 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair41e4d9a2022-05-01 14:40:55 +0000439 << "invalid vector size " << vec->Width();
440 break;
441 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000442 }
443 line(&helpers_) << "}";
444 line(&helpers_);
445 return fn;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000446 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000447
dan sinclair41e4d9a2022-05-01 14:40:55 +0000448 if (name.empty()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000449 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000450 }
451
dan sinclair41e4d9a2022-05-01 14:40:55 +0000452 auto* ast_access_expr = stmt->lhs->As<ast::IndexAccessorExpression>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000453
dan sinclair41e4d9a2022-05-01 14:40:55 +0000454 auto out = line();
455 out << name << "(";
456 if (!EmitExpression(out, ast_access_expr->object)) {
457 return false;
458 }
459 out << ", ";
460 if (!EmitExpression(out, ast_access_expr->index)) {
461 return false;
462 }
463 out << ", ";
464 if (!EmitExpression(out, stmt->rhs)) {
465 return false;
466 }
467 out << ");";
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000468
dan sinclair41e4d9a2022-05-01 14:40:55 +0000469 return true;
470}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000471
dan sinclair41e4d9a2022-05-01 14:40:55 +0000472bool GeneratorImpl::EmitDynamicMatrixVectorAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000473 const type::Matrix* mat) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000474 auto name = utils::GetOrCreate(dynamic_matrix_vector_write_, mat, [&]() -> std::string {
475 std::string fn;
476 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000477 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000478 if (!EmitType(ss, mat, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000479 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000480 return "";
481 }
482 fn = UniqueIdentifier("set_vector_" + ss.str());
483 }
484 {
485 auto out = line(&helpers_);
486 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000487 if (!EmitTypeAndName(out, mat, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000488 builtin::Access::kUndefined, "mat")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000489 return "";
490 }
491 out << ", int col, ";
dan sinclair2a651632023-02-19 04:03:55 +0000492 if (!EmitTypeAndName(out, mat->ColumnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000493 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000494 return "";
495 }
496 out << ") {";
497 }
498 {
499 ScopedIndent si(&helpers_);
500 line(&helpers_) << "switch (col) {";
501 {
502 ScopedIndent si2(&helpers_);
503 for (uint32_t i = 0; i < mat->columns(); ++i) {
504 line(&helpers_) << "case " << i << ": mat[" << i << "] = val; break;";
505 }
506 }
507 line(&helpers_) << "}";
508 }
509 line(&helpers_) << "}";
510 line(&helpers_);
511 return fn;
512 });
513
514 if (name.empty()) {
515 return false;
516 }
517
518 auto* ast_access_expr = stmt->lhs->As<ast::IndexAccessorExpression>();
519
520 auto out = line();
521 out << name << "(";
522 if (!EmitExpression(out, ast_access_expr->object)) {
523 return false;
524 }
525 out << ", ";
526 if (!EmitExpression(out, ast_access_expr->index)) {
527 return false;
528 }
529 out << ", ";
530 if (!EmitExpression(out, stmt->rhs)) {
531 return false;
532 }
533 out << ");";
534
535 return true;
536}
537
538bool GeneratorImpl::EmitDynamicMatrixScalarAssignment(const ast::AssignmentStatement* stmt,
dan sinclair0e780da2022-12-08 22:21:24 +0000539 const type::Matrix* mat) {
Antonio Maioranof031ca22023-02-02 22:16:42 +0000540 auto* lhs_row_access = stmt->lhs->As<ast::IndexAccessorExpression>();
541 auto* lhs_col_access = lhs_row_access->object->As<ast::IndexAccessorExpression>();
dan sinclair41e4d9a2022-05-01 14:40:55 +0000542
543 auto name = utils::GetOrCreate(dynamic_matrix_scalar_write_, mat, [&]() -> std::string {
544 std::string fn;
545 {
dan sinclair2b9d5b32023-02-28 14:49:25 +0000546 utils::StringStream ss;
dan sinclair2a651632023-02-19 04:03:55 +0000547 if (!EmitType(ss, mat, tint::builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000548 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000549 return "";
550 }
551 fn = UniqueIdentifier("set_scalar_" + ss.str());
552 }
553 {
554 auto out = line(&helpers_);
555 out << "void " << fn << "(inout ";
dan sinclair2a651632023-02-19 04:03:55 +0000556 if (!EmitTypeAndName(out, mat, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000557 builtin::Access::kUndefined, "mat")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000558 return "";
559 }
560 out << ", int col, int row, ";
dan sinclair2a651632023-02-19 04:03:55 +0000561 if (!EmitTypeAndName(out, mat->type(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +0000562 builtin::Access::kUndefined, "val")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000563 return "";
564 }
565 out << ") {";
566 }
567 {
568 ScopedIndent si(&helpers_);
569 line(&helpers_) << "switch (col) {";
570 {
571 ScopedIndent si2(&helpers_);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000572 for (uint32_t i = 0; i < mat->columns(); ++i) {
573 line(&helpers_) << "case " << i << ":";
574 {
575 auto vec_name = "mat[" + std::to_string(i) + "]";
576 ScopedIndent si3(&helpers_);
577 {
578 auto out = line(&helpers_);
579 switch (mat->rows()) {
580 case 2:
581 out << vec_name
582 << " = (row.xx == int2(0, 1)) ? val.xx : " << vec_name
583 << ";";
584 break;
585 case 3:
586 out << vec_name
587 << " = (row.xxx == int3(0, 1, 2)) ? val.xxx : " << vec_name
588 << ";";
589 break;
590 case 4:
591 out << vec_name
592 << " = (row.xxxx == int4(0, 1, 2, 3)) ? val.xxxx : "
593 << vec_name << ";";
594 break;
Antonio Maioranof031ca22023-02-02 22:16:42 +0000595 default: {
596 auto* vec = TypeOf(lhs_row_access->object)
597 ->UnwrapRef()
598 ->As<type::Vector>();
Ben Claytondcdf66e2022-06-17 12:48:51 +0000599 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair41e4d9a2022-05-01 14:40:55 +0000600 << "invalid vector size " << vec->Width();
601 break;
Antonio Maioranof031ca22023-02-02 22:16:42 +0000602 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000603 }
604 }
605 line(&helpers_) << "break;";
606 }
607 }
608 }
609 line(&helpers_) << "}";
610 }
611 line(&helpers_) << "}";
612 line(&helpers_);
613 return fn;
614 });
615
616 if (name.empty()) {
617 return false;
618 }
619
620 auto out = line();
621 out << name << "(";
Antonio Maioranof031ca22023-02-02 22:16:42 +0000622 if (!EmitExpression(out, lhs_col_access->object)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000623 return false;
624 }
625 out << ", ";
626 if (!EmitExpression(out, lhs_col_access->index)) {
627 return false;
628 }
629 out << ", ";
630 if (!EmitExpression(out, lhs_row_access->index)) {
631 return false;
632 }
633 out << ", ";
634 if (!EmitExpression(out, stmt->rhs)) {
635 return false;
636 }
637 out << ");";
638
639 return true;
640}
641
dan sinclair2b9d5b32023-02-28 14:49:25 +0000642bool GeneratorImpl::EmitIndexAccessor(utils::StringStream& out,
643 const ast::IndexAccessorExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000644 if (!EmitExpression(out, expr->object)) {
645 return false;
646 }
647 out << "[";
648
649 if (!EmitExpression(out, expr->index)) {
650 return false;
651 }
652 out << "]";
653
654 return true;
655}
656
dan sinclair2b9d5b32023-02-28 14:49:25 +0000657bool GeneratorImpl::EmitBitcast(utils::StringStream& out, const ast::BitcastExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000658 auto* type = TypeOf(expr);
dan sinclair0e780da2022-12-08 22:21:24 +0000659 if (auto* vec = type->UnwrapRef()->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000660 type = vec->type();
661 }
662
663 if (!type->is_integer_scalar() && !type->is_float_scalar()) {
664 diagnostics_.add_error(diag::System::Writer, "Unable to do bitcast to type " +
665 type->FriendlyName(builder_.Symbols()));
666 return false;
667 }
668
669 out << "as";
dan sinclair2a651632023-02-19 04:03:55 +0000670 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000671 return false;
672 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000673 out << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000674 if (!EmitExpression(out, expr->expr)) {
675 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000676 }
677 out << ")";
678 return true;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000679}
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000680
dan sinclair41e4d9a2022-05-01 14:40:55 +0000681bool GeneratorImpl::EmitAssign(const ast::AssignmentStatement* stmt) {
682 if (auto* lhs_access = stmt->lhs->As<ast::IndexAccessorExpression>()) {
683 // BUG(crbug.com/tint/1333): work around assignment of scalar to matrices
684 // with at least one dynamic index
685 if (auto* lhs_sub_access = lhs_access->object->As<ast::IndexAccessorExpression>()) {
dan sinclair0e780da2022-12-08 22:21:24 +0000686 if (auto* mat = TypeOf(lhs_sub_access->object)->UnwrapRef()->As<type::Matrix>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000687 auto* rhs_row_idx_sem = builder_.Sem().GetVal(lhs_access->index);
688 auto* rhs_col_idx_sem = builder_.Sem().GetVal(lhs_sub_access->index);
Antonio Maioranof031ca22023-02-02 22:16:42 +0000689 if (!rhs_row_idx_sem->ConstantValue() || !rhs_col_idx_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000690 return EmitDynamicMatrixScalarAssignment(stmt, mat);
691 }
692 }
693 }
694 // BUG(crbug.com/tint/1333): work around assignment of vector to matrices
695 // with dynamic indices
696 const auto* lhs_access_type = TypeOf(lhs_access->object)->UnwrapRef();
dan sinclair0e780da2022-12-08 22:21:24 +0000697 if (auto* mat = lhs_access_type->As<type::Matrix>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000698 auto* lhs_index_sem = builder_.Sem().GetVal(lhs_access->index);
Ben Claytonaa037ac2022-06-29 19:07:30 +0000699 if (!lhs_index_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000700 return EmitDynamicMatrixVectorAssignment(stmt, mat);
701 }
702 }
703 // BUG(crbug.com/tint/534): work around assignment to vectors with dynamic
704 // indices
dan sinclair0e780da2022-12-08 22:21:24 +0000705 if (auto* vec = lhs_access_type->As<type::Vector>()) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +0000706 auto* rhs_sem = builder_.Sem().GetVal(lhs_access->index);
Ben Claytonaa037ac2022-06-29 19:07:30 +0000707 if (!rhs_sem->ConstantValue()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000708 return EmitDynamicVectorAssignment(stmt, vec);
709 }
710 }
711 }
712
713 auto out = line();
714 if (!EmitExpression(out, stmt->lhs)) {
715 return false;
716 }
717 out << " = ";
718 if (!EmitExpression(out, stmt->rhs)) {
719 return false;
720 }
721 out << ";";
722 return true;
723}
724
dan sinclair2b9d5b32023-02-28 14:49:25 +0000725bool GeneratorImpl::EmitBinary(utils::StringStream& out, const ast::BinaryExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000726 if (expr->op == ast::BinaryOp::kLogicalAnd || expr->op == ast::BinaryOp::kLogicalOr) {
727 auto name = UniqueIdentifier(kTempNamePrefix);
728
729 {
730 auto pre = line();
731 pre << "bool " << name << " = ";
732 if (!EmitExpression(pre, expr->lhs)) {
733 return false;
734 }
735 pre << ";";
736 }
737
738 if (expr->op == ast::BinaryOp::kLogicalOr) {
739 line() << "if (!" << name << ") {";
740 } else {
741 line() << "if (" << name << ") {";
742 }
743
744 {
745 ScopedIndent si(this);
746 auto pre = line();
747 pre << name << " = ";
748 if (!EmitExpression(pre, expr->rhs)) {
749 return false;
750 }
751 pre << ";";
752 }
753
754 line() << "}";
755
756 out << "(" << name << ")";
757 return true;
758 }
759
760 auto* lhs_type = TypeOf(expr->lhs)->UnwrapRef();
761 auto* rhs_type = TypeOf(expr->rhs)->UnwrapRef();
762 // Multiplying by a matrix requires the use of `mul` in order to get the
763 // type of multiply we desire.
764 if (expr->op == ast::BinaryOp::kMultiply &&
dan sinclair0e780da2022-12-08 22:21:24 +0000765 ((lhs_type->Is<type::Vector>() && rhs_type->Is<type::Matrix>()) ||
766 (lhs_type->Is<type::Matrix>() && rhs_type->Is<type::Vector>()) ||
767 (lhs_type->Is<type::Matrix>() && rhs_type->Is<type::Matrix>()))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000768 // Matrices are transposed, so swap LHS and RHS.
769 out << "mul(";
770 if (!EmitExpression(out, expr->rhs)) {
771 return false;
772 }
773 out << ", ";
774 if (!EmitExpression(out, expr->lhs)) {
775 return false;
776 }
777 out << ")";
778
779 return true;
780 }
781
dan sinclairb2ba57b2023-02-28 15:14:09 +0000782 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000783
784 if (!EmitExpression(out, expr->lhs)) {
785 return false;
786 }
787 out << " ";
788
789 switch (expr->op) {
790 case ast::BinaryOp::kAnd:
791 out << "&";
792 break;
793 case ast::BinaryOp::kOr:
794 out << "|";
795 break;
796 case ast::BinaryOp::kXor:
797 out << "^";
798 break;
799 case ast::BinaryOp::kLogicalAnd:
800 case ast::BinaryOp::kLogicalOr: {
801 // These are both handled above.
802 TINT_UNREACHABLE(Writer, diagnostics_);
803 return false;
804 }
805 case ast::BinaryOp::kEqual:
806 out << "==";
807 break;
808 case ast::BinaryOp::kNotEqual:
809 out << "!=";
810 break;
811 case ast::BinaryOp::kLessThan:
812 out << "<";
813 break;
814 case ast::BinaryOp::kGreaterThan:
815 out << ">";
816 break;
817 case ast::BinaryOp::kLessThanEqual:
818 out << "<=";
819 break;
820 case ast::BinaryOp::kGreaterThanEqual:
821 out << ">=";
822 break;
823 case ast::BinaryOp::kShiftLeft:
824 out << "<<";
825 break;
826 case ast::BinaryOp::kShiftRight:
827 // TODO(dsinclair): MSL is based on C++14, and >> in C++14 has
828 // implementation-defined behaviour for negative LHS. We may have to
829 // generate extra code to implement WGSL-specified behaviour for negative
830 // LHS.
831 out << R"(>>)";
832 break;
833
834 case ast::BinaryOp::kAdd:
835 out << "+";
836 break;
837 case ast::BinaryOp::kSubtract:
838 out << "-";
839 break;
840 case ast::BinaryOp::kMultiply:
841 out << "*";
842 break;
843 case ast::BinaryOp::kDivide:
844 out << "/";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000845 break;
846 case ast::BinaryOp::kModulo:
847 out << "%";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000848 break;
849 case ast::BinaryOp::kNone:
850 diagnostics_.add_error(diag::System::Writer, "missing binary operation type");
851 return false;
852 }
853 out << " ";
854
855 if (!EmitExpression(out, expr->rhs)) {
856 return false;
857 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000858
859 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000860}
861
Ben Clayton783b1692022-08-02 17:03:35 +0000862bool GeneratorImpl::EmitStatements(utils::VectorRef<const ast::Statement*> stmts) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000863 for (auto* s : stmts) {
864 if (!EmitStatement(s)) {
865 return false;
866 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000867 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000868 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000869}
870
Ben Clayton783b1692022-08-02 17:03:35 +0000871bool GeneratorImpl::EmitStatementsWithIndent(utils::VectorRef<const ast::Statement*> stmts) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000872 ScopedIndent si(this);
873 return EmitStatements(stmts);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000874}
875
876bool GeneratorImpl::EmitBlock(const ast::BlockStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000877 line() << "{";
878 if (!EmitStatementsWithIndent(stmt->statements)) {
879 return false;
880 }
881 line() << "}";
882 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000883}
884
885bool GeneratorImpl::EmitBreak(const ast::BreakStatement*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000886 line() << "break;";
887 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000888}
889
dan sinclairb8b0c212022-10-20 22:45:50 +0000890bool GeneratorImpl::EmitBreakIf(const ast::BreakIfStatement* b) {
891 auto out = line();
892 out << "if (";
893 if (!EmitExpression(out, b->condition)) {
894 return false;
895 }
896 out << ") { break; }";
897 return true;
898}
899
dan sinclair2b9d5b32023-02-28 14:49:25 +0000900bool GeneratorImpl::EmitCall(utils::StringStream& out, const ast::CallExpression* expr) {
Ben Claytone9f8b092022-06-01 13:14:39 +0000901 auto* call = builder_.Sem().Get<sem::Call>(expr);
dan sinclair41e4d9a2022-05-01 14:40:55 +0000902 auto* target = call->Target();
903 return Switch(
Ben Clayton54a104e2023-02-22 20:04:40 +0000904 target, //
905 [&](const sem::Function* func) { return EmitFunctionCall(out, call, func); },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000906 [&](const sem::Builtin* builtin) { return EmitBuiltinCall(out, call, builtin); },
Ben Clayton54a104e2023-02-22 20:04:40 +0000907 [&](const sem::ValueConversion* conv) { return EmitValueConversion(out, call, conv); },
908 [&](const sem::ValueConstructor* ctor) { return EmitValueConstructor(out, call, ctor); },
dan sinclair41e4d9a2022-05-01 14:40:55 +0000909 [&](Default) {
910 TINT_ICE(Writer, diagnostics_) << "unhandled call target: " << target->TypeInfo().name;
911 return false;
912 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000913}
914
dan sinclair2b9d5b32023-02-28 14:49:25 +0000915bool GeneratorImpl::EmitFunctionCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000916 const sem::Call* call,
917 const sem::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000918 auto* expr = call->Declaration();
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000919
dan sinclair41e4d9a2022-05-01 14:40:55 +0000920 if (ast::HasAttribute<transform::CalculateArrayLength::BufferSizeIntrinsic>(
921 func->Declaration()->attributes)) {
922 // Special function generated by the CalculateArrayLength transform for
923 // calling X.GetDimensions(Y)
924 if (!EmitExpression(out, call->Arguments()[0]->Declaration())) {
925 return false;
926 }
927 out << ".GetDimensions(";
928 if (!EmitExpression(out, call->Arguments()[1]->Declaration())) {
929 return false;
930 }
931 out << ")";
932 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000933 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000934
935 if (auto* intrinsic = ast::GetAttribute<transform::DecomposeMemoryAccess::Intrinsic>(
936 func->Declaration()->attributes)) {
dan sinclairff7cf212022-10-03 14:05:23 +0000937 switch (intrinsic->address_space) {
dan sinclair2a651632023-02-19 04:03:55 +0000938 case builtin::AddressSpace::kUniform:
dan sinclair41e4d9a2022-05-01 14:40:55 +0000939 return EmitUniformBufferAccess(out, expr, intrinsic);
dan sinclair2a651632023-02-19 04:03:55 +0000940 case builtin::AddressSpace::kStorage:
Antonio Maiorano08f4b552022-05-31 13:20:28 +0000941 if (!intrinsic->IsAtomic()) {
942 return EmitStorageBufferAccess(out, expr, intrinsic);
943 }
944 break;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000945 default:
946 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclairff7cf212022-10-03 14:05:23 +0000947 << "unsupported DecomposeMemoryAccess::Intrinsic address space:"
948 << intrinsic->address_space;
dan sinclair41e4d9a2022-05-01 14:40:55 +0000949 return false;
950 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000951 }
dan sinclair41e4d9a2022-05-01 14:40:55 +0000952
Ben Claytonce31d182023-02-09 10:34:14 +0000953 out << builder_.Symbols().NameFor(func->Declaration()->name->symbol) << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +0000954
955 bool first = true;
956 for (auto* arg : call->Arguments()) {
957 if (!first) {
958 out << ", ";
959 }
960 first = false;
961
962 if (!EmitExpression(out, arg->Declaration())) {
963 return false;
964 }
965 }
966
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000967 out << ")";
968 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000969}
970
dan sinclair2b9d5b32023-02-28 14:49:25 +0000971bool GeneratorImpl::EmitBuiltinCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000972 const sem::Call* call,
973 const sem::Builtin* builtin) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +0000974 const auto type = builtin->Type();
975
dan sinclair41e4d9a2022-05-01 14:40:55 +0000976 auto* expr = call->Declaration();
977 if (builtin->IsTexture()) {
978 return EmitTextureCall(out, call, builtin);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000979 }
dan sinclair9543f742023-03-09 01:20:16 +0000980 if (type == builtin::Function::kSelect) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000981 return EmitSelectCall(out, expr);
Ryan Harrisondbc13af2022-02-21 15:19:07 +0000982 }
dan sinclair9543f742023-03-09 01:20:16 +0000983 if (type == builtin::Function::kModf) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000984 return EmitModfCall(out, expr, builtin);
985 }
dan sinclair9543f742023-03-09 01:20:16 +0000986 if (type == builtin::Function::kFrexp) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000987 return EmitFrexpCall(out, expr, builtin);
988 }
dan sinclair9543f742023-03-09 01:20:16 +0000989 if (type == builtin::Function::kDegrees) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000990 return EmitDegreesCall(out, expr, builtin);
991 }
dan sinclair9543f742023-03-09 01:20:16 +0000992 if (type == builtin::Function::kRadians) {
dan sinclair41e4d9a2022-05-01 14:40:55 +0000993 return EmitRadiansCall(out, expr, builtin);
994 }
dan sinclair9543f742023-03-09 01:20:16 +0000995 if (type == builtin::Function::kSign) {
dan sinclair70927862023-01-11 13:18:29 +0000996 return EmitSignCall(out, call, builtin);
997 }
dan sinclair9543f742023-03-09 01:20:16 +0000998 if (type == builtin::Function::kQuantizeToF16) {
Ben Clayton2bea9052022-11-02 00:09:50 +0000999 return EmitQuantizeToF16Call(out, expr, builtin);
1000 }
Antonio Maiorano5cf943e2023-03-27 18:55:25 +00001001 if (type == builtin::Function::kTrunc) {
1002 return EmitTruncCall(out, expr, builtin);
1003 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001004 if (builtin->IsDataPacking()) {
1005 return EmitDataPackingCall(out, expr, builtin);
1006 }
1007 if (builtin->IsDataUnpacking()) {
1008 return EmitDataUnpackingCall(out, expr, builtin);
1009 }
1010 if (builtin->IsBarrier()) {
1011 return EmitBarrierCall(out, builtin);
1012 }
1013 if (builtin->IsAtomic()) {
1014 return EmitWorkgroupAtomicCall(out, expr, builtin);
1015 }
Jiawei Shaoab975702022-05-13 00:09:56 +00001016 if (builtin->IsDP4a()) {
1017 return EmitDP4aCall(out, expr, builtin);
1018 }
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001019
dan sinclair41e4d9a2022-05-01 14:40:55 +00001020 auto name = generate_builtin_name(builtin);
1021 if (name.empty()) {
1022 return false;
1023 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001024
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001025 // Handle single argument builtins that only accept and return uint (not int overload). We need
1026 // to explicitly cast the return value (we also cast the arg for good measure). See
1027 // crbug.com/tint/1550
dan sinclair9543f742023-03-09 01:20:16 +00001028 if (type == builtin::Function::kCountOneBits || type == builtin::Function::kReverseBits) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001029 auto* arg = call->Arguments()[0];
Ben Clayton6c337aa2022-12-07 19:25:17 +00001030 if (arg->Type()->UnwrapRef()->is_signed_integer_scalar_or_vector()) {
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001031 out << "asint(" << name << "(asuint(";
1032 if (!EmitExpression(out, arg->Declaration())) {
1033 return false;
1034 }
1035 out << ")))";
1036 return true;
1037 }
1038 }
1039
dan sinclair41e4d9a2022-05-01 14:40:55 +00001040 out << name << "(";
1041
1042 bool first = true;
1043 for (auto* arg : call->Arguments()) {
1044 if (!first) {
1045 out << ", ";
1046 }
1047 first = false;
1048
1049 if (!EmitExpression(out, arg->Declaration())) {
1050 return false;
1051 }
1052 }
1053
1054 out << ")";
Antonio Maioranoab4c0352022-05-20 01:58:40 +00001055
dan sinclair41e4d9a2022-05-01 14:40:55 +00001056 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001057}
1058
dan sinclair2b9d5b32023-02-28 14:49:25 +00001059bool GeneratorImpl::EmitValueConversion(utils::StringStream& out,
Ben Clayton54a104e2023-02-22 20:04:40 +00001060 const sem::Call* call,
1061 const sem::ValueConversion* conv) {
dan sinclair2a651632023-02-19 04:03:55 +00001062 if (!EmitType(out, conv->Target(), builtin::AddressSpace::kUndefined,
1063 builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001064 return false;
1065 }
1066 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001067
dan sinclair41e4d9a2022-05-01 14:40:55 +00001068 if (!EmitExpression(out, call->Arguments()[0]->Declaration())) {
1069 return false;
1070 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001071
dan sinclair41e4d9a2022-05-01 14:40:55 +00001072 out << ")";
1073 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001074}
1075
dan sinclair2b9d5b32023-02-28 14:49:25 +00001076bool GeneratorImpl::EmitValueConstructor(utils::StringStream& out,
Ben Clayton54a104e2023-02-22 20:04:40 +00001077 const sem::Call* call,
1078 const sem::ValueConstructor* ctor) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001079 auto* type = call->Type();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001080
Ben Clayton54a104e2023-02-22 20:04:40 +00001081 // If the value constructor arguments are empty then we need to construct with the zero value
1082 // for all components.
Ben Clayton958a4642022-07-26 07:55:24 +00001083 if (call->Arguments().IsEmpty()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001084 return EmitZeroValue(out, type);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001085 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001086
dan sinclair6e77b472022-10-20 13:38:28 +00001087 // Single parameter matrix initializers must be identity initializer.
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001088 // It could also be conversions between f16 and f32 matrix when f16 is properly supported.
dan sinclair0e780da2022-12-08 22:21:24 +00001089 if (type->Is<type::Matrix>() && call->Arguments().Length() == 1) {
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001090 if (!ctor->Parameters()[0]->Type()->UnwrapRef()->is_float_matrix()) {
1091 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair6e77b472022-10-20 13:38:28 +00001092 << "found a single-parameter matrix initializer that is not identity initializer";
Zhaoming Jiangc5f7e8f2022-06-24 17:21:59 +00001093 return false;
Ben Clayton3b5edf12022-05-16 21:14:11 +00001094 }
1095 }
1096
dan sinclair946858a2022-12-08 22:21:24 +00001097 bool brackets = type->IsAnyOf<type::Array, sem::Struct>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001098
dan sinclair41e4d9a2022-05-01 14:40:55 +00001099 // For single-value vector initializers, swizzle the scalar to the right
1100 // vector dimension using .x
1101 const bool is_single_value_vector_init = type->is_scalar_vector() &&
Ben Clayton958a4642022-07-26 07:55:24 +00001102 call->Arguments().Length() == 1 &&
dan sinclair41e4d9a2022-05-01 14:40:55 +00001103 ctor->Parameters()[0]->Type()->is_scalar();
1104
Ben Clayton6c098ba2022-07-14 20:46:39 +00001105 if (brackets) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001106 out << "{";
1107 } else {
dan sinclair2a651632023-02-19 04:03:55 +00001108 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
1109 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001110 return false;
1111 }
1112 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001113 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001114
dan sinclair41e4d9a2022-05-01 14:40:55 +00001115 if (is_single_value_vector_init) {
1116 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001117 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001118
dan sinclair41e4d9a2022-05-01 14:40:55 +00001119 bool first = true;
1120 for (auto* e : call->Arguments()) {
1121 if (!first) {
1122 out << ", ";
1123 }
1124 first = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001125
dan sinclair41e4d9a2022-05-01 14:40:55 +00001126 if (!EmitExpression(out, e->Declaration())) {
1127 return false;
1128 }
1129 }
1130
1131 if (is_single_value_vector_init) {
dan sinclair0e780da2022-12-08 22:21:24 +00001132 out << ")." << std::string(type->As<type::Vector>()->Width(), 'x');
dan sinclair41e4d9a2022-05-01 14:40:55 +00001133 }
1134
1135 out << (brackets ? "}" : ")");
1136 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001137}
1138
1139bool GeneratorImpl::EmitUniformBufferAccess(
dan sinclair2b9d5b32023-02-28 14:49:25 +00001140 utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001141 const ast::CallExpression* expr,
1142 const transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
Ben Clayton63d0fab2023-03-06 15:43:16 +00001143 auto const buffer = program_->Symbols().NameFor(intrinsic->Buffer()->identifier->symbol);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001144 auto* const offset = expr->args[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001145
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001146 // offset in bytes
1147 uint32_t scalar_offset_bytes = 0;
1148 // offset in uint (4 bytes)
1149 uint32_t scalar_offset_index = 0;
1150 // expression to calculate offset in bytes
1151 std::string scalar_offset_bytes_expr;
1152 // expression to calculate offset in uint, by dividing scalar_offset_bytes_expr by 4
1153 std::string scalar_offset_index_expr;
1154 // expression to calculate offset in uint, independently
1155 std::string scalar_offset_index_unified_expr;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001156
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001157 // If true, use scalar_offset_index, otherwise use scalar_offset_index_expr
dan sinclair41e4d9a2022-05-01 14:40:55 +00001158 bool scalar_offset_constant = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001159
Ben Clayton1a1b5272023-02-24 17:16:55 +00001160 if (auto* val = builder_.Sem().GetVal(offset)->ConstantValue()) {
dan sinclaird37ecf92022-12-08 16:39:59 +00001161 TINT_ASSERT(Writer, val->Type()->Is<type::U32>());
dan sinclairb53b8cf2022-12-15 16:25:31 +00001162 scalar_offset_bytes = static_cast<uint32_t>(val->ValueAs<AInt>());
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001163 scalar_offset_index = scalar_offset_bytes / 4; // bytes -> scalar index
dan sinclair41e4d9a2022-05-01 14:40:55 +00001164 scalar_offset_constant = true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001165 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001166
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001167 // If true, scalar_offset_bytes or scalar_offset_bytes_expr should be used, otherwise only use
1168 // scalar_offset_index or scalar_offset_index_unified_expr. Currently only loading f16 scalar
1169 // require using offset in bytes.
1170 const bool need_offset_in_bytes =
1171 intrinsic->type == transform::DecomposeMemoryAccess::Intrinsic::DataType::kF16;
1172
dan sinclair41e4d9a2022-05-01 14:40:55 +00001173 if (!scalar_offset_constant) {
1174 // UBO offset not compile-time known.
1175 // Calculate the scalar offset into a temporary.
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001176 if (need_offset_in_bytes) {
1177 scalar_offset_bytes_expr = UniqueIdentifier("scalar_offset_bytes");
1178 scalar_offset_index_expr = UniqueIdentifier("scalar_offset_index");
1179 {
1180 auto pre = line();
1181 pre << "const uint " << scalar_offset_bytes_expr << " = (";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001182 if (!EmitExpression(pre, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001183 return false;
1184 }
1185 pre << ");";
1186 }
1187 line() << "const uint " << scalar_offset_index_expr << " = " << scalar_offset_bytes_expr
1188 << " / 4;";
1189 } else {
1190 scalar_offset_index_unified_expr = UniqueIdentifier("scalar_offset");
1191 auto pre = line();
1192 pre << "const uint " << scalar_offset_index_unified_expr << " = (";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001193 if (!EmitExpression(pre, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001194 return false;
1195 }
1196 pre << ") / 4;";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001197 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001198 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001199
Austin Enga0e96b52023-02-18 00:39:01 +00001200 const char swizzle[] = {'x', 'y', 'z', 'w'};
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001201
dan sinclair41e4d9a2022-05-01 14:40:55 +00001202 using Op = transform::DecomposeMemoryAccess::Intrinsic::Op;
1203 using DataType = transform::DecomposeMemoryAccess::Intrinsic::DataType;
1204 switch (intrinsic->op) {
1205 case Op::kLoad: {
1206 auto cast = [&](const char* to, auto&& load) {
1207 out << to << "(";
1208 auto result = load();
1209 out << ")";
1210 return result;
1211 };
dan sinclair2b9d5b32023-02-28 14:49:25 +00001212 auto load_u32_to = [&](utils::StringStream& target) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001213 target << buffer;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001214 if (scalar_offset_constant) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001215 target << "[" << (scalar_offset_index / 4) << "]."
1216 << swizzle[scalar_offset_index & 3];
dan sinclair41e4d9a2022-05-01 14:40:55 +00001217 } else {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001218 target << "[" << scalar_offset_index_unified_expr << " / 4]["
1219 << scalar_offset_index_unified_expr << " % 4]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001220 }
1221 return true;
1222 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001223 auto load_u32 = [&] { return load_u32_to(out); };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001224 // Has a minimum alignment of 8 bytes, so is either .xy or .zw
dan sinclair2b9d5b32023-02-28 14:49:25 +00001225 auto load_vec2_u32_to = [&](utils::StringStream& target) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001226 if (scalar_offset_constant) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001227 target << buffer << "[" << (scalar_offset_index / 4) << "]"
1228 << ((scalar_offset_index & 2) == 0 ? ".xy" : ".zw");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001229 } else {
1230 std::string ubo_load = UniqueIdentifier("ubo_load");
1231 {
1232 auto pre = line();
Ben Clayton1a1b5272023-02-24 17:16:55 +00001233 pre << "uint4 " << ubo_load << " = " << buffer << "["
1234 << scalar_offset_index_unified_expr << " / 4];";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001235 }
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001236 target << "((" << scalar_offset_index_unified_expr << " & 2) ? " << ubo_load
1237 << ".zw : " << ubo_load << ".xy)";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001238 }
1239 return true;
1240 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001241 auto load_vec2_u32 = [&] { return load_vec2_u32_to(out); };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001242 // vec4 has a minimum alignment of 16 bytes, easiest case
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001243 auto load_vec4_u32 = [&] {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001244 out << buffer;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001245 if (scalar_offset_constant) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001246 out << "[" << (scalar_offset_index / 4) << "]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001247 } else {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001248 out << "[" << scalar_offset_index_unified_expr << " / 4]";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001249 }
1250 return true;
1251 };
1252 // vec3 has a minimum alignment of 16 bytes, so is just a .xyz swizzle
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001253 auto load_vec3_u32 = [&] {
1254 if (!load_vec4_u32()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001255 return false;
1256 }
1257 out << ".xyz";
1258 return true;
1259 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001260 auto load_scalar_f16 = [&] {
1261 // offset bytes = 4k, ((buffer[index].x) & 0xFFFF)
1262 // offset bytes = 4k+2, ((buffer[index].x >> 16) & 0xFFFF)
Ben Clayton1a1b5272023-02-24 17:16:55 +00001263 out << "float16_t(f16tof32(((" << buffer;
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001264 if (scalar_offset_constant) {
1265 out << "[" << (scalar_offset_index / 4) << "]."
1266 << swizzle[scalar_offset_index & 3];
1267 // WGSL spec ensure little endian memory layout.
1268 if (scalar_offset_bytes % 4 == 0) {
1269 out << ") & 0xFFFF)";
1270 } else {
1271 out << " >> 16) & 0xFFFF)";
1272 }
1273 } else {
1274 out << "[" << scalar_offset_index_expr << " / 4][" << scalar_offset_index_expr
1275 << " % 4] >> (" << scalar_offset_bytes_expr
1276 << " % 4 == 0 ? 0 : 16)) & 0xFFFF)";
1277 }
1278 out << "))";
1279 return true;
1280 };
1281 auto load_vec2_f16 = [&] {
1282 // vec2<f16> is aligned to 4 bytes
1283 // Preclude code load the vec2<f16> data as a uint:
1284 // uint ubo_load = buffer[id0][id1];
1285 // Loading code convert it to vec2<f16>:
1286 // vector<float16_t, 2>(float16_t(f16tof32(ubo_load & 0xFFFF)),
1287 // float16_t(f16tof32(ubo_load >> 16)))
1288 std::string ubo_load = UniqueIdentifier("ubo_load");
1289 {
1290 auto pre = line();
1291 // Load the 4 bytes f16 vector as an uint
1292 pre << "uint " << ubo_load << " = ";
1293 if (!load_u32_to(pre)) {
1294 return false;
1295 }
1296 pre << ";";
1297 }
1298 out << "vector<float16_t, 2>(float16_t(f16tof32(" << ubo_load
1299 << " & 0xFFFF)), float16_t(f16tof32(" << ubo_load << " >> 16)))";
1300 return true;
1301 };
1302 auto load_vec3_f16 = [&] {
1303 // vec3<f16> is aligned to 8 bytes
1304 // Preclude code load the vec3<f16> data as uint2 and convert its elements to
1305 // float16_t:
1306 // uint2 ubo_load = buffer[id0].xy;
1307 // /* The low 8 bits of two uint are the x and z elements of vec3<f16> */
1308 // vector<float16_t> ubo_load_xz = vector<float16_t, 2>(f16tof32(ubo_load &
1309 // 0xFFFF));
1310 // /* The high 8 bits of first uint is the y element of vec3<f16> */
1311 // float16_t ubo_load_y = f16tof32(ubo_load[0] >> 16);
1312 // Loading code convert it to vec3<f16>:
1313 // vector<float16_t, 3>(ubo_load_xz[0], ubo_load_y, ubo_load_xz[1])
1314 std::string ubo_load = UniqueIdentifier("ubo_load");
1315 std::string ubo_load_xz = UniqueIdentifier(ubo_load + "_xz");
1316 std::string ubo_load_y = UniqueIdentifier(ubo_load + "_y");
1317 {
1318 auto pre = line();
1319 // Load the 8 bytes uint2 with the f16 vector at lower 6 bytes
1320 pre << "uint2 " << ubo_load << " = ";
1321 if (!load_vec2_u32_to(pre)) {
1322 return false;
1323 }
1324 pre << ";";
1325 }
1326 {
1327 auto pre = line();
1328 pre << "vector<float16_t, 2> " << ubo_load_xz
1329 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " & 0xFFFF));";
1330 }
1331 {
1332 auto pre = line();
1333 pre << "float16_t " << ubo_load_y << " = f16tof32(" << ubo_load
1334 << "[0] >> 16);";
1335 }
1336 out << "vector<float16_t, 3>(" << ubo_load_xz << "[0], " << ubo_load_y << ", "
1337 << ubo_load_xz << "[1])";
1338 return true;
1339 };
1340 auto load_vec4_f16 = [&] {
1341 // vec4<f16> is aligned to 8 bytes
1342 // Preclude code load the vec4<f16> data as uint2 and convert its elements to
1343 // float16_t:
1344 // uint2 ubo_load = buffer[id0].xy;
1345 // /* The low 8 bits of two uint are the x and z elements of vec4<f16> */
1346 // vector<float16_t> ubo_load_xz = vector<float16_t, 2>(f16tof32(ubo_load &
1347 // 0xFFFF));
1348 // /* The high 8 bits of two uint are the y and w elements of vec4<f16> */
1349 // vector<float16_t, 2> ubo_load_yw = vector<float16_t, 2>(f16tof32(ubo_load >>
1350 // 16));
1351 // Loading code convert it to vec4<f16>:
1352 // vector<float16_t, 4>(ubo_load_xz[0], ubo_load_yw[0], ubo_load_xz[1],
1353 // ubo_load_yw[1])
1354 std::string ubo_load = UniqueIdentifier("ubo_load");
1355 std::string ubo_load_xz = UniqueIdentifier(ubo_load + "_xz");
1356 std::string ubo_load_yw = UniqueIdentifier(ubo_load + "_yw");
1357 {
1358 auto pre = line();
1359 // Load the 8 bytes f16 vector as an uint2
1360 pre << "uint2 " << ubo_load << " = ";
1361 if (!load_vec2_u32_to(pre)) {
1362 return false;
1363 }
1364 pre << ";";
1365 }
1366 {
1367 auto pre = line();
1368 pre << "vector<float16_t, 2> " << ubo_load_xz
1369 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " & 0xFFFF));";
1370 }
1371 {
1372 auto pre = line();
1373 pre << "vector<float16_t, 2> " << ubo_load_yw
1374 << " = vector<float16_t, 2>(f16tof32(" << ubo_load << " >> 16));";
1375 }
1376 out << "vector<float16_t, 4>(" << ubo_load_xz << "[0], " << ubo_load_yw << "[0], "
1377 << ubo_load_xz << "[1], " << ubo_load_yw << "[1])";
1378 return true;
1379 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001380 switch (intrinsic->type) {
1381 case DataType::kU32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001382 return load_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001383 case DataType::kF32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001384 return cast("asfloat", load_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001385 case DataType::kI32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001386 return cast("asint", load_u32);
1387 case DataType::kF16:
1388 return load_scalar_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001389 case DataType::kVec2U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001390 return load_vec2_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001391 case DataType::kVec2F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001392 return cast("asfloat", load_vec2_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001393 case DataType::kVec2I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001394 return cast("asint", load_vec2_u32);
1395 case DataType::kVec2F16:
1396 return load_vec2_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001397 case DataType::kVec3U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001398 return load_vec3_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001399 case DataType::kVec3F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001400 return cast("asfloat", load_vec3_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001401 case DataType::kVec3I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001402 return cast("asint", load_vec3_u32);
1403 case DataType::kVec3F16:
1404 return load_vec3_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001405 case DataType::kVec4U32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001406 return load_vec4_u32();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001407 case DataType::kVec4F32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001408 return cast("asfloat", load_vec4_u32);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001409 case DataType::kVec4I32:
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001410 return cast("asint", load_vec4_u32);
1411 case DataType::kVec4F16:
1412 return load_vec4_f16();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001413 }
1414 TINT_UNREACHABLE(Writer, diagnostics_)
1415 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1416 << static_cast<int>(intrinsic->type);
1417 return false;
1418 }
1419 default:
1420 break;
1421 }
1422 TINT_UNREACHABLE(Writer, diagnostics_)
1423 << "unsupported DecomposeMemoryAccess::Intrinsic::Op: " << static_cast<int>(intrinsic->op);
1424 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001425}
1426
1427bool GeneratorImpl::EmitStorageBufferAccess(
dan sinclair2b9d5b32023-02-28 14:49:25 +00001428 utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001429 const ast::CallExpression* expr,
1430 const transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
Ben Clayton63d0fab2023-03-06 15:43:16 +00001431 auto const buffer = program_->Symbols().NameFor(intrinsic->Buffer()->identifier->symbol);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001432 auto* const offset = expr->args[0];
1433 auto* const value = expr->args[1];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001434
dan sinclair41e4d9a2022-05-01 14:40:55 +00001435 using Op = transform::DecomposeMemoryAccess::Intrinsic::Op;
1436 using DataType = transform::DecomposeMemoryAccess::Intrinsic::DataType;
1437 switch (intrinsic->op) {
1438 case Op::kLoad: {
1439 auto load = [&](const char* cast, int n) {
1440 if (cast) {
1441 out << cast << "(";
1442 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001443 out << buffer << ".Load";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001444 if (n > 1) {
1445 out << n;
1446 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00001447 ScopedParen sp(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001448 if (!EmitExpression(out, offset)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001449 return false;
1450 }
1451 if (cast) {
1452 out << ")";
1453 }
1454 return true;
1455 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001456 // Templated load used for f16 types, requires SM6.2 or higher and DXC
1457 // Used by loading f16 types, e.g. for f16 type, set type parameter to "float16_t"
1458 // to emit `buffer.Load<float16_t>(offset)`.
1459 auto templated_load = [&](const char* type) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001460 out << buffer << ".Load<" << type << ">"; // templated load
dan sinclairb2ba57b2023-02-28 15:14:09 +00001461 ScopedParen sp(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001462 if (!EmitExpression(out, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001463 return false;
1464 }
1465 return true;
1466 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001467 switch (intrinsic->type) {
1468 case DataType::kU32:
1469 return load(nullptr, 1);
1470 case DataType::kF32:
1471 return load("asfloat", 1);
1472 case DataType::kI32:
1473 return load("asint", 1);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001474 case DataType::kF16:
1475 return templated_load("float16_t");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001476 case DataType::kVec2U32:
1477 return load(nullptr, 2);
1478 case DataType::kVec2F32:
1479 return load("asfloat", 2);
1480 case DataType::kVec2I32:
1481 return load("asint", 2);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001482 case DataType::kVec2F16:
1483 return templated_load("vector<float16_t, 2> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001484 case DataType::kVec3U32:
1485 return load(nullptr, 3);
1486 case DataType::kVec3F32:
1487 return load("asfloat", 3);
1488 case DataType::kVec3I32:
1489 return load("asint", 3);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001490 case DataType::kVec3F16:
1491 return templated_load("vector<float16_t, 3> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001492 case DataType::kVec4U32:
1493 return load(nullptr, 4);
1494 case DataType::kVec4F32:
1495 return load("asfloat", 4);
1496 case DataType::kVec4I32:
1497 return load("asint", 4);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001498 case DataType::kVec4F16:
1499 return templated_load("vector<float16_t, 4> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001500 }
1501 TINT_UNREACHABLE(Writer, diagnostics_)
1502 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1503 << static_cast<int>(intrinsic->type);
1504 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001505 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001506
1507 case Op::kStore: {
1508 auto store = [&](int n) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001509 out << buffer << ".Store";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001510 if (n > 1) {
1511 out << n;
1512 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00001513 ScopedParen sp1(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001514 if (!EmitExpression(out, offset)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001515 return false;
1516 }
1517 out << ", asuint";
dan sinclairb2ba57b2023-02-28 15:14:09 +00001518 ScopedParen sp2(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001519 if (!EmitExpression(out, value)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001520 return false;
1521 }
1522 return true;
1523 };
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001524 // Templated stored used for f16 types, requires SM6.2 or higher and DXC
1525 // Used by storing f16 types, e.g. for f16 type, set type parameter to "float16_t"
1526 // to emit `buffer.Store<float16_t>(offset)`.
1527 auto templated_store = [&](const char* type) {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001528 out << buffer << ".Store<" << type << ">"; // templated store
dan sinclairb2ba57b2023-02-28 15:14:09 +00001529 ScopedParen sp1(out);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001530 if (!EmitExpression(out, offset)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001531 return false;
1532 }
1533 out << ", ";
Ben Clayton1a1b5272023-02-24 17:16:55 +00001534 if (!EmitExpression(out, value)) {
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001535 return false;
1536 }
1537 return true;
1538 };
dan sinclair41e4d9a2022-05-01 14:40:55 +00001539 switch (intrinsic->type) {
1540 case DataType::kU32:
1541 return store(1);
1542 case DataType::kF32:
1543 return store(1);
1544 case DataType::kI32:
1545 return store(1);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001546 case DataType::kF16:
1547 return templated_store("float16_t");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001548 case DataType::kVec2U32:
1549 return store(2);
1550 case DataType::kVec2F32:
1551 return store(2);
1552 case DataType::kVec2I32:
1553 return store(2);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001554 case DataType::kVec2F16:
1555 return templated_store("vector<float16_t, 2> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001556 case DataType::kVec3U32:
1557 return store(3);
1558 case DataType::kVec3F32:
1559 return store(3);
1560 case DataType::kVec3I32:
1561 return store(3);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001562 case DataType::kVec3F16:
1563 return templated_store("vector<float16_t, 3> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001564 case DataType::kVec4U32:
1565 return store(4);
1566 case DataType::kVec4F32:
1567 return store(4);
1568 case DataType::kVec4I32:
1569 return store(4);
Zhaoming Jiangab9b5f32022-11-24 05:25:35 +00001570 case DataType::kVec4F16:
1571 return templated_store("vector<float16_t, 4> ");
dan sinclair41e4d9a2022-05-01 14:40:55 +00001572 }
1573 TINT_UNREACHABLE(Writer, diagnostics_)
1574 << "unsupported DecomposeMemoryAccess::Intrinsic::DataType: "
1575 << static_cast<int>(intrinsic->type);
1576 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001577 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001578 default:
Ben Clayton1a1b5272023-02-24 17:16:55 +00001579 // Break out to error case below
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001580 // Note that atomic intrinsics are generated as functions.
1581 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001582 }
1583
dan sinclair41e4d9a2022-05-01 14:40:55 +00001584 TINT_UNREACHABLE(Writer, diagnostics_)
1585 << "unsupported DecomposeMemoryAccess::Intrinsic::Op: " << static_cast<int>(intrinsic->op);
1586 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001587}
1588
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001589bool GeneratorImpl::EmitStorageAtomicIntrinsic(
1590 const ast::Function* func,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001591 const transform::DecomposeMemoryAccess::Intrinsic* intrinsic) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001592 using Op = transform::DecomposeMemoryAccess::Intrinsic::Op;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001593
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001594 const sem::Function* sem_func = builder_.Sem().Get(func);
1595 auto* result_ty = sem_func->ReturnType();
Ben Claytonce31d182023-02-09 10:34:14 +00001596 const auto name = builder_.Symbols().NameFor(func->name->symbol);
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001597 auto& buf = *current_buffer_;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001598
Ben Clayton63d0fab2023-03-06 15:43:16 +00001599 auto const buffer = program_->Symbols().NameFor(intrinsic->Buffer()->identifier->symbol);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001600
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001601 auto rmw = [&](const char* hlsl) -> bool {
1602 {
1603 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001604 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001605 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001606 return false;
1607 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001608 fn << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001609 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001610 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001611 return false;
1612 }
1613 fn << ") {";
1614 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001615
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001616 buf.IncrementIndent();
1617 TINT_DEFER({
1618 buf.DecrementIndent();
1619 line(&buf) << "}";
1620 line(&buf);
1621 });
1622
1623 {
1624 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001625 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001626 builtin::Access::kUndefined, "original_value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001627 return false;
1628 }
1629 l << " = 0;";
1630 }
1631 {
1632 auto l = line(&buf);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001633 l << buffer << "." << hlsl << "(offset, ";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001634 if (intrinsic->op == Op::kAtomicSub) {
1635 l << "-";
1636 }
1637 l << "value, original_value);";
1638 }
1639 line(&buf) << "return original_value;";
1640 return true;
1641 };
1642
1643 switch (intrinsic->op) {
1644 case Op::kAtomicAdd:
1645 return rmw("InterlockedAdd");
1646
1647 case Op::kAtomicSub:
1648 // Use add with the operand negated.
1649 return rmw("InterlockedAdd");
1650
1651 case Op::kAtomicMax:
1652 return rmw("InterlockedMax");
1653
1654 case Op::kAtomicMin:
1655 return rmw("InterlockedMin");
1656
1657 case Op::kAtomicAnd:
1658 return rmw("InterlockedAnd");
1659
1660 case Op::kAtomicOr:
1661 return rmw("InterlockedOr");
1662
1663 case Op::kAtomicXor:
1664 return rmw("InterlockedXor");
1665
1666 case Op::kAtomicExchange:
1667 return rmw("InterlockedExchange");
1668
1669 case Op::kAtomicLoad: {
1670 // HLSL does not have an InterlockedLoad, so we emulate it with
1671 // InterlockedOr using 0 as the OR value
dan sinclair41e4d9a2022-05-01 14:40:55 +00001672 {
1673 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001674 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001675 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001676 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001677 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001678 fn << "(uint offset) {";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001679 }
1680
1681 buf.IncrementIndent();
1682 TINT_DEFER({
1683 buf.DecrementIndent();
1684 line(&buf) << "}";
1685 line(&buf);
1686 });
1687
1688 {
1689 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001690 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001691 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001692 return false;
1693 }
1694 l << " = 0;";
1695 }
1696
Ben Clayton1a1b5272023-02-24 17:16:55 +00001697 line(&buf) << buffer << ".InterlockedOr(offset, 0, value);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001698 line(&buf) << "return value;";
1699 return true;
1700 }
1701 case Op::kAtomicStore: {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001702 auto* const value_ty = sem_func->Parameters()[1]->Type()->UnwrapRef();
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001703 // HLSL does not have an InterlockedStore, so we emulate it with
1704 // InterlockedExchange and discard the returned value
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001705 {
1706 auto fn = line(&buf);
Ben Clayton1a1b5272023-02-24 17:16:55 +00001707 fn << "void " << name << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001708 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001709 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001710 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001711 }
1712 fn << ") {";
1713 }
1714
1715 buf.IncrementIndent();
1716 TINT_DEFER({
1717 buf.DecrementIndent();
1718 line(&buf) << "}";
1719 line(&buf);
1720 });
1721
1722 {
1723 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001724 if (!EmitTypeAndName(l, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001725 builtin::Access::kUndefined, "ignored")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001726 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001727 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001728 l << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001729 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001730 line(&buf) << buffer << ".InterlockedExchange(offset, value, ignored);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001731 return true;
1732 }
1733 case Op::kAtomicCompareExchangeWeak: {
Ben Clayton1a1b5272023-02-24 17:16:55 +00001734 auto* const value_ty = sem_func->Parameters()[1]->Type()->UnwrapRef();
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001735 // NOTE: We don't need to emit the return type struct here as DecomposeMemoryAccess
1736 // already added it to the AST, and it should have already been emitted by now.
dan sinclair41e4d9a2022-05-01 14:40:55 +00001737 {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001738 auto fn = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001739 if (!EmitTypeAndName(fn, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001740 builtin::Access::kUndefined, name)) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001741 return false;
1742 }
Ben Clayton1a1b5272023-02-24 17:16:55 +00001743 fn << "(uint offset, ";
dan sinclair2a651632023-02-19 04:03:55 +00001744 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001745 builtin::Access::kUndefined, "compare")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001746 return false;
1747 }
1748 fn << ", ";
dan sinclair2a651632023-02-19 04:03:55 +00001749 if (!EmitTypeAndName(fn, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001750 builtin::Access::kUndefined, "value")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001751 return false;
1752 }
1753 fn << ") {";
1754 }
1755
1756 buf.IncrementIndent();
1757 TINT_DEFER({
1758 buf.DecrementIndent();
1759 line(&buf) << "}";
1760 line(&buf);
1761 });
1762
1763 { // T result = {0};
dan sinclair41e4d9a2022-05-01 14:40:55 +00001764 auto l = line(&buf);
dan sinclair2a651632023-02-19 04:03:55 +00001765 if (!EmitTypeAndName(l, result_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001766 builtin::Access::kUndefined, "result")) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001767 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00001768 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001769 l << "=";
1770 if (!EmitZeroValue(l, result_ty)) {
1771 return false;
1772 }
1773 l << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001774 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001775
Ben Clayton1a1b5272023-02-24 17:16:55 +00001776 line(&buf) << buffer
1777 << ".InterlockedCompareExchange(offset, compare, value, result.old_value);";
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001778 line(&buf) << "result.exchanged = result.old_value == compare;";
1779 line(&buf) << "return result;";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001780
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001781 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001782 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001783 default:
1784 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001785 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001786
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001787 TINT_UNREACHABLE(Writer, diagnostics_)
1788 << "unsupported atomic DecomposeMemoryAccess::Intrinsic::Op: "
1789 << static_cast<int>(intrinsic->op);
1790 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001791}
1792
dan sinclair2b9d5b32023-02-28 14:49:25 +00001793bool GeneratorImpl::EmitWorkgroupAtomicCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001794 const ast::CallExpression* expr,
1795 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001796 std::string result = UniqueIdentifier("atomic_result");
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001797
dan sinclaird37ecf92022-12-08 16:39:59 +00001798 if (!builtin->ReturnType()->Is<type::Void>()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001799 auto pre = line();
dan sinclair2a651632023-02-19 04:03:55 +00001800 if (!EmitTypeAndName(pre, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001801 builtin::Access::kUndefined, result)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001802 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001803 }
1804 pre << " = ";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001805 if (!EmitZeroValue(pre, builtin->ReturnType())) {
1806 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001807 }
1808 pre << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001809 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001810
dan sinclair41e4d9a2022-05-01 14:40:55 +00001811 auto call = [&](const char* name) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001812 auto pre = line();
dan sinclair41e4d9a2022-05-01 14:40:55 +00001813 pre << name;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001814
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001815 {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001816 ScopedParen sp(pre);
Ben Clayton783b1692022-08-02 17:03:35 +00001817 for (size_t i = 0; i < expr->args.Length(); i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001818 auto* arg = expr->args[i];
1819 if (i > 0) {
1820 pre << ", ";
1821 }
dan sinclair9543f742023-03-09 01:20:16 +00001822 if (i == 1 && builtin->Type() == builtin::Function::kAtomicSub) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001823 // Sub uses InterlockedAdd with the operand negated.
1824 pre << "-";
1825 }
1826 if (!EmitExpression(pre, arg)) {
1827 return false;
1828 }
1829 }
1830
1831 pre << ", " << result;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001832 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00001833
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001834 pre << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001835
dan sinclair41e4d9a2022-05-01 14:40:55 +00001836 out << result;
1837 return true;
1838 };
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001839
dan sinclair41e4d9a2022-05-01 14:40:55 +00001840 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00001841 case builtin::Function::kAtomicLoad: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001842 // HLSL does not have an InterlockedLoad, so we emulate it with
1843 // InterlockedOr using 0 as the OR value
1844 auto pre = line();
1845 pre << "InterlockedOr";
1846 {
1847 ScopedParen sp(pre);
1848 if (!EmitExpression(pre, expr->args[0])) {
1849 return false;
1850 }
1851 pre << ", 0, " << result;
1852 }
1853 pre << ";";
1854
1855 out << result;
1856 return true;
1857 }
dan sinclair9543f742023-03-09 01:20:16 +00001858 case builtin::Function::kAtomicStore: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001859 // HLSL does not have an InterlockedStore, so we emulate it with
1860 // InterlockedExchange and discard the returned value
1861 { // T result = 0;
1862 auto pre = line();
1863 auto* value_ty = builtin->Parameters()[1]->Type()->UnwrapRef();
dan sinclair2a651632023-02-19 04:03:55 +00001864 if (!EmitTypeAndName(pre, value_ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00001865 builtin::Access::kUndefined, result)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001866 return false;
1867 }
1868 pre << " = ";
1869 if (!EmitZeroValue(pre, value_ty)) {
1870 return false;
1871 }
1872 pre << ";";
1873 }
1874
1875 out << "InterlockedExchange";
1876 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00001877 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001878 if (!EmitExpression(out, expr->args[0])) {
1879 return false;
1880 }
1881 out << ", ";
1882 if (!EmitExpression(out, expr->args[1])) {
1883 return false;
1884 }
1885 out << ", " << result;
1886 }
1887 return true;
1888 }
dan sinclair9543f742023-03-09 01:20:16 +00001889 case builtin::Function::kAtomicCompareExchangeWeak: {
Ben Clayton329dfd72022-11-23 00:05:05 +00001890 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<sem::Struct>())) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001891 return false;
1892 }
1893
dan sinclair41e4d9a2022-05-01 14:40:55 +00001894 auto* dest = expr->args[0];
1895 auto* compare_value = expr->args[1];
1896 auto* value = expr->args[2];
1897
1898 std::string compare = UniqueIdentifier("atomic_compare_value");
1899
1900 { // T compare_value = <compare_value>;
1901 auto pre = line();
Antonio Maioranof99671b2022-06-23 13:14:54 +00001902 if (!EmitTypeAndName(pre, TypeOf(compare_value)->UnwrapRef(),
dan sinclair2a651632023-02-19 04:03:55 +00001903 builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclair61c16eb2023-01-21 23:44:38 +00001904 compare)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001905 return false;
1906 }
1907 pre << " = ";
1908 if (!EmitExpression(pre, compare_value)) {
1909 return false;
1910 }
1911 pre << ";";
1912 }
1913
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001914 { // InterlockedCompareExchange(dst, compare, value, result.old_value);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001915 auto pre = line();
1916 pre << "InterlockedCompareExchange";
1917 {
1918 ScopedParen sp(pre);
1919 if (!EmitExpression(pre, dest)) {
1920 return false;
1921 }
1922 pre << ", " << compare << ", ";
1923 if (!EmitExpression(pre, value)) {
1924 return false;
1925 }
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001926 pre << ", " << result << ".old_value";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001927 }
1928 pre << ";";
1929 }
1930
Antonio Maiorano08f4b552022-05-31 13:20:28 +00001931 // result.exchanged = result.old_value == compare;
1932 line() << result << ".exchanged = " << result << ".old_value == " << compare << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00001933
1934 out << result;
1935 return true;
1936 }
1937
dan sinclair9543f742023-03-09 01:20:16 +00001938 case builtin::Function::kAtomicAdd:
1939 case builtin::Function::kAtomicSub:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001940 return call("InterlockedAdd");
1941
dan sinclair9543f742023-03-09 01:20:16 +00001942 case builtin::Function::kAtomicMax:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001943 return call("InterlockedMax");
1944
dan sinclair9543f742023-03-09 01:20:16 +00001945 case builtin::Function::kAtomicMin:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001946 return call("InterlockedMin");
1947
dan sinclair9543f742023-03-09 01:20:16 +00001948 case builtin::Function::kAtomicAnd:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001949 return call("InterlockedAnd");
1950
dan sinclair9543f742023-03-09 01:20:16 +00001951 case builtin::Function::kAtomicOr:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001952 return call("InterlockedOr");
1953
dan sinclair9543f742023-03-09 01:20:16 +00001954 case builtin::Function::kAtomicXor:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001955 return call("InterlockedXor");
1956
dan sinclair9543f742023-03-09 01:20:16 +00001957 case builtin::Function::kAtomicExchange:
dan sinclair41e4d9a2022-05-01 14:40:55 +00001958 return call("InterlockedExchange");
1959
1960 default:
1961 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001962 }
1963
dan sinclair41e4d9a2022-05-01 14:40:55 +00001964 TINT_UNREACHABLE(Writer, diagnostics_) << "unsupported atomic builtin: " << builtin->Type();
1965 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001966}
1967
dan sinclair2b9d5b32023-02-28 14:49:25 +00001968bool GeneratorImpl::EmitSelectCall(utils::StringStream& out, const ast::CallExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001969 auto* expr_false = expr->args[0];
1970 auto* expr_true = expr->args[1];
1971 auto* expr_cond = expr->args[2];
dan sinclairb2ba57b2023-02-28 15:14:09 +00001972 ScopedParen paren(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00001973 if (!EmitExpression(out, expr_cond)) {
1974 return false;
1975 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001976
dan sinclair41e4d9a2022-05-01 14:40:55 +00001977 out << " ? ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001978
dan sinclair41e4d9a2022-05-01 14:40:55 +00001979 if (!EmitExpression(out, expr_true)) {
1980 return false;
1981 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001982
dan sinclair41e4d9a2022-05-01 14:40:55 +00001983 out << " : ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001984
dan sinclair41e4d9a2022-05-01 14:40:55 +00001985 if (!EmitExpression(out, expr_false)) {
1986 return false;
1987 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001988
dan sinclair41e4d9a2022-05-01 14:40:55 +00001989 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001990}
1991
dan sinclair2b9d5b32023-02-28 14:49:25 +00001992bool GeneratorImpl::EmitModfCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001993 const ast::CallExpression* expr,
1994 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00001995 return CallBuiltinHelper(
1996 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
1997 auto* ty = builtin->Parameters()[0]->Type();
1998 auto in = params[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001999
dan sinclair41e4d9a2022-05-01 14:40:55 +00002000 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002001 if (auto* vec = ty->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002002 width = std::to_string(vec->Width());
2003 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002004
dan sinclair41e4d9a2022-05-01 14:40:55 +00002005 // Emit the builtin return type unique to this overload. This does not
2006 // exist in the AST, so it will not be generated in Generate().
2007 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<sem::Struct>())) {
2008 return false;
2009 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002010
dan sinclair41e4d9a2022-05-01 14:40:55 +00002011 {
2012 auto l = line(b);
dan sinclair2a651632023-02-19 04:03:55 +00002013 if (!EmitType(l, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002014 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002015 return false;
2016 }
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002017 l << " result;";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002018 }
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002019 line(b) << "result.fract = modf(" << params[0] << ", result.whole);";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002020 line(b) << "return result;";
2021 return true;
2022 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002023}
2024
dan sinclair2b9d5b32023-02-28 14:49:25 +00002025bool GeneratorImpl::EmitFrexpCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002026 const ast::CallExpression* expr,
2027 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002028 return CallBuiltinHelper(
2029 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2030 auto* ty = builtin->Parameters()[0]->Type();
2031 auto in = params[0];
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002032
dan sinclair41e4d9a2022-05-01 14:40:55 +00002033 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002034 if (auto* vec = ty->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002035 width = std::to_string(vec->Width());
2036 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002037
dan sinclair41e4d9a2022-05-01 14:40:55 +00002038 // Emit the builtin return type unique to this overload. This does not
2039 // exist in the AST, so it will not be generated in Generate().
2040 if (!EmitStructType(&helpers_, builtin->ReturnType()->As<sem::Struct>())) {
2041 return false;
2042 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002043
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002044 std::string member_type;
dan sinclaird37ecf92022-12-08 16:39:59 +00002045 if (Is<type::F16>(type::Type::DeepestElementOf(ty))) {
Zhaoming Jiang20cddbf2022-08-05 15:11:44 +00002046 member_type = width.empty() ? "float16_t" : ("vector<float16_t, " + width + ">");
2047 } else {
2048 member_type = "float" + width;
2049 }
2050
2051 line(b) << member_type << " exp;";
Antonio Maiorano52cd8ca2023-03-16 21:31:15 +00002052 line(b) << member_type << " fract = sign(" << in << ") * frexp(" << in << ", exp);";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002053 {
2054 auto l = line(b);
dan sinclair2a651632023-02-19 04:03:55 +00002055 if (!EmitType(l, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002056 builtin::Access::kUndefined, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002057 return false;
2058 }
Ben Clayton10fae7a2022-11-14 15:29:29 +00002059 l << " result = {fract, int" << width << "(exp)};";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002060 }
2061 line(b) << "return result;";
2062 return true;
2063 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002064}
2065
dan sinclair2b9d5b32023-02-28 14:49:25 +00002066bool GeneratorImpl::EmitDegreesCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002067 const ast::CallExpression* expr,
2068 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002069 return CallBuiltinHelper(out, expr, builtin,
2070 [&](TextBuffer* b, const std::vector<std::string>& params) {
2071 line(b) << "return " << params[0] << " * " << std::setprecision(20)
2072 << sem::kRadToDeg << ";";
2073 return true;
2074 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002075}
2076
dan sinclair2b9d5b32023-02-28 14:49:25 +00002077bool GeneratorImpl::EmitRadiansCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002078 const ast::CallExpression* expr,
2079 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002080 return CallBuiltinHelper(out, expr, builtin,
2081 [&](TextBuffer* b, const std::vector<std::string>& params) {
2082 line(b) << "return " << params[0] << " * " << std::setprecision(20)
2083 << sem::kDegToRad << ";";
2084 return true;
2085 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002086}
2087
dan sinclair70927862023-01-11 13:18:29 +00002088// The HLSL `sign` method always returns an `int` result (scalar or vector). In WGSL the result is
2089// expected to be the same type as the argument. This injects a cast to the expected WGSL result
2090// type after the call to `sign`.
dan sinclair2b9d5b32023-02-28 14:49:25 +00002091bool GeneratorImpl::EmitSignCall(utils::StringStream& out,
2092 const sem::Call* call,
2093 const sem::Builtin*) {
dan sinclair70927862023-01-11 13:18:29 +00002094 auto* arg = call->Arguments()[0];
dan sinclair2a651632023-02-19 04:03:55 +00002095 if (!EmitType(out, arg->Type(), builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002096 "")) {
dan sinclair70927862023-01-11 13:18:29 +00002097 return false;
2098 }
2099 out << "(sign(";
2100 if (!EmitExpression(out, arg->Declaration())) {
2101 return false;
2102 }
2103 out << "))";
2104 return true;
2105}
2106
dan sinclair2b9d5b32023-02-28 14:49:25 +00002107bool GeneratorImpl::EmitQuantizeToF16Call(utils::StringStream& out,
Ben Clayton2bea9052022-11-02 00:09:50 +00002108 const ast::CallExpression* expr,
2109 const sem::Builtin* builtin) {
Antonio Maiorano51249b82023-03-31 08:00:33 +00002110 // Cast to f16 and back
Ben Clayton2bea9052022-11-02 00:09:50 +00002111 std::string width;
dan sinclair0e780da2022-12-08 22:21:24 +00002112 if (auto* vec = builtin->ReturnType()->As<type::Vector>()) {
Ben Clayton2bea9052022-11-02 00:09:50 +00002113 width = std::to_string(vec->Width());
2114 }
Antonio Maiorano51249b82023-03-31 08:00:33 +00002115 out << "f16tof32(f32tof16"
2116 << "(";
Ben Clayton2bea9052022-11-02 00:09:50 +00002117 if (!EmitExpression(out, expr->args[0])) {
2118 return false;
2119 }
2120 out << "))";
2121 return true;
2122}
2123
Antonio Maiorano5cf943e2023-03-27 18:55:25 +00002124bool GeneratorImpl::EmitTruncCall(utils::StringStream& out,
2125 const ast::CallExpression* expr,
2126 const sem::Builtin* builtin) {
2127 // HLSL's trunc is broken for very large/small float values.
2128 // See crbug.com/tint/1883
2129 return CallBuiltinHelper( //
2130 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2131 // value < 0 ? ceil(value) : floor(value)
2132 line(b) << "return " << params[0] << " < 0 ? ceil(" << params[0] << ") : floor("
2133 << params[0] << ");";
2134 return true;
2135 });
2136}
2137
dan sinclair2b9d5b32023-02-28 14:49:25 +00002138bool GeneratorImpl::EmitDataPackingCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002139 const ast::CallExpression* expr,
2140 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002141 return CallBuiltinHelper(
2142 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2143 uint32_t dims = 2;
2144 bool is_signed = false;
2145 uint32_t scale = 65535;
dan sinclair9543f742023-03-09 01:20:16 +00002146 if (builtin->Type() == builtin::Function::kPack4X8Snorm ||
2147 builtin->Type() == builtin::Function::kPack4X8Unorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002148 dims = 4;
2149 scale = 255;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002150 }
dan sinclair9543f742023-03-09 01:20:16 +00002151 if (builtin->Type() == builtin::Function::kPack4X8Snorm ||
2152 builtin->Type() == builtin::Function::kPack2X16Snorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002153 is_signed = true;
2154 scale = (scale - 1) / 2;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002155 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002156 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002157 case builtin::Function::kPack4X8Snorm:
2158 case builtin::Function::kPack4X8Unorm:
2159 case builtin::Function::kPack2X16Snorm:
2160 case builtin::Function::kPack2X16Unorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002161 {
2162 auto l = line(b);
2163 l << (is_signed ? "" : "u") << "int" << dims
2164 << " i = " << (is_signed ? "" : "u") << "int" << dims << "(round(clamp("
2165 << params[0] << ", " << (is_signed ? "-1.0" : "0.0") << ", 1.0) * "
2166 << scale << ".0))";
2167 if (is_signed) {
2168 l << " & " << (dims == 4 ? "0xff" : "0xffff");
2169 }
2170 l << ";";
2171 }
2172 {
2173 auto l = line(b);
2174 l << "return ";
2175 if (is_signed) {
2176 l << "asuint";
2177 }
2178 l << "(i.x | i.y << " << (32 / dims);
2179 if (dims == 4) {
2180 l << " | i.z << 16 | i.w << 24";
2181 }
2182 l << ");";
2183 }
2184 break;
2185 }
dan sinclair9543f742023-03-09 01:20:16 +00002186 case builtin::Function::kPack2X16Float: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002187 line(b) << "uint2 i = f32tof16(" << params[0] << ");";
2188 line(b) << "return i.x | (i.y << 16);";
2189 break;
2190 }
2191 default:
2192 diagnostics_.add_error(diag::System::Writer,
2193 "Internal error: unhandled data packing builtin");
2194 return false;
2195 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002196
dan sinclair41e4d9a2022-05-01 14:40:55 +00002197 return true;
2198 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002199}
2200
dan sinclair2b9d5b32023-02-28 14:49:25 +00002201bool GeneratorImpl::EmitDataUnpackingCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002202 const ast::CallExpression* expr,
2203 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002204 return CallBuiltinHelper(
2205 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2206 uint32_t dims = 2;
2207 bool is_signed = false;
2208 uint32_t scale = 65535;
dan sinclair9543f742023-03-09 01:20:16 +00002209 if (builtin->Type() == builtin::Function::kUnpack4X8Snorm ||
2210 builtin->Type() == builtin::Function::kUnpack4X8Unorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002211 dims = 4;
2212 scale = 255;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002213 }
dan sinclair9543f742023-03-09 01:20:16 +00002214 if (builtin->Type() == builtin::Function::kUnpack4X8Snorm ||
2215 builtin->Type() == builtin::Function::kUnpack2X16Snorm) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002216 is_signed = true;
2217 scale = (scale - 1) / 2;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002218 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002219 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002220 case builtin::Function::kUnpack4X8Snorm:
2221 case builtin::Function::kUnpack2X16Snorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002222 line(b) << "int j = int(" << params[0] << ");";
2223 { // Perform sign extension on the converted values.
2224 auto l = line(b);
2225 l << "int" << dims << " i = int" << dims << "(";
2226 if (dims == 2) {
2227 l << "j << 16, j) >> 16";
2228 } else {
2229 l << "j << 24, j << 16, j << 8, j) >> 24";
2230 }
2231 l << ";";
2232 }
2233 line(b) << "return clamp(float" << dims << "(i) / " << scale << ".0, "
2234 << (is_signed ? "-1.0" : "0.0") << ", 1.0);";
2235 break;
2236 }
dan sinclair9543f742023-03-09 01:20:16 +00002237 case builtin::Function::kUnpack4X8Unorm:
2238 case builtin::Function::kUnpack2X16Unorm: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002239 line(b) << "uint j = " << params[0] << ";";
2240 {
2241 auto l = line(b);
2242 l << "uint" << dims << " i = uint" << dims << "(";
2243 l << "j & " << (dims == 2 ? "0xffff" : "0xff") << ", ";
2244 if (dims == 4) {
2245 l << "(j >> " << (32 / dims) << ") & 0xff, (j >> 16) & 0xff, j >> 24";
2246 } else {
2247 l << "j >> " << (32 / dims);
2248 }
2249 l << ");";
2250 }
2251 line(b) << "return float" << dims << "(i) / " << scale << ".0;";
2252 break;
2253 }
dan sinclair9543f742023-03-09 01:20:16 +00002254 case builtin::Function::kUnpack2X16Float:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002255 line(b) << "uint i = " << params[0] << ";";
2256 line(b) << "return f16tof32(uint2(i & 0xffff, i >> 16));";
2257 break;
2258 default:
2259 diagnostics_.add_error(diag::System::Writer,
2260 "Internal error: unhandled data packing builtin");
2261 return false;
2262 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002263
dan sinclair41e4d9a2022-05-01 14:40:55 +00002264 return true;
2265 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002266}
2267
dan sinclair2b9d5b32023-02-28 14:49:25 +00002268bool GeneratorImpl::EmitDP4aCall(utils::StringStream& out,
Jiawei Shaoab975702022-05-13 00:09:56 +00002269 const ast::CallExpression* expr,
2270 const sem::Builtin* builtin) {
2271 // TODO(crbug.com/tint/1497): support the polyfill version of DP4a functions.
2272 return CallBuiltinHelper(
2273 out, expr, builtin, [&](TextBuffer* b, const std::vector<std::string>& params) {
2274 std::string functionName;
2275 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002276 case builtin::Function::kDot4I8Packed:
Jiawei Shao1c759212022-05-15 13:53:21 +00002277 line(b) << "int accumulator = 0;";
Jiawei Shaoab975702022-05-13 00:09:56 +00002278 functionName = "dot4add_i8packed";
2279 break;
dan sinclair9543f742023-03-09 01:20:16 +00002280 case builtin::Function::kDot4U8Packed:
Jiawei Shao1c759212022-05-15 13:53:21 +00002281 line(b) << "uint accumulator = 0u;";
Jiawei Shaoab975702022-05-13 00:09:56 +00002282 functionName = "dot4add_u8packed";
2283 break;
2284 default:
2285 diagnostics_.add_error(diag::System::Writer,
2286 "Internal error: unhandled DP4a builtin");
2287 return false;
2288 }
2289 line(b) << "return " << functionName << "(" << params[0] << ", " << params[1]
Jiawei Shao1c759212022-05-15 13:53:21 +00002290 << ", accumulator);";
Jiawei Shaoab975702022-05-13 00:09:56 +00002291
2292 return true;
2293 });
2294}
2295
dan sinclair2b9d5b32023-02-28 14:49:25 +00002296bool GeneratorImpl::EmitBarrierCall(utils::StringStream& out, const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002297 // TODO(crbug.com/tint/661): Combine sequential barriers to a single
2298 // instruction.
dan sinclair9543f742023-03-09 01:20:16 +00002299 if (builtin->Type() == builtin::Function::kWorkgroupBarrier) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002300 out << "GroupMemoryBarrierWithGroupSync()";
dan sinclair9543f742023-03-09 01:20:16 +00002301 } else if (builtin->Type() == builtin::Function::kStorageBarrier) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002302 out << "DeviceMemoryBarrierWithGroupSync()";
2303 } else {
2304 TINT_UNREACHABLE(Writer, diagnostics_)
dan sinclair9543f742023-03-09 01:20:16 +00002305 << "unexpected barrier builtin type " << builtin::str(builtin->Type());
dan sinclair41e4d9a2022-05-01 14:40:55 +00002306 return false;
2307 }
2308 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002309}
2310
dan sinclair2b9d5b32023-02-28 14:49:25 +00002311bool GeneratorImpl::EmitTextureCall(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002312 const sem::Call* call,
2313 const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002314 using Usage = sem::ParameterUsage;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002315
dan sinclair41e4d9a2022-05-01 14:40:55 +00002316 auto& signature = builtin->Signature();
2317 auto* expr = call->Declaration();
2318 auto arguments = expr->args;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002319
dan sinclair41e4d9a2022-05-01 14:40:55 +00002320 // Returns the argument with the given usage
2321 auto arg = [&](Usage usage) {
2322 int idx = signature.IndexOf(usage);
dan sinclair3a2a2792022-06-29 14:38:15 +00002323 return (idx >= 0) ? arguments[static_cast<size_t>(idx)] : nullptr;
dan sinclair41e4d9a2022-05-01 14:40:55 +00002324 };
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002325
dan sinclair41e4d9a2022-05-01 14:40:55 +00002326 auto* texture = arg(Usage::kTexture);
Ben Clayton884f9522023-01-12 22:52:57 +00002327 if (TINT_UNLIKELY(!texture)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002328 TINT_ICE(Writer, diagnostics_) << "missing texture argument";
2329 return false;
2330 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002331
dan sinclair4595fb72022-12-08 14:14:10 +00002332 auto* texture_type = TypeOf(texture)->UnwrapRef()->As<type::Texture>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002333
dan sinclair41e4d9a2022-05-01 14:40:55 +00002334 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002335 case builtin::Function::kTextureDimensions:
2336 case builtin::Function::kTextureNumLayers:
2337 case builtin::Function::kTextureNumLevels:
2338 case builtin::Function::kTextureNumSamples: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002339 // All of these builtins use the GetDimensions() method on the texture
2340 bool is_ms =
dan sinclair4595fb72022-12-08 14:14:10 +00002341 texture_type->IsAnyOf<type::MultisampledTexture, type::DepthMultisampledTexture>();
dan sinclair41e4d9a2022-05-01 14:40:55 +00002342 int num_dimensions = 0;
2343 std::string swizzle;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002344
dan sinclair41e4d9a2022-05-01 14:40:55 +00002345 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002346 case builtin::Function::kTextureDimensions:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002347 switch (texture_type->dim()) {
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002348 case type::TextureDimension::kNone:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002349 TINT_ICE(Writer, diagnostics_) << "texture dimension is kNone";
2350 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002351 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002352 num_dimensions = 1;
2353 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002354 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002355 num_dimensions = is_ms ? 3 : 2;
2356 swizzle = is_ms ? ".xy" : "";
2357 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002358 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002359 num_dimensions = is_ms ? 4 : 3;
2360 swizzle = ".xy";
2361 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002362 case type::TextureDimension::k3d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002363 num_dimensions = 3;
2364 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002365 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002366 num_dimensions = 2;
2367 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002368 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002369 num_dimensions = 3;
2370 swizzle = ".xy";
2371 break;
2372 }
2373 break;
dan sinclair9543f742023-03-09 01:20:16 +00002374 case builtin::Function::kTextureNumLayers:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002375 switch (texture_type->dim()) {
2376 default:
2377 TINT_ICE(Writer, diagnostics_) << "texture dimension is not arrayed";
2378 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002379 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002380 num_dimensions = is_ms ? 4 : 3;
2381 swizzle = ".z";
2382 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002383 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002384 num_dimensions = 3;
2385 swizzle = ".z";
2386 break;
2387 }
2388 break;
dan sinclair9543f742023-03-09 01:20:16 +00002389 case builtin::Function::kTextureNumLevels:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002390 switch (texture_type->dim()) {
2391 default:
2392 TINT_ICE(Writer, diagnostics_)
2393 << "texture dimension does not support mips";
2394 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002395 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002396 num_dimensions = 2;
2397 swizzle = ".y";
2398 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002399 case type::TextureDimension::k2d:
2400 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002401 num_dimensions = 3;
2402 swizzle = ".z";
2403 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002404 case type::TextureDimension::k2dArray:
2405 case type::TextureDimension::k3d:
2406 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002407 num_dimensions = 4;
2408 swizzle = ".w";
2409 break;
2410 }
2411 break;
dan sinclair9543f742023-03-09 01:20:16 +00002412 case builtin::Function::kTextureNumSamples:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002413 switch (texture_type->dim()) {
2414 default:
2415 TINT_ICE(Writer, diagnostics_)
2416 << "texture dimension does not support multisampling";
2417 return false;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002418 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002419 num_dimensions = 3;
2420 swizzle = ".z";
2421 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00002422 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002423 num_dimensions = 4;
2424 swizzle = ".w";
2425 break;
2426 }
2427 break;
2428 default:
2429 TINT_ICE(Writer, diagnostics_) << "unexpected builtin";
2430 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002431 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002432
2433 auto* level_arg = arg(Usage::kLevel);
2434
2435 if (level_arg) {
2436 // `NumberOfLevels` is a non-optional argument if `MipLevel` was passed.
2437 // Increment the number of dimensions for the temporary vector to
2438 // accommodate this.
2439 num_dimensions++;
2440
2441 // If the swizzle was empty, the expression will evaluate to the whole
2442 // vector. As we've grown the vector by one element, we now need to
2443 // swizzle to keep the result expression equivalent.
2444 if (swizzle.empty()) {
2445 static constexpr const char* swizzles[] = {"", ".x", ".xy", ".xyz"};
2446 swizzle = swizzles[num_dimensions - 1];
2447 }
2448 }
2449
Ben Clayton884f9522023-01-12 22:52:57 +00002450 if (TINT_UNLIKELY(num_dimensions > 4)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002451 TINT_ICE(Writer, diagnostics_) << "Texture query builtin temporary vector has "
2452 << num_dimensions << " dimensions";
2453 return false;
2454 }
2455
2456 // Declare a variable to hold the queried texture info
2457 auto dims = UniqueIdentifier(kTempNamePrefix);
2458 if (num_dimensions == 1) {
Ben Clayton068eb3e2023-03-08 02:48:34 +00002459 line() << "uint " << dims << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002460 } else {
Ben Clayton068eb3e2023-03-08 02:48:34 +00002461 line() << "uint" << num_dimensions << " " << dims << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002462 }
2463
2464 { // texture.GetDimensions(...)
2465 auto pre = line();
2466 if (!EmitExpression(pre, texture)) {
2467 return false;
2468 }
2469 pre << ".GetDimensions(";
2470
2471 if (level_arg) {
2472 if (!EmitExpression(pre, level_arg)) {
2473 return false;
2474 }
2475 pre << ", ";
dan sinclair9543f742023-03-09 01:20:16 +00002476 } else if (builtin->Type() == builtin::Function::kTextureNumLevels) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002477 pre << "0, ";
2478 }
2479
2480 if (num_dimensions == 1) {
2481 pre << dims;
2482 } else {
2483 static constexpr char xyzw[] = {'x', 'y', 'z', 'w'};
Ben Clayton884f9522023-01-12 22:52:57 +00002484 if (TINT_UNLIKELY(num_dimensions < 0 || num_dimensions > 4)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002485 TINT_ICE(Writer, diagnostics_)
2486 << "vector dimensions are " << num_dimensions;
2487 return false;
2488 }
2489 for (int i = 0; i < num_dimensions; i++) {
2490 if (i > 0) {
2491 pre << ", ";
2492 }
2493 pre << dims << "." << xyzw[i];
2494 }
2495 }
2496
2497 pre << ");";
2498 }
2499
2500 // The out parameters of the GetDimensions() call is now in temporary
2501 // `dims` variable. This may be packed with other data, so the final
2502 // expression may require a swizzle.
2503 out << dims << swizzle;
2504 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002505 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002506 default:
2507 break;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002508 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002509
Austin Eng86a617f2022-05-19 20:08:19 +00002510 if (!EmitExpression(out, texture)) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002511 return false;
Austin Eng86a617f2022-05-19 20:08:19 +00002512 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002513
2514 // If pack_level_in_coords is true, then the mip level will be appended as the
2515 // last value of the coordinates argument. If the WGSL builtin overload does
2516 // not have a level parameter and pack_level_in_coords is true, then a zero
2517 // mip level will be inserted.
2518 bool pack_level_in_coords = false;
2519
2520 uint32_t hlsl_ret_width = 4u;
2521
2522 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002523 case builtin::Function::kTextureSample:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002524 out << ".Sample(";
2525 break;
dan sinclair9543f742023-03-09 01:20:16 +00002526 case builtin::Function::kTextureSampleBias:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002527 out << ".SampleBias(";
2528 break;
dan sinclair9543f742023-03-09 01:20:16 +00002529 case builtin::Function::kTextureSampleLevel:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002530 out << ".SampleLevel(";
2531 break;
dan sinclair9543f742023-03-09 01:20:16 +00002532 case builtin::Function::kTextureSampleGrad:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002533 out << ".SampleGrad(";
2534 break;
dan sinclair9543f742023-03-09 01:20:16 +00002535 case builtin::Function::kTextureSampleCompare:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002536 out << ".SampleCmp(";
2537 hlsl_ret_width = 1;
2538 break;
dan sinclair9543f742023-03-09 01:20:16 +00002539 case builtin::Function::kTextureSampleCompareLevel:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002540 out << ".SampleCmpLevelZero(";
2541 hlsl_ret_width = 1;
2542 break;
dan sinclair9543f742023-03-09 01:20:16 +00002543 case builtin::Function::kTextureLoad:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002544 out << ".Load(";
2545 // Multisampled textures do not support mip-levels.
dan sinclair4595fb72022-12-08 14:14:10 +00002546 if (!texture_type->Is<type::MultisampledTexture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002547 pack_level_in_coords = true;
2548 }
2549 break;
dan sinclair9543f742023-03-09 01:20:16 +00002550 case builtin::Function::kTextureGather:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002551 out << ".Gather";
2552 if (builtin->Parameters()[0]->Usage() == sem::ParameterUsage::kComponent) {
dan sinclair5addefb2022-12-14 20:46:32 +00002553 switch (call->Arguments()[0]->ConstantValue()->ValueAs<AInt>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002554 case 0:
2555 out << "Red";
2556 break;
2557 case 1:
2558 out << "Green";
2559 break;
2560 case 2:
2561 out << "Blue";
2562 break;
2563 case 3:
2564 out << "Alpha";
2565 break;
2566 }
2567 }
2568 out << "(";
2569 break;
dan sinclair9543f742023-03-09 01:20:16 +00002570 case builtin::Function::kTextureGatherCompare:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002571 out << ".GatherCmp(";
2572 break;
dan sinclair9543f742023-03-09 01:20:16 +00002573 case builtin::Function::kTextureStore:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002574 out << "[";
2575 break;
2576 default:
2577 diagnostics_.add_error(diag::System::Writer,
2578 "Internal compiler error: Unhandled texture builtin '" +
2579 std::string(builtin->str()) + "'");
2580 return false;
2581 }
2582
2583 if (auto* sampler = arg(Usage::kSampler)) {
Austin Eng86a617f2022-05-19 20:08:19 +00002584 if (!EmitExpression(out, sampler)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002585 return false;
Austin Eng86a617f2022-05-19 20:08:19 +00002586 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002587 out << ", ";
2588 }
2589
2590 auto* param_coords = arg(Usage::kCoords);
Ben Clayton884f9522023-01-12 22:52:57 +00002591 if (TINT_UNLIKELY(!param_coords)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002592 TINT_ICE(Writer, diagnostics_) << "missing coords argument";
2593 return false;
2594 }
2595
2596 auto emit_vector_appended_with_i32_zero = [&](const ast::Expression* vector) {
dan sinclaird37ecf92022-12-08 16:39:59 +00002597 auto* i32 = builder_.create<type::I32>();
Ben Clayton0ce9ab02022-05-05 20:23:40 +00002598 auto* zero = builder_.Expr(0_i);
dan sinclair41e4d9a2022-05-01 14:40:55 +00002599 auto* stmt = builder_.Sem().Get(vector)->Stmt();
Ben Clayton3fb9a3f2023-02-04 21:20:26 +00002600 builder_.Sem().Add(zero, builder_.create<sem::ValueExpression>(
2601 zero, i32, sem::EvaluationStage::kRuntime, stmt,
2602 /* constant_value */ nullptr,
2603 /* has_side_effects */ false));
dan sinclair41e4d9a2022-05-01 14:40:55 +00002604 auto* packed = AppendVector(&builder_, vector, zero);
2605 return EmitExpression(out, packed->Declaration());
2606 };
2607
2608 auto emit_vector_appended_with_level = [&](const ast::Expression* vector) {
2609 if (auto* level = arg(Usage::kLevel)) {
2610 auto* packed = AppendVector(&builder_, vector, level);
2611 return EmitExpression(out, packed->Declaration());
2612 }
2613 return emit_vector_appended_with_i32_zero(vector);
2614 };
2615
2616 if (auto* array_index = arg(Usage::kArrayIndex)) {
2617 // Array index needs to be appended to the coordinates.
2618 auto* packed = AppendVector(&builder_, param_coords, array_index);
2619 if (pack_level_in_coords) {
2620 // Then mip level needs to be appended to the coordinates.
2621 if (!emit_vector_appended_with_level(packed->Declaration())) {
2622 return false;
2623 }
2624 } else {
2625 if (!EmitExpression(out, packed->Declaration())) {
2626 return false;
2627 }
2628 }
2629 } else if (pack_level_in_coords) {
2630 // Mip level needs to be appended to the coordinates.
2631 if (!emit_vector_appended_with_level(param_coords)) {
2632 return false;
2633 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002634 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002635 if (!EmitExpression(out, param_coords)) {
2636 return false;
2637 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002638 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002639
dan sinclair41e4d9a2022-05-01 14:40:55 +00002640 for (auto usage : {Usage::kDepthRef, Usage::kBias, Usage::kLevel, Usage::kDdx, Usage::kDdy,
2641 Usage::kSampleIndex, Usage::kOffset}) {
2642 if (usage == Usage::kLevel && pack_level_in_coords) {
2643 continue; // mip level already packed in coordinates.
2644 }
2645 if (auto* e = arg(usage)) {
2646 out << ", ";
2647 if (!EmitExpression(out, e)) {
2648 return false;
2649 }
2650 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002651 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002652
dan sinclair9543f742023-03-09 01:20:16 +00002653 if (builtin->Type() == builtin::Function::kTextureStore) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002654 out << "] = ";
2655 if (!EmitExpression(out, arg(Usage::kValue))) {
2656 return false;
2657 }
2658 } else {
2659 out << ")";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002660
dan sinclair41e4d9a2022-05-01 14:40:55 +00002661 // If the builtin return type does not match the number of elements of the
2662 // HLSL builtin, we need to swizzle the expression to generate the correct
2663 // number of components.
2664 uint32_t wgsl_ret_width = 1;
dan sinclair0e780da2022-12-08 22:21:24 +00002665 if (auto* vec = builtin->ReturnType()->As<type::Vector>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002666 wgsl_ret_width = vec->Width();
2667 }
2668 if (wgsl_ret_width < hlsl_ret_width) {
2669 out << ".";
2670 for (uint32_t i = 0; i < wgsl_ret_width; i++) {
2671 out << "xyz"[i];
2672 }
2673 }
Ben Clayton884f9522023-01-12 22:52:57 +00002674 if (TINT_UNLIKELY(wgsl_ret_width > hlsl_ret_width)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002675 TINT_ICE(Writer, diagnostics_)
2676 << "WGSL return width (" << wgsl_ret_width << ") is wider than HLSL return width ("
2677 << hlsl_ret_width << ") for " << builtin->Type();
2678 return false;
2679 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002680 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002681
dan sinclair41e4d9a2022-05-01 14:40:55 +00002682 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002683}
2684
2685std::string GeneratorImpl::generate_builtin_name(const sem::Builtin* builtin) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002686 switch (builtin->Type()) {
dan sinclair9543f742023-03-09 01:20:16 +00002687 case builtin::Function::kAbs:
2688 case builtin::Function::kAcos:
2689 case builtin::Function::kAll:
2690 case builtin::Function::kAny:
2691 case builtin::Function::kAsin:
2692 case builtin::Function::kAtan:
2693 case builtin::Function::kAtan2:
2694 case builtin::Function::kCeil:
2695 case builtin::Function::kClamp:
2696 case builtin::Function::kCos:
2697 case builtin::Function::kCosh:
2698 case builtin::Function::kCross:
2699 case builtin::Function::kDeterminant:
2700 case builtin::Function::kDistance:
2701 case builtin::Function::kDot:
2702 case builtin::Function::kExp:
2703 case builtin::Function::kExp2:
2704 case builtin::Function::kFloor:
2705 case builtin::Function::kFrexp:
2706 case builtin::Function::kLdexp:
2707 case builtin::Function::kLength:
2708 case builtin::Function::kLog:
2709 case builtin::Function::kLog2:
2710 case builtin::Function::kMax:
2711 case builtin::Function::kMin:
2712 case builtin::Function::kModf:
2713 case builtin::Function::kNormalize:
2714 case builtin::Function::kPow:
2715 case builtin::Function::kReflect:
2716 case builtin::Function::kRefract:
2717 case builtin::Function::kRound:
2718 case builtin::Function::kSaturate:
2719 case builtin::Function::kSin:
2720 case builtin::Function::kSinh:
2721 case builtin::Function::kSqrt:
2722 case builtin::Function::kStep:
2723 case builtin::Function::kTan:
2724 case builtin::Function::kTanh:
2725 case builtin::Function::kTranspose:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002726 return builtin->str();
dan sinclair9543f742023-03-09 01:20:16 +00002727 case builtin::Function::kCountOneBits: // uint
dan sinclair41e4d9a2022-05-01 14:40:55 +00002728 return "countbits";
dan sinclair9543f742023-03-09 01:20:16 +00002729 case builtin::Function::kDpdx:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002730 return "ddx";
dan sinclair9543f742023-03-09 01:20:16 +00002731 case builtin::Function::kDpdxCoarse:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002732 return "ddx_coarse";
dan sinclair9543f742023-03-09 01:20:16 +00002733 case builtin::Function::kDpdxFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002734 return "ddx_fine";
dan sinclair9543f742023-03-09 01:20:16 +00002735 case builtin::Function::kDpdy:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002736 return "ddy";
dan sinclair9543f742023-03-09 01:20:16 +00002737 case builtin::Function::kDpdyCoarse:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002738 return "ddy_coarse";
dan sinclair9543f742023-03-09 01:20:16 +00002739 case builtin::Function::kDpdyFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002740 return "ddy_fine";
dan sinclair9543f742023-03-09 01:20:16 +00002741 case builtin::Function::kFaceForward:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002742 return "faceforward";
dan sinclair9543f742023-03-09 01:20:16 +00002743 case builtin::Function::kFract:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002744 return "frac";
dan sinclair9543f742023-03-09 01:20:16 +00002745 case builtin::Function::kFma:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002746 return "mad";
dan sinclair9543f742023-03-09 01:20:16 +00002747 case builtin::Function::kFwidth:
2748 case builtin::Function::kFwidthCoarse:
2749 case builtin::Function::kFwidthFine:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002750 return "fwidth";
dan sinclair9543f742023-03-09 01:20:16 +00002751 case builtin::Function::kInverseSqrt:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002752 return "rsqrt";
dan sinclair9543f742023-03-09 01:20:16 +00002753 case builtin::Function::kMix:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002754 return "lerp";
dan sinclair9543f742023-03-09 01:20:16 +00002755 case builtin::Function::kReverseBits: // uint
dan sinclair41e4d9a2022-05-01 14:40:55 +00002756 return "reversebits";
dan sinclair9543f742023-03-09 01:20:16 +00002757 case builtin::Function::kSmoothstep:
dan sinclair41e4d9a2022-05-01 14:40:55 +00002758 return "smoothstep";
2759 default:
2760 diagnostics_.add_error(diag::System::Writer,
2761 "Unknown builtin method: " + std::string(builtin->str()));
2762 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002763
dan sinclair41e4d9a2022-05-01 14:40:55 +00002764 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002765}
2766
2767bool GeneratorImpl::EmitCase(const ast::SwitchStatement* s, size_t case_idx) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002768 auto* stmt = s->body[case_idx];
dan sinclairf148f082022-10-19 15:55:02 +00002769 auto* sem = builder_.Sem().Get<sem::CaseStatement>(stmt);
2770 for (auto* selector : sem->Selectors()) {
2771 auto out = line();
2772 if (selector->IsDefault()) {
2773 out << "default";
2774 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002775 out << "case ";
Ben Clayton329dfd72022-11-23 00:05:05 +00002776 if (!EmitConstant(out, selector->Value(), /* is_variable_initializer */ false)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002777 return false;
2778 }
dan sinclairf148f082022-10-19 15:55:02 +00002779 }
2780 out << ":";
2781 if (selector == sem->Selectors().back()) {
2782 out << " {";
dan sinclair41e4d9a2022-05-01 14:40:55 +00002783 }
2784 }
2785
2786 increment_indent();
2787 TINT_DEFER({
2788 decrement_indent();
2789 line() << "}";
2790 });
2791
2792 // Emit the case statement
2793 if (!EmitStatements(stmt->body->statements)) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002794 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002795 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002796
dan sinclair267f1742022-11-15 00:30:33 +00002797 if (!tint::IsAnyOf<ast::BreakStatement>(stmt->body->Last())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002798 line() << "break;";
2799 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002800
dan sinclair41e4d9a2022-05-01 14:40:55 +00002801 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002802}
2803
2804bool GeneratorImpl::EmitContinue(const ast::ContinueStatement*) {
dan sinclair4b88dbc2022-06-16 15:27:38 +00002805 if (!emit_continuing_ || !emit_continuing_()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002806 return false;
2807 }
2808 line() << "continue;";
2809 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002810}
2811
2812bool GeneratorImpl::EmitDiscard(const ast::DiscardStatement*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002813 // TODO(dsinclair): Verify this is correct when the discard semantics are
2814 // defined for WGSL (https://github.com/gpuweb/gpuweb/issues/361)
2815 line() << "discard;";
2816 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002817}
2818
dan sinclair2b9d5b32023-02-28 14:49:25 +00002819bool GeneratorImpl::EmitExpression(utils::StringStream& out, const ast::Expression* expr) {
Ben Clayton0b4a2f12023-02-05 22:59:40 +00002820 if (auto* sem = builder_.Sem().GetVal(expr)) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00002821 if (auto* constant = sem->ConstantValue()) {
Ben Clayton329dfd72022-11-23 00:05:05 +00002822 bool is_variable_initializer = false;
2823 if (auto* stmt = sem->Stmt()) {
2824 if (auto* decl = As<ast::VariableDeclStatement>(stmt->Declaration())) {
2825 is_variable_initializer = decl->variable->initializer == expr;
2826 }
2827 }
2828 return EmitConstant(out, constant, is_variable_initializer);
Ben Claytone9f8b092022-06-01 13:14:39 +00002829 }
2830 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002831 return Switch(
Ben Claytonb90b6bf2022-08-23 16:23:05 +00002832 expr, //
2833 [&](const ast::IndexAccessorExpression* a) { return EmitIndexAccessor(out, a); },
2834 [&](const ast::BinaryExpression* b) { return EmitBinary(out, b); },
2835 [&](const ast::BitcastExpression* b) { return EmitBitcast(out, b); },
2836 [&](const ast::CallExpression* c) { return EmitCall(out, c); },
2837 [&](const ast::IdentifierExpression* i) { return EmitIdentifier(out, i); },
2838 [&](const ast::LiteralExpression* l) { return EmitLiteral(out, l); },
2839 [&](const ast::MemberAccessorExpression* m) { return EmitMemberAccessor(out, m); },
2840 [&](const ast::UnaryOpExpression* u) { return EmitUnaryOp(out, u); },
2841 [&](Default) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002842 diagnostics_.add_error(diag::System::Writer, "unknown expression type: " +
2843 std::string(expr->TypeInfo().name));
2844 return false;
2845 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002846}
2847
dan sinclair2b9d5b32023-02-28 14:49:25 +00002848bool GeneratorImpl::EmitIdentifier(utils::StringStream& out,
2849 const ast::IdentifierExpression* expr) {
Ben Clayton6cba18b2023-02-02 20:37:19 +00002850 out << builder_.Symbols().NameFor(expr->identifier->symbol);
dan sinclair41e4d9a2022-05-01 14:40:55 +00002851 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002852}
2853
2854bool GeneratorImpl::EmitIf(const ast::IfStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002855 {
2856 auto out = line();
2857 out << "if (";
2858 if (!EmitExpression(out, stmt->condition)) {
2859 return false;
2860 }
2861 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002862 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002863
dan sinclair41e4d9a2022-05-01 14:40:55 +00002864 if (!EmitStatementsWithIndent(stmt->body->statements)) {
James Price26ebe5e2022-04-29 00:14:53 +00002865 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002866 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002867
dan sinclair41e4d9a2022-05-01 14:40:55 +00002868 if (stmt->else_statement) {
2869 line() << "} else {";
2870 if (auto* block = stmt->else_statement->As<ast::BlockStatement>()) {
2871 if (!EmitStatementsWithIndent(block->statements)) {
2872 return false;
2873 }
2874 } else {
Ben Clayton783b1692022-08-02 17:03:35 +00002875 if (!EmitStatementsWithIndent(utils::Vector{stmt->else_statement})) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002876 return false;
2877 }
2878 }
2879 }
2880 line() << "}";
2881
2882 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002883}
2884
2885bool GeneratorImpl::EmitFunction(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002886 auto* sem = builder_.Sem().Get(func);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002887
Antonio Maiorano08f4b552022-05-31 13:20:28 +00002888 // Emit storage atomic helpers
2889 if (auto* intrinsic =
2890 ast::GetAttribute<transform::DecomposeMemoryAccess::Intrinsic>(func->attributes)) {
dan sinclair2a651632023-02-19 04:03:55 +00002891 if (intrinsic->address_space == builtin::AddressSpace::kStorage && intrinsic->IsAtomic()) {
Antonio Maiorano08f4b552022-05-31 13:20:28 +00002892 if (!EmitStorageAtomicIntrinsic(func, intrinsic)) {
2893 return false;
2894 }
2895 }
2896 return true;
2897 }
2898
dan sinclair41e4d9a2022-05-01 14:40:55 +00002899 if (ast::HasAttribute<ast::InternalAttribute>(func->attributes)) {
2900 // An internal function. Do not emit.
2901 return true;
2902 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002903
dan sinclair41e4d9a2022-05-01 14:40:55 +00002904 {
2905 auto out = line();
Ben Claytonce31d182023-02-09 10:34:14 +00002906 auto name = builder_.Symbols().NameFor(func->name->symbol);
dan sinclair41e4d9a2022-05-01 14:40:55 +00002907 // If the function returns an array, then we need to declare a typedef for
2908 // this.
dan sinclair946858a2022-12-08 22:21:24 +00002909 if (sem->ReturnType()->Is<type::Array>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002910 auto typedef_name = UniqueIdentifier(name + "_ret");
2911 auto pre = line();
2912 pre << "typedef ";
dan sinclair2a651632023-02-19 04:03:55 +00002913 if (!EmitTypeAndName(pre, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002914 builtin::Access::kReadWrite, typedef_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002915 return false;
2916 }
2917 pre << ";";
2918 out << typedef_name;
2919 } else {
dan sinclair2a651632023-02-19 04:03:55 +00002920 if (!EmitType(out, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002921 builtin::Access::kReadWrite, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002922 return false;
2923 }
2924 }
2925
2926 out << " " << name << "(";
2927
2928 bool first = true;
2929
2930 for (auto* v : sem->Parameters()) {
2931 if (!first) {
2932 out << ", ";
2933 }
2934 first = false;
2935
2936 auto const* type = v->Type();
dan sinclair2a651632023-02-19 04:03:55 +00002937 auto address_space = builtin::AddressSpace::kUndefined;
dan sinclairb6cc4cb2023-02-19 04:01:29 +00002938 auto access = builtin::Access::kUndefined;
dan sinclair41e4d9a2022-05-01 14:40:55 +00002939
dan sinclair4d56b482022-12-08 17:50:50 +00002940 if (auto* ptr = type->As<type::Pointer>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002941 type = ptr->StoreType();
dan sinclairff7cf212022-10-03 14:05:23 +00002942 switch (ptr->AddressSpace()) {
dan sinclair2a651632023-02-19 04:03:55 +00002943 case builtin::AddressSpace::kStorage:
2944 case builtin::AddressSpace::kUniform:
Ben Clayton2032d032022-06-15 19:32:37 +00002945 // Not allowed by WGSL, but is used by certain transforms (e.g. DMA) to pass
2946 // storage buffers and uniform buffers down into transform-generated
2947 // functions. In this situation we want to generate the parameter without an
dan sinclairff7cf212022-10-03 14:05:23 +00002948 // 'inout', using the address space and access from the pointer.
2949 address_space = ptr->AddressSpace();
Ben Clayton2032d032022-06-15 19:32:37 +00002950 access = ptr->Access();
2951 break;
2952 default:
2953 // Transform regular WGSL pointer parameters in to `inout` parameters.
2954 out << "inout ";
2955 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00002956 }
2957
Ben Clayton1b90f932023-02-18 12:37:34 +00002958 // Note: WGSL only allows for AddressSpace::kUndefined on parameters, however
dan sinclair41e4d9a2022-05-01 14:40:55 +00002959 // the sanitizer transforms generates load / store functions for storage
2960 // or uniform buffers. These functions have a buffer parameter with
dan sinclairff7cf212022-10-03 14:05:23 +00002961 // AddressSpace::kStorage or AddressSpace::kUniform. This is required to
dan sinclair41e4d9a2022-05-01 14:40:55 +00002962 // correctly translate the parameter to a [RW]ByteAddressBuffer for
2963 // storage buffers and a uint4[N] for uniform buffers.
dan sinclairff7cf212022-10-03 14:05:23 +00002964 if (!EmitTypeAndName(out, type, address_space, access,
Ben Clayton651d9e22023-02-09 10:34:14 +00002965 builder_.Symbols().NameFor(v->Declaration()->name->symbol))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002966 return false;
2967 }
2968 }
2969 out << ") {";
2970 }
2971
dan sinclaird37ecf92022-12-08 16:39:59 +00002972 if (sem->DiscardStatement() && !sem->ReturnType()->Is<type::Void>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002973 // BUG(crbug.com/tint/1081): work around non-void functions with discard
2974 // failing compilation sometimes
2975 if (!EmitFunctionBodyWithDiscard(func)) {
2976 return false;
2977 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002978 } else {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002979 if (!EmitStatementsWithIndent(func->body->statements)) {
2980 return false;
2981 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002982 }
2983
dan sinclair41e4d9a2022-05-01 14:40:55 +00002984 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002985
dan sinclair41e4d9a2022-05-01 14:40:55 +00002986 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002987}
2988
2989bool GeneratorImpl::EmitFunctionBodyWithDiscard(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00002990 // FXC sometimes fails to compile functions that discard with 'Not all control
2991 // paths return a value'. We work around this by wrapping the function body
2992 // within an "if (true) { <body> } return <default return type obj>;" so that
2993 // there is always an (unused) return statement.
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002994
dan sinclair41e4d9a2022-05-01 14:40:55 +00002995 auto* sem = builder_.Sem().Get(func);
dan sinclaird37ecf92022-12-08 16:39:59 +00002996 TINT_ASSERT(Writer, sem->DiscardStatement() && !sem->ReturnType()->Is<type::Void>());
Ryan Harrisondbc13af2022-02-21 15:19:07 +00002997
dan sinclair41e4d9a2022-05-01 14:40:55 +00002998 ScopedIndent si(this);
2999 line() << "if (true) {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003000
dan sinclair41e4d9a2022-05-01 14:40:55 +00003001 if (!EmitStatementsWithIndent(func->body->statements)) {
3002 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003003 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003004
dan sinclair41e4d9a2022-05-01 14:40:55 +00003005 line() << "}";
3006
3007 // Return an unused result that matches the type of the return value
3008 auto name = builder_.Symbols().NameFor(builder_.Symbols().New("unused"));
3009 {
3010 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003011 if (!EmitTypeAndName(out, sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003012 builtin::Access::kReadWrite, name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003013 return false;
3014 }
3015 out << ";";
3016 }
3017 line() << "return " << name << ";";
3018
3019 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003020}
3021
3022bool GeneratorImpl::EmitGlobalVariable(const ast::Variable* global) {
Ben Claytondcdf66e2022-06-17 12:48:51 +00003023 return Switch(
3024 global, //
3025 [&](const ast::Var* var) {
3026 auto* sem = builder_.Sem().Get(global);
dan sinclairff7cf212022-10-03 14:05:23 +00003027 switch (sem->AddressSpace()) {
dan sinclair2a651632023-02-19 04:03:55 +00003028 case builtin::AddressSpace::kUniform:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003029 return EmitUniformVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003030 case builtin::AddressSpace::kStorage:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003031 return EmitStorageVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003032 case builtin::AddressSpace::kHandle:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003033 return EmitHandleVariable(var, sem);
dan sinclair2a651632023-02-19 04:03:55 +00003034 case builtin::AddressSpace::kPrivate:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003035 return EmitPrivateVariable(sem);
dan sinclair2a651632023-02-19 04:03:55 +00003036 case builtin::AddressSpace::kWorkgroup:
Ben Claytondcdf66e2022-06-17 12:48:51 +00003037 return EmitWorkgroupVariable(sem);
dan sinclair2a651632023-02-19 04:03:55 +00003038 case builtin::AddressSpace::kPushConstant:
dan sinclair4abf28e2022-08-02 15:55:35 +00003039 diagnostics_.add_error(
3040 diag::System::Writer,
dan sinclairff7cf212022-10-03 14:05:23 +00003041 "unhandled address space " + utils::ToString(sem->AddressSpace()));
dan sinclair4abf28e2022-08-02 15:55:35 +00003042 return false;
dan sinclair8dbd4d02022-07-27 18:54:05 +00003043 default: {
Ben Claytondcdf66e2022-06-17 12:48:51 +00003044 TINT_ICE(Writer, diagnostics_)
dan sinclairff7cf212022-10-03 14:05:23 +00003045 << "unhandled address space " << sem->AddressSpace();
Ben Claytondcdf66e2022-06-17 12:48:51 +00003046 return false;
dan sinclair8dbd4d02022-07-27 18:54:05 +00003047 }
Ben Claytondcdf66e2022-06-17 12:48:51 +00003048 }
3049 },
dan sinclairf6a94042022-09-09 16:16:19 +00003050 [&](const ast::Override*) {
3051 // Override is removed with SubstituteOverride
Ben Clayton490d9882022-09-21 21:05:45 +00003052 diagnostics_.add_error(diag::System::Writer,
Ben Claytonf10a5792022-10-13 13:47:39 +00003053 "override-expressions should have been removed with the "
Ben Clayton490d9882022-09-21 21:05:45 +00003054 "SubstituteOverride transform");
dan sinclairf6a94042022-09-09 16:16:19 +00003055 return false;
3056 },
Ben Clayton19576e92022-06-28 12:44:16 +00003057 [&](const ast::Const*) {
3058 return true; // Constants are embedded at their use
3059 },
Ben Claytondcdf66e2022-06-17 12:48:51 +00003060 [&](Default) {
3061 TINT_ICE(Writer, diagnostics_)
3062 << "unhandled global variable type " << global->TypeInfo().name;
dan sinclair4abf28e2022-08-02 15:55:35 +00003063
Ben Claytondcdf66e2022-06-17 12:48:51 +00003064 return false;
3065 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003066}
3067
Ben Claytondcdf66e2022-06-17 12:48:51 +00003068bool GeneratorImpl::EmitUniformVariable(const ast::Var* var, const sem::Variable* sem) {
dan sinclairacdf6e12022-08-24 15:47:25 +00003069 auto binding_point = sem->As<sem::GlobalVariable>()->BindingPoint();
Ben Claytondcdf66e2022-06-17 12:48:51 +00003070 auto* type = sem->Type()->UnwrapRef();
Ben Clayton651d9e22023-02-09 10:34:14 +00003071 auto name = builder_.Symbols().NameFor(var->name->symbol);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003072 line() << "cbuffer cbuffer_" << name << RegisterAndSpace('b', binding_point) << " {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003073
dan sinclair41e4d9a2022-05-01 14:40:55 +00003074 {
3075 ScopedIndent si(this);
3076 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003077 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kUniform, sem->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003078 return false;
3079 }
3080 out << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003081 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003082
dan sinclair41e4d9a2022-05-01 14:40:55 +00003083 line() << "};";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003084
dan sinclair41e4d9a2022-05-01 14:40:55 +00003085 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003086}
3087
Ben Claytondcdf66e2022-06-17 12:48:51 +00003088bool GeneratorImpl::EmitStorageVariable(const ast::Var* var, const sem::Variable* sem) {
3089 auto* type = sem->Type()->UnwrapRef();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003090 auto out = line();
dan sinclair2a651632023-02-19 04:03:55 +00003091 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kStorage, sem->Access(),
Ben Clayton651d9e22023-02-09 10:34:14 +00003092 builder_.Symbols().NameFor(var->name->symbol))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003093 return false;
3094 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003095
dan sinclairacdf6e12022-08-24 15:47:25 +00003096 auto* global_sem = sem->As<sem::GlobalVariable>();
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003097 out << RegisterAndSpace(sem->Access() == builtin::Access::kRead ? 't' : 'u',
dan sinclairacdf6e12022-08-24 15:47:25 +00003098 global_sem->BindingPoint())
dan sinclair41e4d9a2022-05-01 14:40:55 +00003099 << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003100
dan sinclair41e4d9a2022-05-01 14:40:55 +00003101 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003102}
3103
Ben Claytondcdf66e2022-06-17 12:48:51 +00003104bool GeneratorImpl::EmitHandleVariable(const ast::Var* var, const sem::Variable* sem) {
3105 auto* unwrapped_type = sem->Type()->UnwrapRef();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003106 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003107
Ben Clayton651d9e22023-02-09 10:34:14 +00003108 auto name = builder_.Symbols().NameFor(var->name->symbol);
Ben Claytondcdf66e2022-06-17 12:48:51 +00003109 auto* type = sem->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003110 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003111 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003112 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003113
dan sinclair41e4d9a2022-05-01 14:40:55 +00003114 const char* register_space = nullptr;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003115
dan sinclair4595fb72022-12-08 14:14:10 +00003116 if (unwrapped_type->Is<type::Texture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003117 register_space = "t";
dan sinclair4595fb72022-12-08 14:14:10 +00003118 if (unwrapped_type->Is<type::StorageTexture>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003119 register_space = "u";
3120 }
dan sinclair5ee58b62022-12-08 15:25:18 +00003121 } else if (unwrapped_type->Is<type::Sampler>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003122 register_space = "s";
3123 }
3124
3125 if (register_space) {
dan sinclairacdf6e12022-08-24 15:47:25 +00003126 auto bp = sem->As<sem::GlobalVariable>()->BindingPoint();
Peng Huangc00ff7f2023-03-31 17:55:19 +00003127 out << " : register(" << register_space << bp.binding;
3128 // Omit the space if it's 0, as it's the default.
3129 // SM 5.0 doesn't support spaces, so we don't emit them if group is 0 for better
3130 // compatibility.
3131 if (bp.group == 0) {
3132 out << ")";
3133 } else {
3134 out << ", space" << bp.group << ")";
3135 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003136 }
3137
3138 out << ";";
3139 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003140}
3141
3142bool GeneratorImpl::EmitPrivateVariable(const sem::Variable* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003143 auto* decl = var->Declaration();
3144 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003145
dan sinclair41e4d9a2022-05-01 14:40:55 +00003146 out << "static ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003147
Ben Clayton651d9e22023-02-09 10:34:14 +00003148 auto name = builder_.Symbols().NameFor(decl->name->symbol);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003149 auto* type = var->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003150 if (!EmitTypeAndName(out, type, var->AddressSpace(), var->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003151 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003152 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003153
dan sinclair41e4d9a2022-05-01 14:40:55 +00003154 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00003155 if (auto* initializer = decl->initializer) {
3156 if (!EmitExpression(out, initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003157 return false;
3158 }
3159 } else {
3160 if (!EmitZeroValue(out, var->Type()->UnwrapRef())) {
3161 return false;
3162 }
3163 }
3164
3165 out << ";";
3166 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003167}
3168
3169bool GeneratorImpl::EmitWorkgroupVariable(const sem::Variable* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003170 auto* decl = var->Declaration();
3171 auto out = line();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003172
dan sinclair41e4d9a2022-05-01 14:40:55 +00003173 out << "groupshared ";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003174
Ben Clayton651d9e22023-02-09 10:34:14 +00003175 auto name = builder_.Symbols().NameFor(decl->name->symbol);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003176 auto* type = var->Type()->UnwrapRef();
dan sinclairff7cf212022-10-03 14:05:23 +00003177 if (!EmitTypeAndName(out, type, var->AddressSpace(), var->Access(), name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003178 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003179 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003180
dan sinclair6e77b472022-10-20 13:38:28 +00003181 if (auto* initializer = decl->initializer) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003182 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00003183 if (!EmitExpression(out, initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003184 return false;
3185 }
3186 }
3187
3188 out << ";";
3189 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003190}
3191
dan sinclair63925792023-02-17 21:56:35 +00003192std::string GeneratorImpl::builtin_to_attribute(builtin::BuiltinValue builtin) const {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003193 switch (builtin) {
dan sinclair63925792023-02-17 21:56:35 +00003194 case builtin::BuiltinValue::kPosition:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003195 return "SV_Position";
dan sinclair63925792023-02-17 21:56:35 +00003196 case builtin::BuiltinValue::kVertexIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003197 return "SV_VertexID";
dan sinclair63925792023-02-17 21:56:35 +00003198 case builtin::BuiltinValue::kInstanceIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003199 return "SV_InstanceID";
dan sinclair63925792023-02-17 21:56:35 +00003200 case builtin::BuiltinValue::kFrontFacing:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003201 return "SV_IsFrontFace";
dan sinclair63925792023-02-17 21:56:35 +00003202 case builtin::BuiltinValue::kFragDepth:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003203 return "SV_Depth";
dan sinclair63925792023-02-17 21:56:35 +00003204 case builtin::BuiltinValue::kLocalInvocationId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003205 return "SV_GroupThreadID";
dan sinclair63925792023-02-17 21:56:35 +00003206 case builtin::BuiltinValue::kLocalInvocationIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003207 return "SV_GroupIndex";
dan sinclair63925792023-02-17 21:56:35 +00003208 case builtin::BuiltinValue::kGlobalInvocationId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003209 return "SV_DispatchThreadID";
dan sinclair63925792023-02-17 21:56:35 +00003210 case builtin::BuiltinValue::kWorkgroupId:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003211 return "SV_GroupID";
dan sinclair63925792023-02-17 21:56:35 +00003212 case builtin::BuiltinValue::kSampleIndex:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003213 return "SV_SampleIndex";
dan sinclair63925792023-02-17 21:56:35 +00003214 case builtin::BuiltinValue::kSampleMask:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003215 return "SV_Coverage";
3216 default:
3217 break;
3218 }
3219 return "";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003220}
3221
dan sinclair993a6582023-02-20 08:37:45 +00003222std::string GeneratorImpl::interpolation_to_modifiers(
3223 builtin::InterpolationType type,
3224 builtin::InterpolationSampling sampling) const {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003225 std::string modifiers;
3226 switch (type) {
dan sinclair993a6582023-02-20 08:37:45 +00003227 case builtin::InterpolationType::kPerspective:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003228 modifiers += "linear ";
3229 break;
dan sinclair993a6582023-02-20 08:37:45 +00003230 case builtin::InterpolationType::kLinear:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003231 modifiers += "noperspective ";
3232 break;
dan sinclair993a6582023-02-20 08:37:45 +00003233 case builtin::InterpolationType::kFlat:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003234 modifiers += "nointerpolation ";
3235 break;
dan sinclair993a6582023-02-20 08:37:45 +00003236 case builtin::InterpolationType::kUndefined:
Ben Claytonf9ed9d32022-10-11 19:49:17 +00003237 break;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003238 }
3239 switch (sampling) {
dan sinclair993a6582023-02-20 08:37:45 +00003240 case builtin::InterpolationSampling::kCentroid:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003241 modifiers += "centroid ";
3242 break;
dan sinclair993a6582023-02-20 08:37:45 +00003243 case builtin::InterpolationSampling::kSample:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003244 modifiers += "sample ";
3245 break;
dan sinclair993a6582023-02-20 08:37:45 +00003246 case builtin::InterpolationSampling::kCenter:
3247 case builtin::InterpolationSampling::kUndefined:
dan sinclair41e4d9a2022-05-01 14:40:55 +00003248 break;
3249 }
3250 return modifiers;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003251}
3252
3253bool GeneratorImpl::EmitEntryPointFunction(const ast::Function* func) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003254 auto* func_sem = builder_.Sem().Get(func);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003255
dan sinclair41e4d9a2022-05-01 14:40:55 +00003256 {
3257 auto out = line();
3258 if (func->PipelineStage() == ast::PipelineStage::kCompute) {
3259 // Emit the workgroup_size attribute.
3260 auto wgsize = func_sem->WorkgroupSize();
3261 out << "[numthreads(";
dan sinclair3a2a2792022-06-29 14:38:15 +00003262 for (size_t i = 0; i < 3; i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003263 if (i > 0) {
3264 out << ", ";
3265 }
Ben Clayton490d9882022-09-21 21:05:45 +00003266 if (!wgsize[i].has_value()) {
3267 diagnostics_.add_error(
3268 diag::System::Writer,
Ben Claytonf10a5792022-10-13 13:47:39 +00003269 "override-expressions should have been removed with the SubstituteOverride "
Ben Clayton490d9882022-09-21 21:05:45 +00003270 "transform");
3271 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003272 }
Ben Clayton490d9882022-09-21 21:05:45 +00003273 out << std::to_string(wgsize[i].value());
dan sinclair41e4d9a2022-05-01 14:40:55 +00003274 }
3275 out << ")]" << std::endl;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003276 }
3277
dan sinclair2a651632023-02-19 04:03:55 +00003278 if (!EmitTypeAndName(out, func_sem->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003279 builtin::Access::kUndefined,
Ben Claytonce31d182023-02-09 10:34:14 +00003280 builder_.Symbols().NameFor(func->name->symbol))) {
Ben Clayton19068572023-02-07 21:28:09 +00003281 return false;
3282 }
3283 out << "(";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003284
3285 bool first = true;
3286
3287 // Emit entry point parameters.
3288 for (auto* var : func->params) {
3289 auto* sem = builder_.Sem().Get(var);
3290 auto* type = sem->Type();
Ben Clayton884f9522023-01-12 22:52:57 +00003291 if (TINT_UNLIKELY(!type->Is<sem::Struct>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003292 // ICE likely indicates that the CanonicalizeEntryPointIO transform was
3293 // not run, or a builtin parameter was added after it was run.
3294 TINT_ICE(Writer, diagnostics_) << "Unsupported non-struct entry point parameter";
3295 }
3296
3297 if (!first) {
3298 out << ", ";
3299 }
3300 first = false;
3301
dan sinclairff7cf212022-10-03 14:05:23 +00003302 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(),
Ben Clayton651d9e22023-02-09 10:34:14 +00003303 builder_.Symbols().NameFor(var->name->symbol))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003304 return false;
3305 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003306 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003307
3308 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003309 }
3310
dan sinclair41e4d9a2022-05-01 14:40:55 +00003311 {
3312 ScopedIndent si(this);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003313
dan sinclair41e4d9a2022-05-01 14:40:55 +00003314 if (!EmitStatements(func->body->statements)) {
3315 return false;
3316 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003317
dan sinclair41e4d9a2022-05-01 14:40:55 +00003318 if (!Is<ast::ReturnStatement>(func->body->Last())) {
Ben Clayton4a92a3c2022-07-18 20:50:02 +00003319 ast::ReturnStatement ret(ProgramID(), ast::NodeID{}, Source{});
dan sinclair41e4d9a2022-05-01 14:40:55 +00003320 if (!EmitStatement(&ret)) {
3321 return false;
3322 }
3323 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003324 }
3325
dan sinclair41e4d9a2022-05-01 14:40:55 +00003326 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003327
dan sinclair41e4d9a2022-05-01 14:40:55 +00003328 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003329}
3330
dan sinclair2b9d5b32023-02-28 14:49:25 +00003331bool GeneratorImpl::EmitConstant(utils::StringStream& out,
dan sinclairb53b8cf2022-12-15 16:25:31 +00003332 const constant::Value* constant,
Ben Clayton329dfd72022-11-23 00:05:05 +00003333 bool is_variable_initializer) {
Ben Clayton50414802022-06-24 08:06:19 +00003334 return Switch(
Ben Claytonaa037ac2022-06-29 19:07:30 +00003335 constant->Type(), //
dan sinclaird37ecf92022-12-08 16:39:59 +00003336 [&](const type::Bool*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003337 out << (constant->ValueAs<AInt>() ? "true" : "false");
Ben Claytone9f8b092022-06-01 13:14:39 +00003338 return true;
Ben Clayton50414802022-06-24 08:06:19 +00003339 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003340 [&](const type::F32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003341 PrintF32(out, constant->ValueAs<f32>());
Ben Clayton50414802022-06-24 08:06:19 +00003342 return true;
3343 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003344 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003345 // emit a f16 scalar with explicit float16_t type declaration.
3346 out << "float16_t(";
dan sinclair5addefb2022-12-14 20:46:32 +00003347 PrintF16(out, constant->ValueAs<f16>());
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003348 out << ")";
Antonio Maiorano679cf4f2022-09-03 21:43:01 +00003349 return true;
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003350 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003351 [&](const type::I32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003352 out << constant->ValueAs<AInt>();
Ben Clayton50414802022-06-24 08:06:19 +00003353 return true;
3354 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003355 [&](const type::U32*) {
dan sinclair5addefb2022-12-14 20:46:32 +00003356 out << constant->ValueAs<AInt>() << "u";
Ben Clayton50414802022-06-24 08:06:19 +00003357 return true;
3358 },
dan sinclair0e780da2022-12-08 22:21:24 +00003359 [&](const type::Vector* v) {
James Price7bca4d72023-03-13 19:05:16 +00003360 if (auto* splat = constant->As<constant::Splat>()) {
Ben Clayton50414802022-06-24 08:06:19 +00003361 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00003362 ScopedParen sp(out);
James Price7bca4d72023-03-13 19:05:16 +00003363 if (!EmitConstant(out, splat->el, is_variable_initializer)) {
Ben Clayton50414802022-06-24 08:06:19 +00003364 return false;
3365 }
3366 }
3367 out << ".";
Ben Claytonaa037ac2022-06-29 19:07:30 +00003368 for (size_t i = 0; i < v->Width(); i++) {
Ben Clayton50414802022-06-24 08:06:19 +00003369 out << "x";
3370 }
3371 return true;
3372 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003373
dan sinclair2a651632023-02-19 04:03:55 +00003374 if (!EmitType(out, v, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003375 "")) {
Ben Clayton50414802022-06-24 08:06:19 +00003376 return false;
3377 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003378
dan sinclairb2ba57b2023-02-28 15:14:09 +00003379 ScopedParen sp(out);
Ben Claytone9f8b092022-06-01 13:14:39 +00003380
Ben Claytonaa037ac2022-06-29 19:07:30 +00003381 for (size_t i = 0; i < v->Width(); i++) {
3382 if (i > 0) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003383 out << ", ";
3384 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003385 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003386 return false;
3387 }
3388 }
3389 return true;
Ben Clayton50414802022-06-24 08:06:19 +00003390 },
dan sinclair0e780da2022-12-08 22:21:24 +00003391 [&](const type::Matrix* m) {
dan sinclair2a651632023-02-19 04:03:55 +00003392 if (!EmitType(out, m, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003393 "")) {
Ben Claytone9f8b092022-06-01 13:14:39 +00003394 return false;
3395 }
Ben Clayton50414802022-06-24 08:06:19 +00003396
dan sinclairb2ba57b2023-02-28 15:14:09 +00003397 ScopedParen sp(out);
Ben Clayton50414802022-06-24 08:06:19 +00003398
Ben Claytonaa037ac2022-06-29 19:07:30 +00003399 for (size_t i = 0; i < m->columns(); i++) {
3400 if (i > 0) {
Ben Clayton50414802022-06-24 08:06:19 +00003401 out << ", ";
3402 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003403 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Clayton50414802022-06-24 08:06:19 +00003404 return false;
3405 }
3406 }
3407 return true;
3408 },
dan sinclair946858a2022-12-08 22:21:24 +00003409 [&](const type::Array* a) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00003410 if (constant->AllZero()) {
Ben Clayton19576e92022-06-28 12:44:16 +00003411 out << "(";
dan sinclair2a651632023-02-19 04:03:55 +00003412 if (!EmitType(out, a, builtin::AddressSpace::kUndefined,
3413 builtin::Access::kUndefined, "")) {
Ben Clayton19576e92022-06-28 12:44:16 +00003414 return false;
3415 }
3416 out << ")0";
3417 return true;
3418 }
3419
3420 out << "{";
3421 TINT_DEFER(out << "}");
3422
dan sinclair78f80672022-09-22 22:28:21 +00003423 auto count = a->ConstantCount();
3424 if (!count) {
dan sinclair946858a2022-12-08 22:21:24 +00003425 diagnostics_.add_error(diag::System::Writer,
3426 type::Array::kErrExpectedConstantCount);
dan sinclair78f80672022-09-22 22:28:21 +00003427 return false;
3428 }
3429
3430 for (size_t i = 0; i < count; i++) {
Ben Claytonaa037ac2022-06-29 19:07:30 +00003431 if (i > 0) {
Ben Clayton19576e92022-06-28 12:44:16 +00003432 out << ", ";
3433 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003434 if (!EmitConstant(out, constant->Index(i), is_variable_initializer)) {
Ben Clayton19576e92022-06-28 12:44:16 +00003435 return false;
3436 }
3437 }
3438
3439 return true;
3440 },
Ben Clayton6c098ba2022-07-14 20:46:39 +00003441 [&](const sem::Struct* s) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003442 if (!EmitStructType(&helpers_, s)) {
3443 return false;
3444 }
3445
Ben Clayton6c098ba2022-07-14 20:46:39 +00003446 if (constant->AllZero()) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003447 out << "(" << StructName(s) << ")0";
Ben Clayton6c098ba2022-07-14 20:46:39 +00003448 return true;
3449 }
3450
dan sinclair2b9d5b32023-02-28 14:49:25 +00003451 auto emit_member_values = [&](utils::StringStream& o) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003452 o << "{";
dan sinclairad9cd0a2022-12-06 20:01:54 +00003453 for (size_t i = 0; i < s->Members().Length(); i++) {
Ben Clayton329dfd72022-11-23 00:05:05 +00003454 if (i > 0) {
3455 o << ", ";
3456 }
3457 if (!EmitConstant(o, constant->Index(i), is_variable_initializer)) {
3458 return false;
3459 }
Ben Clayton6c098ba2022-07-14 20:46:39 +00003460 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003461 o << "}";
3462 return true;
3463 };
3464
3465 if (is_variable_initializer) {
3466 if (!emit_member_values(out)) {
Ben Clayton6c098ba2022-07-14 20:46:39 +00003467 return false;
3468 }
Ben Clayton329dfd72022-11-23 00:05:05 +00003469 } else {
3470 // HLSL requires structure initializers to be assigned directly to a variable.
3471 auto name = UniqueIdentifier("c");
3472 {
3473 auto decl = line();
3474 decl << "const " << StructName(s) << " " << name << " = ";
3475 if (!emit_member_values(decl)) {
3476 return false;
3477 }
3478 decl << ";";
3479 }
3480 out << name;
Ben Clayton6c098ba2022-07-14 20:46:39 +00003481 }
3482
3483 return true;
3484 },
Ben Claytone9f8b092022-06-01 13:14:39 +00003485 [&](Default) {
3486 diagnostics_.add_error(
3487 diag::System::Writer,
Ben Claytonaa037ac2022-06-29 19:07:30 +00003488 "unhandled constant type: " + builder_.FriendlyName(constant->Type()));
Ben Claytone9f8b092022-06-01 13:14:39 +00003489 return false;
3490 });
3491}
3492
dan sinclair2b9d5b32023-02-28 14:49:25 +00003493bool GeneratorImpl::EmitLiteral(utils::StringStream& out, const ast::LiteralExpression* lit) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003494 return Switch(
3495 lit,
3496 [&](const ast::BoolLiteralExpression* l) {
3497 out << (l->value ? "true" : "false");
3498 return true;
3499 },
Ben Clayton3ad927c2022-05-25 23:12:14 +00003500 [&](const ast::FloatLiteralExpression* l) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003501 if (l->suffix == ast::FloatLiteralExpression::Suffix::kH) {
3502 // Emit f16 literal with explicit float16_t type declaration.
3503 out << "float16_t(";
Antonio Maiorano679cf4f2022-09-03 21:43:01 +00003504 PrintF16(out, static_cast<float>(l->value));
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003505 out << ")";
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003506 }
Ben Claytone9f8b092022-06-01 13:14:39 +00003507 PrintF32(out, static_cast<float>(l->value));
dan sinclair41e4d9a2022-05-01 14:40:55 +00003508 return true;
3509 },
Ben Clayton8822e292022-05-04 22:18:49 +00003510 [&](const ast::IntLiteralExpression* i) {
3511 out << i->value;
3512 switch (i->suffix) {
3513 case ast::IntLiteralExpression::Suffix::kNone:
3514 case ast::IntLiteralExpression::Suffix::kI:
3515 return true;
3516 case ast::IntLiteralExpression::Suffix::kU:
3517 out << "u";
3518 return true;
3519 }
3520 diagnostics_.add_error(diag::System::Writer, "unknown integer literal suffix type");
3521 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003522 },
3523 [&](Default) {
3524 diagnostics_.add_error(diag::System::Writer, "unknown literal type");
3525 return false;
3526 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003527}
3528
dan sinclair2b9d5b32023-02-28 14:49:25 +00003529bool GeneratorImpl::EmitValue(utils::StringStream& out, const type::Type* type, int value) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003530 return Switch(
3531 type,
dan sinclaird37ecf92022-12-08 16:39:59 +00003532 [&](const type::Bool*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003533 out << (value == 0 ? "false" : "true");
3534 return true;
3535 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003536 [&](const type::F32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003537 out << value << ".0f";
3538 return true;
3539 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003540 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00003541 out << "float16_t(" << value << ".0h)";
3542 return true;
3543 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003544 [&](const type::I32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003545 out << value;
3546 return true;
3547 },
dan sinclaird37ecf92022-12-08 16:39:59 +00003548 [&](const type::U32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003549 out << value << "u";
3550 return true;
3551 },
dan sinclair0e780da2022-12-08 22:21:24 +00003552 [&](const type::Vector* vec) {
dan sinclair2a651632023-02-19 04:03:55 +00003553 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
Ben Clayton1b90f932023-02-18 12:37:34 +00003554 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003555 return false;
3556 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00003557 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003558 for (uint32_t i = 0; i < vec->Width(); i++) {
3559 if (i != 0) {
3560 out << ", ";
3561 }
3562 if (!EmitValue(out, vec->type(), value)) {
3563 return false;
3564 }
3565 }
3566 return true;
3567 },
dan sinclair0e780da2022-12-08 22:21:24 +00003568 [&](const type::Matrix* mat) {
dan sinclair2a651632023-02-19 04:03:55 +00003569 if (!EmitType(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kReadWrite,
Ben Clayton1b90f932023-02-18 12:37:34 +00003570 "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003571 return false;
3572 }
dan sinclairb2ba57b2023-02-28 15:14:09 +00003573 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00003574 for (uint32_t i = 0; i < (mat->rows() * mat->columns()); i++) {
3575 if (i != 0) {
3576 out << ", ";
3577 }
3578 if (!EmitValue(out, mat->type(), value)) {
3579 return false;
3580 }
3581 }
3582 return true;
3583 },
3584 [&](const sem::Struct*) {
3585 out << "(";
3586 TINT_DEFER(out << ")" << value);
dan sinclair2a651632023-02-19 04:03:55 +00003587 return EmitType(out, type, builtin::AddressSpace::kUndefined,
3588 builtin::Access::kUndefined, "");
dan sinclair41e4d9a2022-05-01 14:40:55 +00003589 },
dan sinclair946858a2022-12-08 22:21:24 +00003590 [&](const type::Array*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003591 out << "(";
3592 TINT_DEFER(out << ")" << value);
dan sinclair2a651632023-02-19 04:03:55 +00003593 return EmitType(out, type, builtin::AddressSpace::kUndefined,
3594 builtin::Access::kUndefined, "");
dan sinclair41e4d9a2022-05-01 14:40:55 +00003595 },
3596 [&](Default) {
3597 diagnostics_.add_error(
3598 diag::System::Writer,
3599 "Invalid type for value emission: " + type->FriendlyName(builder_.Symbols()));
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003600 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003601 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003602}
3603
dan sinclair2b9d5b32023-02-28 14:49:25 +00003604bool GeneratorImpl::EmitZeroValue(utils::StringStream& out, const type::Type* type) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003605 return EmitValue(out, type, 0);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003606}
3607
3608bool GeneratorImpl::EmitLoop(const ast::LoopStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003609 auto emit_continuing = [this, stmt]() {
3610 if (stmt->continuing && !stmt->continuing->Empty()) {
3611 if (!EmitBlock(stmt->continuing)) {
3612 return false;
3613 }
3614 }
3615 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003616 };
3617
3618 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
Antonio Maiorano06844a52022-09-29 16:53:58 +00003619 line() << "while (true) {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003620 {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003621 ScopedIndent si(this);
3622 if (!EmitStatements(stmt->body->statements)) {
3623 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003624 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003625 if (!emit_continuing_()) {
3626 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003627 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003628 }
3629 line() << "}";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003630
dan sinclair41e4d9a2022-05-01 14:40:55 +00003631 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003632}
3633
dan sinclair41e4d9a2022-05-01 14:40:55 +00003634bool GeneratorImpl::EmitForLoop(const ast::ForLoopStatement* stmt) {
3635 // Nest a for loop with a new block. In HLSL the initializer scope is not
3636 // nested by the for-loop, so we may get variable redefinitions.
3637 line() << "{";
3638 increment_indent();
3639 TINT_DEFER({
3640 decrement_indent();
3641 line() << "}";
3642 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003643
dan sinclair41e4d9a2022-05-01 14:40:55 +00003644 TextBuffer init_buf;
3645 if (auto* init = stmt->initializer) {
3646 TINT_SCOPED_ASSIGNMENT(current_buffer_, &init_buf);
3647 if (!EmitStatement(init)) {
3648 return false;
3649 }
3650 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003651
dan sinclair41e4d9a2022-05-01 14:40:55 +00003652 TextBuffer cond_pre;
dan sinclair2b9d5b32023-02-28 14:49:25 +00003653 utils::StringStream cond_buf;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003654 if (auto* cond = stmt->condition) {
3655 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cond_pre);
3656 if (!EmitExpression(cond_buf, cond)) {
3657 return false;
3658 }
3659 }
3660
3661 TextBuffer cont_buf;
3662 if (auto* cont = stmt->continuing) {
3663 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cont_buf);
3664 if (!EmitStatement(cont)) {
3665 return false;
3666 }
3667 }
3668
3669 // If the for-loop has a multi-statement conditional and / or continuing, then
3670 // we cannot emit this as a regular for-loop in HLSL. Instead we need to
3671 // generate a `while(true)` loop.
3672 bool emit_as_loop = cond_pre.lines.size() > 0 || cont_buf.lines.size() > 1;
3673
3674 // If the for-loop has multi-statement initializer, or is going to be emitted
3675 // as a `while(true)` loop, then declare the initializer statement(s) before
3676 // the loop.
3677 if (init_buf.lines.size() > 1 || (stmt->initializer && emit_as_loop)) {
3678 current_buffer_->Append(init_buf);
3679 init_buf.lines.clear(); // Don't emit the initializer again in the 'for'
3680 }
3681
3682 if (emit_as_loop) {
3683 auto emit_continuing = [&]() {
3684 current_buffer_->Append(cont_buf);
3685 return true;
3686 };
3687
3688 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
Antonio Maiorano06844a52022-09-29 16:53:58 +00003689 line() << "while (true) {";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003690 increment_indent();
3691 TINT_DEFER({
3692 decrement_indent();
3693 line() << "}";
3694 });
3695
3696 if (stmt->condition) {
3697 current_buffer_->Append(cond_pre);
3698 line() << "if (!(" << cond_buf.str() << ")) { break; }";
3699 }
3700
3701 if (!EmitStatements(stmt->body->statements)) {
3702 return false;
3703 }
3704
3705 if (!emit_continuing_()) {
3706 return false;
3707 }
3708 } else {
3709 // For-loop can be generated.
3710 {
3711 auto out = line();
Antonio Maiorano06844a52022-09-29 16:53:58 +00003712 out << "for";
dan sinclair41e4d9a2022-05-01 14:40:55 +00003713 {
3714 ScopedParen sp(out);
3715
3716 if (!init_buf.lines.empty()) {
3717 out << init_buf.lines[0].content << " ";
3718 } else {
3719 out << "; ";
3720 }
3721
3722 out << cond_buf.str() << "; ";
3723
3724 if (!cont_buf.lines.empty()) {
3725 out << TrimSuffix(cont_buf.lines[0].content, ";");
3726 }
3727 }
3728 out << " {";
3729 }
3730 {
3731 auto emit_continuing = [] { return true; };
3732 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
3733 if (!EmitStatementsWithIndent(stmt->body->statements)) {
3734 return false;
3735 }
3736 }
3737 line() << "}";
3738 }
3739
3740 return true;
3741}
3742
dan sinclair49d1a2d2022-06-16 12:01:27 +00003743bool GeneratorImpl::EmitWhile(const ast::WhileStatement* stmt) {
3744 TextBuffer cond_pre;
dan sinclair2b9d5b32023-02-28 14:49:25 +00003745 utils::StringStream cond_buf;
dan sinclair49d1a2d2022-06-16 12:01:27 +00003746 {
3747 auto* cond = stmt->condition;
3748 TINT_SCOPED_ASSIGNMENT(current_buffer_, &cond_pre);
3749 if (!EmitExpression(cond_buf, cond)) {
3750 return false;
3751 }
3752 }
3753
dan sinclair4b88dbc2022-06-16 15:27:38 +00003754 auto emit_continuing = [&]() { return true; };
3755 TINT_SCOPED_ASSIGNMENT(emit_continuing_, emit_continuing);
3756
dan sinclair49d1a2d2022-06-16 12:01:27 +00003757 // If the while has a multi-statement conditional, then we cannot emit this
3758 // as a regular while in HLSL. Instead we need to generate a `while(true)` loop.
3759 bool emit_as_loop = cond_pre.lines.size() > 0;
3760 if (emit_as_loop) {
Antonio Maiorano06844a52022-09-29 16:53:58 +00003761 line() << "while (true) {";
dan sinclair49d1a2d2022-06-16 12:01:27 +00003762 increment_indent();
3763 TINT_DEFER({
3764 decrement_indent();
3765 line() << "}";
3766 });
3767
3768 current_buffer_->Append(cond_pre);
3769 line() << "if (!(" << cond_buf.str() << ")) { break; }";
3770 if (!EmitStatements(stmt->body->statements)) {
3771 return false;
3772 }
3773 } else {
3774 // While can be generated.
3775 {
3776 auto out = line();
Antonio Maiorano06844a52022-09-29 16:53:58 +00003777 out << "while";
dan sinclair49d1a2d2022-06-16 12:01:27 +00003778 {
3779 ScopedParen sp(out);
3780 out << cond_buf.str();
3781 }
3782 out << " {";
3783 }
3784 if (!EmitStatementsWithIndent(stmt->body->statements)) {
3785 return false;
3786 }
3787 line() << "}";
3788 }
3789
3790 return true;
3791}
3792
dan sinclair2b9d5b32023-02-28 14:49:25 +00003793bool GeneratorImpl::EmitMemberAccessor(utils::StringStream& out,
dan sinclair41e4d9a2022-05-01 14:40:55 +00003794 const ast::MemberAccessorExpression* expr) {
Ben Claytonad315652023-02-05 12:36:50 +00003795 if (!EmitExpression(out, expr->object)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003796 return false;
3797 }
3798 out << ".";
3799
Ben Clayton2f9a9882022-12-17 02:20:04 +00003800 auto* sem = builder_.Sem().Get(expr)->UnwrapLoad();
dan sinclair41e4d9a2022-05-01 14:40:55 +00003801
Ben Clayton10fae7a2022-11-14 15:29:29 +00003802 return Switch(
3803 sem,
3804 [&](const sem::Swizzle*) {
3805 // Swizzles output the name directly
Ben Claytona4117ca2023-02-02 20:44:53 +00003806 out << builder_.Symbols().NameFor(expr->member->symbol);
Ben Clayton10fae7a2022-11-14 15:29:29 +00003807 return true;
3808 },
3809 [&](const sem::StructMemberAccess* member_access) {
3810 out << program_->Symbols().NameFor(member_access->Member()->Name());
3811 return true;
3812 },
3813 [&](Default) {
3814 TINT_ICE(Writer, diagnostics_)
3815 << "unknown member access type: " << sem->TypeInfo().name;
3816 return false;
3817 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003818}
3819
3820bool GeneratorImpl::EmitReturn(const ast::ReturnStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003821 if (stmt->value) {
3822 auto out = line();
3823 out << "return ";
3824 if (!EmitExpression(out, stmt->value)) {
3825 return false;
3826 }
3827 out << ";";
3828 } else {
3829 line() << "return;";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003830 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003831 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003832}
3833
3834bool GeneratorImpl::EmitStatement(const ast::Statement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003835 return Switch(
3836 stmt,
3837 [&](const ast::AssignmentStatement* a) { //
3838 return EmitAssign(a);
3839 },
3840 [&](const ast::BlockStatement* b) { //
3841 return EmitBlock(b);
3842 },
3843 [&](const ast::BreakStatement* b) { //
3844 return EmitBreak(b);
3845 },
dan sinclairb8b0c212022-10-20 22:45:50 +00003846 [&](const ast::BreakIfStatement* b) { //
3847 return EmitBreakIf(b);
3848 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003849 [&](const ast::CallStatement* c) { //
3850 auto out = line();
3851 if (!EmitCall(out, c->expr)) {
3852 return false;
3853 }
3854 out << ";";
3855 return true;
3856 },
3857 [&](const ast::ContinueStatement* c) { //
3858 return EmitContinue(c);
3859 },
3860 [&](const ast::DiscardStatement* d) { //
3861 return EmitDiscard(d);
3862 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003863 [&](const ast::IfStatement* i) { //
3864 return EmitIf(i);
3865 },
3866 [&](const ast::LoopStatement* l) { //
3867 return EmitLoop(l);
3868 },
3869 [&](const ast::ForLoopStatement* l) { //
3870 return EmitForLoop(l);
3871 },
dan sinclair49d1a2d2022-06-16 12:01:27 +00003872 [&](const ast::WhileStatement* l) { //
3873 return EmitWhile(l);
3874 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003875 [&](const ast::ReturnStatement* r) { //
3876 return EmitReturn(r);
3877 },
3878 [&](const ast::SwitchStatement* s) { //
3879 return EmitSwitch(s);
3880 },
3881 [&](const ast::VariableDeclStatement* v) { //
Ben Claytondcdf66e2022-06-17 12:48:51 +00003882 return Switch(
3883 v->variable, //
3884 [&](const ast::Var* var) { return EmitVar(var); },
3885 [&](const ast::Let* let) { return EmitLet(let); },
Ben Clayton19576e92022-06-28 12:44:16 +00003886 [&](const ast::Const*) {
3887 return true; // Constants are embedded at their use
3888 },
Ben Claytondcdf66e2022-06-17 12:48:51 +00003889 [&](Default) { //
3890 TINT_ICE(Writer, diagnostics_)
3891 << "unknown variable type: " << v->variable->TypeInfo().name;
3892 return false;
3893 });
dan sinclair41e4d9a2022-05-01 14:40:55 +00003894 },
Ben Claytonc98d57d2023-01-24 14:59:43 +00003895 [&](const ast::ConstAssert*) {
Ben Claytonb4744ac2022-08-03 07:01:08 +00003896 return true; // Not emitted
3897 },
dan sinclair41e4d9a2022-05-01 14:40:55 +00003898 [&](Default) { //
3899 diagnostics_.add_error(diag::System::Writer,
3900 "unknown statement type: " + std::string(stmt->TypeInfo().name));
3901 return false;
3902 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003903}
3904
3905bool GeneratorImpl::EmitDefaultOnlySwitch(const ast::SwitchStatement* stmt) {
dan sinclairf148f082022-10-19 15:55:02 +00003906 TINT_ASSERT(Writer, stmt->body.Length() == 1 && stmt->body[0]->ContainsDefault());
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003907
dan sinclair41e4d9a2022-05-01 14:40:55 +00003908 // FXC fails to compile a switch with just a default case, ignoring the
3909 // default case body. We work around this here by emitting the default case
3910 // without the switch.
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003911
Antonio Maioranoeab1f622023-02-01 15:46:34 +00003912 // Emit the switch condition as-is if it has side-effects (e.g.
3913 // function call). Note that we can ignore the result of the expression (if any).
Ben Clayton0b4a2f12023-02-05 22:59:40 +00003914 if (auto* sem_cond = builder_.Sem().GetVal(stmt->condition); sem_cond->HasSideEffects()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003915 auto out = line();
3916 if (!EmitExpression(out, stmt->condition)) {
3917 return false;
3918 }
3919 out << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003920 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003921
dan sinclair41e4d9a2022-05-01 14:40:55 +00003922 // Emit "do { <default case body> } while(false);". We use a 'do' loop so
3923 // that break statements work as expected, and make it 'while (false)' in
3924 // case there isn't a break statement.
3925 line() << "do {";
3926 {
3927 ScopedIndent si(this);
3928 if (!EmitStatements(stmt->body[0]->body->statements)) {
3929 return false;
3930 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003931 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00003932 line() << "} while (false);";
3933 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003934}
3935
3936bool GeneratorImpl::EmitSwitch(const ast::SwitchStatement* stmt) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003937 // BUG(crbug.com/tint/1188): work around default-only switches
dan sinclairf148f082022-10-19 15:55:02 +00003938 if (stmt->body.Length() == 1 && stmt->body[0]->selectors.Length() == 1 &&
3939 stmt->body[0]->ContainsDefault()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003940 return EmitDefaultOnlySwitch(stmt);
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003941 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003942
dan sinclair41e4d9a2022-05-01 14:40:55 +00003943 { // switch(expr) {
3944 auto out = line();
3945 out << "switch(";
3946 if (!EmitExpression(out, stmt->condition)) {
3947 return false;
3948 }
3949 out << ") {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003950 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003951
dan sinclair41e4d9a2022-05-01 14:40:55 +00003952 {
3953 ScopedIndent si(this);
Ben Clayton783b1692022-08-02 17:03:35 +00003954 for (size_t i = 0; i < stmt->body.Length(); i++) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003955 if (!EmitCase(stmt, i)) {
3956 return false;
3957 }
3958 }
3959 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003960
dan sinclair41e4d9a2022-05-01 14:40:55 +00003961 line() << "}";
3962
3963 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003964}
3965
dan sinclair2b9d5b32023-02-28 14:49:25 +00003966bool GeneratorImpl::EmitType(utils::StringStream& out,
dan sinclair5f764d82022-12-08 00:32:27 +00003967 const type::Type* type,
dan sinclair2a651632023-02-19 04:03:55 +00003968 builtin::AddressSpace address_space,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003969 builtin::Access access,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003970 const std::string& name,
3971 bool* name_printed /* = nullptr */) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003972 if (name_printed) {
3973 *name_printed = false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003974 }
dan sinclairff7cf212022-10-03 14:05:23 +00003975 switch (address_space) {
dan sinclair2a651632023-02-19 04:03:55 +00003976 case builtin::AddressSpace::kStorage:
dan sinclairb6cc4cb2023-02-19 04:01:29 +00003977 if (access != builtin::Access::kRead) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003978 out << "RW";
3979 }
3980 out << "ByteAddressBuffer";
3981 return true;
dan sinclair2a651632023-02-19 04:03:55 +00003982 case builtin::AddressSpace::kUniform: {
dan sinclair41e4d9a2022-05-01 14:40:55 +00003983 auto array_length = (type->Size() + 15) / 16;
3984 out << "uint4 " << name << "[" << array_length << "]";
3985 if (name_printed) {
3986 *name_printed = true;
3987 }
3988 return true;
3989 }
3990 default:
3991 break;
3992 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00003993
dan sinclair41e4d9a2022-05-01 14:40:55 +00003994 return Switch(
3995 type,
dan sinclair946858a2022-12-08 22:21:24 +00003996 [&](const type::Array* ary) {
dan sinclair5f764d82022-12-08 00:32:27 +00003997 const type::Type* base_type = ary;
dan sinclair41e4d9a2022-05-01 14:40:55 +00003998 std::vector<uint32_t> sizes;
dan sinclair946858a2022-12-08 22:21:24 +00003999 while (auto* arr = base_type->As<type::Array>()) {
Ben Clayton884f9522023-01-12 22:52:57 +00004000 if (TINT_UNLIKELY(arr->Count()->Is<type::RuntimeArrayCount>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004001 TINT_ICE(Writer, diagnostics_)
dan sinclair78f80672022-09-22 22:28:21 +00004002 << "runtime arrays may only exist in storage buffers, which should have "
Ben Clayton3a68ab42022-06-24 08:30:28 +00004003 "been transformed into a ByteAddressBuffer";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004004 return false;
4005 }
dan sinclair78f80672022-09-22 22:28:21 +00004006 const auto count = arr->ConstantCount();
4007 if (!count) {
4008 diagnostics_.add_error(diag::System::Writer,
dan sinclair946858a2022-12-08 22:21:24 +00004009 type::Array::kErrExpectedConstantCount);
dan sinclair78f80672022-09-22 22:28:21 +00004010 return false;
4011 }
4012
4013 sizes.push_back(count.value());
dan sinclair41e4d9a2022-05-01 14:40:55 +00004014 base_type = arr->ElemType();
4015 }
dan sinclairff7cf212022-10-03 14:05:23 +00004016 if (!EmitType(out, base_type, address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004017 return false;
4018 }
4019 if (!name.empty()) {
4020 out << " " << name;
4021 if (name_printed) {
4022 *name_printed = true;
4023 }
4024 }
4025 for (uint32_t size : sizes) {
4026 out << "[" << size << "]";
4027 }
4028 return true;
4029 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004030 [&](const type::Bool*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004031 out << "bool";
4032 return true;
4033 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004034 [&](const type::F32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004035 out << "float";
4036 return true;
4037 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004038 [&](const type::F16*) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004039 out << "float16_t";
4040 return true;
Zhaoming Jiang62bfd312022-05-13 12:01:11 +00004041 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004042 [&](const type::I32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004043 out << "int";
4044 return true;
4045 },
dan sinclair0e780da2022-12-08 22:21:24 +00004046 [&](const type::Matrix* mat) {
dan sinclaird37ecf92022-12-08 16:39:59 +00004047 if (mat->type()->Is<type::F16>()) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004048 // Use matrix<type, N, M> for f16 matrix
4049 out << "matrix<";
dan sinclairff7cf212022-10-03 14:05:23 +00004050 if (!EmitType(out, mat->type(), address_space, access, "")) {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004051 return false;
4052 }
4053 out << ", " << mat->columns() << ", " << mat->rows() << ">";
4054 return true;
4055 }
dan sinclairff7cf212022-10-03 14:05:23 +00004056 if (!EmitType(out, mat->type(), address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004057 return false;
4058 }
4059 // Note: HLSL's matrices are declared as <type>NxM, where N is the
4060 // number of rows and M is the number of columns. Despite HLSL's
4061 // matrices being column-major by default, the index operator and
dan sinclair6e77b472022-10-20 13:38:28 +00004062 // initializers actually operate on row-vectors, where as WGSL operates
dan sinclair41e4d9a2022-05-01 14:40:55 +00004063 // on column vectors. To simplify everything we use the transpose of the
4064 // matrices. See:
4065 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-per-component-math#matrix-ordering
4066 out << mat->columns() << "x" << mat->rows();
4067 return true;
4068 },
dan sinclair4d56b482022-12-08 17:50:50 +00004069 [&](const type::Pointer*) {
Ben Clayton559e5a22023-04-17 14:24:58 +00004070 TINT_ICE(Writer, diagnostics_) << "Attempting to emit pointer type. These should have "
4071 "been removed with the SimplifyPointers transform";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004072 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004073 },
dan sinclair5ee58b62022-12-08 15:25:18 +00004074 [&](const type::Sampler* sampler) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004075 out << "Sampler";
4076 if (sampler->IsComparison()) {
4077 out << "Comparison";
4078 }
4079 out << "State";
4080 return true;
4081 },
4082 [&](const sem::Struct* str) {
4083 out << StructName(str);
4084 return true;
4085 },
dan sinclair4595fb72022-12-08 14:14:10 +00004086 [&](const type::Texture* tex) {
Ben Clayton884f9522023-01-12 22:52:57 +00004087 if (TINT_UNLIKELY(tex->Is<type::ExternalTexture>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004088 TINT_ICE(Writer, diagnostics_)
4089 << "Multiplanar external texture transform was not run.";
4090 return false;
4091 }
Brandon Jones6661b282022-02-25 20:14:52 +00004092
dan sinclair4595fb72022-12-08 14:14:10 +00004093 auto* storage = tex->As<type::StorageTexture>();
4094 auto* ms = tex->As<type::MultisampledTexture>();
4095 auto* depth_ms = tex->As<type::DepthMultisampledTexture>();
4096 auto* sampled = tex->As<type::SampledTexture>();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004097
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004098 if (storage && storage->access() != builtin::Access::kRead) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004099 out << "RW";
4100 }
4101 out << "Texture";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004102
dan sinclair41e4d9a2022-05-01 14:40:55 +00004103 switch (tex->dim()) {
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004104 case type::TextureDimension::k1d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004105 out << "1D";
4106 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004107 case type::TextureDimension::k2d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004108 out << ((ms || depth_ms) ? "2DMS" : "2D");
4109 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004110 case type::TextureDimension::k2dArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004111 out << ((ms || depth_ms) ? "2DMSArray" : "2DArray");
4112 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004113 case type::TextureDimension::k3d:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004114 out << "3D";
4115 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004116 case type::TextureDimension::kCube:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004117 out << "Cube";
4118 break;
dan sinclair3cbf3fc2023-01-21 19:16:15 +00004119 case type::TextureDimension::kCubeArray:
dan sinclair41e4d9a2022-05-01 14:40:55 +00004120 out << "CubeArray";
4121 break;
4122 default:
4123 TINT_UNREACHABLE(Writer, diagnostics_)
4124 << "unexpected TextureDimension " << tex->dim();
4125 return false;
4126 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004127
dan sinclair41e4d9a2022-05-01 14:40:55 +00004128 if (storage) {
4129 auto* component = image_format_to_rwtexture_type(storage->texel_format());
Ben Clayton884f9522023-01-12 22:52:57 +00004130 if (TINT_UNLIKELY(!component)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004131 TINT_ICE(Writer, diagnostics_) << "Unsupported StorageTexture TexelFormat: "
4132 << static_cast<int>(storage->texel_format());
4133 return false;
4134 }
4135 out << "<" << component << ">";
4136 } else if (depth_ms) {
4137 out << "<float4>";
4138 } else if (sampled || ms) {
4139 auto* subtype = sampled ? sampled->type() : ms->type();
4140 out << "<";
dan sinclaird37ecf92022-12-08 16:39:59 +00004141 if (subtype->Is<type::F32>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004142 out << "float4";
dan sinclaird37ecf92022-12-08 16:39:59 +00004143 } else if (subtype->Is<type::I32>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004144 out << "int4";
Ben Clayton884f9522023-01-12 22:52:57 +00004145 } else if (TINT_LIKELY(subtype->Is<type::U32>())) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004146 out << "uint4";
4147 } else {
4148 TINT_ICE(Writer, diagnostics_) << "Unsupported multisampled texture type";
4149 return false;
4150 }
4151 out << ">";
4152 }
4153 return true;
4154 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004155 [&](const type::U32*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004156 out << "uint";
4157 return true;
4158 },
dan sinclair0e780da2022-12-08 22:21:24 +00004159 [&](const type::Vector* vec) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004160 auto width = vec->Width();
dan sinclaird37ecf92022-12-08 16:39:59 +00004161 if (vec->type()->Is<type::F32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004162 out << "float" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004163 } else if (vec->type()->Is<type::I32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004164 out << "int" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004165 } else if (vec->type()->Is<type::U32>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004166 out << "uint" << width;
dan sinclaird37ecf92022-12-08 16:39:59 +00004167 } else if (vec->type()->Is<type::Bool>() && width >= 1 && width <= 4) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004168 out << "bool" << width;
4169 } else {
Zhaoming Jianga5988a32022-07-11 15:43:38 +00004170 // For example, use "vector<float16_t, N>" for f16 vector.
dan sinclair41e4d9a2022-05-01 14:40:55 +00004171 out << "vector<";
dan sinclairff7cf212022-10-03 14:05:23 +00004172 if (!EmitType(out, vec->type(), address_space, access, "")) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004173 return false;
4174 }
4175 out << ", " << width << ">";
4176 }
4177 return true;
4178 },
dan sinclaird8a08452022-12-08 22:21:24 +00004179 [&](const type::Atomic* atomic) {
dan sinclairff7cf212022-10-03 14:05:23 +00004180 return EmitType(out, atomic->Type(), address_space, access, name);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004181 },
dan sinclaird37ecf92022-12-08 16:39:59 +00004182 [&](const type::Void*) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004183 out << "void";
4184 return true;
4185 },
4186 [&](Default) {
4187 diagnostics_.add_error(diag::System::Writer, "unknown type in EmitType");
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004188 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004189 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004190}
4191
dan sinclair2b9d5b32023-02-28 14:49:25 +00004192bool GeneratorImpl::EmitTypeAndName(utils::StringStream& out,
dan sinclair5f764d82022-12-08 00:32:27 +00004193 const type::Type* type,
dan sinclair2a651632023-02-19 04:03:55 +00004194 builtin::AddressSpace address_space,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004195 builtin::Access access,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004196 const std::string& name) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004197 bool name_printed = false;
dan sinclairff7cf212022-10-03 14:05:23 +00004198 if (!EmitType(out, type, address_space, access, name, &name_printed)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004199 return false;
4200 }
4201 if (!name.empty() && !name_printed) {
4202 out << " " << name;
4203 }
4204 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004205}
4206
4207bool GeneratorImpl::EmitStructType(TextBuffer* b, const sem::Struct* str) {
Ben Clayton329dfd72022-11-23 00:05:05 +00004208 auto it = emitted_structs_.emplace(str);
4209 if (!it.second) {
4210 return true;
4211 }
4212
dan sinclair41e4d9a2022-05-01 14:40:55 +00004213 line(b) << "struct " << StructName(str) << " {";
4214 {
4215 ScopedIndent si(b);
4216 for (auto* mem : str->Members()) {
4217 auto mem_name = builder_.Symbols().NameFor(mem->Name());
dan sinclair41e4d9a2022-05-01 14:40:55 +00004218 auto* ty = mem->Type();
dan sinclair41e4d9a2022-05-01 14:40:55 +00004219 auto out = line(b);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004220 std::string pre, post;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004221 if (auto* decl = mem->Declaration()) {
4222 for (auto* attr : decl->attributes) {
dan sinclairf9eeed62022-09-07 22:25:24 +00004223 if (attr->Is<ast::LocationAttribute>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004224 auto& pipeline_stage_uses = str->PipelineStageUses();
Ben Clayton884f9522023-01-12 22:52:57 +00004225 if (TINT_UNLIKELY(pipeline_stage_uses.size() != 1)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004226 TINT_ICE(Writer, diagnostics_) << "invalid entry point IO struct uses";
4227 }
4228
dan sinclairf9eeed62022-09-07 22:25:24 +00004229 auto loc = mem->Location().value();
dan sinclairf53b2b52022-12-08 22:21:24 +00004230 if (pipeline_stage_uses.count(type::PipelineStageUsage::kVertexInput)) {
dan sinclairf9eeed62022-09-07 22:25:24 +00004231 post += " : TEXCOORD" + std::to_string(loc);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004232 } else if (pipeline_stage_uses.count(
dan sinclairf53b2b52022-12-08 22:21:24 +00004233 type::PipelineStageUsage::kVertexOutput)) {
dan sinclairf9eeed62022-09-07 22:25:24 +00004234 post += " : TEXCOORD" + std::to_string(loc);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004235 } else if (pipeline_stage_uses.count(
dan sinclairf53b2b52022-12-08 22:21:24 +00004236 type::PipelineStageUsage::kFragmentInput)) {
dan sinclairf9eeed62022-09-07 22:25:24 +00004237 post += " : TEXCOORD" + std::to_string(loc);
Ben Clayton884f9522023-01-12 22:52:57 +00004238 } else if (TINT_LIKELY(pipeline_stage_uses.count(
4239 type::PipelineStageUsage::kFragmentOutput))) {
dan sinclairf9eeed62022-09-07 22:25:24 +00004240 post += " : SV_Target" + std::to_string(loc);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004241 } else {
4242 TINT_ICE(Writer, diagnostics_) << "invalid use of location attribute";
4243 }
Ben Clayton4d3ff972023-02-21 17:33:54 +00004244 } else if (auto* builtin_attr = attr->As<ast::BuiltinAttribute>()) {
4245 auto builtin = program_->Sem().Get(builtin_attr)->Value();
4246 auto name = builtin_to_attribute(builtin);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004247 if (name.empty()) {
4248 diagnostics_.add_error(diag::System::Writer, "unsupported builtin");
4249 return false;
4250 }
4251 post += " : " + name;
4252 } else if (auto* interpolate = attr->As<ast::InterpolateAttribute>()) {
Ben Claytonf0b4dbb2023-02-21 21:05:28 +00004253 auto& sem = program_->Sem();
4254 auto i_type =
4255 sem.Get<sem::BuiltinEnumExpression<builtin::InterpolationType>>(
4256 interpolate->type)
4257 ->Value();
4258
4259 auto i_smpl = builtin::InterpolationSampling::kUndefined;
4260 if (interpolate->sampling) {
4261 i_smpl =
4262 sem.Get<sem::BuiltinEnumExpression<builtin::InterpolationSampling>>(
4263 interpolate->sampling)
4264 ->Value();
4265 }
4266
4267 auto mod = interpolation_to_modifiers(i_type, i_smpl);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004268 if (mod.empty()) {
4269 diagnostics_.add_error(diag::System::Writer,
4270 "unsupported interpolation");
4271 return false;
4272 }
4273 pre += mod;
4274
4275 } else if (attr->Is<ast::InvariantAttribute>()) {
4276 // Note: `precise` is not exactly the same as `invariant`, but is
4277 // stricter and therefore provides the necessary guarantees.
4278 // See discussion here: https://github.com/gpuweb/gpuweb/issues/893
4279 pre += "precise ";
Ben Clayton884f9522023-01-12 22:52:57 +00004280 } else if (TINT_UNLIKELY((!attr->IsAnyOf<ast::StructMemberAlignAttribute,
4281 ast::StructMemberOffsetAttribute,
4282 ast::StructMemberSizeAttribute>()))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004283 TINT_ICE(Writer, diagnostics_)
4284 << "unhandled struct member attribute: " << attr->Name();
4285 return false;
4286 }
4287 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004288 }
4289
dan sinclair41e4d9a2022-05-01 14:40:55 +00004290 out << pre;
dan sinclair2a651632023-02-19 04:03:55 +00004291 if (!EmitTypeAndName(out, ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004292 builtin::Access::kReadWrite, mem_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004293 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004294 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004295 out << post << ";";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004296 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004297 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004298
dan sinclair41e4d9a2022-05-01 14:40:55 +00004299 line(b) << "};";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004300 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004301}
4302
dan sinclair2b9d5b32023-02-28 14:49:25 +00004303bool GeneratorImpl::EmitUnaryOp(utils::StringStream& out, const ast::UnaryOpExpression* expr) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004304 switch (expr->op) {
4305 case ast::UnaryOp::kIndirection:
4306 case ast::UnaryOp::kAddressOf:
4307 return EmitExpression(out, expr->expr);
4308 case ast::UnaryOp::kComplement:
4309 out << "~";
4310 break;
4311 case ast::UnaryOp::kNot:
4312 out << "!";
4313 break;
4314 case ast::UnaryOp::kNegation:
4315 out << "-";
4316 break;
4317 }
4318 out << "(";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004319
dan sinclair41e4d9a2022-05-01 14:40:55 +00004320 if (!EmitExpression(out, expr->expr)) {
4321 return false;
4322 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004323
dan sinclair41e4d9a2022-05-01 14:40:55 +00004324 out << ")";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004325
dan sinclair41e4d9a2022-05-01 14:40:55 +00004326 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004327}
4328
Ben Claytondcdf66e2022-06-17 12:48:51 +00004329bool GeneratorImpl::EmitVar(const ast::Var* var) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004330 auto* sem = builder_.Sem().Get(var);
4331 auto* type = sem->Type()->UnwrapRef();
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004332
dan sinclair41e4d9a2022-05-01 14:40:55 +00004333 auto out = line();
dan sinclairff7cf212022-10-03 14:05:23 +00004334 if (!EmitTypeAndName(out, type, sem->AddressSpace(), sem->Access(),
Ben Clayton651d9e22023-02-09 10:34:14 +00004335 builder_.Symbols().NameFor(var->name->symbol))) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004336 return false;
4337 }
4338
4339 out << " = ";
4340
dan sinclair6e77b472022-10-20 13:38:28 +00004341 if (var->initializer) {
4342 if (!EmitExpression(out, var->initializer)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004343 return false;
4344 }
4345 } else {
4346 if (!EmitZeroValue(out, type)) {
4347 return false;
4348 }
4349 }
4350 out << ";";
4351
4352 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004353}
4354
Ben Claytondcdf66e2022-06-17 12:48:51 +00004355bool GeneratorImpl::EmitLet(const ast::Let* let) {
4356 auto* sem = builder_.Sem().Get(let);
4357 auto* type = sem->Type()->UnwrapRef();
4358
4359 auto out = line();
4360 out << "const ";
dan sinclair2a651632023-02-19 04:03:55 +00004361 if (!EmitTypeAndName(out, type, builtin::AddressSpace::kUndefined, builtin::Access::kUndefined,
Ben Clayton651d9e22023-02-09 10:34:14 +00004362 builder_.Symbols().NameFor(let->name->symbol))) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004363 return false;
dan sinclair41e4d9a2022-05-01 14:40:55 +00004364 }
Ben Claytondcdf66e2022-06-17 12:48:51 +00004365 out << " = ";
dan sinclair6e77b472022-10-20 13:38:28 +00004366 if (!EmitExpression(out, let->initializer)) {
Ben Claytondcdf66e2022-06-17 12:48:51 +00004367 return false;
4368 }
4369 out << ";";
dan sinclair41e4d9a2022-05-01 14:40:55 +00004370
Ben Claytondcdf66e2022-06-17 12:48:51 +00004371 return true;
4372}
4373
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004374template <typename F>
dan sinclair2b9d5b32023-02-28 14:49:25 +00004375bool GeneratorImpl::CallBuiltinHelper(utils::StringStream& out,
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004376 const ast::CallExpression* call,
4377 const sem::Builtin* builtin,
4378 F&& build) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004379 // Generate the helper function if it hasn't been created already
4380 auto fn = utils::GetOrCreate(builtins_, builtin, [&]() -> std::string {
4381 TextBuffer b;
4382 TINT_DEFER(helpers_.Append(b));
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004383
dan sinclair9543f742023-03-09 01:20:16 +00004384 auto fn_name = UniqueIdentifier(std::string("tint_") + builtin::str(builtin->Type()));
dan sinclair41e4d9a2022-05-01 14:40:55 +00004385 std::vector<std::string> parameter_names;
4386 {
4387 auto decl = line(&b);
dan sinclair2a651632023-02-19 04:03:55 +00004388 if (!EmitTypeAndName(decl, builtin->ReturnType(), builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004389 builtin::Access::kUndefined, fn_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004390 return "";
4391 }
4392 {
4393 ScopedParen sp(decl);
4394 for (auto* param : builtin->Parameters()) {
4395 if (!parameter_names.empty()) {
4396 decl << ", ";
4397 }
4398 auto param_name = "param_" + std::to_string(parameter_names.size());
4399 const auto* ty = param->Type();
dan sinclair4d56b482022-12-08 17:50:50 +00004400 if (auto* ptr = ty->As<type::Pointer>()) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004401 decl << "inout ";
4402 ty = ptr->StoreType();
4403 }
dan sinclair2a651632023-02-19 04:03:55 +00004404 if (!EmitTypeAndName(decl, ty, builtin::AddressSpace::kUndefined,
dan sinclairb6cc4cb2023-02-19 04:01:29 +00004405 builtin::Access::kUndefined, param_name)) {
dan sinclair41e4d9a2022-05-01 14:40:55 +00004406 return "";
4407 }
4408 parameter_names.emplace_back(std::move(param_name));
4409 }
4410 }
4411 decl << " {";
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004412 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004413 {
4414 ScopedIndent si(&b);
4415 if (!build(&b, parameter_names)) {
4416 return "";
4417 }
4418 }
4419 line(&b) << "}";
4420 line(&b);
4421 return fn_name;
4422 });
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004423
dan sinclair41e4d9a2022-05-01 14:40:55 +00004424 if (fn.empty()) {
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004425 return false;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004426 }
dan sinclair41e4d9a2022-05-01 14:40:55 +00004427
4428 // Call the helper
4429 out << fn;
4430 {
dan sinclairb2ba57b2023-02-28 15:14:09 +00004431 ScopedParen sp(out);
dan sinclair41e4d9a2022-05-01 14:40:55 +00004432 bool first = true;
4433 for (auto* arg : call->args) {
4434 if (!first) {
4435 out << ", ";
4436 }
4437 first = false;
4438 if (!EmitExpression(out, arg)) {
4439 return false;
4440 }
4441 }
4442 }
4443 return true;
Ryan Harrisondbc13af2022-02-21 15:19:07 +00004444}
4445
dan sinclair6a5bef12022-04-07 14:30:24 +00004446} // namespace tint::writer::hlsl