transform: More robustness for texture ops

Clamp the `level` and `array_index` arguments to `textureLoad()` and `textureStore()`.
Also fix the off-by-one error for the coordinates.

See: https://github.com/gpuweb/gpuweb/pull/1906

Fixed: tint:748
Change-Id: Id7505578b632dcaf75b2a3a020fc0190c612972c
Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/57700
Kokoro: Kokoro <noreply+kokoro@google.com>
Auto-Submit: Ben Clayton <bclayton@google.com>
Reviewed-by: David Neto <dneto@google.com>
Commit-Queue: Ben Clayton <bclayton@google.com>
This commit is contained in:
Ben Clayton 2021-07-15 16:41:05 +00:00 committed by Tint LUCI CQ
parent 487a913e31
commit 1d10086d28
3 changed files with 246 additions and 136 deletions

View File

@ -18,6 +18,7 @@
#include <utility>
#include "src/program_builder.h"
#include "src/sem/block_statement.h"
#include "src/sem/call.h"
#include "src/sem/expression.h"
#include "src/sem/statement.h"
@ -27,113 +28,180 @@ TINT_INSTANTIATE_TYPEINFO(tint::transform::Robustness);
namespace tint {
namespace transform {
/// State holds the current transform state
struct Robustness::State {
/// The clone context
CloneContext& ctx;
/// Applies the transformation state to `ctx`.
void Transform() {
ctx.ReplaceAll(
[&](ast::ArrayAccessorExpression* expr) { return Transform(expr); });
ctx.ReplaceAll([&](ast::CallExpression* expr) { return Transform(expr); });
}
/// Apply bounds clamping to array, vector and matrix indexing
/// @param expr the array, vector or matrix index expression
/// @return the clamped replacement expression, or nullptr if `expr` should be
/// cloned without changes.
ast::ArrayAccessorExpression* Transform(ast::ArrayAccessorExpression* expr) {
auto* ret_type = ctx.src->Sem().Get(expr->array())->Type()->UnwrapRef();
if (!ret_type->IsAnyOf<sem::Array, sem::Matrix, sem::Vector>()) {
return nullptr;
}
ProgramBuilder& b = *ctx.dst;
using u32 = ProgramBuilder::u32;
uint32_t size = 0;
bool is_vec = ret_type->Is<sem::Vector>();
bool is_arr = ret_type->Is<sem::Array>();
if (is_vec || is_arr) {
size = is_vec ? ret_type->As<sem::Vector>()->size()
: ret_type->As<sem::Array>()->Count();
} else {
// The row accessor would have been an embedded array accessor and already
// handled, so we just need to do columns here.
size = ret_type->As<sem::Matrix>()->columns();
}
auto* const old_idx = expr->idx_expr();
b.SetSource(ctx.Clone(old_idx->source()));
ast::Expression* new_idx = nullptr;
if (size == 0) {
if (!is_arr) {
b.Diagnostics().add_error(diag::System::Transform,
"invalid 0 sized non-array", expr->source());
return nullptr;
}
// Runtime sized array
auto* arr = ctx.Clone(expr->array());
auto* arr_len = b.Call("arrayLength", b.AddressOf(arr));
auto* limit = b.Sub(arr_len, b.Expr(1u));
new_idx = b.Call("min", b.Construct<u32>(ctx.Clone(old_idx)), limit);
} else if (auto* c = old_idx->As<ast::ScalarConstructorExpression>()) {
// Scalar constructor we can re-write the value to be within bounds.
auto* lit = c->literal();
if (auto* sint = lit->As<ast::SintLiteral>()) {
int32_t max = static_cast<int32_t>(size) - 1;
new_idx = b.Expr(std::max(std::min(sint->value(), max), 0));
} else if (auto* uint = lit->As<ast::UintLiteral>()) {
new_idx = b.Expr(std::min(uint->value(), size - 1));
} else {
b.Diagnostics().add_error(
diag::System::Transform,
"unknown scalar constructor type for accessor", expr->source());
return nullptr;
}
} else {
auto* cloned_idx = ctx.Clone(old_idx);
new_idx = b.Call("min", b.Construct<u32>(cloned_idx), b.Expr(size - 1));
}
// Clone arguments outside of create() call to have deterministic ordering
auto src = ctx.Clone(expr->source());
auto* arr = ctx.Clone(expr->array());
return b.IndexAccessor(src, arr, new_idx);
}
/// @param type intrinsic type
/// @returns true if the given intrinsic is a texture function that requires
/// argument clamping,
bool TextureIntrinsicNeedsClamping(sem::IntrinsicType type) {
return type == sem::IntrinsicType::kTextureLoad ||
type == sem::IntrinsicType::kTextureStore;
}
/// Apply bounds clamping to the coordinates, array index and level arguments
/// of the `textureLoad()` and `textureStore()` intrinsics.
/// @param expr the intrinsic call expression
/// @return the clamped replacement call expression, or nullptr if `expr`
/// should be cloned without changes.
ast::CallExpression* Transform(ast::CallExpression* expr) {
auto* call = ctx.src->Sem().Get(expr);
auto* call_target = call->Target();
auto* intrinsic = call_target->As<sem::Intrinsic>();
if (!intrinsic || !TextureIntrinsicNeedsClamping(intrinsic->Type())) {
return nullptr; // No transform, just clone.
}
ProgramBuilder& b = *ctx.dst;
// Indices of the mandatory texture and coords parameters, and the optional
// array and level parameters.
auto texture_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kTexture);
auto coords_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kCoords);
auto array_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kArrayIndex);
auto level_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kLevel);
auto* texture_arg = expr->params()[texture_idx];
auto* coords_arg = expr->params()[coords_idx];
auto* coords_ty = intrinsic->Parameters()[coords_idx].type;
// If the level is provided, then we need to clamp this. As the level is
// used by textureDimensions() and the texture[Load|Store]() calls, we need
// to clamp both usages.
// TODO(bclayton): We probably want to place this into a let so that the
// calculation can be reused. This is fiddly to get right.
std::function<ast::Expression*()> level_arg;
if (level_idx >= 0) {
level_arg = [&] {
auto* arg = expr->params()[level_idx];
auto* num_levels = b.Call("textureNumLevels", ctx.Clone(texture_arg));
auto* zero = b.Expr(0);
auto* max = ctx.dst->Sub(num_levels, 1);
auto* clamped = b.Call("clamp", ctx.Clone(arg), zero, max);
return clamped;
};
}
// Clamp the coordinates argument
{
auto* texture_dims =
level_arg
? b.Call("textureDimensions", ctx.Clone(texture_arg), level_arg())
: b.Call("textureDimensions", ctx.Clone(texture_arg));
auto* zero = b.Construct(CreateASTTypeFor(&ctx, coords_ty));
auto* max = ctx.dst->Sub(
texture_dims, b.Construct(CreateASTTypeFor(&ctx, coords_ty), 1));
auto* clamped_coords = b.Call("clamp", ctx.Clone(coords_arg), zero, max);
ctx.Replace(coords_arg, clamped_coords);
}
// Clamp the array_index argument, if provided
if (array_idx >= 0) {
auto* arg = expr->params()[array_idx];
auto* num_layers = b.Call("textureNumLayers", ctx.Clone(texture_arg));
auto* zero = b.Expr(0);
auto* max = ctx.dst->Sub(num_layers, 1);
auto* clamped = b.Call("clamp", ctx.Clone(arg), zero, max);
ctx.Replace(arg, clamped);
}
// Clamp the level argument, if provided
if (level_idx >= 0) {
auto* arg = expr->params()[level_idx];
ctx.Replace(arg, level_arg ? level_arg() : ctx.dst->Expr(0));
}
return nullptr; // Clone, which will use the argument replacements above.
}
};
Robustness::Robustness() = default;
Robustness::~Robustness() = default;
void Robustness::Run(CloneContext& ctx, const DataMap&, DataMap&) {
ctx.ReplaceAll([&](ast::ArrayAccessorExpression* expr) {
return Transform(expr, &ctx);
});
ctx.ReplaceAll(
[&](ast::CallExpression* expr) { return Transform(expr, &ctx); });
State state{ctx};
state.Transform();
ctx.Clone();
}
// Apply bounds clamping to array, vector and matrix indexing
ast::ArrayAccessorExpression* Robustness::Transform(
ast::ArrayAccessorExpression* expr,
CloneContext* ctx) {
auto* ret_type = ctx->src->Sem().Get(expr->array())->Type()->UnwrapRef();
if (!ret_type->IsAnyOf<sem::Array, sem::Matrix, sem::Vector>()) {
return nullptr;
}
ProgramBuilder& b = *ctx->dst;
using u32 = ProgramBuilder::u32;
uint32_t size = 0;
bool is_vec = ret_type->Is<sem::Vector>();
bool is_arr = ret_type->Is<sem::Array>();
if (is_vec || is_arr) {
size = is_vec ? ret_type->As<sem::Vector>()->size()
: ret_type->As<sem::Array>()->Count();
} else {
// The row accessor would have been an embedded array accessor and already
// handled, so we just need to do columns here.
size = ret_type->As<sem::Matrix>()->columns();
}
auto* const old_idx = expr->idx_expr();
b.SetSource(ctx->Clone(old_idx->source()));
ast::Expression* new_idx = nullptr;
if (size == 0) {
if (!is_arr) {
b.Diagnostics().add_error(diag::System::Transform,
"invalid 0 sized non-array", expr->source());
return nullptr;
}
// Runtime sized array
auto* arr = ctx->Clone(expr->array());
auto* arr_len = b.Call("arrayLength", b.AddressOf(arr));
auto* limit = b.Sub(arr_len, b.Expr(1u));
new_idx = b.Call("min", b.Construct<u32>(ctx->Clone(old_idx)), limit);
} else if (auto* c = old_idx->As<ast::ScalarConstructorExpression>()) {
// Scalar constructor we can re-write the value to be within bounds.
auto* lit = c->literal();
if (auto* sint = lit->As<ast::SintLiteral>()) {
int32_t max = static_cast<int32_t>(size) - 1;
new_idx = b.Expr(std::max(std::min(sint->value(), max), 0));
} else if (auto* uint = lit->As<ast::UintLiteral>()) {
new_idx = b.Expr(std::min(uint->value(), size - 1));
} else {
b.Diagnostics().add_error(diag::System::Transform,
"unknown scalar constructor type for accessor",
expr->source());
return nullptr;
}
} else {
auto* cloned_idx = ctx->Clone(old_idx);
new_idx = b.Call("min", b.Construct<u32>(cloned_idx), b.Expr(size - 1));
}
// Clone arguments outside of create() call to have deterministic ordering
auto src = ctx->Clone(expr->source());
auto* arr = ctx->Clone(expr->array());
return b.IndexAccessor(src, arr, new_idx);
}
// Apply bounds clamping textureLoad() and textureStore() coordinates
ast::CallExpression* Robustness::Transform(ast::CallExpression* expr,
CloneContext* ctx) {
auto* call = ctx->src->Sem().Get(expr);
auto* call_target = call->Target();
auto* intrinsic = call_target->As<sem::Intrinsic>();
if (!intrinsic || (intrinsic->Type() != sem::IntrinsicType::kTextureLoad &&
intrinsic->Type() != sem::IntrinsicType::kTextureStore)) {
return nullptr; // No transform, just clone.
}
// Index of the texture and coords parameters for the intrinsic overload
auto texture_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kTexture);
auto coords_idx =
sem::IndexOf(intrinsic->Parameters(), sem::ParameterUsage::kCoords);
auto* texture_arg = expr->params()[texture_idx];
auto* coords_arg = expr->params()[coords_idx];
auto* coords_ty = intrinsic->Parameters()[coords_idx].type;
ProgramBuilder& b = *ctx->dst;
auto* texture_dims = b.Call("textureDimensions", ctx->Clone(texture_arg));
auto* zero_dims = b.Construct(CreateASTTypeFor(ctx, coords_ty));
auto* clamped_coords =
b.Call("clamp", ctx->Clone(coords_arg), zero_dims, texture_dims);
ctx->Replace(coords_arg, clamped_coords);
return nullptr; // Clone, which will use the coords replacement above.
}
} // namespace transform
} // namespace tint

View File

@ -49,9 +49,7 @@ class Robustness : public Castable<Robustness, Transform> {
void Run(CloneContext& ctx, const DataMap& inputs, DataMap& outputs) override;
private:
ast::ArrayAccessorExpression* Transform(ast::ArrayAccessorExpression* expr,
CloneContext* ctx);
ast::CallExpression* Transform(ast::CallExpression* expr, CloneContext* ctx);
struct State;
};
using BoundArrayAccessors = Robustness;

View File

@ -571,39 +571,83 @@ TEST_F(RobustnessTest, DISABLED_Atomics_Clamp) {
FAIL();
}
// Clamp textureLoad() coord values
TEST_F(RobustnessTest, TextureLoad_TextureCoord_Clamp) {
// Clamp textureLoad() coord, array_index and level values
TEST_F(RobustnessTest, TextureLoad_Clamp) {
auto* src = R"(
[[group(0), binding(0)]] var tex1d : texture_1d<f32>;
[[group(0), binding(1)]] var tex2d : texture_2d<f32>;
[[group(0), binding(2)]] var tex3d : texture_3d<f32>;
[[group(0), binding(3)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, read>;
[[group(0), binding(0)]] var tex_1d : texture_1d<f32>;
[[group(0), binding(0)]] var tex_2d : texture_2d<f32>;
[[group(0), binding(0)]] var tex_2d_arr : texture_2d_array<f32>;
[[group(0), binding(0)]] var tex_3d : texture_3d<f32>;
[[group(0), binding(0)]] var tex_ms_2d : texture_multisampled_2d<f32>;
[[group(0), binding(0)]] var tex_depth_2d : texture_depth_2d;
[[group(0), binding(0)]] var tex_depth_2d_arr : texture_depth_2d_array;
[[group(0), binding(0)]] var tex_storage_1d : texture_storage_1d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_2d : texture_storage_2d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_2d_arr : texture_storage_2d_array<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_3d : texture_storage_3d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_external : texture_external;
fn f() {
ignore(textureLoad(tex1d, 10, 100));
ignore(textureLoad(tex2d, vec2<i32>(10, 20), 100));
ignore(textureLoad(tex3d, vec3<i32>(10, 20, 30), 100));
ignore(textureLoad(tex2d_arr, vec2<i32>(10, 20), 100));
var array_idx : i32;
var level_idx : i32;
var sample_idx : i32;
ignore(textureLoad(tex_1d, 1, level_idx));
ignore(textureLoad(tex_2d, vec2<i32>(1, 2), level_idx));
ignore(textureLoad(tex_2d_arr, vec2<i32>(1, 2), array_idx, level_idx));
ignore(textureLoad(tex_3d, vec3<i32>(1, 2, 3), level_idx));
ignore(textureLoad(tex_ms_2d, vec2<i32>(1, 2), sample_idx));
ignore(textureLoad(tex_depth_2d, vec2<i32>(1, 2), level_idx));
ignore(textureLoad(tex_depth_2d_arr, vec2<i32>(1, 2), array_idx, level_idx));
ignore(textureLoad(tex_storage_1d, 1));
ignore(textureLoad(tex_storage_2d, vec2<i32>(1, 2)));
ignore(textureLoad(tex_storage_2d_arr, vec2<i32>(1, 2), array_idx));
ignore(textureLoad(tex_storage_3d, vec3<i32>(1, 2, 3)));
ignore(textureLoad(tex_external, vec2<i32>(1, 2)));
}
)";
auto* expect = R"(
[[group(0), binding(0)]] var tex1d : texture_1d<f32>;
[[group(0), binding(0)]] var tex_1d : texture_1d<f32>;
[[group(0), binding(1)]] var tex2d : texture_2d<f32>;
[[group(0), binding(0)]] var tex_2d : texture_2d<f32>;
[[group(0), binding(2)]] var tex3d : texture_3d<f32>;
[[group(0), binding(0)]] var tex_2d_arr : texture_2d_array<f32>;
[[group(0), binding(3)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, read>;
[[group(0), binding(0)]] var tex_3d : texture_3d<f32>;
[[group(0), binding(0)]] var tex_ms_2d : texture_multisampled_2d<f32>;
[[group(0), binding(0)]] var tex_depth_2d : texture_depth_2d;
[[group(0), binding(0)]] var tex_depth_2d_arr : texture_depth_2d_array;
[[group(0), binding(0)]] var tex_storage_1d : texture_storage_1d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_2d : texture_storage_2d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_2d_arr : texture_storage_2d_array<rgba8sint, read>;
[[group(0), binding(0)]] var tex_storage_3d : texture_storage_3d<rgba8sint, read>;
[[group(0), binding(0)]] var tex_external : external_texture;
fn f() {
ignore(textureLoad(tex1d, clamp(10, i32(), textureDimensions(tex1d)), 100));
ignore(textureLoad(tex2d, clamp(vec2<i32>(10, 20), vec2<i32>(), textureDimensions(tex2d)), 100));
ignore(textureLoad(tex3d, clamp(vec3<i32>(10, 20, 30), vec3<i32>(), textureDimensions(tex3d)), 100));
ignore(textureLoad(tex2d_arr, clamp(vec2<i32>(10, 20), vec2<i32>(), textureDimensions(tex2d_arr)), 100));
var array_idx : i32;
var level_idx : i32;
var sample_idx : i32;
ignore(textureLoad(tex_1d, clamp(1, i32(), (textureDimensions(tex_1d, clamp(level_idx, 0, (textureNumLevels(tex_1d) - 1))) - i32(1))), clamp(level_idx, 0, (textureNumLevels(tex_1d) - 1))));
ignore(textureLoad(tex_2d, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_2d, clamp(level_idx, 0, (textureNumLevels(tex_2d) - 1))) - vec2<i32>(1))), clamp(level_idx, 0, (textureNumLevels(tex_2d) - 1))));
ignore(textureLoad(tex_2d_arr, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_2d_arr, clamp(level_idx, 0, (textureNumLevels(tex_2d_arr) - 1))) - vec2<i32>(1))), clamp(array_idx, 0, (textureNumLayers(tex_2d_arr) - 1)), clamp(level_idx, 0, (textureNumLevels(tex_2d_arr) - 1))));
ignore(textureLoad(tex_3d, clamp(vec3<i32>(1, 2, 3), vec3<i32>(), (textureDimensions(tex_3d, clamp(level_idx, 0, (textureNumLevels(tex_3d) - 1))) - vec3<i32>(1))), clamp(level_idx, 0, (textureNumLevels(tex_3d) - 1))));
ignore(textureLoad(tex_ms_2d, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_ms_2d) - vec2<i32>(1))), sample_idx));
ignore(textureLoad(tex_depth_2d, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_depth_2d, clamp(level_idx, 0, (textureNumLevels(tex_depth_2d) - 1))) - vec2<i32>(1))), clamp(level_idx, 0, (textureNumLevels(tex_depth_2d) - 1))));
ignore(textureLoad(tex_depth_2d_arr, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_depth_2d_arr, clamp(level_idx, 0, (textureNumLevels(tex_depth_2d_arr) - 1))) - vec2<i32>(1))), clamp(array_idx, 0, (textureNumLayers(tex_depth_2d_arr) - 1)), clamp(level_idx, 0, (textureNumLevels(tex_depth_2d_arr) - 1))));
ignore(textureLoad(tex_storage_1d, clamp(1, i32(), (textureDimensions(tex_storage_1d) - i32(1)))));
ignore(textureLoad(tex_storage_2d, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_storage_2d) - vec2<i32>(1)))));
ignore(textureLoad(tex_storage_2d_arr, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_storage_2d_arr) - vec2<i32>(1))), clamp(array_idx, 0, (textureNumLayers(tex_storage_2d_arr) - 1))));
ignore(textureLoad(tex_storage_3d, clamp(vec3<i32>(1, 2, 3), vec3<i32>(), (textureDimensions(tex_storage_3d) - vec3<i32>(1)))));
ignore(textureLoad(tex_external, clamp(vec2<i32>(1, 2), vec2<i32>(), (textureDimensions(tex_external) - vec2<i32>(1)))));
}
)";
@ -612,22 +656,22 @@ fn f() {
EXPECT_EQ(expect, str(got));
}
// Clamp textureStore() coord values
TEST_F(RobustnessTest, TextureStore_TextureCoord_Clamp) {
// Clamp textureStore() coord, array_index and level values
TEST_F(RobustnessTest, TextureStore_Clamp) {
auto* src = R"(
[[group(0), binding(0)]] var tex1d : texture_storage_1d<rgba8sint, write>;
[[group(0), binding(1)]] var tex2d : texture_storage_2d<rgba8sint, write>;
[[group(0), binding(2)]] var tex3d : texture_storage_3d<rgba8sint, write>;
[[group(0), binding(2)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, write>;
[[group(0), binding(3)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, write>;
[[group(0), binding(3)]] var tex3d : texture_storage_3d<rgba8sint, write>;
fn f() {
textureStore(tex1d, 10, vec4<i32>());
textureStore(tex2d, vec2<i32>(10, 20), vec4<i32>());
textureStore(tex3d, vec3<i32>(10, 20, 30), vec4<i32>());
textureStore(tex2d_arr, vec2<i32>(10, 20), 50, vec4<i32>());
textureStore(tex3d, vec3<i32>(10, 20, 30), vec4<i32>());
}
)";
@ -636,15 +680,15 @@ fn f() {
[[group(0), binding(1)]] var tex2d : texture_storage_2d<rgba8sint, write>;
[[group(0), binding(2)]] var tex3d : texture_storage_3d<rgba8sint, write>;
[[group(0), binding(2)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, write>;
[[group(0), binding(3)]] var tex2d_arr : texture_storage_2d_array<rgba8sint, write>;
[[group(0), binding(3)]] var tex3d : texture_storage_3d<rgba8sint, write>;
fn f() {
textureStore(tex1d, clamp(10, i32(), textureDimensions(tex1d)), vec4<i32>());
textureStore(tex2d, clamp(vec2<i32>(10, 20), vec2<i32>(), textureDimensions(tex2d)), vec4<i32>());
textureStore(tex3d, clamp(vec3<i32>(10, 20, 30), vec3<i32>(), textureDimensions(tex3d)), vec4<i32>());
textureStore(tex2d_arr, clamp(vec2<i32>(10, 20), vec2<i32>(), textureDimensions(tex2d_arr)), 50, vec4<i32>());
textureStore(tex1d, clamp(10, i32(), (textureDimensions(tex1d) - i32(1))), vec4<i32>());
textureStore(tex2d, clamp(vec2<i32>(10, 20), vec2<i32>(), (textureDimensions(tex2d) - vec2<i32>(1))), vec4<i32>());
textureStore(tex2d_arr, clamp(vec2<i32>(10, 20), vec2<i32>(), (textureDimensions(tex2d_arr) - vec2<i32>(1))), clamp(50, 0, (textureNumLayers(tex2d_arr) - 1)), vec4<i32>());
textureStore(tex3d, clamp(vec3<i32>(10, 20, 30), vec3<i32>(), (textureDimensions(tex3d) - vec3<i32>(1))), vec4<i32>());
}
)";