float16-as-float32-specialization-for-dataview-setfloat16.js (1983B)
1 const nativeIsLittleEndian = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; 2 3 function float32(dv, i) { 4 // Unbox to Int32. 5 i = i|0; 6 7 // Float32 addition. 8 let x = Math.fround(i + 0.1); 9 10 // Float32 square root. 11 let y = Math.fround(Math.sqrt(x)); 12 13 // Store as Float16. 14 dv.setFloat16(0, y, nativeIsLittleEndian); 15 } 16 17 function float64(dv, i) { 18 // Unbox to Int32. 19 i = i|0; 20 21 // Float32 addition. 22 let x = Math.fround(i + 0.1); 23 24 // Float64 square root. 25 let y = Math.sqrt(x); 26 27 // Store as Float16. 28 dv.setFloat16(0, y, nativeIsLittleEndian); 29 } 30 31 function toBaseline(f) { 32 let source = f.toString(); 33 assertEq(source.at(-1), "}"); 34 35 // Add with-statement to disable Ion compilation. 36 source = source.slice(0, -1) + "; with ({}); }"; 37 38 return Function(`return ${source};`)(); 39 } 40 41 // Different results are expected for these inputs: 42 // 43 // Input Float64-SQRT Float32-SQRT 44 // ----------------------------------- 45 // 1527 39.09375 39.0625 46 // 16464 128.375 128.25 47 // 18581 136.375 136.25 48 // 20826 144.375 144.25 49 // 23199 152.375 152.25 50 // 25700 160.375 160.25 51 // 28329 168.375 168.25 52 // 31086 176.375 176.25 53 // 54 // Limit execution to 1550 to avoid spending too much time on this single test. 55 // 56 // 1550 iterations should still be enough to allow tiering up to Ion, at least 57 // under eager compilation settings. 58 const LIMIT = 1550; 59 60 let float32_baseline = toBaseline(float32); 61 let float64_baseline = toBaseline(float64); 62 63 let dv = new DataView(new ArrayBuffer(Float16Array.BYTES_PER_ELEMENT)); 64 65 let n = 0; 66 for (let i = 0; i < LIMIT; ++i) { 67 float32(dv, i); 68 let x = dv.getUint16(0, nativeIsLittleEndian); 69 70 float32_baseline(dv, i); 71 assertEq(x, dv.getUint16(0, nativeIsLittleEndian)); 72 73 float64(dv, i); 74 let y = dv.getUint16(0, nativeIsLittleEndian); 75 76 float64_baseline(dv, i); 77 assertEq(y, dv.getUint16(0, nativeIsLittleEndian)); 78 79 if (x !== y) { 80 n++; 81 } 82 } 83 assertEq(n, 1);