Debian Codegraph @

js/src/jit-test/tests/wasm/multi-value/random-tests.js

raw
1
2 // This file tests multi-value returns. It creates a chain of wasm functions
3 //
4 // fnStart -> fnMid0 -> fnMid1 -> fnMid2 -> fnMid3 -> fnEnd
5 //
6 // When run, fnStart creates 12 (or in the non-simd case, 8) random values, of
7 // various types. It then passes them to fnMid0. That reorders them and
8 // passes them on to fnMid1, etc, until they arrive at fnEnd.
9 //
10 // fnEnd makes a small and reversible change to each value. It then reorders
11 // them and returns all of them. The returned values get passed back along
12 // the chain, being randomly reordered at each step, until they arrive back at
13 // fnStart.
14 //
15 // fnStart backs out the changes made in fnEnd and checks that the resulting
16 // values are the same as the originals it created. If they are not, the test
17 // has failed.
18 //
19 // If the test passes, we can be sure each value got passed along the chain
20 // and back again correctly, despite being in a probably different argument or
21 // return position each time (due to the reordering). As a side effect, this
22 // test also is a pretty good test of argument passing. The number of values
23 // (10) is chosen so as to be larger than the number of args that can be
24 // passed in regs on any target; hence it also tests the logic for passing
25 // args in regs vs memory too.
26 //
27 // The whole process (generate and run a test program) is repeated 120 times.
28 //
29 // Doing this requires some supporting functions to be defined in wasm, by
30 // `funcs_util` and `funcs_rng` (a random number generator).
31 //
32 // It is almost impossible to understand what the tests do by reading the JS
33 // below. Reading the generated wasm is required. Search for "if (0)" below.
34
35 // Some utility functions for use in the generated code.
36 function funcs_util(simdEnabled) {
37 let t =
38 (simdEnabled ?
39 `;; Create a v128 value from 2 i64 values
40 (func $v128_from_i64HL (export "v128_from_i64HL")
41 (param $i64hi i64) (param $i64lo i64) (result v128)
42 (local $vec v128)
43 (local.set $vec (i64x2.replace_lane 0 (local.get $vec) (local.get $i64lo)))
44 (local.set $vec (i64x2.replace_lane 1 (local.get $vec) (local.get $i64hi)))
45 (local.get $vec)
46 )
47 ;; Split a v128 up into pieces.
48 (func $v128hi (export "v128hi") (param $vec v128) (result i64)
49 (return (i64x2.extract_lane 1 (local.get $vec)))
50 )
51 (func $v128lo (export "v128lo") (param $vec v128) (result i64)
52 (return (i64x2.extract_lane 0 (local.get $vec)))
53 )
54 ;; Return an i32 value, which is 0 if the args are identical and 1 otherwise.
55 (func $v128ne (export "v128ne")
56 (param $vec1 v128) (param $vec2 v128) (result i32)
57 (return (v128.any_true (v128.xor (local.get $vec1) (local.get $vec2))))
58 )`
59 : ``/* simd not enabled*/
60 ) +
61 `;; Move an i32 value forwards and backwards.
62 (func $step_i32 (export "step_i32") (param $n i32) (result i32)
63 (return (i32.add (local.get $n) (i32.const 1337)))
64 )
65 (func $unstep_i32 (export "unstep_i32") (param $n i32) (result i32)
66 (return (i32.sub (local.get $n) (i32.const 1337)))
67 )
68 ;; Move an i64 value forwards and backwards.
69 (func $step_i64 (export "step_i64") (param $n i64) (result i64)
70 (return (i64.add (local.get $n) (i64.const 4771)))
71 )
72 (func $unstep_i64 (export "unstep_i64") (param $n i64) (result i64)
73 (return (i64.sub (local.get $n) (i64.const 4771)))
74 )
75 ;; Move a f32 value forwards and backwards. This is a bit tricky because
76 ;; we need to guarantee that the backwards move exactly cancels out the
77 ;; forward move. So we multiply/divide exactly by 2 on the basis that that
78 ;; will change the exponent but not the mantissa, at least for normalised
79 ;; numbers.
80 (func $step_f32 (export "step_f32") (param $n f32) (result f32)
81 (return (f32.mul (local.get $n) (f32.const 2.0)))
82 )
83 (func $unstep_f32 (export "unstep_f32") (param $n f32) (result f32)
84 (return (f32.div (local.get $n) (f32.const 2.0)))
85 )
86 ;; Move a f64 value forwards and backwards.
87 (func $step_f64 (export "step_f64") (param $n f64) (result f64)
88 (return (f64.mul (local.get $n) (f64.const 4.0)))
89 )
90 (func $unstep_f64 (export "unstep_f64") (param $n f64) (result f64)
91 (return (f64.div (local.get $n) (f64.const 4.0)))
92 )`
93 + (simdEnabled ?
94 `;; Move a v128 value forwards and backwards.
95 (func $step_v128 (export "step_v128") (param $vec v128) (result v128)
96 (return (call $v128_from_i64HL
97 (i64.add (call $v128hi (local.get $vec)) (i64.const 1234))
98 (i64.add (call $v128lo (local.get $vec)) (i64.const 4321))
99 ))
100 )
101 (func $unstep_v128 (export "unstep_v128") (param $vec v128) (result v128)
102 (return (call $v128_from_i64HL
103 (i64.sub (call $v128hi (local.get $vec)) (i64.const 1234))
104 (i64.sub (call $v128lo (local.get $vec)) (i64.const 4321))
105 ))
106 )`
107 : ``/* simd not enabled*/
108 );
109 return t;
110 }
111
112 // A Pseudo-RNG based on the C standard. The core function generates only 16
113 // random bits. We have to use it twice to generate a 32-bit random number
114 // and four times for a 64-bit random number.
115 let decls_rng =
116 `;; The RNG's state
117 (global $rand_state
118 (mut i32) (i32.const 1)
119 )`;
120 function funcs_rng(simdEnabled) {
121 let t =
122 `;; Set the seed
123 (func $rand_setSeed (param $seed i32)
124 (global.set $rand_state (local.get $seed))
125 )
126 ;; Generate a 16-bit random number
127 (func $rand_i16 (export "rand_i16") (result i32)
128 (local $t i32)
129 ;; update $rand_state
130 (local.set $t (global.get $rand_state))
131 (local.set $t (i32.mul (local.get $t) (i32.const 1103515245)))
132 (local.set $t (i32.add (local.get $t) (i32.const 12345)))
133 (global.set $rand_state (local.get $t))
134 ;; pull 16 random bits out of it
135 (local.set $t (i32.shr_u (local.get $t) (i32.const 15)))
136 (local.set $t (i32.and (local.get $t) (i32.const 0xFFFF)))
137 (local.get $t)
138 )
139 ;; Generate a 32-bit random number
140 (func $rand_i32 (export "rand_i32") (result i32)
141 (local $t i32)
142 (local.set $t (call $rand_i16))
143 (local.set $t (i32.shl (local.get $t) (i32.const 16)))
144 (local.set $t (i32.or (local.get $t) (call $rand_i16)))
145 (local.get $t)
146 )
147 ;; Generate a 64-bit random number
148 (func $rand_i64 (export "rand_i64") (result i64)
149 (local $t i64)
150 (local.set $t (i64.extend_i32_u (call $rand_i16)))
151 (local.set $t (i64.shl (local.get $t) (i64.const 16)))
152 (local.set $t (i64.or (local.get $t) (i64.extend_i32_u (call $rand_i16))))
153 (local.set $t (i64.shl (local.get $t) (i64.const 16)))
154 (local.set $t (i64.or (local.get $t) (i64.extend_i32_u (call $rand_i16))))
155 (local.set $t (i64.shl (local.get $t) (i64.const 16)))
156 (local.set $t (i64.or (local.get $t) (i64.extend_i32_u (call $rand_i16))))
157 (local.get $t)
158 )
159 ;; Generate a 32-bit random float. This is something of a kludge in as much
160 ;; as it does it by converting a random signed-int32 to a float32, which
161 ;; means that we don't get any NaNs, infinities, denorms, etc, but OTOH
162 ;; there's somewhat less randomness then there would be if we had allowed
163 ;; such denorms in.
164 (func $rand_f32 (export "rand_f32") (result f32)
165 (f32.convert_i32_s (call $rand_i32))
166 )
167 ;; And similarly for 64-bit random floats
168 (func $rand_f64 (export "rand_f64") (result f64)
169 (f64.convert_i64_s (call $rand_i64))
170 )`
171 + (simdEnabled ?
172 `;; Generate a random 128-bit vector.
173 (func $rand_v128 (export "rand_v128") (result v128)
174 (call $v128_from_i64HL (call $rand_i64) (call $rand_i64))
175 )`
176 : ``/* simd not enabled*/
177 );
178 return t;
179 }
180
181 // Helpers for function generation
182 function strcmp(s1,s2) {
183 if (s1 < s2) return -1;
184 if (s1 > s2) return 1;
185 return 0;
186 }
187
188 // This generates the last function in the chain. It merely returns its
189 // arguments in a different order, but first applies the relevant `_step`
190 // function to each value. This is the only place in the process where
191 // the passed/return values are modified. Hence it gives us a way to be
192 // sure that the values made it all the way from the start function to the
193 // end of the chain (here) and back to the start function. Back in the
194 // start function, we will apply the relevant `_unstep` function to each
195 // returned value, which should give the value that was sent up the chain
196 // originally.
197 //
198 // Here and below, the following naming scheme is used:
199 //
200 // * taIn -- types of arguments that come in to this function
201 // * taOut -- types of arguments that this function passes
202 // to the next in the chain
203 // * trOut -- types of results that this function returns
204 // * trIn -- types of results that the next function in the chain
205 // returns to this function
206 //
207 // Hence 'a' vs 'r' distinguishes argument from return types, and 'In' vs
208 // 'Out' distinguishes values coming "in" to the function from those going
209 // "out". The 'a'/'r' naming scheme is also used in the generated wasm (text).
210 function genEnd(myFuncName, taIn, trOut) {
211 assertEq(taIn.length, trOut.length);
212 let params = taIn.map(pair => `(param $a${pair.name} ${pair.type})`)
213 .join(` `);
214 let retTys = trOut.map(pair => pair.type).join(` `);
215 let t =
216 `(func $${myFuncName} (export "${myFuncName}") ` +
217 ` ${params} (result ${retTys})\n` +
218 trOut.map(pair =>
219 ` (call $step_${pair.type} (local.get $a${pair.name}))`)
220 .join(`\n`) + `\n` +
221 `)`;
222 return t;
223 }
224
225 // This generates an intermediate function in the chain. It takes args as
226 // specified by `taIn`, rearranges them to match `taOut`, passes those to the
227 // next function in the chain. From which it receives return values as
228 // described by `trIn`, which it rearranges to match `trOut`, and returns
229 // those. Overall, then, it permutes values both in the calling direction and
230 // in the returning direction.
231 function genMiddle(myFuncName, nextFuncName, taIn, trOut, taOut, trIn) {
232 assertEq(taIn.length, taOut.length);
233 assertEq(taIn.length, trIn.length);
234 assertEq(taIn.length, trOut.length);
235 let params = taIn.map(pair => `(param $a${pair.name} ${pair.type})`)
236 .join(` `);
237 let retTys = trOut.map(pair => pair.type).join(` `);
238 let trInSorted = trIn.toSorted((p1,p2) => strcmp(p1.name,p2.name));
239 let t =
240 `(func $${myFuncName} (export "${myFuncName}") ` +
241 ` ${params} (result ${retTys})\n` +
242 // Declare locals
243 trInSorted
244 .map(pair => ` (local $r${pair.name} ${pair.type})`)
245 .join(`\n`) + `\n` +
246 // Make the call
247 ` (call $${nextFuncName} ` +
248 taOut.map(pair => `(local.get $a${pair.name})`).join(` `) + `)\n` +
249 // Capture the returned values
250 trIn.toReversed()
251 .map(pair => ` (local.set $r${pair.name})`).join(`\n`) + `\n` +
252 // Return
253 ` (return ` + trOut.map(pair => `(local.get $r${pair.name})`)
254 .join (` `) + `)\n` +
255 `)`;
256 return t;
257 }
258
259 // This generates the first function in the chain. It creates random values
260 // for the initial arguments, passes them to the next arg in the chain,
261 // receives results, and checks that the results are as expected.
262 // NOTE! The generated function returns zero on success, non-zero on failure.
263 function genStart(myFuncName, nextFuncName, taOut, trIn) {
264 assertEq(taOut.length, trIn.length);
265 let taOutSorted = taOut.toSorted((p1,p2) => strcmp(p1.name,p2.name));
266 let trInSorted = trIn.toSorted((p1,p2) => strcmp(p1.name,p2.name));
267 // `taOutSorted` and `trInSorted` should be identical.
268 assertEq(taOutSorted.length, trInSorted.length);
269 for (let i = 0; i < taOutSorted.length; i++) {
270 assertEq(taOutSorted[i].name, trInSorted[i].name);
271 assertEq(taOutSorted[i].type, trInSorted[i].type);
272 }
273 let t =
274 `(func $${myFuncName} (export "${myFuncName}") (result i32)\n` +
275 // Declare locals
276 taOutSorted
277 .map(pair => ` (local $a${pair.name} ${pair.type})`)
278 .join(`\n`) + `\n` +
279 trInSorted
280 .map(pair => ` (local $r${pair.name} ${pair.type})`)
281 .join(`\n`) + `\n` +
282 ` (local $anyNotEqual i32)\n` +
283 // Set up the initial values to be fed up the chain of calls and back
284 // down again. We expect them to be the same when they finally arrive
285 // back. Note we re-initialise the (wasm-side) RNG even though this
286 // isn't actually necessary.
287 ` (call $rand_setSeed (i32.const 1))\n` +
288 taOutSorted
289 .map(pair => ` (local.set $a${pair.name} (call $rand_${pair.type}))`)
290 .join(`\n`) + `\n` +
291 // Actually make the call
292 ` (call $${nextFuncName} ` +
293 taOut.map(pair => `(local.get $a${pair.name})`).join(` `) + `)\n` +
294 // Capture the returned values
295 trIn.toReversed()
296 .map(pair => ` (local.set $r${pair.name})`).join(`\n`) + `\n` +
297
298 // For each returned value, apply the relevant `_unstep` function,
299 // then compare it against the original. It should be the same, so
300 // accumulate any signs of difference in $anyNotEqual. Since
301 // `taOutSorted` and `trInSorted` are identical we can iterate over
302 // either.
303 taOutSorted
304 .map(pair =>
305 ` (local.set $anyNotEqual \n` +
306 ` (i32.or (local.get $anyNotEqual)\n` +
307 ` (` +
308 // v128 doesn't have a suitable .ne operator, so call a helper fn
309 (pair.type === `v128` ? `call $v128ne` : `${pair.type}.ne`) +
310 ` (local.get $a${pair.name})` +
311 ` (call $unstep_${pair.type} (local.get $r${pair.name})))))`
312 )
313 .join(`\n`) + `\n` +
314 ` (return (local.get $anyNotEqual))\n` +
315 `)`;
316 return t;
317 }
318
319 // A pseudo-random number generator that is independent of the one baked into
320 // each wasm program generated. This is for use in JS only. It isn't great,
321 // but at least it starts from a fixed place, which Math.random doesn't. This
322 // produces a function `rand4js`, which takes an argument `n` and produces an
323 // integer value in the range `0 .. n-1` inclusive. `n` needs to be less than
324 // or equal to 2^21 for this to work at all, and it needs to be much less than
325 // 2^21 (say, no more than 2^14) in order to get a reasonably even
326 // distribution of the values generated.
327 let rand4js_txt =
328 `(module
329 (global $rand4js_state (mut i32) (i32.const 1))
330 (func $rand4js (export "rand4js") (param $maxPlus1 i32) (result i32)
331 (local $t i32)
332 ;; update $rand4js_state
333 (local.set $t (global.get $rand4js_state))
334 (local.set $t (i32.mul (local.get $t) (i32.const 1103515245)))
335 (local.set $t (i32.add (local.get $t) (i32.const 12345)))
336 (global.set $rand4js_state (local.get $t))
337 ;; Note, the low order bits are not very random. Hence we dump the
338 ;; low-order 11 bits. This leaves us with at best 21 usable bits.
339 (local.set $t (i32.shr_u (local.get $t) (i32.const 11)))
340 (i32.rem_u (local.get $t) (local.get $maxPlus1))
341 )
342 )`;
343 let rand4js = new WebAssembly.Instance(
344 new WebAssembly.Module(wasmTextToBinary(rand4js_txt)))
345 .exports.rand4js;
346
347 // Fisher-Yates scheme for generating random permutations of a sequence.
348 // Result is a new array containing the original items in a different order.
349 // Original is unchanged.
350 function toRandomPermutation(input) {
351 let n = input.length;
352 let result = input.slice();
353 assertEq(result.length, n);
354 if (n < 2) return result;
355 for (let i = 0; i < n - 1; i++) {
356 let j = i + rand4js(n - i);
357 let t = result[i];
358 result[i] = result[j];
359 result[j] = t;
360 }
361 return result;
362 }
363
364 // Top level test runner
365 function testMain(numIters) {
366 // Check whether we can use SIMD.
367 let simdEnabled = wasmSimdEnabled();
368
369 // Names tagged with types. This is set up to provide 10 values that
370 // potentially can be passed in integer registers (5 x i32, 5 x i64) and
371 // 10 values that potentially can be passed in FP/SIMD registers (3 x f32,
372 // 3 x f64, 4 x v128). This should cover both sides of the
373 // arg-passed-in-reg/arg-passed-in-mem boundary for all of the primary
374 // targets.
375 let val0 = {name: "0", type: "i32"};
376 let val1 = {name: "1", type: "i32"};
377 let val2 = {name: "2", type: "i32"};
378 let val3 = {name: "3", type: "i32"};
379 let val4 = {name: "4", type: "i32"};
380
381 let val5 = {name: "5", type: "i64"};
382 let val6 = {name: "6", type: "i64"};
383 let val7 = {name: "7", type: "i64"};
384 let val8 = {name: "8", type: "i64"};
385 let val9 = {name: "9", type: "i64"};
386
387 let vala = {name: "a", type: "f32"};
388 let valb = {name: "b", type: "f32"};
389 let valc = {name: "c", type: "f32"};
390
391 let vald = {name: "d", type: "f64"};
392 let vale = {name: "e", type: "f64"};
393 let valf = {name: "f", type: "f64"};
394
395 let valg = {name: "g", type: "v128"};
396 let valh = {name: "h", type: "v128"};
397 let vali = {name: "i", type: "v128"};
398 let valj = {name: "j", type: "v128"};
399
400 // This is the base name/type vector,
401 // of which we will create random permutations.
402 let baseValVec;
403 if (simdEnabled) {
404 baseValVec
405 = [val0, val1, val2, val3, val4, val5, val6, val7, val8, val9,
406 vala, valb, valc, vald, vale, valf, valg, valh, vali, valj];
407 } else {
408 baseValVec
409 = [val0, val1, val2, val3, val4, val5, val6, val7, val8, val9,
410 vala, valb, valc, vald, vale, valf];
411 }
412
413 function summariseVec(valVec) {
414 return valVec.map(pair => pair.name).join("");
415 }
416
417 print("\nsimdEnabled = " + simdEnabled + "\n");
418
419 for (let testRun = 0; testRun < numIters; testRun++) {
420 let tx0a = toRandomPermutation(baseValVec);
421 let tx0r = toRandomPermutation(baseValVec);
422 let tx1a = toRandomPermutation(baseValVec);
423 let tx1r = toRandomPermutation(baseValVec);
424 let tx2a = toRandomPermutation(baseValVec);
425 let tx2r = toRandomPermutation(baseValVec);
426 let tx3a = toRandomPermutation(baseValVec);
427 let tx3r = toRandomPermutation(baseValVec);
428 let tx4a = toRandomPermutation(baseValVec);
429 let tx4r = toRandomPermutation(baseValVec);
430
431 // Generate a 5-step chain of functions, each one passing and
432 // returning different permutation of `baseValVec`. The chain is:
433 // fnStart -> fnMid0 -> fnMid1 -> fnMid2 -> fnMid3 -> fnEnd
434 let t_end = genEnd("fnEnd", tx4a, tx4r);
435 let t_mid3 = genMiddle("fnMid3", "fnEnd", tx3a, tx3r, tx4a, tx4r);
436 let t_mid2 = genMiddle("fnMid2", "fnMid3", tx2a, tx2r, tx3a, tx3r);
437 let t_mid1 = genMiddle("fnMid1", "fnMid2", tx1a, tx1r, tx2a, tx2r);
438 let t_mid0 = genMiddle("fnMid0", "fnMid1", tx0a, tx0r, tx1a, tx1r);
439 let t_start = genStart("fnStart", "fnMid0", tx0a, tx0r);
440
441 let txt = "(module (memory 1) " + "\n" +
442 decls_rng + "\n" +
443 funcs_util(simdEnabled) + "\n" + funcs_rng(simdEnabled) + "\n" +
444 t_end + "\n" +
445 t_mid3 + "\n" + t_mid2 + "\n" + t_mid1 + "\n" + t_mid0 + "\n" +
446 t_start + "\n" +
447 ")";
448
449 if (0) print(txt);
450
451 let mod = new WebAssembly.Module(wasmTextToBinary(txt));
452 let ins = new WebAssembly.Instance(mod);
453 let fns = ins.exports;
454
455 // result == 0 means success, any other value means failure
456 let result = fns.fnStart();
457 if (/*failure*/result != 0 || (testRun % 120) == 0)
458 print(" " + testRun + " " +
459 [tx0a,tx0r,tx1a,tx1r,tx2a,tx2r,tx3a,tx3r,tx4a,tx4r]
460 .map(e => summariseVec(e)).join("/") + " "
461 + (result == 0 ? "pass" : "FAIL"));
462
463 assertEq(result, 0);
464 }
465 }
466
467 testMain(/*numIters=*/120);