summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/shader/validation/expression/binary/div_rem.spec.ts
blob: 0f07abe3aed64df842475a33b22462ec5c4be1ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
export const description = `
Validation tests for division and remainder expressions.
`;

import { makeTestGroup } from '../../../../../common/framework/test_group.js';
import { keysOf, objectsToRecord } from '../../../../../common/util/data_tables.js';
import { assert } from '../../../../../common/util/util.js';
import { kBit } from '../../../../util/constants.js';
import {
  ScalarType,
  Type,
  Value,
  VectorType,
  kAllScalarsAndVectors,
  kConcreteNumericScalarsAndVectors,
  kConvertableToFloatScalar,
  scalarTypeOf,
} from '../../../../util/conversion.js';
import { ShaderValidationTest } from '../../shader_validation_test.js';
import {
  kConstantAndOverrideStages,
  validateConstOrOverrideBinaryOpEval,
} from '../call/builtin/const_override_validation.js';

export const g = makeTestGroup(ShaderValidationTest);

// A list of operators tested in this file.
const kOperators = {
  div: { op: '/' },
  rem: { op: '%' },
} as const;

// A list of scalar and vector types.
const kScalarAndVectorTypes = objectsToRecord(kAllScalarsAndVectors);
const kConcreteNumericScalarAndVectorTypes = objectsToRecord(kConcreteNumericScalarsAndVectors);

g.test('scalar_vector')
  .desc(
    `
  Validates that scalar and vector expressions are only accepted for compatible numeric types.
  `
  )
  .params(u =>
    u
      .combine('lhs', keysOf(kScalarAndVectorTypes))
      .combine(
        'rhs',
        // Skip vec3 and vec4 on the RHS to keep the number of subcases down.
        // vec3 + vec3 and vec4 + vec4 is tested in execution tests.
        keysOf(kScalarAndVectorTypes).filter(
          value => !(value.startsWith('vec3') || value.startsWith('vec4'))
        )
      )
      .beginSubcases()
      .combine('op', keysOf(kOperators))
  )
  .beforeAllSubcases(t => {
    if (
      scalarTypeOf(kScalarAndVectorTypes[t.params.lhs]) === Type.f16 ||
      scalarTypeOf(kScalarAndVectorTypes[t.params.rhs]) === Type.f16
    ) {
      t.selectDeviceOrSkipTestCase('shader-f16');
    }
  })
  .fn(t => {
    const op = kOperators[t.params.op];
    const lhs = kScalarAndVectorTypes[t.params.lhs];
    const rhs = kScalarAndVectorTypes[t.params.rhs];
    const lhsElement = scalarTypeOf(lhs);
    const rhsElement = scalarTypeOf(rhs);
    const hasF16 = lhsElement === Type.f16 || rhsElement === Type.f16;
    const code = `
${hasF16 ? 'enable f16;' : ''}
const lhs = ${lhs.create(1).wgsl()};
const rhs = ${rhs.create(1).wgsl()};
const foo = lhs ${op.op} rhs;
`;

    let elementsCompatible = lhsElement === rhsElement;
    const elementTypes = [lhsElement, rhsElement];

    // Booleans are not allowed for arithmetic expressions.
    if (elementTypes.includes(Type.bool)) {
      elementsCompatible = false;

      // AbstractInt is allowed with everything but booleans which are already checked above.
    } else if (elementTypes.includes(Type.abstractInt)) {
      elementsCompatible = true;

      // AbstractFloat is allowed with AbstractInt (checked above) or float types
    } else if (elementTypes.includes(Type.abstractFloat)) {
      elementsCompatible = elementTypes.every(e => kConvertableToFloatScalar.includes(e));
    }

    // Determine if the full type is compatible. The only invalid case is mixed vector sizes.
    let valid = elementsCompatible;
    if (lhs instanceof VectorType && rhs instanceof VectorType) {
      valid = valid && lhs.width === rhs.width;
    }

    t.expectCompileResult(valid, code);
  });

g.test('scalar_vector_out_of_range')
  .desc(
    `
    Checks that constant or override evaluation of div/rem operations on scalar/vectors that produce out of division by 0 or out of range values cause validation errors.
      - Checks for all concrete numeric scalar and vector types, including scalar * vector and vector * scalar.
      - Checks for all vector elements that could cause the out of range to happen.
      - Checks for valid small cases and 0, also the minimum i32.
  `
  )
  .params(u =>
    u
      .combine('op', keysOf(kOperators))
      .combine('lhs', keysOf(kConcreteNumericScalarAndVectorTypes))
      .expand('rhs', p => {
        if (kScalarAndVectorTypes[p.lhs] instanceof VectorType) {
          return [p.lhs, scalarTypeOf(kScalarAndVectorTypes[p.lhs]).toString()];
        }
        return [p.lhs];
      })
      .beginSubcases()
      .expand('swap', p => {
        if (p.lhs === p.rhs) {
          return [false];
        }
        return [false, true];
      })
      .combine('nonOneIndex', [0, 1, 2, 3])
      .filter(p => {
        const lType = kScalarAndVectorTypes[p.lhs];
        if (lType instanceof VectorType) {
          return lType.width > p.nonOneIndex;
        }
        return p.nonOneIndex === 0;
      })
      .expandWithParams(p => {
        const cases = [
          { leftValue: 42, rightValue: 0, error: true, leftRuntime: false },
          { leftValue: 42, rightValue: 0, error: true, leftRuntime: true },
          { leftValue: 0, rightValue: 0, error: true, leftRuntime: true },
          { leftValue: 0, rightValue: 42, error: false, leftRuntime: false },
        ];
        if (p.lhs === 'i32') {
          cases.push({
            leftValue: -kBit.i32.negative.min,
            rightValue: -1,
            error: true,
            leftRuntime: false,
          });
          cases.push({
            leftValue: -kBit.i32.negative.min + 1,
            rightValue: -1,
            error: false,
            leftRuntime: false,
          });
        }
        return cases;
      })
      .combine('stage', kConstantAndOverrideStages)
  )
  .beforeAllSubcases(t => {
    if (
      scalarTypeOf(kScalarAndVectorTypes[t.params.lhs]) === Type.f16 ||
      scalarTypeOf(kScalarAndVectorTypes[t.params.rhs]) === Type.f16
    ) {
      t.selectDeviceOrSkipTestCase('shader-f16');
    }
  })
  .fn(t => {
    const { op, leftValue, rightValue, error, leftRuntime, nonOneIndex, swap } = t.params;
    let { lhs, rhs } = t.params;

    // Handle the swapping of LHS and RHS to test all cases of scalar * vector.
    if (swap) {
      [rhs, lhs] = [lhs, rhs];
    }

    // Creates either a scalar with the value, or a vector with the value only at a specific index.
    const create = (type: ScalarType | VectorType, index: number, value: number): Value => {
      if (type instanceof ScalarType) {
        return type.create(value);
      } else {
        assert(type instanceof VectorType);
        const values = new Array(type.width);
        values.fill(1);
        values[index] = value;
        return type.create(values);
      }
    };

    // Check if there is overflow
    validateConstOrOverrideBinaryOpEval(
      t,
      kOperators[op].op,
      !error,
      leftRuntime ? 'runtime' : t.params.stage,
      create(kScalarAndVectorTypes[lhs], nonOneIndex, leftValue),
      t.params.stage,
      create(kScalarAndVectorTypes[rhs], nonOneIndex, rightValue)
    );
  });

interface InvalidTypeConfig {
  // An expression that produces a value of the target type.
  expr: string;
  // A function that converts an expression of the target type into a valid integer operand.
  control: (x: string) => string;
}
const kInvalidTypes: Record<string, InvalidTypeConfig> = {
  array: {
    expr: 'arr',
    control: e => `${e}[0]`,
  },

  ptr: {
    expr: '(&u)',
    control: e => `*${e}`,
  },

  atomic: {
    expr: 'a',
    control: e => `atomicLoad(&${e})`,
  },

  texture: {
    expr: 't',
    control: e => `i32(textureLoad(${e}, vec2(), 0).x)`,
  },

  sampler: {
    expr: 's',
    control: e => `i32(textureSampleLevel(t, ${e}, vec2(), 0).x)`,
  },

  struct: {
    expr: 'str',
    control: e => `${e}.u`,
  },
};

g.test('invalid_type_with_itself')
  .desc(
    `
  Validates that expressions are never accepted for non-scalar, non-vector, and non-matrix types.
  `
  )
  .params(u =>
    u
      .combine('op', keysOf(kOperators))
      .combine('type', keysOf(kInvalidTypes))
      .combine('control', [true, false])
      .beginSubcases()
  )
  .fn(t => {
    const op = kOperators[t.params.op];
    const type = kInvalidTypes[t.params.type];
    const expr = t.params.control ? type.control(type.expr) : type.expr;
    const code = `
@group(0) @binding(0) var t : texture_2d<f32>;
@group(0) @binding(1) var s : sampler;
@group(0) @binding(2) var<storage, read_write> a : atomic<i32>;

struct S { u : u32 }

var<private> u : u32;
var<private> m : mat2x2f;
var<private> arr : array<i32, 4>;
var<private> str : S;

@compute @workgroup_size(1)
fn main() {
  let foo = ${expr} ${op.op} ${expr};
}
`;

    t.expectCompileResult(t.params.control, code);
  });