@gasm-compiler/core 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +0,0 @@
1
- function R(n,t){let e=new Error(n);return e.name="CompileError",t&&(e.functionName=t.functionName,e.instructionName=t.instructionName,e.offset=t.offset),e}function Vs(n){return n instanceof Error&&n.name==="CompileError"}var a={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_store:54,i64_store:55,f32_store:56,f64_store:57,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i32_clz:103,i32_ctz:104,i32_popcnt:105,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,i64_div_u:128,i64_rem_s:129,i64_rem_u:130,i64_and:131,i64_or:132,i64_xor:133,i64_shl:134,i64_shr_s:135,i64_shr_u:136,i64_rotl:137,i64_rotr:138,i64_clz:121,i64_ctz:122,i64_popcnt:123,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store8:58,i32_store16:59,i64_load8_s:48,i64_load8_u:49,i64_load16_s:50,i64_load16_u:51,i64_load32_s:52,i64_load32_u:53,i64_store8:60,i64_store16:61,i64_store32:62,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,i64_trunc_f32_s:174,i64_trunc_f32_u:175,i64_trunc_f64_s:176,i64_trunc_f64_u:177,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_convert_i64_u:181,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_convert_i64_u:186,f64_promote_f32:187,i32_reinterpret_f32:188,i64_reinterpret_f64:189,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193,i64_extend8_s:194,i64_extend16_s:195,i64_extend32_s:196,i32_trunc_sat_f32_s:64512,i32_trunc_sat_f32_u:64513,i32_trunc_sat_f64_s:64514,i32_trunc_sat_f64_u:64515,i64_trunc_sat_f32_s:64516,i64_trunc_sat_f32_u:64517,i64_trunc_sat_f64_s:64518,i64_trunc_sat_f64_u:64519,memory_init:64520,data_drop:64521,memory_copy:64522,memory_fill:64523,table_init:64524,elem_drop:64525,table_copy:64526,table_grow:64527,table_size:64528,table_fill:64529,v128_const:12,i8x16_splat:13,i16x8_splat:14,i32x4_splat:15,i64x2_splat:16,f32x4_splat:17,f64x2_splat:18,i8x16_extract_lane_s:21,i8x16_extract_lane_u:22,i8x16_replace_lane:23,i16x8_extract_lane_s:24,i16x8_extract_lane_u:25,i16x8_replace_lane:26,i32x4_extract_lane:27,i32x4_replace_lane:28,i64x2_extract_lane:29,i64x2_replace_lane:30,f32x4_extract_lane:31,f32x4_replace_lane:32,f64x2_extract_lane:33,f64x2_replace_lane:34,i8x16_add:35,i8x16_sub:36,i16x8_add:37,i16x8_sub:38,i16x8_mul:39,i32x4_add:40,i32x4_sub:41,i32x4_mul:42,i64x2_add:43,i64x2_sub:44,i64x2_mul:45,f32x4_add:46,f32x4_sub:47,f32x4_mul:48,f32x4_div:49,f64x2_add:50,f64x2_sub:51,f64x2_mul:52,f64x2_div:53,i32x4_eq:54,i32x4_ne:55,i32x4_lt_s:56,i32x4_lt_u:57,i32x4_gt_s:58,i32x4_gt_u:59,i32x4_le_s:60,i32x4_le_u:61,i32x4_ge_s:62,i32x4_ge_u:63,f32x4_eq:64,f32x4_ne:65,f32x4_lt:66,f32x4_gt:67,f32x4_le:68,f32x4_ge:69,f64x2_eq:70,f64x2_ne:71,f64x2_lt:72,f64x2_gt:73,f64x2_le:74,f64x2_ge:75,i8x16_eq:76,i8x16_ne:77,i16x8_eq:78,i16x8_ne:79,i64x2_eq:80,i64x2_ne:81,v128_and:82,v128_or:83,v128_xor:84,v128_not:85,v128_andnot:86,v128_bitselect:87,i8x16_shl:88,i8x16_shr_s:89,i8x16_shr_u:90,i16x8_shl:91,i16x8_shr_s:92,i16x8_shr_u:93,i32x4_shl:94,i32x4_shr_s:95,i32x4_shr_u:96,i64x2_shl:97,i64x2_shr_s:98,i64x2_shr_u:99,v128_any_true:100,i8x16_all_true:101,i8x16_bitmask:102,i16x8_all_true:103,i16x8_bitmask:104,i32x4_all_true:105,i32x4_bitmask:106,i64x2_all_true:107,i64x2_bitmask:108,i8x16_shuffle:109,i8x16_swizzle:110,f32x4_abs:111,f32x4_neg:112,f32x4_sqrt:113,f32x4_ceil:114,f32x4_floor:115,f32x4_trunc:116,f32x4_nearest:117,f32x4_min:118,f32x4_max:119,f64x2_abs:120,f64x2_neg:121,f64x2_sqrt:122,f64x2_ceil:123,f64x2_floor:124,f64x2_trunc:125,f64x2_nearest:126,f64x2_min:127,f64x2_max:128,v128_load:0,v128_store:11};var Fe=class{view;offset=0;bytes;constructor(t){this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}get pos(){return this.offset}set pos(t){this.offset=t}get length(){return this.bytes.length}isEOF(){return this.offset>=this.bytes.length}readByte(){if(this.offset>=this.bytes.length)throw R("Unexpected EOF",{offset:this.offset});return this.bytes[this.offset++]}readBytes(t){if(this.offset+t>this.bytes.length)throw R("Unexpected EOF",{offset:this.offset});let e=this.bytes.subarray(this.offset,this.offset+t);return this.offset+=t,e}readUint32(){let t=this.view.getUint32(this.offset,!0);return this.offset+=4,t}readF32(){let t=this.view.getFloat32(this.offset,!0);return this.offset+=4,t}readF64(){let t=this.view.getFloat64(this.offset,!0);return this.offset+=8,t}readVarUint32(){let t=0,e=0;for(;;){let s=this.readByte();if(t|=(s&127)<<e,(s&128)===0)break;e+=7}return t}readVarInt32(){let t=0,e=0,s;for(;s=this.readByte(),t|=(s&127)<<e,e+=7,(s&128)!==0;);return e<32&&(s&64)!==0&&(t|=-1<<e),t}readVarInt64(){let t=0n,e=0n,s;for(;s=this.readByte(),t|=BigInt(s&127)<<e,e+=7n,(s&128)!==0;);return e<64&&(s&64)!==0&&(t|=~0n<<e),t}readString(){let t=this.readVarUint32(),e=this.readBytes(t);return new TextDecoder("utf-8").decode(e)}readType(){let t=this.readByte();switch(t){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 112:return"funcref";case 111:return"externref";case 64:return"void";default:throw R(`Unknown value type: 0x${t.toString(16)}`,{offset:this.offset-1})}}};function Ls(n){let t=new Fe(n);if(t.readByte()!==0||t.readByte()!==97||t.readByte()!==115||t.readByte()!==109)return R("Invalid magic bytes",{offset:0});if(t.readByte()!==1||t.readByte()!==0||t.readByte()!==0||t.readByte()!==0)return R("Unsupported Wasm version",{offset:4});let e={types:[],functions:[],globals:[],memories:[],data:[],exports:[],imports:[]},s=[];for(;!t.isEOF();){let i=t.readByte(),r=t.readVarUint32(),o=t.pos+r;switch(i){case 1:{let c=t.readVarUint32();for(let u=0;u<c;u++){if(t.readByte()!==96)throw R("Expected 0x60 for func type",{offset:t.pos-1});let d=t.readVarUint32(),f=[];for(let x=0;x<d;x++)f.push(t.readType());let p=t.readVarUint32(),g=[];for(let x=0;x<p;x++)g.push(t.readType());e.types.push({params:f,results:g})}}break;case 2:{let c=t.readVarUint32();for(let u=0;u<c;u++){let l=t.readString(),d=t.readString(),f=t.readByte(),p={module:l,name:d,kind:"func"};switch(f){case 0:p.kind="func",p.typeIndex=t.readVarUint32();break;case 1:p.kind="table",t.readByte(),t.readByte(),t.readVarUint32();break;case 2:p.kind="mem";let g=t.readByte();t.readVarUint32(),g&1&&t.readVarUint32();break;case 3:p.kind="global";let x=t.readType();t.readByte();let w=e.globals.length;e.globals.push({kind:"import",index:w,module:l,name:d,type:x});break}e.imports.push(p)}}break;case 3:{let c=t.readVarUint32();for(let u=0;u<c;u++)s.push(t.readVarUint32())}break;case 5:{let c=t.readVarUint32();for(let u=0;u<c;u++){let l=t.readByte(),d=t.readVarUint32(),f=l&1?t.readVarUint32():void 0;e.memories.push({index:u,min:d,max:f})}}break;case 6:{let c=t.readVarUint32();for(let u=0;u<c;u++){let l=t.readType(),d=t.readByte()===1,f=gt(t),p=e.globals.length,g;if(f.length>=1){let x=f[0];(x.opcode===a.i32_const||x.opcode===a.f32_const||x.opcode===a.i64_const||x.opcode===a.f64_const)&&(g=x.immediates?.[0])}e.globals.push({kind:"definition",index:p,type:l,mutable:d,initExpr:f,initValue:g})}}break;case 7:{let c=t.readVarUint32();for(let u=0;u<c;u++){let l=t.readString(),d=t.readByte(),f=t.readVarUint32(),p;switch(d){case 0:p="func";break;case 1:p="table";break;case 2:p="mem";break;case 3:p="global";break;default:throw R("Unknown export kind",{offset:t.pos})}e.exports.push({name:l,kind:p,index:f})}}break;case 8:{let c=t.readVarUint32();e.startFunctionIndex=c}break;case 10:{let c=t.readVarUint32();s.length;for(let u=0;u<c;u++){let l=t.readVarUint32(),d=t.pos+l,f=s[u],p=e.types[f],g=t.readVarUint32(),x=[],w=0;for(let _=0;_<g;_++){let b=t.readVarUint32(),S=t.readType();for(let v=0;v<b;v++)x.push({index:w++,type:S,mutable:!0})}let I=gt(t);e.functions.push({index:e.imports.filter(_=>_.kind==="func").length+u,params:p.params,results:p.results,locals:x,body:I}),t.pos!==d&&(t.pos=d)}}break;default:t.pos=o;break}}return e}function gt(n){let t=[],e=0;for(;;){let s=n.pos,i=n.readByte(),r,o={opcode:i,name:"",offset:s,immediates:[]},c=!1,u=!1;if(i===253?(i=64768|n.readVarUint32(),o.opcode=i,c=!0):i===252&&(i=64512|n.readVarUint32(),o.opcode=i,u=!0),r=In(i),o.name=r,i===a.block||i===a.loop||i===a.if)e++;else if(i===11){if(e===0){t.push(o);break}e--}switch(i){case a.block:case a.loop:case a.if:{let l=n.readByte();o.immediates.push(l)}break;case a.br:case a.br_if:o.immediates.push(n.readVarUint32());break;case a.br_table:{let l=n.readVarUint32(),d=[];for(let f=0;f<l;f++)d.push(n.readVarUint32());d.push(n.readVarUint32()),o.immediates.push(d)}break;case a.call:case a.call_indirect:o.immediates.push(n.readVarUint32()),i===a.call_indirect&&o.immediates.push(n.readVarUint32());break;case a.local_get:case a.local_set:case a.local_tee:case a.global_get:case a.global_set:o.immediates.push(n.readVarUint32());break;case a.i32_const:o.immediates.push(n.readVarInt32());break;case a.i64_const:o.immediates.push(n.readVarInt64());break;case a.f32_const:o.immediates.push(n.readF32());break;case a.f64_const:o.immediates.push(n.readF64());break;case a.i32_load:case a.i64_load:case a.f32_load:case a.f64_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:case a.i64_load8_s:case a.i64_load8_u:case a.i64_load16_s:case a.i64_load16_u:case a.i64_load32_s:case a.i64_load32_u:case a.i32_store:case a.i64_store:case a.f32_store:case a.f64_store:case a.i32_store8:case a.i32_store16:case a.i64_store8:case a.i64_store16:case a.i64_store32:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case 63:case 64:n.readByte();break}if(c)switch(i&255){case 12:o.immediates.push(Array.from(n.readBytes(16)));break;case 21:case 22:case 23:case 24:case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:o.immediates.push(n.readByte());break;case 13:o.immediates.push(Array.from(n.readBytes(16)));break;case 0:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case 11:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break}if(u){let l=i&255;switch(i){case a.memory_init:o.immediates.push(n.readVarUint32()),n.readByte();break;case a.data_drop:o.immediates.push(n.readVarUint32());break;case a.memory_copy:n.readByte(),n.readByte();break;case a.memory_fill:n.readByte();break;case a.table_init:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case a.elem_drop:o.immediates.push(n.readVarUint32());break;case a.table_copy:o.immediates.push(n.readVarUint32()),o.immediates.push(n.readVarUint32());break;case a.table_grow:case a.table_size:case a.table_fill:o.immediates.push(n.readVarUint32());break}}t.push(o)}return t}function zs(n){return n?.name==="CompileError"}function In(n){let t=Object.entries(a).find(([,e])=>e===n);return t?t[0]:`0x${n.toString(16)}`}function ci(n,t={}){try{if(t.strictConformance){if(n.memories.length===0)throw R("Module must declare exactly one memory (M001: ERR_MEMORY_COUNT)");for(let i of n.imports)if(i.kind==="func"&&i.module!=="gasm")throw R(`Function import from "${i.module}" is forbidden; only "gasm" imports are allowed (M006: ERR_FUNCTION_IMPORT)`,{functionName:`${i.module}.${i.name}`});let e=n.imports.filter(i=>i.kind==="func").length;if(!n.exports.some(i=>{if(i.kind!=="func")return!1;let r=i.index;if(r<e){let c=n.imports.filter(u=>u.kind==="func")[r];if(c?.typeIndex!==void 0){let u=n.types[c.typeIndex];return u&&u.params.length===0&&u.results.length===0}return!1}let o=n.functions.find(c=>c.index===r);return o?o.params.length===0&&o.results.length===0:!1}))throw R("Module must export at least one () -> () function as an entry point (M007: ERR_NO_ENTRY_POINT)")}for(let e of n.functions)wn(e);if(Vn(n),n.startFunctionIndex!==void 0)throw R("Start section not allowed",{functionName:"start"});return n}catch(e){if(yn(e))return e;throw e}}function yn(n){return n?.name==="CompileError"}function wn(n){let t=0;for(let e of n.body){let s=(e.opcode&65280)===64768;if(e.opcode===a.call_indirect)throw R("Invalid instruction: call_indirect",{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset});if(e.opcode===a.memory_grow)throw R(`Invalid instruction: ${e.name}`,{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset});if(e.opcode>=208&&e.opcode<=210)throw R("Invalid instruction: Reference types not allowed",{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset});if(e.opcode===37||e.opcode===38)throw R("Invalid instruction: Table operations not allowed",{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset});if($n(e.opcode)){let i=e.immediates[0];if(![a.i32_load,a.i32_store,a.f32_load,a.f32_store,a.i64_load,a.i64_store,a.f64_load,a.f64_store,a.i32_load8_s,a.i32_load8_u,a.i32_load16_s,a.i32_load16_u,a.i32_store8,a.i32_store16,a.i64_load8_s,a.i64_load8_u,a.i64_load16_s,a.i64_load16_u,a.i64_load32_s,a.i64_load32_u,a.i64_store8,a.i64_store16,a.i64_store32].includes(e.opcode))throw R(`Invalid instruction: ${e.name} (only 32-bit and full 64-bit load/store allowed)`,{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset});let o=2;if([a.i32_load8_s,a.i32_load8_u,a.i32_store8,a.i64_load8_s,a.i64_load8_u,a.i64_store8].includes(e.opcode)?o=0:[a.i32_load16_s,a.i32_load16_u,a.i32_store16,a.i64_load16_s,a.i64_load16_u,a.i64_store16].includes(e.opcode)?o=1:[a.i64_load32_s,a.i64_load32_u,a.i64_store32].includes(e.opcode)?o=2:[a.i64_load,a.i64_store,a.f64_load,a.f64_store].includes(e.opcode)&&(o=3),i<o)throw R(`Misaligned memory access: ${e.name} (must be aligned)`,{functionName:n.name||`func${n.index}`,instructionName:e.name,offset:e.offset})}e.opcode,a.loop}}function $n(n){return n>=40&&n<=62}function Vn(n){let t=new Map;for(let r of n.functions){let o=new Set;for(let c of r.body)if(c.opcode===a.call){let u=c.immediates[0];o.add(u)}t.set(r.index,o)}let e=new Set,s=new Set;function i(r){e.add(r),s.add(r);let o=t.get(r);if(o){for(let c of o)if(e.has(c)){if(s.has(c))return!0}else if(i(c))return!0}return s.delete(r),!1}for(let r of n.functions)if(!e.has(r.index)&&i(r.index))throw R("Recursion detected",{functionName:r.name||`func${r.index}`})}var Be=new Map([["sin",{name:"sin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sin",supportsVector:!0,description:"Sine of angle in radians"}],["cos",{name:"cos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cos",supportsVector:!0,description:"Cosine of angle in radians"}],["tan",{name:"tan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tan",supportsVector:!0,description:"Tangent of angle in radians"}],["asin",{name:"asin",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asin",supportsVector:!0,description:"Arc sine, returns radians"}],["acos",{name:"acos",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acos",supportsVector:!0,description:"Arc cosine, returns radians"}],["atan",{name:"atan",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atan",supportsVector:!0,description:"Arc tangent, returns radians"}],["atan2",{name:"atan2",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"atan2",supportsVector:!0,description:"Arc tangent of y/x, returns radians"}],["sinh",{name:"sinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sinh",supportsVector:!0,description:"Hyperbolic sine"}],["cosh",{name:"cosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"cosh",supportsVector:!0,description:"Hyperbolic cosine"}],["tanh",{name:"tanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"tanh",supportsVector:!0,description:"Hyperbolic tangent"}],["asinh",{name:"asinh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"asinh",supportsVector:!0,description:"Inverse hyperbolic sine"}],["acosh",{name:"acosh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"acosh",supportsVector:!0,description:"Inverse hyperbolic cosine"}],["atanh",{name:"atanh",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"atanh",supportsVector:!0,description:"Inverse hyperbolic tangent"}],["exp",{name:"exp",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp",supportsVector:!0,description:"e raised to the power of x"}],["exp2",{name:"exp2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"exp2",supportsVector:!0,description:"2 raised to the power of x"}],["log",{name:"log",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log",supportsVector:!0,description:"Natural logarithm"}],["log2",{name:"log2",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"log2",supportsVector:!0,description:"Base-2 logarithm"}],["pow",{name:"pow",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"pow",supportsVector:!0,description:"x raised to the power of y"}],["sqrt",{name:"sqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sqrt",supportsVector:!0,description:"Square root"}],["inverseSqrt",{name:"inverseSqrt",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"inverseSqrt",supportsVector:!0,description:"Inverse square root (1/sqrt(x))"}],["abs",{name:"abs",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"abs",supportsVector:!0,description:"Absolute value"}],["sign",{name:"sign",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"sign",supportsVector:!0,description:"Sign of x (-1, 0, or 1)"}],["floor",{name:"floor",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"floor",supportsVector:!0,description:"Floor (round toward negative infinity)"}],["ceil",{name:"ceil",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"ceil",supportsVector:!0,description:"Ceiling (round toward positive infinity)"}],["trunc",{name:"trunc",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"trunc",supportsVector:!0,description:"Truncate (round toward zero)"}],["round",{name:"round",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"round",supportsVector:!0,description:"Round to nearest integer"}],["fract",{name:"fract",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"fract",supportsVector:!0,description:"Fractional part (x - floor(x))"}],["min",{name:"min",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"min",supportsVector:!0,description:"Minimum of two values"}],["max",{name:"max",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"max",supportsVector:!0,description:"Maximum of two values"}],["clamp",{name:"clamp",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"clamp",supportsVector:!0,description:"Clamp value between min and max"}],["saturate",{name:"saturate",level:"M0",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"saturate",supportsVector:!0,description:"Clamp to [0, 1]"}],["mix",{name:"mix",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"mix",supportsVector:!0,description:"Linear interpolation"}],["step",{name:"step",level:"M0",wasmParams:["f32","f32"],wasmResults:["f32"],wgslBuiltin:"step",supportsVector:!0,description:"Step function (0 if x < edge, else 1)"}],["smoothstep",{name:"smoothstep",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"smoothstep",supportsVector:!0,description:"Smooth Hermite interpolation"}],["fma",{name:"fma",level:"M0",wasmParams:["f32","f32","f32"],wasmResults:["f32"],wgslBuiltin:"fma",supportsVector:!0,description:"Fused multiply-add (a * b + c)"}],["length",{name:"length",level:"M1",wasmParams:["v128"],wasmResults:["f32"],wgslBuiltin:"length",supportsVector:!1,description:"Vector length (magnitude)"}],["distance",{name:"distance",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"distance",supportsVector:!1,description:"Distance between two points"}],["dot",{name:"dot",level:"M1",wasmParams:["v128","v128"],wasmResults:["f32"],wgslBuiltin:"dot",supportsVector:!1,description:"Dot product"}],["cross",{name:"cross",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"cross",supportsVector:!1,description:"Cross product (vec3 only)"}],["normalize",{name:"normalize",level:"M1",wasmParams:["v128"],wasmResults:["v128"],wgslBuiltin:"normalize",supportsVector:!1,description:"Normalize vector to unit length"}],["reflect",{name:"reflect",level:"M1",wasmParams:["v128","v128"],wasmResults:["v128"],wgslBuiltin:"reflect",supportsVector:!1,description:"Reflect incident vector off surface"}],["refract",{name:"refract",level:"M1",wasmParams:["v128","v128","f32"],wasmResults:["v128"],wgslBuiltin:"refract",supportsVector:!1,description:"Refract vector through surface"}],["faceForward",{name:"faceForward",level:"M1",wasmParams:["v128","v128","v128"],wasmResults:["v128"],wgslBuiltin:"faceForward",supportsVector:!1,description:"Flip normal to face forward"}],["modf",{name:"modf",level:"M2",wasmParams:["f32"],wasmResults:["f32","f32"],wgslBuiltin:"modf",supportsVector:!0,description:"Split into fractional and integer parts",flags:{returnsStruct:!0,structTypeName:"__modf_result_f32"}}],["frexp",{name:"frexp",level:"M2",wasmParams:["f32"],wasmResults:["f32","i32"],wgslBuiltin:"frexp",supportsVector:!0,description:"Extract significand and exponent",flags:{returnsStruct:!0,structTypeName:"__frexp_result_f32"}}],["ldexp",{name:"ldexp",level:"M2",wasmParams:["f32","i32"],wasmResults:["f32"],wgslBuiltin:"ldexp",supportsVector:!0,description:"Construct value from significand and exponent"}],["degrees",{name:"degrees",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"degrees",supportsVector:!0,description:"Convert radians to degrees"}],["radians",{name:"radians",level:"M2",wasmParams:["f32"],wasmResults:["f32"],wgslBuiltin:"radians",supportsVector:!0,description:"Convert degrees to radians"}],["abs_i32",{name:"abs_i32",level:"M0",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"abs",supportsVector:!1,description:"Absolute value (integer)"}],["min_i32",{name:"min_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"min",supportsVector:!1,description:"Minimum of two integers"}],["max_i32",{name:"max_i32",level:"M0",wasmParams:["i32","i32"],wasmResults:["i32"],wgslBuiltin:"max",supportsVector:!1,description:"Maximum of two integers"}],["clamp_i32",{name:"clamp_i32",level:"M0",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"clamp",supportsVector:!1,description:"Clamp integer between min and max"}],["countOneBits",{name:"countOneBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countOneBits",supportsVector:!1,description:"Count number of 1 bits (popcount)"}],["countLeadingZeros",{name:"countLeadingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countLeadingZeros",supportsVector:!1,description:"Count leading zero bits"}],["countTrailingZeros",{name:"countTrailingZeros",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"countTrailingZeros",supportsVector:!1,description:"Count trailing zero bits"}],["firstLeadingBit",{name:"firstLeadingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstLeadingBit",supportsVector:!1,description:"Position of first leading 1 bit"}],["firstTrailingBit",{name:"firstTrailingBit",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"firstTrailingBit",supportsVector:!1,description:"Position of first trailing 1 bit"}],["reverseBits",{name:"reverseBits",level:"M2",wasmParams:["i32"],wasmResults:["i32"],wgslBuiltin:"reverseBits",supportsVector:!1,description:"Reverse bit order"}],["extractBits",{name:"extractBits",level:"M2",wasmParams:["i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"extractBits",supportsVector:!1,description:"Extract bits from value"}],["insertBits",{name:"insertBits",level:"M2",wasmParams:["i32","i32","i32","i32"],wasmResults:["i32"],wgslBuiltin:"insertBits",supportsVector:!1,description:"Insert bits into value"}]]);function bt(n,t){if(n!=="gasm")return!1;let e=xt(t);return Be.has(e)}function xt(n){let t=n.match(/^(.+)_v([234])f32$/);return t?t[1]:n}function ke(n){let t=xt(n);return Be.get(t)}function li(n){return ke(n)?.wgslBuiltin}function vt(n){let t=n.match(/_v([234])f32$/);return t?parseInt(t[1],10):4}function Ce(n){return/_v[234]f32$/.test(n)}function di(n,t){let e=ke(n);if(!e)return!1;let s=["M0","M1","M2"],i=s.indexOf(e.level),r=s.indexOf(t);return i<=r}function fi(n){let t=["M0","M1","M2"],e=t.indexOf(n);return Array.from(Be.values()).filter(s=>t.indexOf(s.level)<=e)}function pi(n,t,e){let s=ke(n);if(!s)return`Unknown math intrinsic: ${n}`;if(Ce(n)){let r=s.wasmParams.map(c=>c==="f32"&&s.supportsVector?"v128":c),o=s.wasmResults.map(c=>c==="f32"&&s.supportsVector?"v128":c);if(t.length!==r.length)return`${n}: expected ${r.length} parameters, got ${t.length}`;if(e.length!==o.length)return`${n}: expected ${o.length} results, got ${e.length}`;for(let c=0;c<t.length;c++)if(t[c]!==r[c])return`${n}: parameter ${c} expected ${r[c]}, got ${t[c]}`;for(let c=0;c<e.length;c++)if(e[c]!==o[c])return`${n}: result ${c} expected ${o[c]}, got ${e[c]}`}else{if(t.length!==s.wasmParams.length)return`${n}: expected ${s.wasmParams.length} parameters, got ${t.length}`;if(e.length!==s.wasmResults.length)return`${n}: expected ${s.wasmResults.length} results, got ${e.length}`;for(let r=0;r<t.length;r++)if(t[r]!==s.wasmParams[r])return`${n}: parameter ${r} expected ${s.wasmParams[r]}, got ${t[r]}`;for(let r=0;r<e.length;r++)if(e[r]!==s.wasmResults[r])return`${n}: result ${r} expected ${s.wasmResults[r]}, got ${e[r]}`}}function Ae(n,t,e){let s=n.opcode;if(s.startsWith("i64.load")){Fn(n,t,e);return}let i=s==="f32.load",r=s==="i32.load8.s"||s==="i32.load8.u",o=s==="i32.load16.s"||s==="i32.load16.u",c=s==="i32.load8.s"||s==="i32.load16.s",u=n.immediates[1],l=n.args[0];if(u!==0){let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[u]});let w=e.newVar("i32");t.push({type:"instr",id:w,opcode:"i32.add",args:[l,x]}),l=w}let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=e.newU32Var();if(t.push({type:"instr",id:f,opcode:"i32.shr_u",args:[l,d]}),i){t.push({type:"instr",id:n.id,opcode:"wgsl.load_f32",args:[f]});return}let p=r||o,g=p?e.newVar("i32"):n.id;if(t.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[f]}),!!p&&(r||o)){let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[3]});let w=e.newVar("i32");t.push({type:"instr",id:w,opcode:"i32.and",args:[l,x]});let I=e.newVar("i32");t.push({type:"instr",id:I,opcode:"i32.const",args:[],immediates:[8]});let _=e.newVar("i32");t.push({type:"instr",id:_,opcode:"i32.mul",args:[w,I]});let b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.shr_u",args:[g,_]});let S=r?8:16,v=r?255:65535,$=e.newVar("i32");t.push({type:"instr",id:$,opcode:"i32.const",args:[],immediates:[v]});let N=c?e.newVar("i32"):n.id;if(t.push({type:"instr",id:N,opcode:"i32.and",args:[b,$]}),c){let L=32-S,T=e.newVar("i32");t.push({type:"instr",id:T,opcode:"i32.const",args:[],immediates:[L]});let U=e.newVar("i32");t.push({type:"instr",id:U,opcode:"i32.shl",args:[N,T]}),t.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[U,T]})}}}function Fn(n,t,e){let s=n.opcode,i=n.immediates[1],r=n.args[0];if(n.id!==void 0&&e.changeVarType(n.id,"i32"),i!==0){let u=e.newVar("i32");t.push({type:"instr",id:u,opcode:"i32.const",args:[],immediates:[i]});let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.add",args:[r,u]}),r=l}let o=e.newVar("i32");t.push({type:"instr",id:o,opcode:"i32.const",args:[],immediates:[2]});let c=e.newU32Var();if(t.push({type:"instr",id:c,opcode:"i32.shr_u",args:[r,o]}),s==="i64.load"||s==="i64.load32_s"||s==="i64.load32_u")t.push({type:"instr",id:n.id,opcode:"wgsl.load_i32",args:[c]});else if(s==="i64.load8_s"||s==="i64.load8_u"){let u=e.newVar("i32");t.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=e.newVar("i32");t.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[255]});let w=s==="i64.load8_s",I=w?e.newVar("i32"):n.id;if(t.push({type:"instr",id:I,opcode:"i32.and",args:[g,x]}),w){let _=e.newVar("i32");t.push({type:"instr",id:_,opcode:"i32.const",args:[],immediates:[24]});let b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.shl",args:[I,_]}),t.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[b,_]})}}else if(s==="i64.load16_s"||s==="i64.load16_u"){let u=e.newVar("i32");t.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=e.newVar("i32");t.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[65535]});let w=s==="i64.load16_s",I=w?e.newVar("i32"):n.id;if(t.push({type:"instr",id:I,opcode:"i32.and",args:[g,x]}),w){let _=e.newVar("i32");t.push({type:"instr",id:_,opcode:"i32.const",args:[],immediates:[16]});let b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.shl",args:[I,_]}),t.push({type:"instr",id:n.id,opcode:"i32.shr_s",args:[b,_]})}}}function Ee(n,t,e){let s=n.opcode;if(s.startsWith("i64.store")){Bn(n,t,e);return}let i=s==="f32.store",r=s==="i32.store8",o=s==="i32.store16",c=n.immediates[1],u=n.args[0],l=n.args[1];if(c!==0){let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[c]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"i32.add",args:[u,p]}),u=g}let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=e.newU32Var();if(t.push({type:"instr",id:f,opcode:"i32.shr_u",args:[u,d]}),r||o){let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[3]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"i32.and",args:[u,p]});let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[8]});let w=e.newVar("i32");t.push({type:"instr",id:w,opcode:"i32.mul",args:[g,x]});let I=e.newVar("i32");t.push({type:"instr",id:I,opcode:"wgsl.load_i32",args:[f]});let _=r?255:65535,b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.const",args:[],immediates:[_]});let S=e.newVar("i32");t.push({type:"instr",id:S,opcode:"i32.shl",args:[b,w]});let v=e.newVar("i32");t.push({type:"instr",id:v,opcode:"i32.const",args:[],immediates:[-1]});let $=e.newVar("i32");t.push({type:"instr",id:$,opcode:"i32.xor",args:[S,v]});let N=e.newVar("i32");t.push({type:"instr",id:N,opcode:"i32.and",args:[I,$]});let L=e.newVar("i32");t.push({type:"instr",id:L,opcode:"i32.and",args:[l,b]});let T=e.newVar("i32");t.push({type:"instr",id:T,opcode:"i32.shl",args:[L,w]});let U=e.newVar("i32");t.push({type:"instr",id:U,opcode:"i32.or",args:[N,T]}),t.push({type:"instr",opcode:"wgsl.store_i32",args:[f,U]})}else i?t.push({type:"instr",opcode:"wgsl.store_f32",args:[f,l]}):t.push({type:"instr",opcode:"wgsl.store_i32",args:[f,l]})}function Bn(n,t,e){let s=n.opcode,i=n.immediates[1],r=n.args[0],o=n.args[1];if(i!==0){let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[i]});let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.add",args:[r,l]}),r=d}let c=e.newVar("i32");t.push({type:"instr",id:c,opcode:"i32.const",args:[],immediates:[2]});let u=e.newU32Var();if(t.push({type:"instr",id:u,opcode:"i32.shr_u",args:[r,c]}),s==="i64.store"||s==="i64.store32")t.push({type:"instr",opcode:"wgsl.store_i32",args:[u,o]});else if(s==="i64.store8"){let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=e.newVar("i32");t.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[255]});let w=e.newVar("i32");t.push({type:"instr",id:w,opcode:"i32.shl",args:[x,p]});let I=e.newVar("i32");t.push({type:"instr",id:I,opcode:"i32.const",args:[],immediates:[-1]});let _=e.newVar("i32");t.push({type:"instr",id:_,opcode:"i32.xor",args:[w,I]});let b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.and",args:[g,_]});let S=e.newVar("i32");t.push({type:"instr",id:S,opcode:"i32.and",args:[o,x]});let v=e.newVar("i32");t.push({type:"instr",id:v,opcode:"i32.shl",args:[S,p]});let $=e.newVar("i32");t.push({type:"instr",id:$,opcode:"i32.or",args:[b,v]}),t.push({type:"instr",opcode:"wgsl.store_i32",args:[u,$]})}else if(s==="i64.store16"){let l=e.newVar("i32");t.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=e.newVar("i32");t.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=e.newVar("i32");t.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=e.newVar("i32");t.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=e.newVar("i32");t.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let x=e.newVar("i32");t.push({type:"instr",id:x,opcode:"i32.const",args:[],immediates:[65535]});let w=e.newVar("i32");t.push({type:"instr",id:w,opcode:"i32.shl",args:[x,p]});let I=e.newVar("i32");t.push({type:"instr",id:I,opcode:"i32.const",args:[],immediates:[-1]});let _=e.newVar("i32");t.push({type:"instr",id:_,opcode:"i32.xor",args:[w,I]});let b=e.newVar("i32");t.push({type:"instr",id:b,opcode:"i32.and",args:[g,_]});let S=e.newVar("i32");t.push({type:"instr",id:S,opcode:"i32.and",args:[o,x]});let v=e.newVar("i32");t.push({type:"instr",id:v,opcode:"i32.shl",args:[S,p]});let $=e.newVar("i32");t.push({type:"instr",id:$,opcode:"i32.or",args:[b,v]}),t.push({type:"instr",opcode:"wgsl.store_i32",args:[u,$]})}}function St(n){let t=n.functions.map(e=>Cn(e));return{types:n.types,functions:t,globals:n.globals,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports}}function Cn(n){let e=new Me(n).process(n.body);return{...n,body:e}}var Me=class{func;nextVarId;constructor(t){this.func=t;let e=0;for(let s of t.vars.keys())s>e&&(e=s);this.nextVarId=e+1}newVar(t){let e=this.nextVarId++;return this.func.vars.set(e,{id:e,type:t}),e}newU32Var(){let t=this.nextVarId++;return this.func.vars.set(t,{id:t,type:"i32",emitAsU32:!0}),t}changeVarType(t,e){this.func.vars.get(t)&&this.func.vars.set(t,{id:t,type:e})}process(t){switch(t.kind){case"block":return{...t,children:t.children.map(e=>this.process(e))};case"loop":return{...t,body:this.process(t.body)};case"parallel_loop":return{...t,body:this.process(t.body),epilogue:t.epilogue?this.process(t.epilogue):void 0};case"if":return{...t,thenBranch:this.process(t.thenBranch),elseBranch:t.elseBranch?this.process(t.elseBranch):void 0};case"simple":return{...t,instructions:this.lowerInstructions(t.instructions)};default:return t}}lowerInstructions(t){let e=[];for(let s of t)switch(s.opcode){case"i32.load":case"f32.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":Ae(s,e,this);break;case"i32.store":case"f32.store":case"i32.store8":case"i32.store16":case"i64.store":case"i64.store8":case"i64.store16":case"i64.store32":Ee(s,e,this);break;case"memory.size":this.lowerMemorySize(s,e);break;case"memory.grow":e.push(s);break;default:e.push(s)}return e}lowerMemorySize(t,e){let s=this.newVar("i32");e.push({type:"instr",id:s,opcode:"wgsl.buffer_length",args:[]});let i=this.newVar("i32");e.push({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[14]}),e.push({type:"instr",id:t.id,opcode:"i32.shr_u",args:[s,i]})}};function kt(n){let t=n.functions.map(e=>An(e));return{...n,functions:t}}function An(n){let t=new De(n);if(n.inlinedExpressionMap)for(let[r,o]of n.inlinedExpressionMap)t.collectConstantFromInstruction(o);t.collectConstants(n.body);let e=t.optimize(n.body),s=new Map(n.vars);for(let[r,o]of t.newVars)s.set(r,o);let i=new Map(n.inlinedExpressionMap||[]);for(let[r,o]of t.constantValues)i.has(r)||i.set(r,{type:"instr",id:r,opcode:"i32.const",args:[],immediates:[o]});return{...n,body:e,vars:s,inlinedExpressionMap:i}}var De=class{func;constantValues=new Map;constantVarCache=new Map;usedVars=new Set;newVars=new Map;nextVarId;instructionsToRemove=new Set;replacementMap=new Map;constructor(t){this.func=t;let e=0;for(let s of t.vars.keys())s>e&&(e=s);this.nextVarId=e+1}collectConstants(t){switch(t.kind){case"block":for(let e of t.children)this.collectConstants(e);break;case"loop":this.collectConstants(t.body);break;case"parallel_loop":this.collectConstants(t.body),t.epilogue&&this.collectConstants(t.epilogue);break;case"if":this.collectConstants(t.thenBranch),t.elseBranch&&this.collectConstants(t.elseBranch);break;case"simple":for(let e of t.instructions)this.collectConstantFromInstruction(e);break}}collectConstantFromInstruction(t){if(t.id!==void 0){if(t.opcode==="i32.const"&&t.immediates&&t.immediates.length>0){let e=t.immediates[0];this.constantValues.set(t.id,e);let s=`i32:${e}`,i=this.constantVarCache.get(s);i!==void 0?(this.replacementMap.set(t.id,i),this.instructionsToRemove.add(t.id)):this.constantVarCache.set(s,t.id)}if(t.opcode==="i32.shr_u"||t.opcode==="i32.shr_s"){let e=t.args;if(e&&e.length>=2){let s=this.getReplacement(e[0]),i=this.getReplacement(e[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=t.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);this.constantValues.set(t.id,c)}}}}}getReplacement(t){let e=t;for(;this.replacementMap.has(e);)e=this.replacementMap.get(e);return e}updateArgs(t){return t.map(e=>this.getReplacement(e))}optimize(t){switch(t.kind){case"block":return{...t,children:t.children.map(e=>this.optimize(e))};case"loop":return{...t,body:this.optimize(t.body)};case"parallel_loop":return{...t,body:this.optimize(t.body),epilogue:t.epilogue?this.optimize(t.epilogue):void 0};case"if":{let e=this.getReplacement(t.condition);return{...t,condition:e,thenBranch:this.optimize(t.thenBranch),elseBranch:t.elseBranch?this.optimize(t.elseBranch):void 0}}case"simple":return{...t,instructions:this.optimizeInstructions(t.instructions)};case"return":{if(t.value!==void 0){let e=this.getReplacement(t.value);return{...t,value:e}}return t}default:return t}}optimizeInstructions(t){let e=[];for(let s of t){if(s.id!==void 0&&this.instructionsToRemove.has(s.id))continue;let i=this.tryConstantFold(s);if(i){e.push(i);continue}let r={...s,args:this.updateArgs(s.args)};e.push(r)}return e}tryConstantFold(t){if(t.id===void 0)return null;if(t.opcode==="i32.shr_u"||t.opcode==="i32.shr_s"){let e=t.args;if(e&&e.length>=2){let s=this.getReplacement(e[0]),i=this.getReplacement(e[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=t.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);return{type:"instr",id:t.id,opcode:"i32.const",args:[],immediates:[c]}}}}return null}};function Ie(){return{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function En(n){let t=Ie(),e=Mn(n);if(!e)return{module:n,dispatchInfo:t};let s=Dn(e,n);if(s.parallelized){t=s.dispatchInfo;let i=n.functions.map(r=>r.index===e.index?s.func:r);return{module:{...n,functions:i},dispatchInfo:t}}return{module:n,dispatchInfo:t}}function Mn(n){let t=n.exports.find(e=>e.name==="main"&&e.kind==="func");return t?n.functions.find(e=>e.index===t.index)??null:n.functions[0]??null}function Dn(n,t){let e={func:n,parallelized:!1,dispatchInfo:Ie()},s=Rn(n.body,n,t);if(!s)return e;let i=Pn(n.body,s,n),r=64,o=s.upperBound;return{func:{...n,body:i,parallelLoopInfo:s},parallelized:!0,dispatchInfo:{workItemsX:o,workItemsY:1,workItemsZ:1,workgroupSizeX:r,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!0}}}function Rn(n,t,e){let s=$t(n,[],t,e);if(s.length===1)return s[0];if(s.length>1){let i=s[0];for(let r=1;r<s.length;r++)s[r].upperBound>i.upperBound&&(i=s[r]);return i}return null}function $t(n,t,e,s){let i=[];if(n.kind==="block"){let r=[...t];for(let o of n.children){if(o.kind==="loop"){let c=It(o,r,e,s);c&&i.push(c)}o.kind==="block"&&i.push(...$t(o,r,e,s)),r.push(o)}}else if(n.kind==="loop"){let r=It(n,t,e,s);r&&i.push(r)}return i}function It(n,t,e,s){let i=n.body,r=null;if(i.kind==="block"){for(let l of i.children)if(l.kind==="if"){r=l;break}}else i.kind==="if"&&(r=i);if(!r||r.kind!=="if")return null;let o=Tn(r.condition,e,s);if(!o||!Ne(r.thenBranch,o.localIndex))return null;let u=new Set;if(ie(n.body,u),u.delete(o.localIndex),u.size>0){let l=new Set;re(e.body,n,e.inlinedExpressionMap,l,new Set);for(let d of u)if(l.has(d))return null}return{loopLocalIndex:o.localIndex,upperBound:o.upperBound}}function ie(n,t){switch(n.kind){case"simple":for(let e of n.instructions)if(e.opcode==="local.set"||e.opcode==="local.tee"){let s=e.immediates?.[0];typeof s=="number"&&t.add(s)}return;case"block":for(let e of n.children)ie(e,t);return;case"loop":ie(n.body,t);return;case"parallel_loop":ie(n.body,t),n.epilogue&&ie(n.epilogue,t);return;case"if":ie(n.thenBranch,t),n.elseBranch&&ie(n.elseBranch,t);return;default:return}}function re(n,t,e,s,i,r="before"){if(n===t)return"after";switch(n.kind){case"simple":if(r==="after")for(let o of n.instructions)Vt(o,e,s,i);return r;case"block":for(let o of n.children)r=re(o,t,e,s,i,r);return r;case"loop":return re(n.body,t,e,s,i,r);case"parallel_loop":{let o=re(n.body,t,e,s,i,r);return n.epilogue&&(o=re(n.epilogue,t,e,s,i,o)),o}case"if":{r==="after"&&Re(n.condition,e,s,i);let o=re(n.thenBranch,t,e,s,i,r),c=n.elseBranch?re(n.elseBranch,t,e,s,i,r):r;return o==="after"||c==="after"?"after":r}case"return":return r==="after"&&n.value!==void 0&&Re(n.value,e,s,i),r;default:return r}}function Vt(n,t,e,s){if(n.opcode==="local.get"||n.opcode==="local.tee"){let i=n.immediates?.[0];typeof i=="number"&&e.add(i)}for(let i of n.args)Re(i,t,e,s)}function Re(n,t,e,s){if(s.has(n))return;s.add(n);let i=t?.get(n);i&&Vt(i,t,e,s)}function te(n,t){if(n.kind==="simple"){for(let e of n.instructions)if(e.id===t)return e}else if(n.kind==="block")for(let e of n.children){let s=te(e,t);if(s)return s}else{if(n.kind==="loop")return te(n.body,t);if(n.kind==="parallel_loop"){let e=te(n.body,t);if(e)return e;if(n.epilogue)return te(n.epilogue,t)}else if(n.kind==="if"){let e=te(n.thenBranch,t);if(e)return e;if(n.elseBranch)return te(n.elseBranch,t)}}return null}function Tn(n,t,e){let s=t.inlinedExpressionMap?.get(n);if(!s||s.opcode!=="i32.lt_s"&&s.opcode!=="i32.lt_u")return null;let i=s.args[0],r=null,o=t.inlinedExpressionMap?.get(i);if(o&&o.opcode==="local.get")r=o.immediates?.[0];else{let l=te(t.body,i);l&&l.opcode==="local.get"&&(r=l.immediates?.[0])}if(r===null)return null;let c=s.args[1],u=Te(c,t,e);return u===null||u<=0?null:{localIndex:r,upperBound:u}}function Te(n,t,e){let s=t.inlinedExpressionMap?.get(n)??te(t.body,n);if(!s)return null;if(s.opcode==="i32.const")return s.immediates?.[0]??null;if(s.opcode==="global.get"){let i=s.immediates?.[0];if(i===void 0)return null;let r=e.globals[i];return r&&r.kind==="definition"&&r.initValue!==void 0&&!Nn(i,e)&&typeof r.initValue=="number"?r.initValue:null}if(s.args&&s.args.length===2){let i=Te(s.args[0],t,e);if(i===null)return null;let r=Te(s.args[1],t,e);if(r===null)return null;switch(s.opcode){case"i32.mul":return Math.imul(i,r);case"i32.add":return i+r|0;case"i32.sub":return i-r|0;case"i32.and":return i&r;case"i32.or":return i|r;case"i32.shl":return i<<(r&31);case"i32.shr_s":return i>>(r&31);case"i32.shr_u":return i>>>(r&31)}}return null}function Nn(n,t){for(let e of t.functions)if(fe(n,e.body))return!0;return!1}function fe(n,t){switch(t.kind){case"simple":for(let e of t.instructions)if(e.opcode==="global.set"&&e.immediates?.[0]===n)return!0;return!1;case"block":return t.children.some(e=>fe(n,e));case"loop":case"parallel_loop":return fe(n,t.body)||(t.kind==="parallel_loop"&&t.epilogue?fe(n,t.epilogue):!1);case"if":return fe(n,t.thenBranch)||(t.elseBranch?fe(n,t.elseBranch):!1);default:return!1}}function Ne(n,t){if(n.kind==="simple"){for(let e of n.instructions)if(On(e,t))return!0}else if(n.kind==="block"){for(let e of n.children)if(Ne(e,t))return!0}return!1}function On(n,t){return n.opcode==="local.set"&&n.immediates?.[0]===t}function Pn(n,t,e){return Ft(n,{loopInfo:t,transformed:!1},!0)}function Ft(n,t,e){switch(n.kind){case"block":{let s=[];for(let i=0;i<n.children.length;i++){let r=n.children[i];if(r.kind==="loop"){if(!t.transformed&&e&&yt(r,t.loopInfo)){t.transformed=!0;let o=n.children.slice(i+1),c;o.length>0&&(c=o.length===1?o[0]:{kind:"block",children:o}),s.push(Ln(r,t.loopInfo,c));break}s.push(r);continue}if(r.kind==="block"&&e&&!t.transformed){if(s.push(Ft(r,t,!0)),t.transformed){let o=n.children.slice(i+1);if(o.length>0){let c=s[s.length-1];Bt(c,o)}break}}else s.push(r)}return{...n,children:s}}case"loop":return!t.transformed&&e&&yt(n,t.loopInfo)?(t.transformed=!0,zn(n,t.loopInfo)):n;case"if":return n;default:return n}}function Ln(n,t,e){let s=Ct(n.body,t.loopLocalIndex);return{kind:"parallel_loop",loopInfo:t,body:s,epilogue:e}}function Bt(n,t){if(n.kind==="parallel_loop"){let e=n.epilogue,s=[];e&&(e.kind==="block"?s.push(...e.children):s.push(e)),s.push(...t),n.epilogue=s.length===1?s[0]:{kind:"block",children:s};return}if(n.kind==="block"){for(let e of n.children)if(e.kind==="parallel_loop"||e.kind==="block"){Bt(e,t);return}}}function yt(n,t){let e=n.body,s=null;if(e.kind==="block"){for(let i of e.children)if(i.kind==="if"){s=i;break}}else e.kind==="if"&&(s=e);return!s||s.kind!=="if"?!1:Ne(s.thenBranch,t.loopLocalIndex)}function zn(n,t){let e=Ct(n.body,t.loopLocalIndex);return{kind:"parallel_loop",loopInfo:t,body:e}}function Ct(n,t){if(n.kind==="block"&&n.children.length>0){let e=n.children[0];if(e.kind==="if")return wt(e.thenBranch,t)}return n.kind==="if"?wt(n.thenBranch,t):n}function wt(n,t){if(n.kind==="block"){let s=n.children.filter(i=>!(i.kind==="block"&&i.children[i.children.length-1]?.kind==="continue"||i.kind==="continue")).map(i=>pe(i,t));return{...n,children:s}}return pe(n,t)}function pe(n,t){if(n.kind==="simple"){let e=n.instructions.filter(s=>!(s.opcode==="local.set"&&s.immediates?.[0]===t));return{...n,instructions:e}}return n.kind==="block"?{...n,children:n.children.map(e=>pe(e,t))}:n.kind==="if"?{...n,thenBranch:pe(n.thenBranch,t),elseBranch:n.elseBranch?pe(n.elseBranch,t):void 0}:n.kind==="loop"?{...n,body:pe(n.body,t)}:n}function Un(n){return n===!0?n="normal":n===!1&&(n="none"),{level:n,includeWasmOffsets:n==="detailed"||n==="verbose",includeSemanticInfo:n!=="none"&&n!=="minimal",includeIRInfo:n==="verbose",includeLanguageTag:n!=="none"}}function Wn(n){let t=At(n,"name");if(!t)return null;let e={functionNames:new Map,localNames:new Map,globalNames:new Map,labelNames:new Map},s=new DataView(t.buffer,t.byteOffset,t.byteLength),i=0;for(;i<t.length;){let[r,o]=j(t,i);i+=o;let[c,u]=j(t,i);i+=u;let l=i+c;switch(r){case 0:{let[d,f]=ne(t,i);e.moduleName=d,i+=f}break;case 1:{let[d,f]=j(t,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(t,i);i+=x;let[w,I]=ne(t,i);i+=I,e.functionNames.set(g,w)}}break;case 2:{let[d,f]=j(t,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(t,i);i+=x;let[w,I]=j(t,i);i+=I;let _=new Map;for(let b=0;b<w;b++){let[S,v]=j(t,i);i+=v;let[$,N]=ne(t,i);i+=N,_.set(S,$)}e.localNames.set(g,_)}}break;case 7:{let[d,f]=j(t,i);i+=f;for(let p=0;p<d;p++){let[g,x]=j(t,i);i+=x;let[w,I]=ne(t,i);i+=I,e.globalNames.set(g,w)}}break;default:i=l;break}i<l&&(i=l)}return e}function Hn(n){let t=At(n,"producers");if(!t)return null;let e={},s=0,[i,r]=j(t,s);s+=r;for(let o=0;o<i;o++){let[c,u]=ne(t,s);s+=u;let[l,d]=j(t,s);s+=d;let f=[];for(let p=0;p<l;p++){let[g,x]=ne(t,s);s+=x;let[w,I]=ne(t,s);s+=I,f.push(w?`${g} ${w}`:g)}switch(c){case"language":e.languages=f;break;case"processed-by":e.processedBy=f;break;case"sdk":e.sdks=f;break}}return e}function At(n,t){if(n.length<8||(n[0]<<0|n[1]<<8|n[2]<<16|n[3]<<24)!==1836278016)return null;let s=8;for(;s<n.length;){let i=n[s++],[r,o]=j(n,s);s+=o;let c=s+r;if(i===0){let[u,l]=ne(n,s);if(u===t)return n.subarray(s+l,c)}s=c}return null}function j(n,t){let e=0,s=0,i=0;for(;;){let r=n[t+i];if(i++,e|=(r&127)<<s,(r&128)===0)break;s+=7}return[e,i]}function ne(n,t){let[e,s]=j(n,t),i=n.subarray(t+s,t+s+e);return[new TextDecoder().decode(i),s+e]}function qn(n,t,e){if(e?.languages)for(let s of e.languages){let i=s.toLowerCase();if(i.includes("assemblyscript"))return"assemblyscript";if(i.includes("rust"))return"rust";if(i.includes("c")&&!i.includes("script"))return"c"}if(e?.processedBy)for(let s of e.processedBy){let i=s.toLowerCase();if(i.includes("assemblyscript")||i.includes("asc"))return"assemblyscript";if(i.includes("rustc"))return"rust";if(i.includes("clang")||i.includes("emscripten"))return"c"}if(t)for(let s of t.functionNames.values()){if(s.includes("~lib/")||s.includes("assembly/"))return"assemblyscript";if(s.includes("core::")||s.includes("alloc::")||s.includes("__rust"))return"rust";if(s.startsWith("__")||s.includes("emscripten"))return"c"}return t&&t.functionNames.size>0&&!e?"wat":"unknown"}function Gn(n){let t=Wn(n),e=Hn(n),s=qn(n,t,e),i="low";return t&&(t.functionNames.size>0&&t.localNames.size>0?i="high":t.functionNames.size>0&&(i="medium")),{language:s,quality:i,functionNames:t?.functionNames??new Map,localNames:t?.localNames??new Map,globalNames:t?.globalNames??new Map,blockLabels:t?.labelNames??new Map,producers:e??void 0}}var Oe=class{options;debugInfo;constructor(t,e){this.options=e,this.debugInfo=Gn(t)}getLanguage(){return this.debugInfo.language}getQuality(){return this.debugInfo.quality}generateHeaderComment(){if(this.options.level==="none")return null;let t=[];if(this.options.includeLanguageTag){let e=this.formatLanguageName(this.debugInfo.language);t.push(`Source Language: ${e}`)}return(this.options.level==="detailed"||this.options.level==="verbose")&&(t.push(`Debug Info: ${this.debugInfo.quality}`),this.debugInfo.producers?.processedBy&&t.push(`Processed By: ${this.debugInfo.producers.processedBy.join(", ")}`)),t.length>0?`// ${t.join(" | ")}`:null}commentForFunction(t,e){if(this.options.level==="none")return null;let s=[],i=this.debugInfo.functionNames.get(t),r=e||i||`func_${t}`;return s.push(`Function ${t}: "${r}"`),i&&i!==e&&i!==r&&s.push(`(debug: ${i})`),`// ${s.join(" ")}`}commentForVariable(t,e,s){if(this.options.level==="none"||this.options.level==="minimal")return null;let r=this.debugInfo.localNames.get(t)?.get(e);return r?` // ${r}${s?" (param)":""}`:null}commentForGlobal(t){if(this.options.level==="none"||this.options.level==="minimal")return null;let e=this.debugInfo.globalNames.get(t);return e?` // ${e}`:null}commentForInstruction(t,e){if(this.options.level==="none"||this.options.level==="minimal")return null;let s=[];if(s.push(`[WAT] ${t.opcode}`),t.opcode==="local.get"||t.opcode==="local.set"||t.opcode==="local.tee"){let i=t.immediates?.[0];if(i!==void 0){let o=this.debugInfo.localNames.get(e)?.get(i);o&&s.push(`(${o})`)}}if(t.opcode==="global.get"||t.opcode==="global.set"){let i=t.immediates?.[0];if(i!==void 0){let r=this.debugInfo.globalNames.get(i);r&&s.push(`(${r})`)}}return this.options.includeIRInfo&&t.id!==void 0&&s.push(`[IR] v${t.id}`),`// ${s.join(" ")}`}commentForStatement(t,e,s=0){if(this.options.level==="none")return null;let i=[];switch(t.kind){case"loop":i.push("[LOOP]"),t.label&&i.push(`${t.label}`);break;case"parallel_loop":i.push("[PARALLEL]");break;case"block":if(t.label)i.push(`[BLOCK] ${t.label}`);else if(this.options.level==="detailed"||this.options.level==="verbose")return null;break;case"if":if(this.options.level!=="minimal")i.push("[IF]");else return null;break;default:return null}return i.length>0?`// ${i.join(" ")}`:null}commentForEndBlock(t){return this.options.level!=="detailed"&&this.options.level!=="verbose"?null:t?`// End: ${t}`:null}formatLanguageName(t){switch(t){case"wat":return"WAT (WebAssembly Text)";case"assemblyscript":return"AssemblyScript";case"c":return"C/C++";case"rust":return"Rust";default:return"Unknown"}}};function Et(n,t){if(!t||t==="none")return null;let e=Un(t);return new Oe(n,e)}var E={"||":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"<":9,">":9,"<=":9,">=":9,"<<":10,">>":10,"+":11,"-":11,"*":12,"/":12,"%":12};var Mt={"+":1,"-":1,"*":1,"/":1,"%":1,"&":2,"|":2,"^":2,"<<":3,">>":3,"<":4,">":4,"<=":4,">=":4,"==":5,"!=":5,"&&":6,"||":6};function jn(n,t,e,s){return n===0||t===0?!1:n===t?!!(n===2&&e&&s&&e!==s||n===3&&e&&s):n===1&&t===2||n===2&&t===1||n===1&&t===3||n===3&&t===1||n===2&&t===3||n===3&&t===2||n===4&&t===5||n===5&&t===4}var h=15;function Dt(n,t,e,s,i){if(s&&i){let r=Mt[s]??0,o=Mt[i]??0;if(jn(r,o,s,i))return!0}return n>=h||n>t?!1:n<t?!0:e}function P(n,t,e=!1,s){return Dt(n.precedence,t,e,n.operator,s)?`(${n.code})`:n.code}function me(n){switch(n){case"i32":return"i32";case"f32":return"f32";case"i64":return"i32";case"f64":return"f32";case"v128":return"vec4<u32>";default:return"void"}}function Pe(n){switch(n){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 64:return;default:return}}function Le(n){for(let[t,e]of n.blocks)if(!(e.preds.length<2))for(let s=0;s<e.instructions.length;s++){let i=e.instructions[s];if(i.args&&i.args.includes(-1)){let r=Rt(n,t,e.preds);r!==-1&&(i.args=i.args.map(o=>o===-1?r:o))}}}function Rt(n,t,e){let s=[];for(let i of e){let r=n.blocks.get(i);if(r)for(let o=r.instructions.length-1;o>=0;o--){let c=r.instructions[o];if(!(c.opcode==="br"||c.opcode==="br_if")&&c.id!==void 0){s.push(c.id);break}}}return s.length===0?-1:s[0]}function ze(n,t,e){let s=n.popStack(),i=n.popStack(),r="i32",o,u={[a.i32_add]:["i32.add","i32"],[a.i32_sub]:["i32.sub","i32"],[a.i32_mul]:["i32.mul","i32"],[a.i32_div_s]:["i32.div_s","i32"],[a.i32_div_u]:["i32.div_u","i32"],[a.i32_rem_s]:["i32.rem_s","i32"],[a.i32_rem_u]:["i32.rem_u","i32"],[a.i32_and]:["i32.and","i32"],[a.i32_or]:["i32.or","i32"],[a.i32_xor]:["i32.xor","i32"],[a.i32_shl]:["i32.shl","i32"],[a.i32_shr_s]:["i32.shr_s","i32"],[a.i32_shr_u]:["i32.shr_u","i32"],[a.i32_rotl]:["i32.rotl","i32"],[a.i32_rotr]:["i32.rotr","i32"],[a.i32_eq]:["i32.eq","i32"],[a.i32_ne]:["i32.ne","i32"],[a.i32_lt_s]:["i32.lt_s","i32"],[a.i32_lt_u]:["i32.lt_u","i32"],[a.i32_le_s]:["i32.le_s","i32"],[a.i32_le_u]:["i32.le_u","i32"],[a.i32_gt_s]:["i32.gt_s","i32"],[a.i32_gt_u]:["i32.gt_u","i32"],[a.i32_ge_s]:["i32.ge_s","i32"],[a.i32_ge_u]:["i32.ge_u","i32"],[a.i64_add]:["i64.add","i64"],[a.i64_sub]:["i64.sub","i64"],[a.i64_mul]:["i64.mul","i64"],[a.i64_div_s]:["i64.div_s","i64"],[a.i64_div_u]:["i64.div_u","i64"],[a.i64_rem_s]:["i64.rem_s","i64"],[a.i64_rem_u]:["i64.rem_u","i64"],[a.i64_and]:["i64.and","i64"],[a.i64_or]:["i64.or","i64"],[a.i64_xor]:["i64.xor","i64"],[a.i64_shl]:["i64.shl","i64"],[a.i64_shr_s]:["i64.shr_s","i64"],[a.i64_shr_u]:["i64.shr_u","i64"],[a.i64_rotl]:["i64.rotl","i64"],[a.i64_rotr]:["i64.rotr","i64"],[a.i64_eq]:["i64.eq","i32"],[a.i64_ne]:["i64.ne","i32"],[a.i64_lt_s]:["i64.lt_s","i32"],[a.i64_lt_u]:["i64.lt_u","i32"],[a.i64_le_s]:["i64.le_s","i32"],[a.i64_le_u]:["i64.le_u","i32"],[a.i64_gt_s]:["i64.gt_s","i32"],[a.i64_gt_u]:["i64.gt_u","i32"],[a.i64_ge_s]:["i64.ge_s","i32"],[a.i64_ge_u]:["i64.ge_u","i32"],[a.f32_add]:["f32.add","f32"],[a.f32_sub]:["f32.sub","f32"],[a.f32_mul]:["f32.mul","f32"],[a.f32_div]:["f32.div","f32"],[a.f32_min]:["f32.min","f32"],[a.f32_max]:["f32.max","f32"],[a.f32_copysign]:["f32.copysign","f32"],[a.f32_eq]:["f32.eq","i32"],[a.f32_ne]:["f32.ne","i32"],[a.f32_lt]:["f32.lt","i32"],[a.f32_le]:["f32.le","i32"],[a.f32_gt]:["f32.gt","i32"],[a.f32_ge]:["f32.ge","i32"],[a.f64_add]:["f64.add","f64"],[a.f64_sub]:["f64.sub","f64"],[a.f64_mul]:["f64.mul","f64"],[a.f64_div]:["f64.div","f64"],[a.f64_min]:["f64.min","f64"],[a.f64_max]:["f64.max","f64"],[a.f64_copysign]:["f64.copysign","f64"],[a.f64_eq]:["f64.eq","i32"],[a.f64_ne]:["f64.ne","i32"],[a.f64_lt]:["f64.lt","i32"],[a.f64_le]:["f64.le","i32"],[a.f64_gt]:["f64.gt","i32"],[a.f64_ge]:["f64.ge","i32"]}[t];if(!u)throw new Error(`Unknown binary opcode: 0x${t.toString(16)}`);[o,r]=u;let l=n.newVar(r);n.addInstruction({type:"instr",id:l,opcode:o,args:[i,s],immediates:[]}),n.pushStack(l)}function Ue(n,t,e){let s=n.popStack(),r={[a.i32_clz]:["i32.clz","i32"],[a.i32_ctz]:["i32.ctz","i32"],[a.i32_popcnt]:["i32.popcnt","i32"],[a.i32_eqz]:["i32.eqz","i32"],[a.i64_clz]:["i64.clz","i64"],[a.i64_ctz]:["i64.ctz","i64"],[a.i64_popcnt]:["i64.popcnt","i64"],[a.i64_eqz]:["i64.eqz","i32"],[a.f32_abs]:["f32.abs","f32"],[a.f32_neg]:["f32.neg","f32"],[a.f32_sqrt]:["f32.sqrt","f32"],[a.f32_ceil]:["f32.ceil","f32"],[a.f32_floor]:["f32.floor","f32"],[a.f32_trunc]:["f32.trunc","f32"],[a.f32_nearest]:["f32.nearest","f32"],[a.f64_abs]:["f64.abs","f64"],[a.f64_neg]:["f64.neg","f64"],[a.f64_sqrt]:["f64.sqrt","f64"],[a.f64_ceil]:["f64.ceil","f64"],[a.f64_floor]:["f64.floor","f64"],[a.f64_trunc]:["f64.trunc","f64"],[a.f64_nearest]:["f64.nearest","f64"],[a.i32_wrap_i64]:["i32.wrap_i64","i32"],[a.i64_extend_i32_s]:["i64.extend_i32_s","i64"],[a.i64_extend_i32_u]:["i64.extend_i32_u","i64"],[a.i32_trunc_f32_s]:["i32.trunc_f32_s","i32"],[a.i32_trunc_f32_u]:["i32.trunc_f32_u","i32"],[a.i32_trunc_f64_s]:["i32.trunc_f64_s","i32"],[a.i32_trunc_f64_u]:["i32.trunc_f64_u","i32"],[a.i64_trunc_f32_s]:["i64.trunc_f32_s","i64"],[a.i64_trunc_f32_u]:["i64.trunc_f32_u","i64"],[a.i64_trunc_f64_s]:["i64.trunc_f64_s","i64"],[a.i64_trunc_f64_u]:["i64.trunc_f64_u","i64"],[a.f32_convert_i32_s]:["f32.convert_i32_s","f32"],[a.f32_convert_i32_u]:["f32.convert_i32_u","f32"],[a.f32_convert_i64_s]:["f32.convert_i64_s","f32"],[a.f32_convert_i64_u]:["f32.convert_i64_u","f32"],[a.f32_demote_f64]:["f32.demote_f64","f32"],[a.f64_convert_i32_s]:["f64.convert_i32_s","f64"],[a.f64_convert_i32_u]:["f64.convert_i32_u","f64"],[a.f64_convert_i64_s]:["f64.convert_i64_s","f64"],[a.f64_convert_i64_u]:["f64.convert_i64_u","f64"],[a.f64_promote_f32]:["f64.promote_f32","f64"],[a.i32_reinterpret_f32]:["i32.reinterpret_f32","i32"],[a.i64_reinterpret_f64]:["i64.reinterpret_f64","i64"],[a.f32_reinterpret_i32]:["f32.reinterpret_i32","f32"],[a.f64_reinterpret_i64]:["f64.reinterpret_i64","f64"],[a.i32_trunc_sat_f32_s]:["i32.trunc_sat_f32_s","i32"],[a.i32_trunc_sat_f32_u]:["i32.trunc_sat_f32_u","i32"],[a.i32_trunc_sat_f64_s]:["i32.trunc_sat_f64_s","i32"],[a.i32_trunc_sat_f64_u]:["i32.trunc_sat_f64_u","i32"],[a.i64_trunc_sat_f32_s]:["i64.trunc_sat_f32_s","i64"],[a.i64_trunc_sat_f32_u]:["i64.trunc_sat_f32_u","i64"],[a.i64_trunc_sat_f64_s]:["i64.trunc_sat_f64_s","i64"],[a.i64_trunc_sat_f64_u]:["i64.trunc_sat_f64_u","i64"]}[t];if(!r)throw new Error(`Unknown unary opcode: 0x${t.toString(16)}`);let[o,c]=r,u=n.newVar(c);n.addInstruction({type:"instr",id:u,opcode:o,args:[s],immediates:[]}),n.pushStack(u)}function We(n,t,e){let s={[a.i32_load]:["i32.load","i32"],[a.i64_load]:["i64.load","i64"],[a.f32_load]:["f32.load","f32"],[a.f64_load]:["f64.load","f64"],[a.i32_load8_s]:["i32.load8_s","i32"],[a.i32_load8_u]:["i32.load8_u","i32"],[a.i32_load16_s]:["i32.load16_s","i32"],[a.i32_load16_u]:["i32.load16_u","i32"],[a.i64_load8_s]:["i64.load8_s","i64"],[a.i64_load8_u]:["i64.load8_u","i64"],[a.i64_load16_s]:["i64.load16_s","i64"],[a.i64_load16_u]:["i64.load16_u","i64"],[a.i64_load32_s]:["i64.load32_s","i64"],[a.i64_load32_u]:["i64.load32_u","i64"]},i={[a.i32_store]:"i32.store",[a.i64_store]:"i64.store",[a.f32_store]:"f32.store",[a.f64_store]:"f64.store",[a.i32_store8]:"i32.store8",[a.i32_store16]:"i32.store16",[a.i64_store8]:"i64.store8",[a.i64_store16]:"i64.store16",[a.i64_store32]:"i64.store32"},r=s[t];if(r){let[c,u]=r,l=n.popStack(),d=n.newVar(u);n.addInstruction({type:"instr",id:d,opcode:c,args:[l],immediates:e}),n.pushStack(d);return}let o=i[t];if(o){let c=n.popStack(),u=n.popStack();n.addInstruction({type:"instr",opcode:o,args:[u,c],immediates:e});return}if(t===a.memory_size){let c=n.newVar("i32");n.addInstruction({type:"instr",id:c,opcode:"memory.size",args:[],immediates:e}),n.pushStack(c);return}throw new Error(`Unknown memory opcode: 0x${t.toString(16)}`)}var m={v128_load:64768,v128_store:64779,v128_const:64780,i8x16_shuffle:64781,i8x16_swizzle:64782,i8x16_splat:64783,i16x8_splat:64784,i32x4_splat:64785,i64x2_splat:64786,f32x4_splat:64787,f64x2_splat:64788,i8x16_extract_lane_s:64789,i8x16_extract_lane_u:64790,i8x16_replace_lane:64791,i16x8_extract_lane_s:64792,i16x8_extract_lane_u:64793,i16x8_replace_lane:64794,i32x4_extract_lane:64795,i32x4_replace_lane:64796,i64x2_extract_lane:64797,i64x2_replace_lane:64798,f32x4_extract_lane:64799,f32x4_replace_lane:64800,f64x2_extract_lane:64801,f64x2_replace_lane:64802,i8x16_eq:64803,i8x16_ne:64804,i8x16_lt_s:64805,i8x16_lt_u:64806,i8x16_gt_s:64807,i8x16_gt_u:64808,i8x16_le_s:64809,i8x16_le_u:64810,i8x16_ge_s:64811,i8x16_ge_u:64812,i16x8_eq:64813,i16x8_ne:64814,i16x8_lt_s:64815,i16x8_lt_u:64816,i16x8_gt_s:64817,i16x8_gt_u:64818,i16x8_le_s:64819,i16x8_le_u:64820,i16x8_ge_s:64821,i16x8_ge_u:64822,i32x4_eq:64823,i32x4_ne:64824,i32x4_lt_s:64825,i32x4_lt_u:64826,i32x4_gt_s:64827,i32x4_gt_u:64828,i32x4_le_s:64829,i32x4_le_u:64830,i32x4_ge_s:64831,i32x4_ge_u:64832,f32x4_eq:64833,f32x4_ne:64834,f32x4_lt:64835,f32x4_gt:64836,f32x4_le:64837,f32x4_ge:64838,f64x2_eq:64839,f64x2_ne:64840,f64x2_lt:64841,f64x2_gt:64842,f64x2_le:64843,f64x2_ge:64844,v128_not:64845,v128_and:64846,v128_andnot:64847,v128_or:64848,v128_xor:64849,v128_bitselect:64850,v128_any_true:64851,i8x16_abs:64864,i8x16_neg:64865,i8x16_all_true:64867,i8x16_bitmask:64868,i8x16_shl:64875,i8x16_shr_s:64876,i8x16_shr_u:64877,i8x16_add:64878,i8x16_sub:64881,i8x16_min_s:64886,i8x16_min_u:64887,i8x16_max_s:64888,i8x16_max_u:64889,i16x8_abs:64896,i16x8_neg:64897,i16x8_all_true:64899,i16x8_bitmask:64900,i16x8_shl:64907,i16x8_shr_s:64908,i16x8_shr_u:64909,i16x8_add:64910,i16x8_sub:64913,i16x8_mul:64917,i16x8_min_s:64918,i16x8_min_u:64919,i16x8_max_s:64920,i16x8_max_u:64921,i32x4_abs:64928,i32x4_neg:64929,i32x4_all_true:64931,i32x4_bitmask:64932,i32x4_shl:64939,i32x4_shr_s:64940,i32x4_shr_u:64941,i32x4_add:64942,i32x4_sub:64945,i32x4_mul:64949,i32x4_min_s:64950,i32x4_min_u:64951,i32x4_max_s:64952,i32x4_max_u:64953,i64x2_abs:64960,i64x2_neg:64961,i64x2_all_true:64963,i64x2_bitmask:64964,i64x2_shl:64971,i64x2_shr_s:64972,i64x2_shr_u:64973,i64x2_add:64974,i64x2_sub:64977,i64x2_mul:64981,i64x2_eq:64982,i64x2_ne:64983,i64x2_lt_s:64984,i64x2_gt_s:64985,i64x2_le_s:64986,i64x2_ge_s:64987,f32x4_abs:64992,f32x4_neg:64993,f32x4_sqrt:64995,f32x4_add:64996,f32x4_sub:64997,f32x4_mul:64998,f32x4_div:64999,f32x4_min:65e3,f32x4_max:65001,f32x4_pmin:65002,f32x4_pmax:65003,f64x2_abs:65004,f64x2_neg:65005,f64x2_sqrt:65007,f64x2_add:65008,f64x2_sub:65009,f64x2_mul:65010,f64x2_div:65011,f64x2_min:65012,f64x2_max:65013,f64x2_pmin:65014,f64x2_pmax:65015,f32x4_convert_i32x4_s:65018,f32x4_convert_i32x4_u:65019};function He(n,t,e){if(t===m.v128_load){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:"v128.load",args:[f],immediates:e}),n.pushStack(p);return}if(t===m.v128_store){let f=n.popStack(),p=n.popStack();n.addInstruction({type:"instr",opcode:"v128.store",args:[p,f],immediates:e});return}if(t===m.v128_const){let f=n.newVar("v128");n.addInstruction({type:"instr",id:f,opcode:"v128.const",args:[],immediates:e}),n.pushStack(f);return}let s={[m.i8x16_extract_lane_s]:{opcode:"i8x16.extract_lane_s",resultType:"i32"},[m.i8x16_extract_lane_u]:{opcode:"i8x16.extract_lane_u",resultType:"i32"},[m.i16x8_extract_lane_s]:{opcode:"i16x8.extract_lane_s",resultType:"i32"},[m.i16x8_extract_lane_u]:{opcode:"i16x8.extract_lane_u",resultType:"i32"},[m.i32x4_extract_lane]:{opcode:"i32x4.extract_lane",resultType:"i32"},[m.i64x2_extract_lane]:{opcode:"i64x2.extract_lane",resultType:"i64"},[m.f32x4_extract_lane]:{opcode:"f32x4.extract_lane",resultType:"f32"},[m.f64x2_extract_lane]:{opcode:"f64x2.extract_lane",resultType:"f64"}};if(s[t]){let f=n.popStack(),p=n.newVar(s[t].resultType);n.addInstruction({type:"instr",id:p,opcode:s[t].opcode,args:[f],immediates:e}),n.pushStack(p);return}let i={[m.i8x16_replace_lane]:"i8x16.replace_lane",[m.i16x8_replace_lane]:"i16x8.replace_lane",[m.i32x4_replace_lane]:"i32x4.replace_lane",[m.i64x2_replace_lane]:"i64x2.replace_lane",[m.f32x4_replace_lane]:"f32x4.replace_lane",[m.f64x2_replace_lane]:"f64x2.replace_lane"};if(i[t]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:i[t],args:[p,f],immediates:e}),n.pushStack(g);return}let r={[m.i8x16_splat]:"i8x16.splat",[m.i16x8_splat]:"i16x8.splat",[m.i32x4_splat]:"i32x4.splat",[m.i64x2_splat]:"i64x2.splat",[m.f32x4_splat]:"f32x4.splat",[m.f64x2_splat]:"f64x2.splat"};if(r[t]){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:r[t],args:[f],immediates:[]}),n.pushStack(p);return}let o={[m.v128_not]:"v128.not",[m.i8x16_abs]:"i8x16.abs",[m.i8x16_neg]:"i8x16.neg",[m.i16x8_abs]:"i16x8.abs",[m.i16x8_neg]:"i16x8.neg",[m.i32x4_abs]:"i32x4.abs",[m.i32x4_neg]:"i32x4.neg",[m.i64x2_abs]:"i64x2.abs",[m.i64x2_neg]:"i64x2.neg",[m.f32x4_abs]:"f32x4.abs",[m.f32x4_neg]:"f32x4.neg",[m.f32x4_sqrt]:"f32x4.sqrt",[m.f64x2_abs]:"f64x2.abs",[m.f64x2_neg]:"f64x2.neg",[m.f64x2_sqrt]:"f64x2.sqrt",[m.f32x4_convert_i32x4_s]:"f32x4.convert_i32x4_s",[m.f32x4_convert_i32x4_u]:"f32x4.convert_i32x4_u"};if(o[t]){let f=n.popStack(),p=n.newVar("v128");n.addInstruction({type:"instr",id:p,opcode:o[t],args:[f],immediates:[]}),n.pushStack(p);return}let c={[m.i8x16_shl]:"i8x16.shl",[m.i8x16_shr_s]:"i8x16.shr_s",[m.i8x16_shr_u]:"i8x16.shr_u",[m.i16x8_shl]:"i16x8.shl",[m.i16x8_shr_s]:"i16x8.shr_s",[m.i16x8_shr_u]:"i16x8.shr_u",[m.i32x4_shl]:"i32x4.shl",[m.i32x4_shr_s]:"i32x4.shr_s",[m.i32x4_shr_u]:"i32x4.shr_u",[m.i64x2_shl]:"i64x2.shl",[m.i64x2_shr_s]:"i64x2.shr_s",[m.i64x2_shr_u]:"i64x2.shr_u"};if(c[t]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:c[t],args:[p,f],immediates:[]}),n.pushStack(g);return}let u={[m.i8x16_eq]:"i8x16.eq",[m.i8x16_ne]:"i8x16.ne",[m.i8x16_lt_s]:"i8x16.lt_s",[m.i8x16_lt_u]:"i8x16.lt_u",[m.i8x16_gt_s]:"i8x16.gt_s",[m.i8x16_gt_u]:"i8x16.gt_u",[m.i8x16_le_s]:"i8x16.le_s",[m.i8x16_le_u]:"i8x16.le_u",[m.i8x16_ge_s]:"i8x16.ge_s",[m.i8x16_ge_u]:"i8x16.ge_u",[m.i16x8_eq]:"i16x8.eq",[m.i16x8_ne]:"i16x8.ne",[m.i16x8_lt_s]:"i16x8.lt_s",[m.i16x8_lt_u]:"i16x8.lt_u",[m.i16x8_gt_s]:"i16x8.gt_s",[m.i16x8_gt_u]:"i16x8.gt_u",[m.i16x8_le_s]:"i16x8.le_s",[m.i16x8_le_u]:"i16x8.le_u",[m.i16x8_ge_s]:"i16x8.ge_s",[m.i16x8_ge_u]:"i16x8.ge_u",[m.i32x4_eq]:"i32x4.eq",[m.i32x4_ne]:"i32x4.ne",[m.i32x4_lt_s]:"i32x4.lt_s",[m.i32x4_lt_u]:"i32x4.lt_u",[m.i32x4_gt_s]:"i32x4.gt_s",[m.i32x4_gt_u]:"i32x4.gt_u",[m.i32x4_le_s]:"i32x4.le_s",[m.i32x4_le_u]:"i32x4.le_u",[m.i32x4_ge_s]:"i32x4.ge_s",[m.i32x4_ge_u]:"i32x4.ge_u",[m.i64x2_eq]:"i64x2.eq",[m.i64x2_ne]:"i64x2.ne",[m.i64x2_lt_s]:"i64x2.lt_s",[m.i64x2_gt_s]:"i64x2.gt_s",[m.i64x2_le_s]:"i64x2.le_s",[m.i64x2_ge_s]:"i64x2.ge_s",[m.f32x4_eq]:"f32x4.eq",[m.f32x4_ne]:"f32x4.ne",[m.f32x4_lt]:"f32x4.lt",[m.f32x4_gt]:"f32x4.gt",[m.f32x4_le]:"f32x4.le",[m.f32x4_ge]:"f32x4.ge",[m.f64x2_eq]:"f64x2.eq",[m.f64x2_ne]:"f64x2.ne",[m.f64x2_lt]:"f64x2.lt",[m.f64x2_gt]:"f64x2.gt",[m.f64x2_le]:"f64x2.le",[m.f64x2_ge]:"f64x2.ge",[m.v128_and]:"v128.and",[m.v128_andnot]:"v128.andnot",[m.v128_or]:"v128.or",[m.v128_xor]:"v128.xor",[m.i8x16_add]:"i8x16.add",[m.i8x16_sub]:"i8x16.sub",[m.i8x16_min_s]:"i8x16.min_s",[m.i8x16_min_u]:"i8x16.min_u",[m.i8x16_max_s]:"i8x16.max_s",[m.i8x16_max_u]:"i8x16.max_u",[m.i16x8_add]:"i16x8.add",[m.i16x8_sub]:"i16x8.sub",[m.i16x8_mul]:"i16x8.mul",[m.i16x8_min_s]:"i16x8.min_s",[m.i16x8_min_u]:"i16x8.min_u",[m.i16x8_max_s]:"i16x8.max_s",[m.i16x8_max_u]:"i16x8.max_u",[m.i32x4_add]:"i32x4.add",[m.i32x4_sub]:"i32x4.sub",[m.i32x4_mul]:"i32x4.mul",[m.i32x4_min_s]:"i32x4.min_s",[m.i32x4_min_u]:"i32x4.min_u",[m.i32x4_max_s]:"i32x4.max_s",[m.i32x4_max_u]:"i32x4.max_u",[m.i64x2_add]:"i64x2.add",[m.i64x2_sub]:"i64x2.sub",[m.i64x2_mul]:"i64x2.mul",[m.f32x4_add]:"f32x4.add",[m.f32x4_sub]:"f32x4.sub",[m.f32x4_mul]:"f32x4.mul",[m.f32x4_div]:"f32x4.div",[m.f32x4_min]:"f32x4.min",[m.f32x4_max]:"f32x4.max",[m.f32x4_pmin]:"f32x4.pmin",[m.f32x4_pmax]:"f32x4.pmax",[m.f64x2_add]:"f64x2.add",[m.f64x2_sub]:"f64x2.sub",[m.f64x2_mul]:"f64x2.mul",[m.f64x2_div]:"f64x2.div",[m.f64x2_min]:"f64x2.min",[m.f64x2_max]:"f64x2.max",[m.f64x2_pmin]:"f64x2.pmin",[m.f64x2_pmax]:"f64x2.pmax"};if(u[t]){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:u[t],args:[p,f],immediates:[]}),n.pushStack(g);return}if(t===m.v128_bitselect){let f=n.popStack(),p=n.popStack(),g=n.popStack(),x=n.newVar("v128");n.addInstruction({type:"instr",id:x,opcode:"v128.bitselect",args:[g,p,f],immediates:[]}),n.pushStack(x);return}if(t===m.v128_any_true){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:"v128.any_true",args:[f],immediates:[]}),n.pushStack(p);return}let l={[m.i8x16_all_true]:"i8x16.all_true",[m.i16x8_all_true]:"i16x8.all_true",[m.i32x4_all_true]:"i32x4.all_true",[m.i64x2_all_true]:"i64x2.all_true"};if(l[t]){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:l[t],args:[f],immediates:[]}),n.pushStack(p);return}let d={[m.i8x16_bitmask]:"i8x16.bitmask",[m.i16x8_bitmask]:"i16x8.bitmask",[m.i32x4_bitmask]:"i32x4.bitmask",[m.i64x2_bitmask]:"i64x2.bitmask"};if(d[t]){let f=n.popStack(),p=n.newVar("i32");n.addInstruction({type:"instr",id:p,opcode:d[t],args:[f],immediates:[]}),n.pushStack(p);return}if(t===m.i8x16_shuffle){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:"i8x16.shuffle",args:[p,f],immediates:e}),n.pushStack(g);return}if(t===m.i8x16_swizzle){let f=n.popStack(),p=n.popStack(),g=n.newVar("v128");n.addInstruction({type:"instr",id:g,opcode:"i8x16.swizzle",args:[p,f],immediates:[]}),n.pushStack(g);return}throw new Error(`Unknown SIMD opcode: 0x${t.toString(16)}`)}function qe(n,t){let e=t.opcode;if(Xn(e))return ze(n,e,t.immediates),!0;if(Yn(e))return Ue(n,e,t.immediates),!0;if(Qn(e))return We(n,e,t.immediates),!0;if(Kn(e))try{return He(n,e,t.immediates),!0}catch{return!1}switch(e){case a.local_get:{let s=t.immediates[0],i=Jn(n,s),r=n.newVar(i);return n.addInstruction({type:"instr",id:r,opcode:"local.get",args:[],immediates:[s]}),n.pushStack(r),!0}case a.local_set:{let s=t.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),!0}case a.local_tee:{let s=t.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),n.pushStack(i),!0}case a.global_get:{let s=t.immediates[0],r=n.module.globals[s].type,o=n.newVar(r);return n.addInstruction({type:"instr",id:o,opcode:"global.get",args:[],immediates:[s]}),n.pushStack(o),!0}case a.global_set:{let s=t.immediates[0],i=n.popStack();return n.addInstruction({type:"instr",opcode:"global.set",args:[i],immediates:[s]}),!0}}switch(e){case a.i32_const:{let s=t.immediates[0],i=n.newVar("i32");return n.addInstruction({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.i64_const:{let s=t.immediates[0],i=n.newVar("i64");return n.addInstruction({type:"instr",id:i,opcode:"i64.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.f32_const:{let s=t.immediates[0],i=n.newVar("f32");return n.addInstruction({type:"instr",id:i,opcode:"f32.const",args:[],immediates:[s]}),n.pushStack(i),!0}case a.f64_const:{let s=t.immediates[0],i=n.newVar("f64");return n.addInstruction({type:"instr",id:i,opcode:"f64.const",args:[],immediates:[s]}),n.pushStack(i),!0}}if(e===a.return){if(n.funcResults.length>0){let s=n.popStack();n.addInstruction({type:"instr",opcode:"return",args:[s],immediates:[],synthetic:!1})}else n.addInstruction({type:"instr",opcode:"return",args:[],immediates:[],synthetic:!1});return!0}return!1}function Xn(n){return n===a.i32_add||n===a.i32_sub||n===a.i32_mul||n===a.i32_div_s||n===a.i32_div_u||n===a.i32_rem_s||n===a.i32_rem_u||n===a.i32_and||n===a.i32_or||n===a.i32_xor||n===a.i32_shl||n===a.i32_shr_s||n===a.i32_shr_u||n===a.i32_rotl||n===a.i32_rotr||n===a.i32_eq||n===a.i32_ne||n===a.i32_lt_s||n===a.i32_lt_u||n===a.i32_le_s||n===a.i32_le_u||n===a.i32_gt_s||n===a.i32_gt_u||n===a.i32_ge_s||n===a.i32_ge_u||n===a.i64_add||n===a.i64_sub||n===a.i64_mul||n===a.i64_div_s||n===a.i64_div_u||n===a.i64_rem_s||n===a.i64_rem_u||n===a.i64_and||n===a.i64_or||n===a.i64_xor||n===a.i64_shl||n===a.i64_shr_s||n===a.i64_shr_u||n===a.i64_rotl||n===a.i64_rotr||n===a.i64_eq||n===a.i64_ne||n===a.i64_lt_s||n===a.i64_lt_u||n===a.i64_le_s||n===a.i64_le_u||n===a.i64_gt_s||n===a.i64_gt_u||n===a.i64_ge_s||n===a.i64_ge_u||n===a.f32_add||n===a.f32_sub||n===a.f32_mul||n===a.f32_div||n===a.f32_min||n===a.f32_max||n===a.f32_copysign||n===a.f32_eq||n===a.f32_ne||n===a.f32_lt||n===a.f32_le||n===a.f32_gt||n===a.f32_ge||n===a.f64_add||n===a.f64_sub||n===a.f64_mul||n===a.f64_div||n===a.f64_min||n===a.f64_max||n===a.f64_copysign||n===a.f64_eq||n===a.f64_ne||n===a.f64_lt||n===a.f64_le||n===a.f64_gt||n===a.f64_ge}function Yn(n){return n===a.i32_clz||n===a.i32_ctz||n===a.i32_popcnt||n===a.i32_eqz||n===a.i64_clz||n===a.i64_ctz||n===a.i64_popcnt||n===a.i64_eqz||n===a.f32_abs||n===a.f32_neg||n===a.f32_sqrt||n===a.f32_ceil||n===a.f32_floor||n===a.f32_trunc||n===a.f32_nearest||n===a.f64_abs||n===a.f64_neg||n===a.f64_sqrt||n===a.f64_ceil||n===a.f64_floor||n===a.f64_trunc||n===a.f64_nearest||n===a.i32_wrap_i64||n===a.i64_extend_i32_s||n===a.i64_extend_i32_u||n===a.i32_trunc_f32_s||n===a.i32_trunc_f32_u||n===a.i32_trunc_f64_s||n===a.i32_trunc_f64_u||n===a.i64_trunc_f32_s||n===a.i64_trunc_f32_u||n===a.i64_trunc_f64_s||n===a.i64_trunc_f64_u||n===a.f32_convert_i32_s||n===a.f32_convert_i32_u||n===a.f32_convert_i64_s||n===a.f32_convert_i64_u||n===a.f32_demote_f64||n===a.f64_convert_i32_s||n===a.f64_convert_i32_u||n===a.f64_convert_i64_s||n===a.f64_convert_i64_u||n===a.f64_promote_f32||n===a.i32_reinterpret_f32||n===a.i64_reinterpret_f64||n===a.f32_reinterpret_i32||n===a.f64_reinterpret_i64||n===a.i32_trunc_sat_f32_s||n===a.i32_trunc_sat_f32_u||n===a.i32_trunc_sat_f64_s||n===a.i32_trunc_sat_f64_u||n===a.i64_trunc_sat_f32_s||n===a.i64_trunc_sat_f32_u||n===a.i64_trunc_sat_f64_s||n===a.i64_trunc_sat_f64_u}function Qn(n){return n===a.i32_load||n===a.i64_load||n===a.f32_load||n===a.f64_load||n===a.i32_load8_s||n===a.i32_load8_u||n===a.i32_load16_s||n===a.i32_load16_u||n===a.i64_load8_s||n===a.i64_load8_u||n===a.i64_load16_s||n===a.i64_load16_u||n===a.i64_load32_s||n===a.i64_load32_u||n===a.i32_store||n===a.i64_store||n===a.f32_store||n===a.f64_store||n===a.i32_store8||n===a.i32_store16||n===a.i64_store8||n===a.i64_store16||n===a.i64_store32||n===a.memory_size}function Kn(n){return(n&65280)===64768}function Jn(n,t){let e=n.funcParams.length;if(t<e)return n.funcParams[t];{let s=t-e;return n.funcLocals[s]}}function we(n,t){if(!n.currentFunc)return;let e=n.currentFunc.inlinedExpressionMap?.get(t);if(e&&e.opcode==="i32.const"&&e.immediates)return e.immediates[0]}function es(n){return new Set(["i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i32.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","i64.eqz","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge"]).has(n)}function M(n,t){let e=n.resolveVarExpr(t);if(!n.currentFunc)return e;let s=n.currentFunc.inlinedExpressionMap?.get(t);if(s&&es(s.opcode)&&!e.code.startsWith("select(0i, 1i,"))return{code:`select(0i, 1i, ${e.code})`,precedence:h};let r=n.currentFunc.vars.get(t)?.type;return!r||r==="i32"?e:r==="f32"?{code:`bitcast<i32>(${e.code})`,precedence:h}:{code:`i32(${e.code})`,precedence:h}}function O(n,t){let e=n.resolveVarExpr(t);if(!n.currentFunc)return e;let i=n.currentFunc.vars.get(t)?.type;return i==="f32"||i==="f64"?e:!i||i==="i32"?{code:`bitcast<f32>(${e.code})`,precedence:h}:{code:`f32(${e.code})`,precedence:h}}function F(n,t){return M(n,t).code}function k(n,t){return O(n,t).code}function Ge(n){switch(n){case"i32":return"0i";case"i64":return"0i";case"f32":return"0.0f";case"f64":return"0.0";case"v128":return"vec4<u32>(0u)";default:return"0i"}}function je(n,t,e){let s=n.resolveVar(e);if(!n.currentFunc)return`local_${t} = ${s}`;let i,r=n.currentFunc.params.length;if(t<r)i=n.currentFunc.params[t];else if(n.currentFunc.locals&&t-r<n.currentFunc.locals.length)i=n.currentFunc.locals[t-r];else return`local_${t} = ${s}`;let c=n.currentFunc.vars.get(e)?.type||"i32",u=me(c),l=me(i);return u===l?l==="f32"&&c!=="f32"?`local_${t} = f32(${s})`:`local_${t} = ${s}`:u==="i32"&&l==="f32"||u==="f32"&&l==="i32"?`local_${t} = bitcast<${l}>(${s})`:`local_${t} = ${l}(${s})`}function H(n){let t=new Set;switch(n.kind){case"block":for(let e of n.children)for(let s of H(e))t.add(s);break;case"loop":for(let e of H(n.body))t.add(e);break;case"parallel_loop":for(let e of H(n.body))t.add(e);if(n.epilogue)for(let e of H(n.epilogue))t.add(e);break;case"if":for(let e of H(n.thenBranch))t.add(e);if(n.elseBranch)for(let e of H(n.elseBranch))t.add(e);break;case"simple":for(let e of n.instructions)e.id!==void 0&&t.add(e.id);break}return t}function Z(n){let t=new Set;switch(n.kind){case"block":for(let e of n.children)for(let s of Z(e))t.add(s);break;case"loop":for(let e of Z(n.body))t.add(e);break;case"parallel_loop":for(let e of Z(n.body))t.add(e);if(n.epilogue)for(let e of Z(n.epilogue))t.add(e);break;case"if":t.add(n.condition);for(let e of Z(n.thenBranch))t.add(e);if(n.elseBranch)for(let e of Z(n.elseBranch))t.add(e);break;case"simple":for(let e of n.instructions)if(e.args)for(let s of e.args)s>=0&&t.add(s);break;case"return":n.value!==void 0&&t.add(n.value);break}return t}function X(n,t,e){switch(n.kind){case"block":{let s=H(n);for(let i of s)t.has(i)&&e.add(i);for(let i of n.children)X(i,t,e);break}case"loop":{let s=H(n.body);for(let i of s)t.has(i)&&e.add(i);X(n.body,t,e);break}case"parallel_loop":{let s=H(n.body);for(let i of s)t.has(i)&&e.add(i);if(X(n.body,t,e),n.epilogue){let i=H(n.epilogue);for(let r of i)t.has(r)&&e.add(r);X(n.epilogue,t,e)}break}case"if":{let s=H(n.thenBranch),i=n.elseBranch?H(n.elseBranch):new Set;for(let d of s)t.has(d)&&e.add(d);for(let d of i)t.has(d)&&e.add(d);let r=d=>{let f=new Set;switch(d.kind){case"simple":for(let p of d.instructions)p.opcode==="assign"&&p.id!==void 0&&f.add(p.id);break;case"block":for(let p of d.children)for(let g of r(p))f.add(g);break;case"loop":for(let p of r(d.body))f.add(p);break;case"parallel_loop":for(let p of r(d.body))f.add(p);if(d.epilogue)for(let p of r(d.epilogue))f.add(p);break;case"if":for(let p of r(d.thenBranch))f.add(p);if(d.elseBranch)for(let p of r(d.elseBranch))f.add(p);break}return f},o=r(n.thenBranch),c=n.elseBranch?r(n.elseBranch):new Set;for(let d of o)e.add(d);for(let d of c)e.add(d);let u=Z(n.thenBranch),l=n.elseBranch?Z(n.elseBranch):new Set;X(n.thenBranch,u,e),n.elseBranch&&X(n.elseBranch,l,e);break}case"simple":break}}function he(n,t=!1){switch(n.kind){case"return":case"break":case"continue":return!0;case"block":return n.children.length===0?!1:he(n.children[n.children.length-1],t);case"if":{let e=he(n.thenBranch,t),s=n.elseBranch?he(n.elseBranch,t):!1;return t&&(e||s)?!0:e&&s}case"simple":return n.instructions.length===0?!1:n.instructions.some(e=>e.opcode==="return"||e.opcode==="unreachable");default:return!1}}function $e(n){switch(n.kind){case"block":return n.children.length===0||n.children.every(t=>$e(t));case"simple":return n.instructions.length===0;case"return":case"break":case"continue":case"loop":case"if":return!1;default:return!0}}function _e(n){switch(n.kind){case"return":return!0;case"block":return n.children.length===0?!1:n.children.some(t=>_e(t));case"if":return _e(n.thenBranch)&&(n.elseBranch?_e(n.elseBranch):!1);case"loop":case"break":case"continue":return!1;case"simple":return n.instructions.length===0?!1:n.instructions.some(t=>t.opcode==="return"||t.opcode==="unreachable");default:return!1}}function Ze(n){let t=new Set;function e(s){switch(s.kind){case"block":for(let i of s.children)e(i);break;case"loop":e(s.body);break;case"parallel_loop":e(s.body),s.epilogue&&e(s.epilogue);break;case"if":e(s.thenBranch),s.elseBranch&&e(s.elseBranch);break;case"simple":for(let i of s.instructions)if((i.opcode==="local.get"||i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates&&i.immediates.length>0){let r=i.immediates[0];t.add(r)}break;case"return":case"break":case"continue":break}}return e(n),t}function Xe(n){let t=new Map;function e(s){switch(s.kind){case"block":for(let i of s.children)e(i);break;case"loop":e(s.body);break;case"parallel_loop":e(s.body),s.epilogue&&e(s.epilogue);break;case"if":e(s.thenBranch),s.elseBranch&&e(s.elseBranch);break;case"simple":for(let i of s.instructions)if((i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates&&i.immediates.length>0){let r=i.immediates[0],o=t.get(r)||0;t.set(r,o+1)}break;case"return":case"break":case"continue":break}}return e(n),t}function Ye(n){function t(e,s=!1){switch(e.kind){case"loop":case"parallel_loop":return t((e.kind==="loop",e.body),!0)?!0:e.kind==="parallel_loop"&&e.epilogue?t(e.epilogue,s):!1;case"block":return e.children.some(c=>t(c,s));case"if":let r=t(e.thenBranch,s),o=e.elseBranch?t(e.elseBranch,s):!1;return r||o;case"simple":return s&&e.instructions.some(c=>c.opcode==="return"&&c.synthetic===!1);case"return":return!1;default:return!1}}return t(n,!1)}function D(n,t,e){let s=E[n];if(s===void 0)return{code:`(${t.code} ${n} ${e.code})`,precedence:h};let i=P(t,s,!1,n),r=P(e,s,!0,n);return{code:`${i} ${n} ${r}`,precedence:s,operator:n}}function Qe(n,t,e,s,i){switch(t){case"i32.const":{let r=s[0];return r===-2147483648?{code:"bitcast<i32>(2147483648u)",precedence:h}:{code:`${r}i`,precedence:h}}case"i32.add":return D("+",M(n,e[0]),M(n,e[1]));case"i32.sub":return D("-",M(n,e[0]),M(n,e[1]));case"i32.mul":return D("*",M(n,e[0]),M(n,e[1]));case"i32.div_s":return D("/",M(n,e[0]),M(n,e[1]));case"i32.div_u":return{code:`bitcast<i32>(bitcast<u32>(${F(n,e[0])}) / bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.rem_s":return D("%",M(n,e[0]),M(n,e[1]));case"i32.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${F(n,e[0])}) % bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.and":return D("&",M(n,e[0]),M(n,e[1]));case"i32.or":return D("|",M(n,e[0]),M(n,e[1]));case"i32.xor":return D("^",M(n,e[0]),M(n,e[1]));case"i32.shl":{let r=we(n,e[1]);if(r!==void 0&&r>=0&&r<=31){let u=M(n,e[0]);return{code:`${P(u,E["<<"],!1,"<<")} << ${r}u`,precedence:E["<<"],operator:"<<"}}let o=M(n,e[0]);return{code:`${P(o,E["<<"],!1,"<<")} << (bitcast<u32>(${F(n,e[1])}) & 31u)`,precedence:E["<<"],operator:"<<"}}case"i32.shr_s":{let r=we(n,e[1]);if(r!==void 0&&r>=0&&r<=31){let u=M(n,e[0]);return{code:`${P(u,E[">>"],!1,">>")} >> ${r}u`,precedence:E[">>"],operator:">>"}}let o=M(n,e[0]);return{code:`${P(o,E[">>"],!1,">>")} >> (bitcast<u32>(${F(n,e[1])}) & 31u)`,precedence:E[">>"],operator:">>"}}case"i32.shr_u":{let r=we(n,e[1]),o=M(n,e[0]),u=(i!==void 0?n.currentFunc?.vars.get(i):void 0)?.emitAsU32===!0,d=n.currentFunc?.vars.get(e[0])?.isNonNegative===!0,f=!o.code.startsWith("bitcast<u32>");if(r!==void 0&&r>=0&&r<=31){let g=o.precedence<h?`(${o.code})`:o.code;return u?d?{code:`u32(${g}) >> ${r}u`,precedence:E[">>"],operator:">>"}:{code:`bitcast<u32>(${g}) >> ${r}u`,precedence:E[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${g}) >> ${r}u)`,precedence:h}:f?{code:`bitcast<i32>(bitcast<u32>(${g}) >> ${r}u)`,precedence:h}:{code:`bitcast<i32>(${o.code} >> ${r}u)`,precedence:h}}let p=o.precedence<h?`(${o.code})`:o.code;return u?d?{code:`u32(${p}) >> (bitcast<u32>(${F(n,e[1])}) & 31u)`,precedence:E[">>"],operator:">>"}:{code:`bitcast<u32>(${p}) >> (bitcast<u32>(${F(n,e[1])}) & 31u)`,precedence:E[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${p}) >> (bitcast<u32>(${F(n,e[1])}) & 31u))`,precedence:h}:{code:`bitcast<i32>(bitcast<u32>(${p}) >> (bitcast<u32>(${F(n,e[1])}) & 31u))`,precedence:h}}case"i32.rotl":{let r=`bitcast<u32>(${F(n,e[0])})`,o=`(bitcast<u32>(${F(n,e[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} << ${o}) | (${r} >> (32u - ${o}))))`,precedence:h}}case"i32.rotr":{let r=`bitcast<u32>(${F(n,e[0])})`,o=`(bitcast<u32>(${F(n,e[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} >> ${o}) | (${r} << (32u - ${o}))))`,precedence:h}}case"i32.clz":return{code:`countLeadingZeros(${F(n,e[0])})`,precedence:h};case"i32.ctz":return{code:`countTrailingZeros(${F(n,e[0])})`,precedence:h};case"i32.popcnt":return{code:`countOneBits(${F(n,e[0])})`,precedence:h};default:return null}}function Tt(n,t,e,s,i){let r=Qe(n,t,e,s,i);return r===null?null:r.precedence<h?`(${r.code})`:r.code}function Ke(n,t,e){let s=(i,r,o)=>{let c=M(n,i),u=E[r];return P(c,u,o,r)};switch(t){case"i32.eq":return{code:`select(0i, 1i, ${s(e[0],"==",!1)} == ${s(e[1],"==",!0)})`,precedence:h};case"i32.ne":return{code:`select(0i, 1i, ${s(e[0],"!=",!1)} != ${s(e[1],"!=",!0)})`,precedence:h};case"i32.lt_s":return{code:`select(0i, 1i, ${s(e[0],"<",!1)} < ${s(e[1],"<",!0)})`,precedence:h};case"i32.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,e[0])}) < bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.gt_s":return{code:`select(0i, 1i, ${s(e[0],">",!1)} > ${s(e[1],">",!0)})`,precedence:h};case"i32.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,e[0])}) > bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.le_s":return{code:`select(0i, 1i, ${s(e[0],"<=",!1)} <= ${s(e[1],"<=",!0)})`,precedence:h};case"i32.le_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,e[0])}) <= bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.ge_s":return{code:`select(0i, 1i, ${s(e[0],">=",!1)} >= ${s(e[1],">=",!0)})`,precedence:h};case"i32.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${F(n,e[0])}) >= bitcast<u32>(${F(n,e[1])}))`,precedence:h};case"i32.eqz":return{code:`select(0i, 1i, ${s(e[0],"==",!1)} == 0i)`,precedence:h};default:return null}}function Nt(n,t,e){let s=Ke(n,t,e);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function Je(n,t,e,s){switch(t){case"f32.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}f`,precedence:h}}case"f32.add":return D("+",O(n,e[0]),O(n,e[1]));case"f32.sub":return D("-",O(n,e[0]),O(n,e[1]));case"f32.mul":return D("*",O(n,e[0]),O(n,e[1]));case"f32.div":return D("/",O(n,e[0]),O(n,e[1]));case"f32.abs":return{code:`abs(${k(n,e[0])})`,precedence:h};case"f32.neg":{let i=O(n,e[0]);return{code:`-${P(i,14)}`,precedence:14}}case"f32.ceil":return{code:`ceil(${k(n,e[0])})`,precedence:h};case"f32.floor":return{code:`floor(${k(n,e[0])})`,precedence:h};case"f32.trunc":return{code:`trunc(${k(n,e[0])})`,precedence:h};case"f32.nearest":return{code:`round(${k(n,e[0])})`,precedence:h};case"f32.sqrt":return{code:`sqrt(${k(n,e[0])})`,precedence:h};case"f32.min":return{code:`min(${k(n,e[0])}, ${k(n,e[1])})`,precedence:h};case"f32.max":return{code:`max(${k(n,e[0])}, ${k(n,e[1])})`,precedence:h};case"f32.copysign":return{code:`bitcast<f32>((bitcast<u32>(${k(n,e[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${k(n,e[1])}) & 0x80000000u))`,precedence:h};default:return null}}function Ot(n,t,e,s){let i=Je(n,t,e,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function et(n,t,e){switch(t){case"f32.eq":return{code:`select(0i, 1i, ${k(n,e[0])} == ${k(n,e[1])})`,precedence:h};case"f32.ne":return{code:`select(0i, 1i, ${k(n,e[0])} != ${k(n,e[1])})`,precedence:h};case"f32.lt":return{code:`select(0i, 1i, ${k(n,e[0])} < ${k(n,e[1])})`,precedence:h};case"f32.gt":return{code:`select(0i, 1i, ${k(n,e[0])} > ${k(n,e[1])})`,precedence:h};case"f32.le":return{code:`select(0i, 1i, ${k(n,e[0])} <= ${k(n,e[1])})`,precedence:h};case"f32.ge":return{code:`select(0i, 1i, ${k(n,e[0])} >= ${k(n,e[1])})`,precedence:h};default:return null}}function Pt(n,t,e){let s=et(n,t,e);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function tt(n,t,e,s){switch(t){case"i64.const":{let i=s[0];return{code:`${BigInt.asIntN(32,i)}`,precedence:h}}case"i64.add":return D("+",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.sub":return D("-",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.mul":return D("*",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.div_s":return D("/",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.div_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(e[0])}) / bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.rem_s":return D("%",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(e[0])}) % bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.and":return D("&",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.or":return D("|",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.xor":return D("^",n.resolveVarExpr(e[0]),n.resolveVarExpr(e[1]));case"i64.shl":{let i=n.resolveVarExpr(e[0]);return{code:`${P(i,E["<<"],!1,"<<")} << (bitcast<u32>(${n.resolveVar(e[1])}) & 31u)`,precedence:E["<<"],operator:"<<"}}case"i64.shr_s":{let i=n.resolveVarExpr(e[0]);return{code:`${P(i,E[">>"],!1,">>")} >> (bitcast<u32>(${n.resolveVar(e[1])}) & 31u)`,precedence:E[">>"],operator:">>"}}case"i64.shr_u":return{code:`bitcast<i32>(bitcast<u32>(${n.resolveVar(e[0])}) >> (bitcast<u32>(${n.resolveVar(e[1])}) & 31u))`,precedence:h};case"i64.rotl":{let i=`bitcast<u32>(${n.resolveVar(e[0])})`,r=`(bitcast<u32>(${n.resolveVar(e[1])}) & 31u)`;return{code:`bitcast<i32>((${i} << ${r}) | (${i} >> (32u - ${r})))`,precedence:h}}case"i64.rotr":{let i=`bitcast<u32>(${n.resolveVar(e[0])})`,r=`(bitcast<u32>(${n.resolveVar(e[1])}) & 31u)`;return{code:`bitcast<i32>((${i} >> ${r}) | (${i} << (32u - ${r})))`,precedence:h}}case"i64.clz":return{code:`countLeadingZeros(${n.resolveVar(e[0])})`,precedence:h};case"i64.ctz":return{code:`countTrailingZeros(${n.resolveVar(e[0])})`,precedence:h};case"i64.popcnt":return{code:`countOneBits(${n.resolveVar(e[0])})`,precedence:h};default:return null}}function Lt(n,t,e,s){let i=tt(n,t,e,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function nt(n,t,e){switch(t){case"i64.eq":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} == ${n.resolveVar(e[1])})`,precedence:h};case"i64.ne":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} != ${n.resolveVar(e[1])})`,precedence:h};case"i64.lt_s":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} < ${n.resolveVar(e[1])})`,precedence:h};case"i64.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(e[0])}) < bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.gt_s":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} > ${n.resolveVar(e[1])})`,precedence:h};case"i64.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(e[0])}) > bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.le_s":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} <= ${n.resolveVar(e[1])})`,precedence:h};case"i64.le_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(e[0])}) <= bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.ge_s":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} >= ${n.resolveVar(e[1])})`,precedence:h};case"i64.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${n.resolveVar(e[0])}) >= bitcast<u32>(${n.resolveVar(e[1])}))`,precedence:h};case"i64.eqz":return{code:`select(0i, 1i, ${n.resolveVar(e[0])} == 0i)`,precedence:h};default:return null}}function zt(n,t,e){let s=nt(n,t,e);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function st(n,t,e,s){switch(t){case"f64.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}`,precedence:h}}case"f64.add":return D("+",O(n,e[0]),O(n,e[1]));case"f64.sub":return D("-",O(n,e[0]),O(n,e[1]));case"f64.mul":return D("*",O(n,e[0]),O(n,e[1]));case"f64.div":return D("/",O(n,e[0]),O(n,e[1]));case"f64.abs":return{code:`abs(${k(n,e[0])})`,precedence:h};case"f64.neg":{let i=O(n,e[0]);return{code:`-${P(i,14)}`,precedence:14}}case"f64.ceil":return{code:`ceil(${k(n,e[0])})`,precedence:h};case"f64.floor":return{code:`floor(${k(n,e[0])})`,precedence:h};case"f64.trunc":return{code:`trunc(${k(n,e[0])})`,precedence:h};case"f64.nearest":return{code:`round(${k(n,e[0])})`,precedence:h};case"f64.sqrt":return{code:`sqrt(${k(n,e[0])})`,precedence:h};case"f64.min":return{code:`min(${k(n,e[0])}, ${k(n,e[1])})`,precedence:h};case"f64.max":return{code:`max(${k(n,e[0])}, ${k(n,e[1])})`,precedence:h};case"f64.copysign":return{code:`bitcast<f32>((bitcast<u32>(${k(n,e[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${k(n,e[1])}) & 0x80000000u))`,precedence:h};default:return null}}function Ut(n,t,e,s){let i=st(n,t,e,s);return i===null?null:i.precedence<h?`(${i.code})`:i.code}function it(n,t,e){switch(t){case"f64.eq":return{code:`select(0i, 1i, ${k(n,e[0])} == ${k(n,e[1])})`,precedence:h};case"f64.ne":return{code:`select(0i, 1i, ${k(n,e[0])} != ${k(n,e[1])})`,precedence:h};case"f64.lt":return{code:`select(0i, 1i, ${k(n,e[0])} < ${k(n,e[1])})`,precedence:h};case"f64.gt":return{code:`select(0i, 1i, ${k(n,e[0])} > ${k(n,e[1])})`,precedence:h};case"f64.le":return{code:`select(0i, 1i, ${k(n,e[0])} <= ${k(n,e[1])})`,precedence:h};case"f64.ge":return{code:`select(0i, 1i, ${k(n,e[0])} >= ${k(n,e[1])})`,precedence:h};default:return null}}function Wt(n,t,e){let s=it(n,t,e);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function rt(n,t,e){switch(t){case"i32.wrap_i64":return n.resolveVarExpr(e[0]);case"i64.extend_i32_s":return n.resolveVarExpr(e[0]);case"i64.extend_i32_u":return n.resolveVarExpr(e[0]);case"f32.convert_i32_s":return{code:`f32(${n.resolveVar(e[0])})`,precedence:h};case"f32.convert_i32_u":return{code:`f32(bitcast<u32>(${n.resolveVar(e[0])}))`,precedence:h};case"f32.convert_i64_s":return{code:`f32(${n.resolveVar(e[0])})`,precedence:h};case"f32.convert_i64_u":return{code:`f32(bitcast<u32>(${n.resolveVar(e[0])}))`,precedence:h};case"f64.convert_i32_s":return{code:`f32(${n.resolveVar(e[0])})`,precedence:h};case"f64.convert_i32_u":return{code:`f32(bitcast<u32>(${n.resolveVar(e[0])}))`,precedence:h};case"f64.convert_i64_s":return{code:`f32(${n.resolveVar(e[0])})`,precedence:h};case"f64.convert_i64_u":return{code:`f32(bitcast<u32>(${n.resolveVar(e[0])}))`,precedence:h};case"i32.trunc_f32_s":return{code:`i32(${n.resolveVar(e[0])})`,precedence:h};case"i32.trunc_f32_u":return{code:`bitcast<i32>(u32(${n.resolveVar(e[0])}))`,precedence:h};case"i64.trunc_f32_s":return{code:`i32(${n.resolveVar(e[0])})`,precedence:h};case"i64.trunc_f32_u":return{code:`bitcast<i32>(u32(${n.resolveVar(e[0])}))`,precedence:h};case"i64.trunc_f64_s":return{code:`i32(${n.resolveVar(e[0])})`,precedence:h};case"i64.trunc_f64_u":return{code:`bitcast<i32>(u32(${n.resolveVar(e[0])}))`,precedence:h};case"i32.trunc_f64_s":return{code:`i32(${n.resolveVar(e[0])})`,precedence:h};case"i32.trunc_f64_u":return{code:`bitcast<i32>(u32(${n.resolveVar(e[0])}))`,precedence:h};case"f32.demote_f64":return n.resolveVarExpr(e[0]);case"f64.promote_f32":return n.resolveVarExpr(e[0]);case"i32.reinterpret_f32":return{code:`bitcast<i32>(${n.resolveVar(e[0])})`,precedence:h};case"f32.reinterpret_i32":return{code:`bitcast<f32>(${n.resolveVar(e[0])})`,precedence:h};case"i64.reinterpret_f64":return{code:`bitcast<i32>(${n.resolveVar(e[0])})`,precedence:h};case"f64.reinterpret_i64":return{code:`bitcast<f32>(${n.resolveVar(e[0])})`,precedence:h};case"i32.trunc_sat_f32_s":return{code:`i32(trunc(${n.resolveVar(e[0])}))`,precedence:h};case"i32.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(e[0])})))`,precedence:h};case"i32.trunc_sat_f64_s":return{code:`i32(trunc(${n.resolveVar(e[0])}))`,precedence:h};case"i32.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(e[0])})))`,precedence:h};case"i64.trunc_sat_f32_s":return{code:`i32(trunc(${n.resolveVar(e[0])}))`,precedence:h};case"i64.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(e[0])})))`,precedence:h};case"i64.trunc_sat_f64_s":return{code:`i32(trunc(${n.resolveVar(e[0])}))`,precedence:h};case"i64.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${n.resolveVar(e[0])})))`,precedence:h};default:return null}}function Ht(n,t,e){let s=rt(n,t,e);return s===null?null:s.precedence<h?`(${s.code})`:s.code}function se(n,t){let e=n.currentFunc?.inlinedExpressionMap?.get(t);return e&&e.opcode==="i32.const"&&e.immediates&&e.immediates.length>0?`${e.immediates[0]>>>0}u`:n.currentFunc?.vars.get(t)?.emitAsU32?`v${t}`:`bitcast<u32>(${F(n,t)})`}function qt(n,t,e){switch(t){case"wgsl.load_i32":{let s=se(n,e[0]);return n.inlineMemoryOps?`bitcast<i32>(memory[${s}])`:`wgsl_load_i32(${s})`}case"wgsl.load_f32":{let s=se(n,e[0]);return n.inlineMemoryOps?`bitcast<f32>(memory[${s}])`:`wgsl_load_f32(${s})`}case"wgsl.buffer_length":return"wgsl_buffer_length()";case"wgsl.load_vec3f":{let s=se(n,e[0]);return`vec3<f32>(bitcast<f32>(memory[${s}]), bitcast<f32>(memory[${s} + 1u]), bitcast<f32>(memory[${s} + 2u]))`}case"wgsl.load_vec4f":{let s=se(n,e[0]);return`vec4<f32>(bitcast<f32>(memory[${s}]), bitcast<f32>(memory[${s} + 1u]), bitcast<f32>(memory[${s} + 2u]), bitcast<f32>(memory[${s} + 3u]))`}default:return null}}function Gt(n,t,e){switch(t){case"wgsl.store_i32":{let s=se(n,e[0]),i=F(n,e[1]);return n.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_i32(${s}, ${i});`}case"wgsl.store_f32":{let s=se(n,e[0]),i=n.resolveVar(e[1]);return n.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_f32(${s}, ${i});`}case"wgsl.store_vec3f":{let s=se(n,e[0]),i=n.resolveVar(e[1]),r=n.resolveVar(e[2]),o=n.resolveVar(e[3]);return`memory[${s}] = bitcast<u32>(${i}); memory[${s} + 1u] = bitcast<u32>(${r}); memory[${s} + 2u] = bitcast<u32>(${o});`}case"wgsl.store_vec4f":{let s=se(n,e[0]),i=n.resolveVar(e[1]),r=n.resolveVar(e[2]),o=n.resolveVar(e[3]),c=n.resolveVar(e[4]);return`memory[${s}] = bitcast<u32>(${i}); memory[${s} + 1u] = bitcast<u32>(${r}); memory[${s} + 2u] = bitcast<u32>(${o}); memory[${s} + 3u] = bitcast<u32>(${c});`}default:return null}}function jt(n,t){let e=n[0];return t!==void 0&&e===t?"i32(_wgpu_global_idx)":`local_${e}`}function Zt(n){return`global_${n[0]}`}function ts(n,t){if(!n.imports||!n.mathExtension)return null;let e=0;for(let s of n.imports)if(s.kind==="func"){if(e===t){if(bt(s.module,s.name)){let i=ke(s.name);if(i){let r=Ce(s.name),o=r?vt(s.name):0;return{name:s.name,wgslBuiltin:i.wgslBuiltin,vectorDim:o,wasmParams:i.wasmParams,wasmResults:i.wasmResults,isVector:r,supportsVector:i.supportsVector}}}return null}e++}return null}function Xt(n,t){let e=`bitcast<vec4<f32>>(${n})`;return t===2?`${e}.xy`:t===3?`${e}.xyz`:e}function Yt(n,t){return t===4?`bitcast<vec4<u32>>(${n})`:t===3?`bitcast<vec4<u32>>(vec4<f32>(${n}, 0.0))`:t===2?`bitcast<vec4<u32>>(vec4<f32>(${n}, 0.0, 0.0))`:n}function Qt(n,t,e){let s=e[0],r=ts(n,s);if(r){if(r.isVector&&r.vectorDim>0){let f=t.map((x,w)=>{let I=r.wasmParams[w];return I==="v128"||I==="f32"&&r.supportsVector?Xt(n.resolveVar(x),r.vectorDim):n.resolveVar(x)}).join(", "),p=`${r.wgslBuiltin}(${f})`,g=r.wasmResults[0];return g==="v128"||g==="f32"&&r.supportsVector?Yt(p,r.vectorDim):p}let l=t.map(d=>n.resolveVar(d)).join(", ");return`${r.wgslBuiltin}(${l})`}let c=n.functionNameMap?.get(s)??`func_${s}`,u=t.map(l=>n.resolveVar(l)).join(", ");return`${c}(${u})`}function Kt(n,t,e){let s="i32";if(e!==void 0&&n.currentFunc){let c=n.currentFunc.vars.get(e);c&&(s=c.type)}let i=n.resolveVarExpr(t[2]),o=`(${P(i,E["!="],!1,"!=")} != 0)`;return s==="f32"||s==="f64"?`select(${k(n,t[0])}, ${k(n,t[1])}, ${o})`:s==="v128"?`select(${n.resolveVar(t[0])}, ${n.resolveVar(t[1])}, ${o})`:`select(${F(n,t[0])}, ${F(n,t[1])}, ${o})`}function Jt(n,t){if(t.length>0){let e=t[0];return e>=0?`return ${n.resolveVar(e)};`:"return 0i;"}return"return;"}function ot(n,t,e){if(t.length===0)return"0i";let s=n.currentFunc?.vars.get(e);return s?.type==="f32"||s?.type==="f64"?k(n,t[0]):s?.type==="v128"?n.resolveVar(t[0]):F(n,t[0])}function en(n,t){let s=`(bitcast<u32>(${n.resolveVar(t[0])}) >> 2u)`;return`vec4<u32>(memory[${s}], memory[${s} + 1u], memory[${s} + 2u], memory[${s} + 3u])`}function tn(n,t){let e=n.resolveVar(t[0]),s=n.resolveVar(t[1]),i=`(bitcast<u32>(${e}) >> 2u)`;return[`memory[${i}] = ${s}.x;`,`memory[${i} + 1u] = ${s}.y;`,`memory[${i} + 2u] = ${s}.z;`,`memory[${i} + 3u] = ${s}.w;`]}function nn(n){let t;if(Array.isArray(n[0]))t=n[0];else if(n.length===16&&typeof n[0]=="number")t=n;else return console.warn("v128.const has invalid immediates:",n),"vec4<u32>(0u, 0u, 0u, 0u)";if(t.length!==16)return console.warn("v128.const has invalid length:",t.length),"vec4<u32>(0u, 0u, 0u, 0u)";let e=[];for(let s=0;s<4;s++){let i=0;for(let r=0;r<4;r++)i|=t[s*4+r]<<r*8;e.push(i>>>0)}return`vec4<u32>(${e.map(s=>`${s}u`).join(", ")})`}function sn(n,t,e){switch(t){case"i32x4.add":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(e[0])}) + bitcast<vec4<i32>>(${n.resolveVar(e[1])})))`;case"i32x4.sub":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(e[0])}) - bitcast<vec4<i32>>(${n.resolveVar(e[1])})))`;case"i32x4.mul":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${n.resolveVar(e[0])}) * bitcast<vec4<i32>>(${n.resolveVar(e[1])})))`;case"i32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`})`;case"i32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`}))`;case"i32x4.min_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<i32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"i32x4.min_u":return`min(${n.resolveVar(e[0])}, ${n.resolveVar(e[1])})`;case"i32x4.max_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<i32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"i32x4.max_u":return`max(${n.resolveVar(e[0])}, ${n.resolveVar(e[1])})`;default:return null}}function Ve(n){let t=[];for(let e=0;e<4;e++){let s=[];for(let i=0;i<4;i++){let r=e*4+i;i===0?s.push(`(u32(${n[r]}) & 0xFFu)`):s.push(`((u32(${n[r]}) & 0xFFu) << ${i*8}u)`)}t.push(`(${s.join(" | ")})`)}return`vec4<u32>(${t.join(", ")})`}function ye(n){let t=[];for(let e=0;e<4;e++){let s=`(u32(${n[e*2]}) & 0xFFFFu)`,i=`((u32(${n[e*2+1]}) & 0xFFFFu) << 16u)`;t.push(`(${s} | ${i})`)}return`vec4<u32>(${t.join(", ")})`}function ns(n,t,e){let s=n.resolveVar(e[0]),i=e.length>1?n.resolveVar(e[1]):null;switch(t){case"i8x16.add":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`,p=l===0?`(${i}.${c} & ${d})`:`((${i}.${c} >> ${l}u) & ${d})`;r.push(`(${f} + ${p})`)}}return Ve(r)}case"i8x16.sub":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`,p=l===0?`(${i}.${c} & ${d})`:`((${i}.${c} >> ${l}u) & ${d})`;r.push(`(${f} - ${p})`)}}return Ve(r)}case"i8x16.neg":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`;r.push(`(-(i32(${f})))`)}}return Ve(r)}case"i8x16.abs":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d="0xFFu",f=l===0?`(${s}.${c} & ${d})`:`((${s}.${c} >> ${l}u) & ${d})`;r.push(`abs(i32(${f}))`)}}return Ve(r)}default:return null}}function ss(n,t,e){let s=n.resolveVar(e[0]),i=e.length>1?n.resolveVar(e[1]):null;switch(t){case"i16x8.add":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} + ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} + ${f})`)}return ye(r)}case"i16x8.sub":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} - ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} - ${f})`)}return ye(r)}case"i16x8.mul":{if(!i)return null;let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`;r.push(`(${u} * ${l})`);let d=`(${s}.${c} >> 16u)`,f=`(${i}.${c} >> 16u)`;r.push(`(${d} * ${f})`)}return ye(r)}case"i16x8.neg":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`;r.push(`(-(i32(${u})))`);let l=`(${s}.${c} >> 16u)`;r.push(`(-(i32(${l})))`)}return ye(r)}case"i16x8.abs":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`;r.push(`abs(i32(${u}))`);let l=`(${s}.${c} >> 16u)`;r.push(`abs(i32(${l}))`)}return ye(r)}default:return null}}function is(n,t,e){let s=n.resolveVar(e[0]),i=n.resolveVar(e[1]);switch(t){case"i8x16.eq":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=[];for(let l=0;l<4;l++){let d=l*8,f="0xFFu",p=d===0?`(${s}.${c} & ${f})`:`((${s}.${c} >> ${d}u) & ${f})`,g=d===0?`(${i}.${c} & ${f})`:`((${i}.${c} >> ${d}u) & ${f})`,x=`select(0u, 0xFFu, ${p} == ${g})`;l===0?u.push(x):u.push(`(${x} << ${d}u)`)}r.push(`(${u.join(" | ")})`)}return`vec4<u32>(${r.join(", ")})`}default:return null}}function rs(n,t,e){let s=n.resolveVar(e[0]),i=n.resolveVar(e[1]);switch(t){case"i16x8.eq":{let r=[];for(let o=0;o<4;o++){let c=["x","y","z","w"][o],u=`(${s}.${c} & 0xFFFFu)`,l=`(${i}.${c} & 0xFFFFu)`,d=`select(0u, 0xFFFFu, ${u} == ${l})`,f=`(${s}.${c} >> 16u)`,p=`(${i}.${c} >> 16u)`,g=`select(0u, 0xFFFFu, ${f} == ${p})`;r.push(`(${d} | (${g} << 16u))`)}return`vec4<u32>(${r.join(", ")})`}default:return null}}function rn(n,t,e){switch(t){case"v128.and":return`(${n.resolveVar(e[0])} & ${n.resolveVar(e[1])})`;case"v128.or":return`(${n.resolveVar(e[0])} | ${n.resolveVar(e[1])})`;case"v128.xor":return`(${n.resolveVar(e[0])} ^ ${n.resolveVar(e[1])})`;case"v128.not":return`(~${n.resolveVar(e[0])})`;case"v128.andnot":return`(${n.resolveVar(e[0])} & ~${n.resolveVar(e[1])})`;case"v128.bitselect":{let s=n.resolveVar(e[0]),i=n.resolveVar(e[1]),r=n.resolveVar(e[2]);return`((${s} & ${r}) | (${i} & ~${r}))`}default:return null}}function on(n,t,e){let s=(i,r)=>{let o=r?`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`:n.resolveVar(e[0]),c=r?`bitcast<vec4<i32>>(${n.resolveVar(e[1])})`:n.resolveVar(e[1]);return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${o} ${i} ${c}))`};switch(t){case"i32x4.eq":return s("==",!0);case"i32x4.ne":return s("!=",!0);case"i32x4.lt_s":return s("<",!0);case"i32x4.lt_u":return s("<",!1);case"i32x4.gt_s":return s(">",!0);case"i32x4.gt_u":return s(">",!1);case"i32x4.le_s":return s("<=",!0);case"i32x4.le_u":return s("<=",!1);case"i32x4.ge_s":return s(">=",!0);case"i32x4.ge_u":return s(">=",!1);case"i64x2.eq":case"i64x2.ne":case"i64x2.lt_s":case"i64x2.gt_s":case"i64x2.le_s":case"i64x2.ge_s":return s("==",!0);case"f32x4.eq":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} == ${r}))`}case"f32x4.ne":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} != ${r}))`}case"f32x4.lt":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} < ${r}))`}case"f32x4.gt":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} > ${r}))`}case"f32x4.le":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} <= ${r}))`}case"f32x4.ge":{let i=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,r=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} >= ${r}))`}case"f64x2.eq":case"f64x2.ne":case"f64x2.lt":case"f64x2.gt":case"f64x2.le":case"f64x2.ge":{let i=`vec2<f32>(bitcast<f32>(${n.resolveVar(e[0])}.x), bitcast<f32>(${n.resolveVar(e[0])}.z))`,r=`vec2<f32>(bitcast<f32>(${n.resolveVar(e[1])}.x), bitcast<f32>(${n.resolveVar(e[1])}.z))`,c={"f64x2.eq":"==","f64x2.ne":"!=","f64x2.lt":"<","f64x2.gt":">","f64x2.le":"<=","f64x2.ge":">="}[t],u=`select(vec2<i32>(0), vec2<i32>(-1), ${i} ${c} ${r})`;return`vec4<u32>(bitcast<u32>(${u}.x), bitcast<u32>(${u}.x), bitcast<u32>(${u}.y), bitcast<u32>(${u}.y))`}default:return null}}function os(n,t,e){switch(t){case"f32x4.add":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(${s} + ${i})`}case"f32x4.sub":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(${s} - ${i})`}case"f32x4.mul":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(${s} * ${i})`}case"f32x4.div":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(${s} / ${i})`}case"f32x4.min":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.max":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.pmin":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.pmax":{let s=`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`,i=`bitcast<vec4<f32>>(${n.resolveVar(e[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`}))`;case"f32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`})`;case"f32x4.sqrt":return`bitcast<vec4<u32>>(sqrt(${`bitcast<vec4<f32>>(${n.resolveVar(e[0])})`}))`;case"f32x4.convert_i32x4_s":return`bitcast<vec4<u32>>(vec4<f32>(${`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`}))`;case"f32x4.convert_i32x4_u":return`bitcast<vec4<u32>>(vec4<f32>(${n.resolveVar(e[0])}))`;default:return null}}function as(n,t,e){switch(t){case"f64x2.add":case"f64x2.sub":case"f64x2.mul":case"f64x2.div":case"f64x2.min":case"f64x2.max":case"f64x2.pmin":case"f64x2.pmax":{let s=`vec2<f32>(bitcast<f32>(${n.resolveVar(e[0])}.x), bitcast<f32>(${n.resolveVar(e[0])}.z))`,i=`vec2<f32>(bitcast<f32>(${n.resolveVar(e[1])}.x), bitcast<f32>(${n.resolveVar(e[1])}.z))`,o={"f64x2.add":"+","f64x2.sub":"-","f64x2.mul":"*","f64x2.div":"/","f64x2.min":"min","f64x2.max":"max","f64x2.pmin":"min","f64x2.pmax":"max"}[t],c;return o==="min"||o==="max"?c=`${o}(${s}, ${i})`:c=`(${s} ${o} ${i})`,`vec4<u32>(bitcast<u32>(${c}.x), 0u, bitcast<u32>(${c}.y), 0u)`}case"f64x2.abs":case"f64x2.neg":case"f64x2.sqrt":{let s=`vec2<f32>(bitcast<f32>(${n.resolveVar(e[0])}.x), bitcast<f32>(${n.resolveVar(e[0])}.z))`,r={"f64x2.abs":"abs","f64x2.neg":"-","f64x2.sqrt":"sqrt"}[t],o;return r==="-"?o=`(-${s})`:o=`${r}(${s})`,`vec4<u32>(bitcast<u32>(${o}.x), 0u, bitcast<u32>(${o}.y), 0u)`}default:return null}}function an(n,t,e){switch(t){case"i32x4.shl":{let s=`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`,r=`vec4<u32>(${`u32(${n.resolveVar(e[1])})`})`;return`bitcast<vec4<u32>>(${s} << ${r})`}case"i32x4.shr_s":{let s=`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`,r=`vec4<u32>(${`u32(${n.resolveVar(e[1])})`})`;return`bitcast<vec4<u32>>(${s} >> ${r})`}case"i32x4.shr_u":{let s=n.resolveVar(e[0]),r=`vec4<u32>(${`u32(${n.resolveVar(e[1])})`})`;return`bitcast<vec4<u32>>(${s} >> ${r})`}case"i8x16.shl":case"i8x16.shr_s":case"i8x16.shr_u":case"i16x8.shl":case"i16x8.shr_s":case"i16x8.shr_u":case"i64x2.shl":case"i64x2.shr_s":case"i64x2.shr_u":return n.resolveVar(e[0]);default:return null}}function cn(n,t,e,s){switch(t){case"i8x16.extract_lane_s":case"i8x16.extract_lane_u":{let i=s[0],o=["x","y","z","w"][Math.floor(i/4)%4],c=i%4*8,u=`((${n.resolveVar(e[0])}.${o} >> ${c}u) & 0xFFu)`;return t.endsWith("_u")?`i32(${u})`:`(bitcast<i32>(${u} << 24u) >> 24)`}case"i16x8.extract_lane_s":case"i16x8.extract_lane_u":{let i=s[0],o=["x","y","z","w"][Math.floor(i/2)%4],c=i%2*16,u=`((${n.resolveVar(e[0])}.${o} >> ${c}u) & 0xFFFFu)`;return t.endsWith("_u")?`i32(${u})`:`(bitcast<i32>(${u} << 16u) >> 16)`}case"i32x4.extract_lane":{let i=s[0],r=["x","y","z","w"];return`bitcast<i32>(${n.resolveVar(e[0])}.${r[i]})`}case"i64x2.extract_lane":return s[0]===0?`bitcast<i64>(vec2<u32>(${n.resolveVar(e[0])}.x, ${n.resolveVar(e[0])}.y))`:`bitcast<i64>(vec2<u32>(${n.resolveVar(e[0])}.z, ${n.resolveVar(e[0])}.w))`;case"f32x4.extract_lane":{let i=s[0],r=["x","y","z","w"];return`bitcast<f32>(${n.resolveVar(e[0])}.${r[i]})`}case"f64x2.extract_lane":return s[0]===0?`bitcast<f32>(${n.resolveVar(e[0])}.x)`:`bitcast<f32>(${n.resolveVar(e[0])}.z)`;default:return null}}function un(n,t,e,s){switch(t){case"i8x16.replace_lane":case"i16x8.replace_lane":{let i=s[0]%4,r=n.resolveVar(e[0]),o=`bitcast<u32>(${n.resolveVar(e[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"i32x4.replace_lane":{let i=s[0],r=n.resolveVar(e[0]),o=`bitcast<u32>(${n.resolveVar(e[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"i64x2.replace_lane":{let i=s[0],r=n.resolveVar(e[0]),o=`bitcast<vec2<u32>>(${n.resolveVar(e[1])})`;return i===0?`vec4<u32>(${o}.x, ${o}.y, ${r}.z, ${r}.w)`:`vec4<u32>(${r}.x, ${r}.y, ${o}.x, ${o}.y)`}case"f32x4.replace_lane":{let i=s[0],r=n.resolveVar(e[0]),o=`bitcast<u32>(${n.resolveVar(e[1])})`;return`vec4<u32>(${["x","y","z","w"].map((l,d)=>d===i?o:`${r}.${l}`).join(", ")})`}case"f64x2.replace_lane":{let i=s[0],r=n.resolveVar(e[0]),o=`bitcast<u32>(${n.resolveVar(e[1])})`;return i===0?`vec4<u32>(${o}, 0u, ${r}.z, ${r}.w)`:`vec4<u32>(${r}.x, ${r}.y, ${o}, 0u)`}default:return null}}function ln(n,t,e){switch(t){case"i32x4.splat":{let s=`bitcast<u32>(${n.resolveVar(e[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i16x8.splat":case"i8x16.splat":{let s=`bitcast<u32>(${n.resolveVar(e[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i64x2.splat":{let s=`bitcast<vec2<u32>>(${n.resolveVar(e[0])})`;return`vec4<u32>(${s}.x, ${s}.y, ${s}.x, ${s}.y)`}case"f32x4.splat":{let s=`bitcast<u32>(${n.resolveVar(e[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"f64x2.splat":{let s=`bitcast<u32>(${n.resolveVar(e[0])})`;return`vec4<u32>(${s}, 0u, ${s}, 0u)`}default:return null}}function dn(n,t,e){switch(t){case"v128.any_true":return`select(0i, 1i, any(${n.resolveVar(e[0])} != vec4<u32>(0u)))`;case"i8x16.all_true":{let s=n.resolveVar(e[0]),i=[];for(let r=0;r<4;r++){let o=["x","y","z","w"][r];for(let c=0;c<4;c++){let u=c===0?`(${s}.${o} & 0xFFu)`:`((${s}.${o} >> ${c*8}u) & 0xFFu)`;i.push(`(${u} != 0u)`)}}return`select(0i, 1i, ${i.join(" && ")})`}case"i16x8.all_true":{let s=n.resolveVar(e[0]),i=[];for(let r=0;r<4;r++){let o=["x","y","z","w"][r];i.push(`((${s}.${o} & 0xFFFFu) != 0u)`),i.push(`((${s}.${o} >> 16u) != 0u)`)}return`select(0i, 1i, ${i.join(" && ")})`}case"i32x4.all_true":case"i64x2.all_true":return`select(0i, 1i, all(${`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`} != vec4<i32>(0)))`;case"i8x16.bitmask":{let s=n.resolveVar(e[0]),i=[],r=0;for(let o=0;o<4;o++){let c=["x","y","z","w"][o];for(let u=0;u<4;u++){let l=u*8,d=`(((${s}.${c} >> ${l}u) & 0x80u) >> 7u)`;i.push(`(${d} << ${r}u)`),r++}}return`i32(${i.join(" | ")})`}case"i16x8.bitmask":{let s=n.resolveVar(e[0]),i=[],r=0;for(let o=0;o<4;o++){let c=["x","y","z","w"][o];i.push(`(((${s}.${c} & 0x8000u) >> 15u) << ${r}u)`),r++,i.push(`(((((${s}.${c} >> 16u) & 0x8000u) >> 15u) << ${r}u))`),r++}return`i32(${i.join(" | ")})`}case"i32x4.bitmask":case"i64x2.bitmask":{let s=`bitcast<vec4<i32>>(${n.resolveVar(e[0])})`;return`((select(0i, 1i, ${s}.x < 0) << 0) | (select(0i, 2i, ${s}.y < 0) << 0) | (select(0i, 4i, ${s}.z < 0) << 0) | (select(0i, 8i, ${s}.w < 0) << 0))`}default:return null}}function fn(n,t,e,s){let i=sn(n,t,e);return i!==null||(i=ns(n,t,e),i!==null)||(i=ss(n,t,e),i!==null)||(i=is(n,t,e),i!==null)||(i=rs(n,t,e),i!==null)||(i=os(n,t,e),i!==null)||(i=as(n,t,e),i!==null)||(i=rn(n,t,e),i!==null)||(i=on(n,t,e),i!==null)||(i=an(n,t,e),i!==null)||s&&(i=cn(n,t,e,s),i!==null||(i=un(n,t,e,s),i!==null)||(i=cs(n,t,e,s),i!==null))||(i=ln(n,t,e),i!==null)||(i=dn(n,t,e),i!==null)?i:null}function cs(n,t,e,s){switch(t){case"i8x16.shuffle":return n.resolveVar(e[0]);case"i8x16.swizzle":return n.resolveVar(e[0]);default:return null}}function at(n,t,e,s,i){let r=Tt(n,t,e,s,i);if(r!==null)return{expression:r,handled:!0};if(r=Nt(n,t,e),r!==null)return{expression:r,handled:!0};if(r=Ot(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=Pt(n,t,e),r!==null)return{expression:r,handled:!0};if(r=Lt(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=zt(n,t,e),r!==null)return{expression:r,handled:!0};if(r=Ut(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=Wt(n,t,e),r!==null)return{expression:r,handled:!0};if(r=Ht(n,t,e),r!==null)return{expression:r,handled:!0};if(t==="wgsl.extract_f32"&&s&&s.length>0){let c=["x","y","z","w"],u=s[0];return{expression:`${n.resolveVar(e[0])}.${c[u]}`,handled:!0}}if(r=qt(n,t,e),r!==null)return{expression:r,handled:!0};let o=Gt(n,t,e);if(o!==null)return{statements:[o],handled:!0};if(r=fn(n,t,e,s),r!==null)return{expression:r,handled:!0};if(t==="v128.load")return{expression:en(n,e),handled:!0};if(t==="v128.const")return{expression:nn(s),handled:!0};if(t==="v128.store")return{statements:tn(n,e),handled:!0};if(t==="local.get"){let c=s[0],u=n.currentFunc?.params.length||0,l=n.currentFunc?.immutableParams||new Set;return c<u&&l.has(c)?{expression:`p${c}`,handled:!0}:{expression:jt(s,n.parallelLoopLocalIndex),handled:!0}}if(t==="global.get")return{expression:Zt(s),handled:!0};if(t==="call")return{expression:Qt(n,e,s),handled:!0};if(t==="select")return{expression:Kt(n,e,i),handled:!0};if(t==="return"){let c=Jt(n,e);if(c!==null)return{statements:[c],handled:!0}}return{handled:!1}}function pn(n,t,e,s,i){let r=Qe(n,t,e,s,i);if(r!==null)return{expression:r,handled:!0};if(r=Ke(n,t,e),r!==null)return{expression:r,handled:!0};if(r=Je(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=et(n,t,e),r!==null)return{expression:r,handled:!0};if(r=tt(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=nt(n,t,e),r!==null)return{expression:r,handled:!0};if(r=st(n,t,e,s),r!==null)return{expression:r,handled:!0};if(r=it(n,t,e),r!==null)return{expression:r,handled:!0};if(r=rt(n,t,e),r!==null)return{expression:r,handled:!0};let o=at(n,t,e,s,i);return o.handled&&o.expression!==void 0?{expression:{code:o.expression,precedence:h},handled:!0}:o.handled&&o.statements!==void 0?{statements:o.statements,handled:!0}:{handled:!1}}var ls="0.3.2",ds="2026-02-27";function mn(n){let t=n.replace(/^\$/,"");return t=t.replace(/[^a-zA-Z0-9_]/g,"_"),/^[0-9]/.test(t)&&(t=`_${t}`),t.length===0&&(t="_unnamed"),t}function co(n){let t=n.functions.map(s=>ps(s,n));for(let s of t)Le(s);let e=n.globals;return{types:n.types,functions:t,globals:e,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports,startFunctionIndex:n.startFunctionIndex}}function hn(n){let t="select(0i, 1i, ";if(!n.startsWith(t)||!n.endsWith(")"))return null;let e=n.slice(t.length,-1),s=0;for(let i of e)if(i==="("?s++:i===")"&&s--,s<0)return null;return s!==0?null:e}function fo(n,t={},e,s){return new ut(n,t,e,s).generate()}var ut=class{module;options;indent=0;output=[];predeclaredVars=new Set;emittedVars=new Set;loopDepth=0;currentFunc=null;usingUnifiedReturn=!1;sourceMapper=null;booleanVarExpressions=new Map;parallelLoopLocalIndex=void 0;inParallelLoopDirect=!1;dispatchInfo;imports;types;mathExtension;functionNameMap=new Map;constructor(t,e,s,i){this.module=t,this.options=e,this.dispatchInfo=i||Ie(),this.imports=t.imports,this.types=t.types,this.mathExtension=e.mathExtension,this.buildFunctionNameMap();let r=e.stripComments||e.releaseMode;e.sourceMapping&&s&&!r&&(this.sourceMapper=Et(s,e.sourceMapping))}buildFunctionNameMap(){let t=this.module.exports.some(e=>e.kind==="func"&&e.name==="main");for(let e of this.module.functions)this.functionNameMap.set(e.index,e.name?mn(e.name):`func_${e.index}`);for(let e of this.module.exports)if(e.kind==="func"){let s=mn(e.name);if(s==="main"&&t)continue;this.functionNameMap.set(e.index,s)}}get inlineMemoryOps(){return this.options.inlineMemoryOps||!1}hasF32MemoryOps(){for(let t of this.module.functions)if(this.statementHasOpcode(t.body,"wgsl.load_f32")||this.statementHasOpcode(t.body,"wgsl.store_f32"))return!0;return!1}statementHasOpcode(t,e){switch(t.kind){case"simple":return t.instructions.some(s=>s.opcode===e);case"block":return t.children.some(s=>this.statementHasOpcode(s,e));case"loop":return this.statementHasOpcode(t.body,e);case"if":return this.statementHasOpcode(t.thenBranch,e)||(t.elseBranch?this.statementHasOpcode(t.elseBranch,e):!1);case"parallel_loop":return this.statementHasOpcode(t.body,e)||(t.epilogue?this.statementHasOpcode(t.epilogue,e):!1);default:return!1}}resolveVar(t){return this.resolveVarExpr(t).code}resolveVarExpr(t){if(this.currentFunc?.inlinedExpressionMap?.has(t)){let e=this.currentFunc.inlinedExpressionMap.get(t),s=pn(this,e.opcode,e.args||[],e.immediates,e.id);if(s.expression)return s.expression}return{code:`v${t}`,precedence:h}}generate(){if(this.emit("// Gasm Compiler Generated WGSL"),this.emit(`// Compiler Version: ${ls}`),this.emit(`// Build Date: ${ds}`),this.emit(`// Generated: ${new Date().toISOString()}`),this.options.compilerMetadata&&this.emit(`// Metadata: ${this.options.compilerMetadata}`),this.sourceMapper){let e=this.sourceMapper.generateHeaderComment();e&&this.emit(e)}this.emit(""),this.module.memories.length>0&&(this.emit("@group(0) @binding(0) var<storage, read_write> memory: array<u32>;"),this.emit(""),this.options.inlineMemoryOps||(this.emit("fn wgsl_load_i32(idx: u32) -> i32 { return bitcast<i32>(memory[idx]); }"),this.emit("fn wgsl_store_i32(idx: u32, val: i32) { memory[idx] = bitcast<u32>(val); }"),this.hasF32MemoryOps()&&(this.emit("fn wgsl_load_f32(idx: u32) -> f32 { return bitcast<f32>(memory[idx]); }"),this.emit("fn wgsl_store_f32(idx: u32, val: f32) { memory[idx] = bitcast<u32>(val); }"))),this.emit("fn wgsl_buffer_length() -> u32 { return arrayLength(&memory); }"),this.emit(""));for(let e of this.module.globals){let s=Y(e.type);if(e.kind==="import")e.module==="gasm"?this.emit(`var<private> global_${e.index}: ${s}; // gasm.${e.name}`):this.emit(`var<private> global_${e.index}: ${s}; // import ${e.module}.${e.name}`);else{let i="";if(e.initValue!==void 0){if(s==="i32"||s==="i64")i=` = ${e.initValue}i`;else if(s==="f32"){let r=e.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}f`}else if(s==="f64"){let r=e.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}`}}this.emit(`var<private> global_${e.index}: ${s}${i};`)}}this.dispatchInfo.isParallelized&&this.emit("var<private> _wgpu_global_idx: u32 = 0u;"),this.emit("");for(let e of this.module.functions)this.emitFunction(e),this.emit("");let t=this.module.exports.find(e=>e.kind==="func"&&e.name==="main");if(t){let e=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeX:this.options.workgroupSize?.[0]||1,s=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeY:this.options.workgroupSize?.[1]||1,i=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeZ:this.options.workgroupSize?.[2]||1;this.emit(`@compute @workgroup_size(${e}, ${s}, ${i})`),this.emit("fn main(@builtin(global_invocation_id) global_id: vec3<u32>, @builtin(local_invocation_id) local_id: vec3<u32>, @builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(num_workgroups) num_workgroups: vec3<u32>) {"),this.pushIndent(),this.dispatchInfo.isParallelized&&this.emit("_wgpu_global_idx = global_id.x;");for(let o of this.module.globals)if(o.kind==="import"&&o.module==="gasm"){let c=o.name.endsWith("_x")?".x":o.name.endsWith("_y")?".y":o.name.endsWith("_z")?".z":"";o.name.startsWith("global_invocation_id")&&c?this.emit(`global_${o.index} = bitcast<i32>(global_id${c});`):o.name.startsWith("local_invocation_id")&&c?this.emit(`global_${o.index} = bitcast<i32>(local_id${c});`):o.name.startsWith("workgroup_id")&&c?this.emit(`global_${o.index} = bitcast<i32>(workgroup_id${c});`):o.name.startsWith("num_workgroups")&&c&&this.emit(`global_${o.index} = bitcast<i32>(num_workgroups${c});`)}let r=this.functionNameMap.get(t.index)??`func_${t.index}`;this.emit(`${r}();`),this.popIndent(),this.emit("}")}return this.output.join(`
2
- `)}emitFunction(t){this.currentFunc=t,this.predeclaredVars=new Set,this.emittedVars=new Set;let e=this.functionNameMap.get(t.index)??t.name??`func_${t.index}`,s=t.params.map((d,f)=>`p${f}: ${Y(d)}`).join(", "),i=t.results.length>0?` -> ${Y(t.results[0])}`:"";if(this.sourceMapper){let d=this.module.exports.find(p=>p.kind==="func"&&p.index===t.index),f=this.sourceMapper.commentForFunction(t.index,d?.name);f&&this.emit(f)}if(this.emit(`fn ${e}(${s})${i} {`),this.pushIndent(),this.usingUnifiedReturn=fs(t.body),this.usingUnifiedReturn&&(this.emit("var _has_returned_internal: bool = false;"),t.results.length>0)){let d=Y(t.results[0]),f=this.getDefaultValue(t.results[0]);this.emit(`var _return_value_internal: ${d} = ${f};`)}let r=t.params.length,o=t.immutableParams||new Set,c=Ze(t.body),u=Xe(t.body);for(let d=0;d<r;d++){if(o.has(d)||!c.has(d))continue;let p=(u.get(d)||0)===0?"let":"var";this.emit(`${p} local_${d} = p${d};`)}if(t.locals)for(let d=0;d<t.locals.length;d++){let f=r+d;if(!c.has(f))continue;let p=t.locals[d];this.emit(`var local_${f}: ${Y(p)};`)}else this.emit("// Warning: locals type info missing");let l=Z(t.body);if(X(t.body,l,this.predeclaredVars),this.predeclaredVars.size>0)for(let d of this.predeclaredVars){if(t.inlinedExpressionMap?.has(d))continue;let f=t.vars.get(d),p=f?.emitAsU32?"u32":f?Y(f.type):"i32";this.emit(`var v${d}: ${p};`)}if(this.emitStatementFlattened(t.body),t.results.length>0&&!this.endsWithReturn(t.body)){let d=this.getDefaultValue(t.results[0]);this.emit(`return ${d};`)}this.popIndent(),this.emit("}"),this.currentFunc=null}endsWithReturn(t){return _e(t)}getDefaultValue(t){return Ge(t)}isEmptyStatement(t){return $e(t)}hasExplicitTerminator(t,e=!1){return he(t,e)}collectDefinedVars(t){return H(t)}collectUsedVars(t){return Z(t)}analyzeVarsForPredeclaration(t,e=new Set){X(t,e,this.predeclaredVars)}ensureI32(t){return F(this,t)}ensureF32(t){return k(this,t)}generateLocalAssignment(t,e){return je(this,t,e)}emitStatementFlattened(t,e=!0){if(t.kind==="block"&&t.children.length===1&&!t.label)this.emitStatementFlattened(t.children[0],e);else if(t.kind==="block"&&!t.label)for(let s=0;s<t.children.length;s++){let i=t.children[s],r=s===t.children.length-1;if(this.emitStatement(i,r&&e),this.hasExplicitTerminator(i,!1))break}else this.emitStatement(t,e)}negateComparison(t){let e=/^(.+?)\s*(<=|>=|<|>|==|!=)\s*(.+)$/,s=t.match(e);if(!s)return null;let[,i,r,o]=s,u={"<":">=","<=":">",">":"<=",">=":"<","==":"!=","!=":"=="}[r];return u?`${i} ${u} ${o}`:null}emitStatement(t,e=!0){switch(t.kind){case"block":let i=t.children.length===1&&!t.label?t.children[0]:null;if(i&&(i.kind==="block"||i.kind==="loop"||i.kind==="if"||i.kind==="simple"))this.emitStatement(i,e);else{if(this.sourceMapper&&t.label){let c=this.sourceMapper.commentForStatement(t,this.currentFunc?.index??0);c&&this.emit(c)}this.emit("{"),this.pushIndent();for(let c=0;c<t.children.length;c++){let u=t.children[c],l=c===t.children.length-1;if(this.emitStatement(u,l),this.hasExplicitTerminator(u,!1))break}if(this.popIndent(),this.emit("}"),this.sourceMapper&&t.label){let c=this.sourceMapper.commentForEndBlock(t.label);c&&this.emit(c)}}break;case"loop":if(this.sourceMapper){let c=this.sourceMapper.commentForStatement(t,this.currentFunc?.index??0);c&&this.emit(c)}t.label,this.emit("loop {"),this.pushIndent(),this.loopDepth++;let o=this.inParallelLoopDirect;if(this.inParallelLoopDirect=!1,this.emitStatementFlattened(t.body,!0),this.inParallelLoopDirect=o,this.loopDepth--,this.popIndent(),this.emit("}"),this.sourceMapper&&t.label){let c=this.sourceMapper.commentForEndBlock(t.label);c&&this.emit(c)}this.usingUnifiedReturn&&(this.loopDepth>0?this.emit("if (_has_returned_internal) { break; }"):this.currentFunc.results.length>0?this.emit("if (_has_returned_internal) { return _return_value_internal; }"):this.emit("if (_has_returned_internal) { return; }"));break;case"if":{let c=this.isEmptyStatement(t.thenBranch),u=!t.elseBranch||this.isEmptyStatement(t.elseBranch);if(c&&u)break;let l=this.hasExplicitTerminator(t.thenBranch,!1),d=t.elseBranch?this.hasExplicitTerminator(t.elseBranch,!1):!1,f=this.loopDepth>0||this.inParallelLoopDirect&&this.loopDepth>0,p=e&&this.loopDepth>0&&!this.inParallelLoopDirect,g=c&&!u&&t.elseBranch,x,w=this.currentFunc?.vars.get(t.condition),I=this.resolveVarExpr(t.condition);if(w?.type==="v128")x=`any(${I.code} != vec4<u32>(0u))`,g&&(x=`!${x}`);else{let b=hn(I.code),S;b||(S=this.booleanVarExpressions.get(t.condition));let v;if(b){let $=b,N=/^v(\d+) == 0i$/,L=$.match(N);if(L){let T=parseInt(L[1],10),U=this.booleanVarExpressions.get(T);U&&(v=U,v=this.negateComparison(v)||`!(${v})`)}v||(v=$)}else S&&(v=S);if(v)if(g){let $=this.negateComparison(v);$?x=$:x=`!(${v})`}else x=v;else{let $=P(I,E["!="],!1,"!=");g?x=`${$} == 0`:x=`${$} != 0`}}if(g){this.emit(`if (${x}) {`),this.pushIndent(),this.emitStatementFlattened(t.elseBranch,!0),this.popIndent(),this.emit("}");break}this.emit(`if (${x}) {`),this.pushIndent(),this.emitStatementFlattened(t.thenBranch,!0),p&&!l&&d&&this.emit("break;"),this.popIndent();let _=p&&!d&&l;t.elseBranch&&(!this.isEmptyStatement(t.elseBranch)||_)?(this.emit("} else {"),this.pushIndent(),this.emitStatementFlattened(t.elseBranch,!0),_&&this.emit("break;"),this.popIndent()):p&&l&&(this.emit("} else {"),this.pushIndent(),this.emit("break;"),this.popIndent()),this.emit("}");break}case"parallel_loop":{let c=t.loopInfo;this.emit(`// [PARALLEL] Loop parallelized: ${c.upperBound} work items`),this.parallelLoopLocalIndex=c.loopLocalIndex;let u=this.inParallelLoopDirect;this.inParallelLoopDirect=!0,this.emit(`if (_wgpu_global_idx < ${c.upperBound}u) {`),this.pushIndent(),this.emitStatementFlattened(t.body,!0),this.popIndent(),this.emit("}"),this.parallelLoopLocalIndex=void 0,this.inParallelLoopDirect=u,t.epilogue&&(this.emit("// [PARALLEL] Epilogue: runs on single invocation"),this.emit("if (_wgpu_global_idx == 0u) {"),this.pushIndent(),this.emitStatementFlattened(t.epilogue,!0),this.popIndent(),this.emit("}"));break}case"simple":for(let c of t.instructions)this.emitInstruction(c);break;case"break":this.inParallelLoopDirect&&this.loopDepth===0?this.emit("// break (parallelized - no-op, guard condition handles bounds)"):this.emit("break;");break;case"continue":this.inParallelLoopDirect&&this.loopDepth===0?this.emit("// continue (parallelized - no-op)"):this.emit("continue;");break;case"return":this.loopDepth>0&&this.usingUnifiedReturn?(t.value!==void 0&&this.emit(`_return_value_internal = v${t.value};`),this.emit("_has_returned_internal = true;"),this.emit("break;")):t.value!==void 0?this.emit(`return v${t.value};`):this.emit("return;");break}}emitInstruction(t){if(this.sourceMapper){let c=this.sourceMapper.commentForInstruction(t,this.currentFunc?.index??0);c&&this.emit(c)}if(t.args){for(let c of t.args)if(!this.currentFunc?.inlinedExpressionMap?.has(c)&&c>=0&&!this.emittedVars.has(c)&&!this.predeclaredVars.has(c)&&(console.warn(`ERROR: Instruction ${t.opcode} references undefined variable v${c}`),console.warn(` Instruction defines: v${t.id}`),console.warn(` Args: [${t.args.join(", ")}]`),console.warn(` Emitted vars so far: [${Array.from(this.emittedVars).join(", ")}]`),!this.predeclaredVars.has(c))){let u="i32",l=this.currentFunc?.vars.get(c);l&&(u=Y(l.type)),u==="f32"?this.emit(`var v${c}: f32 = 0.0f; // ERROR: Missing definition`):u==="vec4<u32>"?this.emit(`var v${c}: vec4<u32> = vec4<u32>(0u); // ERROR: Missing definition`):this.emit(`var v${c}: i32 = 0i; // ERROR: Missing definition`),this.emittedVars.add(c)}}let e=t.opcode;if(e==="return"&&this.loopDepth>0&&this.usingUnifiedReturn){if(t.args&&t.args.length>0){let c=t.args[0],u=this.resolveVar(c);this.emit(`_return_value_internal = ${u};`)}this.emit("_has_returned_internal = true;"),this.emit("break;");return}switch(e){case"global.set":{let c=t.immediates[0],u=t.args[0],l=Y(this.module.globals[c].type),f=this.currentFunc?.vars.get(u)?.type||"i32",p=Y(f),g=this.resolveVar(u);p===l?l==="f32"?this.emit(`global_${c} = f32(${g});`):this.emit(`global_${c} = ${g};`):p==="i32"&&l==="f32"||p==="f32"&&l==="i32"?this.emit(`global_${c} = bitcast<${l}>(${g});`):this.emit(`global_${c} = ${l}(${g});`);return}case"local.set":{let c=t.immediates[0],u=t.args[0],l=this.generateLocalAssignment(c,u);this.emit(`${l};`);return}case"local.tee":{let c=t.immediates[0],u=t.args[0],l=this.generateLocalAssignment(c,u);this.emit(`${l};`);break}case"drop":return;case"unreachable":this.emit("// unreachable");return;case"nop":return;case"assign":{if(t.id!==void 0&&t.args.length>0){if(!this.predeclaredVars.has(t.id)&&!this.emittedVars.has(t.id)){console.warn(`WARNING: assign instruction for v${t.id} not predeclared. This is a compiler bug.`),console.warn(" This variable should have been caught by predeclaration analysis."),console.warn(" Attempting to recover by predeclaring now (will be out of order).");let l=this.currentFunc?.vars.get(t.id),d=l?Y(l.type):"i32";this.emit(`var v${t.id}: ${d}; // EMERGENCY: Should have been predeclared`),this.predeclaredVars.add(t.id)}this.emittedVars.add(t.id);let c=`v${t.id} = `,u=ot(this,t.args,t.id);this.emit(`${c}${u};`)}return}}let i=at(this,e,t.args||[],t.immediates,t.id);if(i.handled){if(i.statements){for(let c of i.statements)this.emit(c);return}if(i.expression!==void 0){if(t.id!==void 0&&this.currentFunc?.inlinedExpressionMap?.has(t.id))return;if(t.id!==void 0&&typeof i.expression=="string"){let u=hn(i.expression);u!==null&&this.booleanVarExpressions.set(t.id,u)}let c="";if(t.id!==void 0&&(this.predeclaredVars.has(t.id)?c=`v${t.id} = `:c=`let v${t.id} = `,this.emittedVars.add(t.id)),e==="local.tee"){let u=t.args[0];this.emit(`${c}${this.resolveVar(u)};`);return}c?this.emit(`${c}${i.expression};`):i.expression&&this.emit(`${i.expression};`);return}}let r="";if(t.id!==void 0){if(this.currentFunc?.inlinedExpressionMap?.has(t.id))return;this.predeclaredVars.has(t.id)?r=`v${t.id} = `:r=`let v${t.id} = `,this.emittedVars.add(t.id)}let o=`/* unhandled: ${e} */ 0`;r?this.emit(`${r}${o};`):o&&this.emit(`${o};`)}emit(t){this.output.push(" ".repeat(this.indent)+t)}pushIndent(){this.indent++}popIndent(){this.indent--}},Y=me,ct=Pe;var fs=Ye,lt=class{module;func;ssa;currentBlockId;stack=[];controlStack=[];constructor(t,e){this.func=t,this.module=e,this.ssa={index:t.index,name:t.name,params:t.params,results:t.results,locals:t.locals.map(i=>i.type),vars:new Map,blocks:new Map,entryBlock:0,nextVarId:0,nextBlockId:0},this.currentBlockId=this.newBlock(),this.ssa.entryBlock=this.currentBlockId;let s=0;for(let i of t.params)this.ssa.vars.set(s,{id:s,type:i}),s++;for(let i of t.locals)this.ssa.vars.set(s,{id:s,type:i.type}),s++;this.ssa.nextVarId=s,this.nextVarId!==void 0&&(this.nextVarId=s)}convert(){this.controlStack.push({kind:"block",targetBlock:-1,continuationBlock:-1,stackHeight:0,unreachable:!1,labelArity:this.func.results.length});for(let t of this.func.body)this.controlStack[this.controlStack.length-1].unreachable&&t.opcode!==a.end&&t.opcode!==a.else||this.processInstruction(t);return this.ssa}processInstruction(t){let e=t.opcode;switch(e){case a.block:{let i=this.newBlock(),r=this.newBlock();this.addBranch(r),this.switchBlock(r);let o=t.immediates[0],c=ct(o),u=0,l;c&&(u=1,l=this.newVar(c)),this.controlStack.push({kind:"block",targetBlock:i,continuationBlock:i,stackHeight:this.stack.length,unreachable:!1,labelArity:u,resultVar:l,resultType:c});break}case a.loop:{let i=this.newBlock(),r=this.newBlock();this.addBranch(i),this.switchBlock(i);let o=t.immediates[0],c=ct(o),u=0,l;c&&(u=1,l=this.newVar(c)),this.controlStack.push({kind:"loop",targetBlock:i,continuationBlock:r,stackHeight:this.stack.length,unreachable:!1,labelArity:u,resultVar:l,resultType:c});break}case a.if:{let i=this.popStack(),r=this.newBlock(),o=this.newBlock(),c=this.newBlock(),u=t.immediates[0],l=ct(u),d=0,f;l&&(d=1,f=this.newVar(l)),this.addInstruction({type:"instr",opcode:"br_if",args:[i],immediates:[r]}),this.getBlock(this.currentBlockId).succs.push(r);let p=this.ssa.blocks.get(r);p&&p.preds.push(this.currentBlockId),this.addBranch(o),this.switchBlock(r),this.controlStack.push({kind:"if",targetBlock:c,continuationBlock:c,stackHeight:this.stack.length,unreachable:!1,labelArity:d,resultVar:f,resultType:l,elseBlock:o,hasElse:!1,conditionVar:i,blocktype:u});break}case a.else:{let i=this.controlStack[this.controlStack.length-1];if(!i||i.kind!=="if"){console.warn("Else without matching if");break}if(i.thenReturned=i.unreachable,i.labelArity>0&&!i.unreachable&&this.stack.length>i.stackHeight){let o=this.popStack();i.thenValue=o,i.resultVar!==void 0&&this.addInstruction({type:"instr",opcode:"assign",id:i.resultVar,args:[o],immediates:[]})}this.stack=this.stack.slice(0,i.stackHeight),i.unreachable||this.addBranch(i.targetBlock);let r=i.elseBlock;this.switchBlock(r),i.unreachable=!1,i.hasElse=!0;break}case a.end:{let i=this.controlStack.pop();if(i.targetBlock===-1||i.continuationBlock===-1){if(!this.controlStack.length&&!i.unreachable){let o=[];i.labelArity>0&&this.stack.length>0&&o.push(this.popStack()),this.addInstruction({type:"instr",opcode:"return",args:o,immediates:[]})}return}let r=i.continuationBlock;if(!i.unreachable){if(i.resultVar!==void 0){let o=this.popStack();this.addInstruction({type:"instr",opcode:"assign",id:i.resultVar,args:[o],immediates:[]})}this.addBranch(r)}if(i.kind==="if"&&!i.hasElse){let o=i.elseBlock;o!==void 0&&(this.switchBlock(o),this.addBranch(r))}this.switchBlock(r),i.resultVar!==void 0&&this.pushStack(i.resultVar);break}case a.br:{let i=t.immediates[0];if(i<this.controlStack.length){let r=this.controlStack[this.controlStack.length-1-i];if(r.targetBlock===-1){let o=[];r.labelArity>0&&this.stack.length>0&&o.push(this.popStack()),this.addInstruction({type:"instr",opcode:"return",args:o,immediates:[]})}else{if(r.resultVar!==void 0){let o=this.popStack();this.addInstruction({type:"instr",opcode:"assign",id:r.resultVar,args:[o],immediates:[]})}this.addBranch(r.targetBlock)}}this.getCurrentFrame().unreachable=!0;break}case a.br_if:{let i=t.immediates[0],r=this.popStack(),o=this.newBlock();if(i<this.controlStack.length){let c=this.controlStack[this.controlStack.length-1-i];if(c.targetBlock===-1){let u=this.newBlock();this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[u]}),this.getBlock(this.currentBlockId).succs.push(u),this.ssa.blocks.get(u).preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId),this.switchBlock(u);let l=[];c.labelArity>0&&this.stack.length>0&&l.push(this.stack[this.stack.length-1]),this.addInstruction({type:"instr",opcode:"return",args:l,immediates:[]}),this.getCurrentFrame().unreachable=!0}else if(c.resultVar!==void 0){let u=this.newBlock();this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[u]}),this.getBlock(this.currentBlockId).succs.push(u),this.ssa.blocks.get(u).preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId),this.switchBlock(u);let l=this.stack[this.stack.length-1];this.addInstruction({type:"instr",opcode:"assign",id:c.resultVar,args:[l],immediates:[]}),this.addBranch(c.targetBlock),this.getCurrentFrame().unreachable=!0}else{this.addInstruction({type:"instr",opcode:"br_if",args:[r],immediates:[c.targetBlock]}),this.getBlock(this.currentBlockId).succs.push(c.targetBlock);let u=this.ssa.blocks.get(c.targetBlock);u&&u.preds.push(this.currentBlockId),this.getBlock(this.currentBlockId).succs.push(o),this.ssa.blocks.get(o).preds.push(this.currentBlockId)}}else this.addBranch(o);this.switchBlock(o),this.getCurrentFrame().unreachable=!1;break}case a.i32_const:{let i=t.immediates[0],r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.i64_const:{let i=t.immediates[0],r=this.newVar("i64");this.addInstruction({type:"instr",id:r,opcode:"i64.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.f32_const:{let i=t.immediates[0],r=this.newVar("f32");this.addInstruction({type:"instr",id:r,opcode:"f32.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.f64_const:{let i=t.immediates[0],r=this.newVar("f64");this.addInstruction({type:"instr",id:r,opcode:"f64.const",args:[],immediates:[i]}),this.pushStack(r);break}case a.i32_add:{let i=this.popStack(),r=this.popStack(),o=this.newVar("i32");this.addInstruction({type:"instr",id:o,opcode:"i32.add",args:[r,i]}),this.pushStack(o);break}case a.local_get:{let i=t.immediates[0],r=this.getLocalType(i),o=this.newVar(r);this.addInstruction({type:"instr",id:o,opcode:"local.get",args:[],immediates:[i]}),this.pushStack(o);break}case a.local_set:{let i=t.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"local.set",args:[r],immediates:[i]});break}case a.global_get:{let i=t.immediates[0],o=this.module.globals[i].type,c=this.newVar(o);this.addInstruction({type:"instr",id:c,opcode:"global.get",args:[],immediates:[i]}),this.pushStack(c);break}case a.global_set:{let i=t.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"global.set",args:[r],immediates:[i]});break}case a.local_tee:{let i=t.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"local.set",args:[r],immediates:[i]}),this.pushStack(r);break}case a.return:{if(this.func.results.length>0){let i=this.popStack();this.addInstruction({type:"instr",opcode:"return",args:[i]})}else this.addInstruction({type:"instr",opcode:"return",args:[]});this.getCurrentFrame().unreachable=!0;break}case a.nop:break;case a.call:{let i=t.immediates[0],r,o=this.module.imports.filter(l=>l.kind==="func").length;if(i<o){let l=this.module.imports.filter(d=>d.kind==="func")[i];r=this.module.types[l.typeIndex]}else{let l=i-o;r=this.module.functions[l]}let c=[];for(let l=0;l<r.params.length;l++)c.unshift(this.popStack());let u=r.results.length>0?this.newVar(r.results[0]):void 0;this.addInstruction({type:"instr",id:u,opcode:"call",args:c,immediates:[i]}),u!==void 0&&this.pushStack(u);break}case a.i32_load:case a.f32_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:{let i=this.popStack(),r=e===a.f32_load?"f32":"i32",o=this.newVar(r);this.addInstruction({type:"instr",id:o,opcode:t.name.replace(/_/g,"."),args:[i],immediates:t.immediates}),this.pushStack(o);break}case a.i32_store:case a.f32_store:case a.i32_store8:case a.i32_store16:{let i=this.popStack(),r=this.popStack();this.addInstruction({type:"instr",opcode:t.name.replace(/_/g,"."),args:[r,i],immediates:t.immediates});break}case a.memory_size:{let i=this.newVar("i32");this.addInstruction({type:"instr",id:i,opcode:"memory.size",args:[],immediates:t.immediates}),this.pushStack(i);break}case 64768:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"v128.load",args:[i],immediates:t.immediates}),this.pushStack(r);break}case 64779:{let i=this.popStack(),r=this.popStack();this.addInstruction({type:"instr",opcode:"v128.store",args:[r,i],immediates:t.immediates});break}case 64780:{let i=this.newVar("v128");this.addInstruction({type:"instr",id:i,opcode:"v128.const",args:[],immediates:t.immediates}),this.pushStack(i);break}case 64795:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32x4.extract_lane",args:[i],immediates:t.immediates}),this.pushStack(r);break}case 64796:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.replace_lane",args:[r,i],immediates:t.immediates}),this.pushStack(o);break}case 64783:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i8x16.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64784:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i16x8.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64785:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.splat",args:[i],immediates:[]}),this.pushStack(r);break}case 64942:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.add",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64823:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.eq",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64945:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.sub",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64949:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.mul",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64950:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.min_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64952:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.max_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64928:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.abs",args:[i],immediates:[]}),this.pushStack(r);break}case 64929:{let i=this.popStack(),r=this.newVar("v128");this.addInstruction({type:"instr",id:r,opcode:"i32x4.neg",args:[i],immediates:[]}),this.pushStack(r);break}case 64846:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.and",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64848:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.or",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64849:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"v128.xor",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64850:{let i=this.popStack(),r=this.popStack(),o=this.popStack(),c=this.newVar("v128");this.addInstruction({type:"instr",id:c,opcode:"v128.bitselect",args:[o,r,i],immediates:[]}),this.pushStack(c);break}case 64939:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shl",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64940:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shr_s",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64941:{let i=this.popStack(),r=this.popStack(),o=this.newVar("v128");this.addInstruction({type:"instr",id:o,opcode:"i32x4.shr_u",args:[r,i],immediates:[]}),this.pushStack(o);break}case 64851:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"v128.any_true",args:[i],immediates:[]}),this.pushStack(r);break}case 64931:{let i=this.popStack(),r=this.newVar("i32");this.addInstruction({type:"instr",id:r,opcode:"i32x4.all_true",args:[i],immediates:[]}),this.pushStack(r);break}case a.drop:this.popStack();break;case a.select:{let i=this.popStack(),r=this.popStack(),o=this.popStack(),c=this.ssa.vars.get(o),u=c?c.type:"i32",l=this.newVar(u);this.addInstruction({type:"instr",id:l,opcode:"select",args:[r,o,i]}),this.pushStack(l);break}default:let s=qe(this.getSSAContext(),t)}}newVar(t){let e=this.ssa.nextVarId++;return this.ssa.vars.set(e,{id:e,type:t}),e}blocktypeToValueType(t){switch(t){case 127:return"i32";case 126:return"i64";case 125:return"f32";case 124:return"f64";case 123:return"v128";case 64:return null;default:return"i32"}}getLocalType(t){let e=this.func.params.length;if(t<e)return this.func.params[t];let s=t-e;return s<this.func.locals.length?this.func.locals[s].type:"i32"}newBlock(){let t=this.ssa.nextBlockId++;return this.ssa.blocks.set(t,{id:t,instructions:[],preds:[],succs:[]}),t}switchBlock(t){this.currentBlockId=t}addBranch(t){this.addInstruction({type:"instr",opcode:"br",args:[],immediates:[t]});let e=this.getBlock(t);e&&(this.getBlock(this.currentBlockId).succs.push(t),e.preds.push(this.currentBlockId))}addInstruction(t){this.getBlock(this.currentBlockId).instructions.push(t)}getBlock(t){return this.ssa.blocks.get(t)}pushStack(t){this.stack.push(t)}popStack(){return this.stack.length===0?-1:this.stack.pop()}peekStack(t=0){let e=this.stack.length-1-t;return e<0?-1:this.stack[e]}getSSAContext(){return{module:this.module,funcParams:this.func.params,funcLocals:this.func.locals.map(t=>t.type),funcResults:this.func.results,pushStack:t=>this.pushStack(t),popStack:()=>this.popStack(),peekStack:t=>this.peekStack(t??0),newVar:t=>this.newVar(t),addInstruction:t=>this.addInstruction(t)}}getCurrentFrame(){return this.controlStack[this.controlStack.length-1]}};function ps(n,t){return new lt(n,t).convert()}function z(){return{min:-1/0,max:1/0,isNonNegative:!1,knownZeroBits:0,knownOneBits:0}}function _n(n){return{min:n,max:n,isNonNegative:n>=0,knownZeroBits:~n,knownOneBits:n}}function ms(n=1/0){return{min:0,max:n,isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}function ge(n,t,e){switch(n){case"i32.and":{if(e.min===e.max){let s=e.min;return{min:0,max:s,isNonNegative:!0,knownZeroBits:~s,knownOneBits:0}}return z()}case"i32.add":return t.min===-1/0||e.min===-1/0?z():{min:t.min+e.min,max:t.max===1/0||e.max===1/0?1/0:t.max+e.max,isNonNegative:t.isNonNegative&&e.isNonNegative,knownZeroBits:0,knownOneBits:0};case"i32.sub":return t.min===-1/0||e.max===1/0?z():{min:t.max===1/0?-1/0:t.min-e.max,max:t.max===1/0||e.min===-1/0?1/0:t.max-e.min,isNonNegative:!1,knownZeroBits:0,knownOneBits:0};case"i32.mul":{if(t.min===-1/0||e.min===-1/0)return z();let s=[t.min*e.min,t.min*(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max),(t.max===1/0?Number.MAX_SAFE_INTEGER:t.max)*e.min,(t.max===1/0?Number.MAX_SAFE_INTEGER:t.max)*(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max)];return{min:Math.min(...s),max:Math.max(...s),isNonNegative:t.isNonNegative&&e.isNonNegative,knownZeroBits:0,knownOneBits:0}}case"i32.shr_u":{if(e.min===e.max&&t.max!==1/0){let s=e.min;return{min:0,max:Math.floor(t.max/Math.pow(2,s)),isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}return ms()}default:return z()}}function vo(n,t={}){let e=n.functions.map(s=>new dt(s,n,t).run());return{...n,functions:e}}var dt=class{func;module;options;usageCounts=new Map;varDefinitions=new Map;aliasMap=new Map;mutatedLocals=new Set;mutatedGlobals=new Set;valueRanges=new Map;metrics={varsBefore:0,varsAfter:0,reductionPct:0,instructionsBefore:0,instructionsAfter:0,copiesPropagated:0,expressionsInlined:0,booleansCanonized:0,deadStoresEliminated:0,blocksFlattened:0,strengthReductions:0,loopInvariantsHoisted:0,commonSubexprsEliminated:0};loops=[];dominators=new Map;changed=!1;constructor(t,e,s={}){this.func=t,this.module=e,this.options=s}run(){this.metrics.varsBefore=this.func.vars.size,this.metrics.instructionsBefore=this.countInstructions();let t=0,e=10;this.analyzeLocalMutability();do this.changed=!1,this.aliasMap.clear(),this.analyze(),this.performConstantFolding(),this.analyze(),this.analyzeValueRanges(),this.analyze(),this.performStrengthReduction(),this.analyze(),this.performCopyPropagation(),this.analyze(),this.performCSE(),this.analyze(),this.performBooleanCanonicalization(),this.performLocalLoadStoreForwarding(),this.performDeadLocalStoreElimination(),this.analyze(),this.performDCE(),this.analyze(),this.performBlockFlattening(),this.analyze(),this.performLICM(),t++;while(this.changed&&t<e);return this.analyze(),this.performInlining(),this.func.immutableParams=new Set(Array.from({length:this.func.params.length},(s,i)=>i).filter(s=>!this.mutatedLocals.has(s))),this.metrics.varsAfter=this.func.vars.size,this.metrics.instructionsAfter=this.countInstructions(),this.metrics.reductionPct=this.metrics.varsBefore>0?Math.round((1-this.metrics.varsAfter/this.metrics.varsBefore)*100):0,this.options.verbose&&this.logMetrics(),this.func}countInstructions(){let t=0;for(let e of this.func.blocks.values())t+=e.instructions.length;return t}logMetrics(){let t=this.func.name||`func_${this.func.index}`;console.log(`[Optimizer] ${t}:`),console.log(` Variables: ${this.metrics.varsBefore} \u2192 ${this.metrics.varsAfter} (${this.metrics.reductionPct}% reduction)`),console.log(` Instructions: ${this.metrics.instructionsBefore} \u2192 ${this.metrics.instructionsAfter}`),console.log(` Copies propagated: ${this.metrics.copiesPropagated}`),console.log(` Expressions inlined: ${this.metrics.expressionsInlined}`),console.log(` Common subexpressions eliminated: ${this.metrics.commonSubexprsEliminated}`),console.log(` Booleans canonized: ${this.metrics.booleansCanonized}`),console.log(` Dead stores eliminated: ${this.metrics.deadStoresEliminated}`),console.log(` Strength reductions: ${this.metrics.strengthReductions}`),console.log(` Loop invariants hoisted: ${this.metrics.loopInvariantsHoisted}`),this.func.immutableParams&&this.func.immutableParams.size>0&&console.log(` Immutable params: [${Array.from(this.func.immutableParams).join(", ")}]`)}analyzeLocalMutability(){this.mutatedLocals.clear(),this.mutatedGlobals.clear();let t=!1;for(let e of this.func.blocks.values())for(let s of e.instructions){if(s.opcode==="local.set"||s.opcode==="local.tee"){let i=s.immediates?.[0];i!==void 0&&this.mutatedLocals.add(i)}if(s.opcode==="global.set"){let i=s.immediates?.[0];i!==void 0&&this.mutatedGlobals.add(i)}(s.opcode==="call"||s.opcode==="call_indirect")&&(t=!0)}if(t&&this.module)for(let e=0;e<this.module.globals.length;e++){let s=this.module.globals[e];(s.kind!=="definition"||s.mutable)&&this.mutatedGlobals.add(e)}}analyzeValueRanges(){this.valueRanges.clear();for(let t of this.func.blocks.values())for(let e of t.instructions){if(e.id===void 0)continue;let s=e.id,i;switch(e.opcode){case"i32.const":{let r=e.immediates[0];i=_n(r);break}case"i32.and":{let r=this.resolveAlias(e.args[0]),o=this.resolveAlias(e.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=ge("i32.and",c,u);break}case"i32.add":{let r=this.resolveAlias(e.args[0]),o=this.resolveAlias(e.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=ge("i32.add",c,u);break}case"i32.sub":{let r=this.resolveAlias(e.args[0]),o=this.resolveAlias(e.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=ge("i32.sub",c,u);break}case"i32.mul":{let r=this.resolveAlias(e.args[0]),o=this.resolveAlias(e.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=ge("i32.mul",c,u);break}case"i32.shr_u":{let r=this.resolveAlias(e.args[0]),o=this.resolveAlias(e.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=ge("i32.shr_u",c,u);break}default:i=z()}this.valueRanges.set(s,i)}for(let[t,e]of this.valueRanges)if(e.isNonNegative){let s=this.func.vars.get(t);s&&(s.isNonNegative=!0)}}analyze(){this.usageCounts.clear(),this.varDefinitions.clear();for(let[e]of this.func.vars)this.usageCounts.set(e,0);let t=e=>{if(e.id!==void 0){let s=this.varDefinitions.get(e.id)||[];s.push(e),this.varDefinitions.set(e.id,s)}if(e.args){for(let s of e.args)if(s>=0){let i=this.usageCounts.get(s)||0;this.usageCounts.set(s,i+1)}}};for(let[e,s]of this.func.blocks)for(let i of s.instructions)t(i);if(this.func.inlinedExpressionMap)for(let e of this.func.inlinedExpressionMap.values())t(e)}resolveAlias(t){let e=t,s=0;for(;this.aliasMap.has(e)&&s<100;)e=this.aliasMap.get(e),s++;return e}performConstantFolding(){for(let t of this.func.blocks.values()){let e=[];for(let s=0;s<t.instructions.length;s++){let i=t.instructions[s];if(i.args&&(i.args=i.args.map(o=>this.resolveAlias(o))),this.isConst(i.opcode)){e.push(i);continue}let r=this.tryFold(i);r===null?e.push(i):typeof r=="object"?(i.id!==void 0&&(r.id=i.id),e.push(r),this.changed=!0):i.id!==void 0&&(this.aliasMap.set(i.id,r),this.changed=!0)}t.instructions=e}}performCopyPropagation(){let t=new Set;for(let[e,s]of this.varDefinitions)s.length===1&&t.add(e);for(let e of this.func.blocks.values()){let s=[];for(let i of e.instructions){if(i.opcode==="assign"&&i.args?.length===1&&i.id!==void 0&&t.has(i.id)){let r=this.resolveAlias(i.args[0]);this.aliasMap.set(i.id,r),this.metrics.copiesPropagated++,this.changed=!0;continue}if(i.args){let r=[...i.args];i.args=i.args.map(o=>this.resolveAlias(o)),r.some((o,c)=>o!==i.args[c])&&(this.changed=!0)}s.push(i)}e.instructions=s}}performCSE(){for(let t of this.func.blocks.values()){let e=new Map,s=new Set,i=new Set,r=[];for(let o of t.instructions){if(o.opcode==="local.set"||o.opcode==="local.tee"){let l=o.immediates?.[0];l!==void 0&&(s.add(l),this.invalidateDependentExpressions(e,"local.get",l)),r.push(o);continue}if(o.opcode==="global.set"){let l=o.immediates?.[0];l!==void 0&&(i.add(l),this.invalidateDependentExpressions(e,"global.get",l)),r.push(o);continue}if(!this.isPureOp(o.opcode)){r.push(o);continue}if(o.id===void 0){r.push(o);continue}if(this.isConst(o.opcode)){r.push(o);continue}if(o.opcode==="local.get"){let l=o.immediates?.[0];if(l!==void 0&&s.has(l)){r.push(o);continue}}if(o.opcode==="global.get"){let l=o.immediates?.[0];if(l!==void 0&&i.has(l)){r.push(o);continue}}let c=this.createExprSignature(o),u=e.get(c);if(u!==void 0){this.aliasMap.set(o.id,u),this.metrics.commonSubexprsEliminated++,this.changed=!0;continue}e.set(c,o.id),r.push(o)}t.instructions=r}}invalidateDependentExpressions(t,e,s){let i=`${e}::${s}`,r=[];for(let o of t.keys())o.includes(i)&&r.push(o);for(let o of r)t.delete(o)}createExprSignature(t){let e=t.args?.map(s=>this.resolveAlias(s))||[];return this.isCommutativeOp(t.opcode)&&e.sort((s,i)=>s-i),`${t.opcode}:${e.join(",")}:${JSON.stringify(t.immediates||[])}`}isCommutativeOp(t){return new Set(["i32.add","i32.mul","i32.and","i32.or","i32.xor","i64.add","i64.mul","i64.and","i64.or","i64.xor","f32.add","f32.mul","f64.add","f64.mul","i32.eq","i32.ne","i64.eq","i64.ne","f32.eq","f32.ne","f64.eq","f64.ne","i32x4.add","i32x4.mul","f32x4.add","f32x4.mul"]).has(t)}performInlining(){this.func.inlinedExpressionMap||(this.func.inlinedExpressionMap=new Map);let t=new Set;for(let[e,s]of this.usageCounts){if(this.func.inlinedExpressionMap?.has(e))continue;let i=this.varDefinitions.get(e);if(i&&i.length===1){let r=i[0];if(this.isConst(r.opcode)){this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0;continue}if(r.opcode==="local.get"){let o=r.immediates?.[0];if(o!==void 0){if(!this.mutatedLocals.has(o)){this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0;continue}if(s===1&&!this.isSafeToInlineLocalGet(e,o)||s!==1)continue}this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0;continue}if(r.opcode==="global.get"){let o=r.immediates?.[0];if(o!==void 0&&this.mutatedGlobals.has(o)){s===1&&this.isSafeToInlineGlobalGet(e,o)&&(this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0);continue}}if(s===1&&this.isPureOp(r.opcode)){this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0;continue}s!==void 0&&s>=2&&s<=3&&this.isPureOp(r.opcode)&&this.isCheapToInline(r)&&(this.func.inlinedExpressionMap.set(e,r),t.add(e),this.metrics.expressionsInlined++,this.changed=!0)}}if(t.size>0)for(let e of this.func.blocks.values()){let s=[];for(let i of e.instructions)i.id!==void 0&&t.has(i.id)||s.push(i);e.instructions=s}}isCheapToInline(t){if(!t.args||t.args.length===0)return!0;for(let e of t.args){let s=this.resolveAlias(e),i=this.varDefinitions.get(s);if(!i||i.length!==1)return!1;let r=i[0];if(!this.isConst(r.opcode))return!1}return!0}isSafeToInlineLocalGet(t,e){let s,i=-1;for(let o of this.func.blocks.values()){for(let c=0;c<o.instructions.length;c++){let u=o.instructions[c];if(u.id===t&&u.opcode==="local.get"){s=o,i=c;break}}if(s)break}if(!s||i<0)return!1;let r=s.instructions[i+1];if(r&&(r.opcode==="local.set"||r.opcode==="local.tee")&&r.immediates?.[0]===e){let o=r.args?.[0];if(o!==void 0&&this.usesVar(o,t,s,i)&&(this.usageCounts.get(t)||0)===1)return!0}for(let o=i+1;o<s.instructions.length;o++){let c=s.instructions[o];if((c.opcode==="local.set"||c.opcode==="local.tee")&&c.immediates?.[0]===e)return!1}return this.isLocalNeverWrittenInReachableBlocks(s,e)}usesVar(t,e,s,i){for(let r=i+1;r<s.instructions.length;r++){let o=s.instructions[r];if(o.id===t){if(o.args?.includes(e))return!0;for(let c of o.args||[])if(this.usesVar(c,e,s,i))return!0;return!1}}return!1}isLocalNeverWrittenInReachableBlocks(t,e){let s=new Set,i=[...t.succs||[]];for(;i.length>0;){let r=i.shift();if(s.has(r))continue;s.add(r);let o=this.func.blocks.get(r);if(o){for(let c of o.instructions)if((c.opcode==="local.set"||c.opcode==="local.tee")&&c.immediates?.[0]===e)return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSafeToInlineGlobalGet(t,e){let s,i=-1;for(let r of this.func.blocks.values()){for(let o=0;o<r.instructions.length;o++){let c=r.instructions[o];if(c.id===t&&c.opcode==="global.get"){s=r,i=o;break}}if(s)break}if(!s||i<0)return!1;for(let r=i+1;r<s.instructions.length;r++){let o=s.instructions[r];if(o.opcode==="global.set"&&o.immediates?.[0]===e||o.opcode==="call"||o.opcode==="call_indirect")return!1}return this.isGlobalNeverWrittenInReachableBlocks(s,e)}isGlobalNeverWrittenInReachableBlocks(t,e){let s=new Set,i=[...t.succs||[]];for(;i.length>0;){let r=i.shift();if(s.has(r))continue;s.add(r);let o=this.func.blocks.get(r);if(o){for(let c of o.instructions)if(c.opcode==="global.set"&&c.immediates?.[0]===e||c.opcode==="call"||c.opcode==="call_indirect")return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSimpleInlinable(t){let e=t.opcode;if(this.isConst(e))return!0;if(e.startsWith("i32.")||e.startsWith("i64.")||e.startsWith("f32.")||e.startsWith("f64."))return!(e.includes("load")||e.includes("store"));if(e==="local.get")return!0;if(e==="global.get"){let s=t.immediates?.[0];return!(s!==void 0&&this.mutatedGlobals.has(s))}return e==="select"}performBooleanCanonicalization(){for(let t of this.func.blocks.values()){let e=[];for(let s of t.instructions){if(s.opcode==="select"&&s.args?.length===3&&s.id!==void 0){let i=this.resolveAlias(s.args[0]),r=this.resolveAlias(s.args[1]),o=this.resolveAlias(s.args[2]),c=this.getSingleDef(i),u=this.getSingleDef(r);if(c&&u&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&u.opcode==="i32.const"&&u.immediates?.[0]===1){this.aliasMap.set(s.id,o),this.metrics.booleansCanonized++,this.changed=!0;continue}if(c&&u&&c.opcode==="i32.const"&&c.immediates?.[0]===1&&u.opcode==="i32.const"&&u.immediates?.[0]===0){let l={type:"instr",id:s.id,opcode:"i32.eqz",args:[o],immediates:[]};e.push(l),this.metrics.booleansCanonized++,this.changed=!0;continue}}if((s.opcode==="i32.ne"||s.opcode==="i32.eq")&&s.args?.length===2&&s.id!==void 0){let i=this.resolveAlias(s.args[0]),r=this.resolveAlias(s.args[1]),o=this.getSingleDef(i),c=this.getSingleDef(r);if(s.opcode==="i32.ne"){if(c&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&this.isDefinitelyBoolean(i)){this.aliasMap.set(s.id,i),this.metrics.booleansCanonized++,this.changed=!0;continue}if(o&&o.opcode==="i32.const"&&o.immediates?.[0]===0&&this.isDefinitelyBoolean(r)){this.aliasMap.set(s.id,r),this.metrics.booleansCanonized++,this.changed=!0;continue}}if(s.opcode==="i32.eq"&&c&&c.opcode==="i32.const"&&c.immediates?.[0]===0&&this.isDefinitelyBoolean(i)){let u={type:"instr",id:s.id,opcode:"i32.eqz",args:[i],immediates:[]};e.push(u),this.metrics.booleansCanonized++,this.changed=!0;continue}}e.push(s)}t.instructions=e}}getSingleDef(t){let e=this.varDefinitions.get(t);return e&&e.length===1?e[0]:null}isDefinitelyBoolean(t){let e=this.getSingleDef(t);if(!e)return!1;let s=e.opcode;if(s.includes(".eq")||s.includes(".ne")||s.includes(".lt")||s.includes(".gt")||s.includes(".le")||s.includes(".ge")||s==="i32.eqz"||s==="i64.eqz")return!0;if(s==="select"&&e.args?.length===3){let i=this.getSingleDef(this.resolveAlias(e.args[0])),r=this.getSingleDef(this.resolveAlias(e.args[1]));if(i&&r&&i.opcode==="i32.const"&&r.opcode==="i32.const"){let o=i.immediates?.[0],c=r.immediates?.[0];if(o===0&&c===1||o===1&&c===0)return!0}}return!1}performStrengthReduction(){let t=r=>r>0&&(r&r-1)===0,e=r=>{let o=0;for(;r>1;)r>>=1,o++;return o},s=r=>{let o=this.func.nextVarId++;return this.func.vars.set(o,{id:o,type:"i32"}),{varId:o,instr:{type:"instr",id:o,opcode:"i32.const",args:[],immediates:[r]}}},i=(r,o,c)=>{let u=this.func.nextVarId++;return this.func.vars.set(u,{id:u,type:"i32"}),{varId:u,instr:{type:"instr",id:u,opcode:r,args:[o,c],immediates:[]}}};for(let r of this.func.blocks.values()){let o=[];for(let c of r.instructions){let u=c.opcode;if(!c.args||c.args.length<2||c.id===void 0){o.push(c);continue}let l=this.resolveAlias(c.args[0]),d=this.resolveAlias(c.args[1]),f=this.getSingleDef(d),g=f&&f.opcode==="i32.const"?f.immediates[0]:null;if(u==="i32.div_u"&&g!==null&&t(g)){let I=e(g),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[I]};o.push(b);let S={type:"instr",id:c.id,opcode:"i32.shr_u",args:[l,_],immediates:[]};o.push(S),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.div_s"&&g!==null&&t(g)){let I=e(g),_=g-1,b=s(31);o.push(b.instr);let S=i("i32.shr_s",l,b.varId);o.push(S.instr);let v=s(_);o.push(v.instr);let $=i("i32.and",S.varId,v.varId);o.push($.instr);let N=i("i32.add",l,$.varId);o.push(N.instr);let L=s(I);o.push(L.instr);let T={type:"instr",id:c.id,opcode:"i32.shr_s",args:[N.varId,L.varId],immediates:[]};o.push(T),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_u"&&g!==null&&t(g)){let I=g-1,_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[I]};o.push(b);let S={type:"instr",id:c.id,opcode:"i32.and",args:[l,_],immediates:[]};o.push(S),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_s"&&g!==null&&t(g)){let I=e(g),_=g-1;if(this.valueRanges.get(l)?.isNonNegative===!0){let V=this.func.nextVarId++;this.func.vars.set(V,{id:V,type:"i32"});let B={type:"instr",id:V,opcode:"i32.const",args:[],immediates:[_]};o.push(B);let A={type:"instr",id:c.id,opcode:"i32.and",args:[l,V],immediates:[]};o.push(A),this.metrics.strengthReductions++,this.changed=!0;continue}let v=s(31);o.push(v.instr);let $=i("i32.shr_s",l,v.varId);o.push($.instr);let N=s(_);o.push(N.instr);let L=i("i32.and",$.varId,N.varId);o.push(L.instr);let T=i("i32.add",l,L.varId);o.push(T.instr);let U=s(I);o.push(U.instr);let Q=i("i32.shr_s",T.varId,U.varId);o.push(Q.instr);let K=s(I);o.push(K.instr);let ee=i("i32.shl",Q.varId,K.varId);o.push(ee.instr);let xe={type:"instr",id:c.id,opcode:"i32.sub",args:[l,ee.varId],immediates:[]};o.push(xe),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.mul"&&g!==null&&t(g)){let I=e(g),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[I]};o.push(b);let S={type:"instr",id:c.id,opcode:"i32.shl",args:[l,_],immediates:[]};o.push(S),this.metrics.strengthReductions++,this.changed=!0;continue}let x=this.getSingleDef(l),w=x&&x.opcode==="i32.const"?x.immediates[0]:null;if(u==="i32.mul"&&w!==null&&t(w)){let I=e(w),_=this.func.nextVarId++;this.func.vars.set(_,{id:_,type:"i32"});let b={type:"instr",id:_,opcode:"i32.const",args:[],immediates:[I]};o.push(b);let S={type:"instr",id:c.id,opcode:"i32.shl",args:[d,_],immediates:[]};o.push(S),this.metrics.strengthReductions++,this.changed=!0;continue}o.push(c)}r.instructions=o}}performDCE(){let t=new Set,e=[],s=i=>{let r=this.resolveAlias(i);r>=0&&!t.has(r)&&(t.add(r),e.push(r))};for(let i of this.func.blocks.values())for(let r of i.instructions)this.hasSideEffects(r)&&r.args&&r.args.forEach(s);for(;e.length>0;){let i=e.pop(),r=this.varDefinitions.get(i);if(r)for(let o of r)o.args&&o.args.forEach(s)}for(let i of this.func.blocks.values()){let r=[];for(let o of i.instructions)this.hasSideEffects(o)?(o.args&&(o.args=o.args.map(c=>this.resolveAlias(c))),r.push(o)):o.id!==void 0&&t.has(o.id)?(o.args&&(o.args=o.args.map(c=>this.resolveAlias(c))),r.push(o)):this.changed=!0;i.instructions=r}}performDeadLocalStoreElimination(){let t=new Map;for(let e of this.func.blocks.values())for(let s of e.instructions)if(s.opcode==="local.get"){let i=s.immediates?.[0];i!==void 0&&t.set(i,(t.get(i)||0)+1)}for(let e of this.func.blocks.values()){let s=[];for(let i of e.instructions){if(i.opcode==="local.set"||i.opcode==="local.tee"){let r=i.immediates?.[0];if(r!==void 0&&(t.get(r)||0)===0){if(i.opcode==="local.tee"&&i.id!==void 0&&i.args&&i.args.length>0){let c=this.resolveAlias(i.args[0]);this.aliasMap.set(i.id,c)}this.metrics.deadStoresEliminated++,this.changed=!0;continue}}s.push(i)}e.instructions=s}}performBlockFlattening(){let t=this.func.blocks,e=!0;for(;e;){e=!1;let s=Array.from(t.keys()).sort((i,r)=>i-r);for(let i of s){let r=t.get(i);if(r&&r.succs.length===1){let o=r.succs[0];if(o===r.id)continue;let c=t.get(o);if(!c)continue;if(c.preds.length===1&&c.preds[0]===i){if(o===this.func.entryBlock)continue;let u=[];for(let l of c.instructions)if(l.type==="phi"){if(l.id!==void 0&&l.args&&l.args.length>0){let d=this.resolveAlias(l.args[0]);this.aliasMap.set(l.id,d)}}else u.push(l);if(r.instructions.length>0){let l=r.instructions[r.instructions.length-1];l.opcode==="br"&&l.immediates&&l.immediates[0]===o&&r.instructions.pop()}r.instructions.push(...u),r.succs=c.succs;for(let l of c.succs){let d=t.get(l);if(d){d.preds=d.preds.map(f=>f===o?i:f);for(let f of d.instructions)if(f.type==="phi"){let p=f;p.phiArgs&&p.phiArgs[o]!==void 0&&(p.phiArgs[i]=p.phiArgs[o],delete p.phiArgs[o])}}}t.delete(o),this.changed=!0,e=!0,this.metrics.blocksFlattened++}}}}}performLocalLoadStoreForwarding(){for(let t of this.func.blocks.values()){let e=new Map,s=[];for(let i of t.instructions){if(i.opcode==="local.set"||i.opcode==="local.tee"){let r=i.immediates?.[0];if(r!==void 0&&i.args&&i.args.length>0){let o=this.resolveAlias(i.args[0]);e.set(r,o)}}if(i.opcode==="local.get"&&i.id!==void 0){let r=i.immediates?.[0];if(r!==void 0&&e.has(r)){let o=e.get(r);this.aliasMap.set(i.id,o),this.changed=!0;continue}}i.args&&(i.args=i.args.map(r=>this.resolveAlias(r))),s.push(i)}t.instructions=s}}hasSideEffects(t){let e=t.opcode;return!!(e==="br"||e==="br_if"||e==="return"||e==="unreachable"||e==="call"||e.includes("store")||e.includes("memory.grow")||e==="local.set"||e==="local.tee"||t.id===void 0)}isConst(t){return t==="i32.const"||t==="i64.const"||t==="f32.const"||t==="f64.const"||t==="v128.const"}tryFold(t){let e=[],s=!0;if(t.args)for(let i of t.args){let r=this.resolveAlias(i),o=this.varDefinitions.get(r),c=o&&o.length===1?o[0]:void 0;!c||!this.isConst(c.opcode)?s=!1:e.push(c)}else s=!1;if(s&&t.args&&t.args.length>0){let i=t.opcode;if(i.startsWith("i32."))return this.foldI32(t,e);if(i.startsWith("f32."))return this.foldF32(t,e);if(i.startsWith("i32x4.")||i.startsWith("f32x4.")||i==="v128.const")return this.foldSIMD(t,e)}if(t.opcode==="f32.mul"&&t.args&&t.args.length===2)for(let i=0;i<2;i++){let r=this.resolveAlias(t.args[i]),o=this.varDefinitions.get(r),c=o&&o.length===1?o[0]:void 0;if(c&&c.opcode==="f32.const"&&c.immediates[0]===0)return{type:"instr",id:t.id,opcode:"f32.const",args:[],immediates:[0]}}return this.tryIdentityReduction(t)}tryIdentityReduction(t){if(!t.args||t.args.length<2)return null;let e=t.opcode,s=this.resolveAlias(t.args[0]),i=this.resolveAlias(t.args[1]),r=this.varDefinitions.get(s),o=this.varDefinitions.get(i),c=r&&r.length===1?r[0]:void 0,u=o&&o.length===1?o[0]:void 0,l=f=>f&&f.opcode==="i32.const"?f.immediates[0]:null,d=f=>f&&f.opcode==="f32.const"?f.immediates[0]:null;if(e==="i32.add"){if(l(u)===0)return s;if(l(c)===0)return i}else if(e==="i32.sub"){if(l(u)===0)return s}else if(e==="i32.mul"){if(l(u)===1)return s;if(l(c)===1)return i}else if(e==="i32.and"){if(l(u)===-1)return s;if(l(c)===-1)return i}else if(e==="i32.or"){if(l(u)===0)return s;if(l(c)===0)return i}else if(e==="i32.xor"){if(l(u)===0)return s;if(l(c)===0)return i}else if(e==="i32.shl"||e==="i32.shr_s"||e==="i32.shr_u"){if(l(u)===0)return s}else if(e==="f32.add"){if(d(u)===0)return s;if(d(c)===0)return i}else if(e==="f32.sub"){if(d(u)===0)return s}else if(e==="f32.mul"){if(d(u)===1)return s;if(d(c)===1)return i}else if(e==="f32.div"){if(d(u)===1)return s}else if(e==="f64.add"){let f=p=>p&&p.opcode==="f64.const"?p.immediates[0]:null;if(f(u)===0)return s;if(f(c)===0)return i}else if(e==="f64.sub"){if((p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===0)return s}else if(e==="f64.mul"){let f=p=>p&&p.opcode==="f64.const"?p.immediates[0]:null;if(f(u)===1)return s;if(f(c)===1)return i}else if(e==="f64.div"&&(p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===1)return s;return null}foldI32(t,e){let s=e[0].immediates[0],i=e.length>1?e[1].immediates[0]:0,r=null;switch(t.opcode){case"i32.add":r=s+i|0;break;case"i32.sub":r=s-i|0;break;case"i32.mul":r=Math.imul(s,i);break;case"i32.div_s":if(i===0)return null;r=Math.trunc(s/i);break;case"i32.div_u":if(i===0)return null;r=(s>>>0)/(i>>>0)>>>0|0;break;case"i32.and":r=s&i;break;case"i32.or":r=s|i;break;case"i32.xor":r=s^i;break;case"i32.shl":r=s<<(i&31);break;case"i32.shr_s":r=s>>(i&31);break;case"i32.shr_u":r=s>>>(i&31);break;case"i32.eq":r=s===i?1:0;break;case"i32.ne":r=s!==i?1:0;break;case"i32.lt_s":r=s<i?1:0;break;case"i32.lt_u":r=s>>>0<i>>>0?1:0;break;case"i32.le_s":r=s<=i?1:0;break;case"i32.le_u":r=s>>>0<=i>>>0?1:0;break;case"i32.gt_s":r=s>i?1:0;break;case"i32.gt_u":r=s>>>0>i>>>0?1:0;break;case"i32.ge_s":r=s>=i?1:0;break;case"i32.ge_u":r=s>>>0>=i>>>0?1:0;break}return r!==null?{type:"instr",id:t.id,opcode:"i32.const",args:[],immediates:[r]}:null}foldF32(t,e){let s=e[0].immediates[0],i=e.length>1?e[1].immediates[0]:0,r=null;switch(t.opcode){case"f32.add":r=s+i;break;case"f32.sub":r=s-i;break;case"f32.mul":r=s*i;break;case"f32.div":r=s/i;break;case"f32.neg":r=-s;break;case"f32.abs":r=Math.abs(s);break;case"f32.eq":r=Number.isNaN(s)||Number.isNaN(i)?0:s===i?1:0;break;case"f32.ne":r=Number.isNaN(s)||Number.isNaN(i)||s!==i?1:0;break;case"f32.lt":r=Number.isNaN(s)||Number.isNaN(i)?0:s<i?1:0;break;case"f32.le":r=Number.isNaN(s)||Number.isNaN(i)?0:s<=i?1:0;break;case"f32.gt":r=Number.isNaN(s)||Number.isNaN(i)?0:s>i?1:0;break;case"f32.ge":r=Number.isNaN(s)||Number.isNaN(i)?0:s>=i?1:0;break}return r!==null?t.opcode.includes("eq")||t.opcode.includes("lt")||t.opcode.includes("gt")||t.opcode.includes("le")||t.opcode.includes("ne")?{type:"instr",id:t.id,opcode:"i32.const",args:[],immediates:[r]}:{type:"instr",id:t.id,opcode:"f32.const",args:[],immediates:[r]}:null}foldSIMD(t,e){let s=t.opcode,i=r=>r.opcode==="v128.const"?r.immediates:null;if(s==="i32x4.splat"){if(e.length>0&&e[0].opcode==="i32.const"){let r=e[0].immediates[0],o=new Int32Array([r,r,r,r]);return{type:"instr",id:t.id,opcode:"v128.const",args:[],immediates:Array.from(new Uint8Array(o.buffer))}}return null}if(s==="i32x4.add"||s==="i32x4.sub"||s==="i32x4.mul"){if(e.length<2)return null;let r=i(e[0]),o=i(e[1]);if(!r||!o||r.length!==16||o.length!==16)return null;let c=new Int32Array(new Uint8Array(r).buffer),u=new Int32Array(new Uint8Array(o).buffer),l=new Int32Array(4);for(let d=0;d<4;d++)s==="i32x4.add"?l[d]=c[d]+u[d]|0:s==="i32x4.sub"?l[d]=c[d]-u[d]|0:s==="i32x4.mul"&&(l[d]=Math.imul(c[d],u[d]));return{type:"instr",id:t.id,opcode:"v128.const",args:[],immediates:Array.from(new Uint8Array(l.buffer))}}return null}performLICM(){if(this.computeDominators(),this.detectLoops(),this.loops.length!==0){this.loops.sort((t,e)=>t.bodyBlocks.size-e.bodyBlocks.size);for(let t of this.loops)this.hoistLoopInvariants(t)}}computeDominators(){this.dominators.clear();let t=this.func.blocks,e=this.func.entryBlock,s=new Set(t.keys());for(let r of t.keys())r===e?this.dominators.set(r,new Set([e])):this.dominators.set(r,new Set(s));let i=!0;for(;i;){i=!1;for(let[r,o]of t){if(r===e)continue;let c;if(o.preds.length===0)c=new Set(s);else{let l=this.dominators.get(o.preds[0]);c=l?new Set(l):new Set(s);for(let d=1;d<o.preds.length;d++){let f=this.dominators.get(o.preds[d]);if(f)for(let p of c)f.has(p)||c.delete(p)}}c.add(r);let u=this.dominators.get(r);(c.size!==u.size||![...c].every(l=>u.has(l)))&&(this.dominators.set(r,c),i=!0)}}}dominates(t,e){let s=this.dominators.get(e);return s?s.has(t):!1}detectLoops(){this.loops=[];let t=this.func.blocks;for(let[e,s]of t)for(let i of s.succs)if(this.dominates(i,e)){let r=this.collectNaturalLoop(i,e);r&&this.loops.push(r)}}collectNaturalLoop(t,e){let s=new Set([t]),i=new Set,r=new Set([e]),o=[e];for(;o.length>0;){let l=o.pop();if(s.has(l))continue;s.add(l);let d=this.func.blocks.get(l);if(d)for(let f of d.preds)s.has(f)||o.push(f)}for(let l of s){let d=this.func.blocks.get(l);if(d)for(let f of d.succs)s.has(f)||i.add(l)}let c,u=this.func.blocks.get(t);if(u){for(let l of u.preds)if(!s.has(l)){c=l;break}}return{headerBlock:t,bodyBlocks:s,exitBlocks:i,backedgeBlocks:r,preheaderBlock:c}}hoistLoopInvariants(t){if(!t.preheaderBlock)return;let e=this.func.blocks.get(t.preheaderBlock);if(!e)return;let s=new Set;for(let l of t.bodyBlocks){let d=this.func.blocks.get(l);if(d)for(let f of d.instructions)f.id!==void 0&&s.add(f.id)}let i=new Set,r=[],o=!0;for(;o;){o=!1;for(let l of t.bodyBlocks){let d=this.func.blocks.get(l);if(d)for(let f of d.instructions)f.id!==void 0&&(i.has(f.id)||this.isLoopInvariant(f,t,s,i)&&(i.add(f.id),this.canHoist(f)&&r.push({blockId:l,instr:f}),o=!0))}}if(r.length===0)return;let c=e.instructions.length;if(c>0){let l=e.instructions[c-1];(l.opcode==="br"||l.opcode==="br_if"||l.opcode==="return")&&c--}let u=[];for(let{blockId:l,instr:d}of r){let f={...d,args:d.args?[...d.args]:[]};u.push(f);let p=this.func.blocks.get(l);p&&(p.instructions=p.instructions.filter(g=>g!==d)),this.metrics.loopInvariantsHoisted++,this.changed=!0}e.instructions.splice(c,0,...u)}isLoopInvariant(t,e,s,i){if(this.isConst(t.opcode))return!0;if(t.opcode==="local.get"){let r=t.immediates?.[0];return!this.mutatedLocals.has(r)}if(t.opcode==="global.get"){let r=t.immediates?.[0];return!this.mutatedGlobals.has(r)}if(!this.isPureOp(t.opcode))return!1;if(!t.args||t.args.length===0)return!0;for(let r of t.args){let o=this.resolveAlias(r);if(s.has(o)&&!i.has(o))return!1}return!0}canHoist(t){if(this.hasSideEffects(t))return!1;if(t.opcode==="local.get"){let e=t.immediates?.[0];if(this.mutatedLocals.has(e))return!1}if(t.opcode==="global.get"){let e=t.immediates?.[0];if(this.mutatedGlobals.has(e))return!1}return!0}isPureOp(t){return this.isConst(t)?!0:t.startsWith("i32.")||t.startsWith("i64.")||t.startsWith("f32.")||t.startsWith("f64.")?!(t.includes("load")||t.includes("store")):t==="local.get"||t==="global.get"||t==="select"?!0:t.startsWith("i8x16.")||t.startsWith("i16x8.")||t.startsWith("i32x4.")||t.startsWith("i64x2.")||t.startsWith("f32x4.")||t.startsWith("f64x2.")||t.startsWith("v128.")?!(t.includes("load")||t.includes("store")):!1}};function ko(n){let t=n.functions.map(e=>hs(e));return{types:n.types,functions:t,globals:n.globals,memories:n.memories,data:n.data,exports:n.exports,imports:n.imports}}function hs(n){let e=new ft(n).process();return{index:n.index,name:n.name,params:n.params,results:n.results,locals:n.locals,vars:n.vars,body:e,immutableParams:n.immutableParams,inlinedExpressionMap:n.inlinedExpressionMap}}var ft=class{func;blocks;dominators=new Map;immediateDominator=new Map;constructor(t){this.func=t,this.blocks=t.blocks}process(){this.calculateDominators();let t=new Set(this.blocks.keys()),e=this.getReachable(this.func.entryBlock);if(this.func.index===3){let s=`Func ${this.func.name||this.func.index}: Blocks ${e.size}
3
- `;for(let i of e){let r=this.blocks.get(i),o=r.instructions.map(c=>c.opcode).join(",");s+=`Block ${i}: Succs [${r.succs.join(",")}] Preds [${r.preds.join(",")}] Instrs [${o}]
4
- `}}return this.reloop(e,this.func.entryBlock)}calculateDominators(){let t=Array.from(this.blocks.keys()),e=this.func.entryBlock;for(let i of t)i===e?this.dominators.set(i,new Set([i])):this.dominators.set(i,new Set(t));let s=!0;for(;s;){s=!1;for(let i of t){if(i===e)continue;let r=this.blocks.get(i).preds;if(r.length===0)continue;let o=new Set(this.dominators.get(r[0]));for(let u=1;u<r.length;u++){let l=this.dominators.get(r[u]);o=new Set([...o].filter(d=>l.has(d)))}o.add(i);let c=this.dominators.get(i);(o.size!==c.size||[...o].some(u=>!c.has(u)))&&(this.dominators.set(i,o),s=!0)}}}getReachable(t){let e=new Set,s=[t];for(;s.length>0;){let i=s.pop();if(e.has(i))continue;e.add(i);let r=this.blocks.get(i);if(r)for(let o of r.succs)s.push(o)}return e}reloop(t,e,s,i){if(!t.has(e))return{kind:"simple",instructions:[]};let r=this.blocks.get(e),o=(_,b)=>{if(s===void 0||b===s)return[];if(t.has(_))return[];let S=this.blocks.get(_);if(!S)return[];if(S.preds.length!==1||S.preds[0]!==b)return[];let v=S.instructions[S.instructions.length-1];return!v||v.opcode!=="br"?[]:S.instructions.filter($=>$.opcode!=="br"&&$.opcode!=="br_if"&&$.opcode!=="return"&&$.opcode!=="unreachable")},u=s===e?[]:r.preds.filter(_=>t.has(_)&&this.dominators.get(_)?.has(e));if(u.length>0){let _=new Set,b=[...u];for(_.add(e);b.length>0;){let V=b.pop();if(!_.has(V)&&t.has(V)){_.add(V);let B=this.blocks.get(V);for(let A of B.preds)b.push(A)}}let S=new Set;for(let V of _){let B=this.blocks.get(V);for(let A of B.succs)if(t.has(A)&&!_.has(A)&&A!==e){let W=B.instructions[B.instructions.length-1];W&&(W.opcode==="br"||W.opcode==="br_if")&&W.immediates?.[0]===A?S.add(A):this.blocks.get(A).succs.length===0||S.add(A)}}let v=!0;for(;v;){v=!1;for(let V of t)if(!_.has(V)){if(S.has(V))continue;let B=this.blocks.get(V),A=B.preds.some(J=>_.has(J)),W=B.succs.length===0||B.succs.every(J=>_.has(J)||J===e?!0:s!==void 0&&J===s?!1:!t.has(J));A&&W&&(_.add(V),v=!0)}}let $=`loop_${e}`,N=r.preds;r.preds=r.preds.filter(V=>!u.includes(V));let L=this.reloop(_,e,e);r.preds=N;let T=new Set,U="";for(let V of _){let B=this.blocks.get(V),A=B.instructions.map(W=>W.opcode).join(",");U+=`Block ${V}: Succs [${B.succs.join(",")}] Preds [${B.preds.join(",")}] Instrs [${A}]
5
- `;for(let W of B.succs)t.has(W)&&!_.has(W)&&W!==e&&T.add(W)}let Q=new Set;for(let V of t)_.has(V)||Q.add(V);let K,ee=!1;if(T.size>0)for(let V of T){let B=this.blocks.get(V);if(B&&B.preds.length>0){ee=!0;break}}if(ee&&T.size>0){let V=T.values().next().value;V!==void 0&&(K=this.reloop(Q,V,s,i))}return{kind:"block",children:[{kind:"loop",body:L,label:$},...K?[K]:[]]}}let l=s!==void 0&&r.succs.some(_=>_===s);if(r.succs.length===2&&!l){let _=r.succs[0],b=r.succs[1],S=-1;for(let v=r.instructions.length-1;v>=0;v--){let $=r.instructions[v];if($.opcode==="br_if"){S=$.args[0];break}$.opcode!=="br"&&$.opcode}if(S!==-1){let v=y=>{if(s===void 0)return!1;if(y===s)return!0;let C=this.blocks.get(y);return C&&C.succs.length===1&&C.succs[0]===s?C.instructions.every(G=>G.opcode==="br"||G.opcode==="nop"):!1},$=s!==void 0&&v(_),N=s!==void 0&&v(b);if($&&!N){let y=r.instructions.filter(C=>C.opcode!=="br"&&C.opcode!=="br_if");return{kind:"block",children:[...y.length>0?[{kind:"simple",instructions:y}]:[],{kind:"if",condition:S,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}}]}}if(N&&!$){let y=r.instructions.filter(C=>C.opcode!=="br"&&C.opcode!=="br_if");return{kind:"block",children:[...y.length>0?[{kind:"simple",instructions:y}]:[],{kind:"if",condition:S,thenBranch:{kind:"break",label:""},elseBranch:{kind:"continue",label:""}}]}}let L=s!==void 0&&!t.has(_)&&t.has(b),T=s!==void 0&&!t.has(b)&&t.has(_);if(L){let y=r.instructions.filter(Se=>Se.opcode!=="br"&&Se.opcode!=="br_if"),C=this.reloop(t,b,s,i),q=o(_,e),G=q.length>0?{kind:"block",children:[{kind:"simple",instructions:q},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...y.length>0?[{kind:"simple",instructions:y}]:[],{kind:"if",condition:S,thenBranch:G},C]}}if(T){let y=r.instructions.filter(Se=>Se.opcode!=="br"&&Se.opcode!=="br_if"),C=this.reloop(t,_,s,i),q=o(b,e),G=q.length>0?{kind:"block",children:[{kind:"simple",instructions:q},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...y.length>0?[{kind:"simple",instructions:y}]:[],{kind:"if",condition:S,thenBranch:C,elseBranch:G}]}}let U=this.blocks.get(_),Q=this.blocks.get(b),K=U?new Set(U.succs):new Set,ee=Q?new Set(Q.succs):new Set,xe=[...K].filter(y=>ee.has(y)),V,B,A,W=ee.has(_),J=K.has(b);if(W)t.has(_)?V=new Set(this.getReachableInSet(_,t,s)):V=new Set,B=new Set,A=new Set([b]);else if(J)V=new Set(this.getReachableInSet(b,t,s)),B=new Set([_]),A=new Set;else if(xe.length>0)V=new Set(this.getReachableInSet(xe[0],t,s)),B=new Set([_]),A=new Set([b]);else{let y=this.getReachableInSet(_,t,s),C=this.getReachableInSet(b,t,s),q=[...y].filter(G=>C.has(G));V=new Set(q),B=new Set([...y].filter(G=>!V.has(G)&&this.blocks.has(G))),A=new Set([...C].filter(G=>!V.has(G)&&this.blocks.has(G)))}let pt=s!==void 0&&(_===s||b===s||!t.has(_)||!t.has(b))&&!(t.has(_)&&t.has(b)),oe,ve;if(pt)ve=!0,oe=!0;else{let y=!t.has(_),C=!t.has(b);oe=!V.has(b)&&A.size>0||C,ve=!V.has(_)&&B.size>0||y}let ae=null,ce=new Set;if(!ve)ce.add(_);else for(let y of B){let C=this.blocks.get(y);if(C)for(let q of C.succs)V.has(q)&&ce.add(q)}if(!oe)ce.add(b);else for(let y of A){let C=this.blocks.get(y);if(C)for(let q of C.succs)V.has(q)&&ce.add(q)}if(ce.size>0){let y=ce.values().next().value;y!==void 0&&(ae=y)}let ue,le,Sn=ve&&B.size===0,kn=oe&&A.size===0,de=(y,C)=>y.length===0?C:{kind:"block",children:[{kind:"simple",instructions:y},C]},mt=y=>y===s||y===i?[]:o(y,e);if(Sn){let y=mt(_);_===s?ue=de(y,{kind:"continue",label:""}):_===i?ue=de(y,{kind:"simple",instructions:[]}):ue=de(y,{kind:"break",label:""})}else ve?ue=this.reloop(B,_,s,ae||i):ue={kind:"simple",instructions:[]};if(kn){let y=mt(b);b===s?le=de(y,{kind:"continue",label:""}):b===i?le=de(y,{kind:"simple",instructions:[]}):le=de(y,{kind:"break",label:""})}else oe?le=this.reloop(A,b,s,ae||i):le=void 0;let ht=ae!==s&&ae!==null&&V.size>0?this.reloop(V,ae,s,i):void 0,_t=r.instructions.filter(y=>y.opcode!=="br"&&y.opcode!=="br_if");return{kind:"block",children:[..._t.length>0?[{kind:"simple",instructions:_t}]:[],{kind:"if",condition:S,thenBranch:ue,elseBranch:le},...ht?[ht]:[]]}}else console.log(`Failed to find condVar for block ${e} despite having 2 succs and br_if?`)}let d=[],f=[],p=!1;for(let _ of r.instructions)if(_.opcode==="br"){let b=_.immediates[0];d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),s!==void 0&&b===s?f.push({kind:"continue",label:""}):i!==void 0&&b===i||t.has(b)||(f.push({kind:"break",label:""}),s===void 0&&(p=!0))}else if(_.opcode==="br_if"){let b=_.immediates[0],S=_.args[0];if(d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),s!==void 0&&b===s)d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:S,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}});else if(!(i!==void 0&&b===i)){if(s!==void 0&&!t.has(b))d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:S,thenBranch:{kind:"break",label:""}});else if(!t.has(b)&&s===void 0)d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:S,thenBranch:{kind:"break",label:""}}),p=!0;else if(t.has(b)){d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0);let v=this.reloop(t,b,s);f.push({kind:"if",condition:S,thenBranch:v})}}}else d.push(_);d.length>0&&f.push({kind:"simple",instructions:d});let g=f.length===1?f[0]:{kind:"block",children:f};p&&(g={kind:"loop",body:{kind:"block",children:[g,{kind:"break",label:""}]},label:""});let x=r.succs.filter(_=>t.has(_)&&(s===void 0||_!==s)),w=new Set;r.instructions.forEach(_=>{_.opcode==="br_if"&&w.add(_.immediates[0])});let I=x.filter(_=>!w.has(_));if(I.length>0){let _=I[0];if(_!==e){let b=this.reloop(t,_,s);return{kind:"block",children:f.length>0?[g,b]:[b]}}}else if(r.succs.length===1){let _=r.succs[0],b=s!==void 0&&_===s,S=f.some(v=>v.kind==="continue"||v.kind==="break"||v.kind==="return")||d.some(v=>v.opcode==="return"||v.opcode==="unreachable");if(t.has(_)&&!b&&!S){let v=this.reloop(t,_,s);return{kind:"block",children:f.length>0?[g,v]:[v]}}}return g}getReachableInSet(t,e,s){let i=new Set;if(!e.has(t)||s!==void 0&&t===s)return i;let r=[t];for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let c=this.blocks.get(o);if(c)for(let u of c.succs)e.has(u)&&(s===void 0||u!==s)&&r.push(u)}return i}leadsToBackEdge(t,e,s){if(t===e)return!0;if(!s.has(t))return!1;let i=new Set,r=[t];for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let c=this.blocks.get(o);if(c)for(let u of c.succs){if(u===e)return!0;s.has(u)&&r.push(u)}}return!1}};function gn(){return{warnings:[],errors:[],demotions:[],featuresUsed:{usesF64:!1,usesI64:!1,usesF64Memory:!1,usesI64Memory:!1,usesSimdF64x2:!1,usesSimdI64x2:!1,usesSimdEmulation:!1}}}function _s(){return{f64:"allow",i64:"deny"}}function bn(n){let t=_s(),e=n?.demotionPolicy;return{f64:e?.f64??t.f64,i64:e?.i64??t.i64}}function be(n){return(n&65280)===64768}function gs(n){return n&255}var bs=new Set([a.f64_const,a.f64_abs,a.f64_neg,a.f64_ceil,a.f64_floor,a.f64_trunc,a.f64_nearest,a.f64_sqrt,a.f64_add,a.f64_sub,a.f64_mul,a.f64_div,a.f64_min,a.f64_max,a.f64_copysign,a.f64_eq,a.f64_ne,a.f64_lt,a.f64_gt,a.f64_le,a.f64_ge,a.i32_trunc_f64_s,a.i32_trunc_f64_u,a.i64_trunc_f64_s,a.i64_trunc_f64_u,a.i32_trunc_sat_f64_s,a.i32_trunc_sat_f64_u,a.i64_trunc_sat_f64_s,a.i64_trunc_sat_f64_u,a.f32_demote_f64,a.f64_convert_i32_s,a.f64_convert_i32_u,a.f64_convert_i64_s,a.f64_convert_i64_u,a.f64_promote_f32,a.i64_reinterpret_f64,a.f64_reinterpret_i64,a.f64_load,a.f64_store]),xn=new Set([a.i64_const,a.i64_eqz,a.i64_eq,a.i64_ne,a.i64_lt_s,a.i64_lt_u,a.i64_gt_s,a.i64_gt_u,a.i64_le_s,a.i64_le_u,a.i64_ge_s,a.i64_ge_u,a.i64_add,a.i64_sub,a.i64_mul,a.i64_div_s,a.i64_div_u,a.i64_rem_s,a.i64_rem_u,a.i64_and,a.i64_or,a.i64_xor,a.i64_shl,a.i64_shr_s,a.i64_shr_u,a.i64_rotl,a.i64_rotr,a.i64_clz,a.i64_ctz,a.i64_popcnt,a.i64_extend_i32_s,a.i64_extend_i32_u,a.i64_trunc_f32_s,a.i64_trunc_f32_u,a.i64_trunc_f64_s,a.i64_trunc_f64_u,a.i64_trunc_sat_f32_s,a.i64_trunc_sat_f32_u,a.i64_trunc_sat_f64_s,a.i64_trunc_sat_f64_u,a.f32_convert_i64_s,a.f32_convert_i64_u,a.f64_convert_i64_s,a.f64_convert_i64_u,a.i64_reinterpret_f64,a.f64_reinterpret_i64,a.i32_wrap_i64,a.i64_load,a.i64_store]),vn=new Set([a.i64_load,a.i64_store,a.i64_load8_s,a.i64_load8_u,a.i64_load16_s,a.i64_load16_u,a.i64_load32_s,a.i64_load32_u,a.i64_store8,a.i64_store16,a.i64_store32]),xs=new Set([a.f64_load,a.f64_store]),vs=new Set([20,33,34,71,72,73,74,75,76,236,237,239,240,241,242,243,244,245,246,247]),Ss=new Set([18,29,30,192,193,195,196,203,204,205,206,209,213,214,215,216,217,218,219]);function ks(n){let t=n.params.includes("i64")||n.results.includes("i64")||n.locals.some(c=>c.type==="i64"),e=t,s=!1,i=!1,r=!1,o=t;for(let c=0;c<n.body.length;c++){let u=n.body[c];if(!be(u.opcode)){if(u.opcode===a.i64_const){let l=n.body[c+1];if(l&&be(l.opcode))continue}if(vn.has(u.opcode)){e=!0,s=!0,o=!0;continue}if(xn.has(u.opcode)&&(e=!0,o=!0,u.opcode===a.i64_const)){let l=u.immediates[0];typeof l=="bigint"&&(l<-2147483648n||l>2147483647n)&&(r=!0)}}}for(let c=0;c<n.body.length;c++){let u=n.body[c];if(be(u.opcode)||!xn.has(u.opcode)&&!vn.has(u.opcode))continue;if(u.opcode===a.i64_const){let d=n.body[c+1];if(d&&be(d.opcode))continue}u.opcode===a.i64_const||u.opcode===a.i32_wrap_i64||(i=!0)}return{usesI64:e,usesI64Memory:s,usesI64ParamOrResultOrLocal:t,hasDisallowedI64Op:i,hasI64ConstOutOfRange:r,usesAnyScalarI64:o}}function Is(n){let t=n.params.includes("f64")||n.results.includes("f64")||n.locals.some(r=>r.type==="f64"),e=t,s=!1,i=t;for(let r of n.body)if(!be(r.opcode)){if(xs.has(r.opcode)){e=!0,s=!0,i=!0;continue}bs.has(r.opcode)&&(e=!0,i=!0)}return{usesF64:e,usesF64Memory:s,usesF64ParamOrResultOrLocal:t,usesAnyScalarF64:i}}function ys(n){let t=!1,e=!1,s=!1;for(let i of n.body){if(!be(i.opcode))continue;let r=gs(i.opcode);vs.has(r)&&(t=!0),Ss.has(r)&&(e=!0)}return{usesSimdF64x2:t,usesSimdI64x2:e,usesSimdEmulation:s}}function Vo(n,t){let e=gn(),s=bn(t),i=new Set,r=new Set;for(let o of n.functions){let c=o.index,u=o.name??`func_${c}`,l=ks(o),d=Is(o),f=ys(o);e.featuresUsed.usesI64||=l.usesI64,e.featuresUsed.usesI64Memory||=l.usesI64Memory,e.featuresUsed.usesF64||=d.usesF64,e.featuresUsed.usesF64Memory||=d.usesF64Memory,e.featuresUsed.usesSimdF64x2||=f.usesSimdF64x2,e.featuresUsed.usesSimdI64x2||=f.usesSimdI64x2,e.featuresUsed.usesSimdEmulation||=f.usesSimdEmulation,(d.usesF64||f.usesSimdF64x2)&&(d.usesF64Memory?e.errors.push({severity:"error",code:"ERR_F64_MEMORY_UNSUPPORTED",message:`Function ${u} uses f64 load/store; memory encoding for f64 is not defined.`,functionIndex:c,functionName:u}):s.f64==="deny"?e.errors.push({severity:"error",code:"ERR_F64_DEMOTION_DENIED",message:`Function ${u} uses f64; demotion to f32 is denied by policy.`,functionIndex:c,functionName:u}):i.has(c)||(e.warnings.push({severity:"warning",code:"WARN_F64_DEMOTED",message:`Function ${u} uses f64; lowering to f32 (precision loss).`,functionIndex:c,functionName:u}),e.demotions.push({kind:"f64->f32",functionIndex:c,functionName:u}),i.add(c))),s.i64==="deny"?(l.usesI64Memory&&e.errors.push({severity:"error",code:"ERR_I64_MEMORY_UNSUPPORTED",message:`Function ${u} uses i64 load/store; memory encoding for i64 is not defined. Enable lossy i64 demotion to allow.`,functionIndex:c,functionName:u}),l.usesI64ParamOrResultOrLocal&&e.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${u} uses scalar i64 parameters/results/locals; i64 is unsupported by default.`,functionIndex:c,functionName:u}),l.hasI64ConstOutOfRange&&e.errors.push({severity:"error",code:"ERR_I64_CONST_OUT_OF_RANGE",message:`Function ${u} uses i64.const outside signed i32 range; enable lossy i64 demotion to allow.`,functionIndex:c,functionName:u}),l.hasDisallowedI64Op&&e.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${u} uses scalar i64 operations; enable lossy i64 demotion to allow.`,functionIndex:c,functionName:u})):l.usesAnyScalarI64&&(r.has(c)||(e.warnings.push({severity:"warning",code:"WARN_I64_DEMOTED_LOSSY",message:`Function ${u} uses i64; lowering to i32 (lossy, modulo 2^32). Shift operations are masked to 31 bits, changing semantics for shift amounts >= 32.`,functionIndex:c,functionName:u}),e.demotions.push({kind:"i64->i32-lossy",functionIndex:c,functionName:u}),r.add(c)))}if(t.warningsAsErrors&&e.warnings.length>0)for(let o of e.warnings)e.errors.push({severity:"error",code:"ERR_WARNINGS_AS_ERRORS",message:o.message,functionIndex:o.functionIndex,functionName:o.functionName});return{diagnostics:e,policy:s}}export{R as a,Vs as b,a as c,Ls as d,zs as e,ci as f,yn as g,Be as h,bt as i,ke as j,li as k,vt as l,di as m,fi as n,pi as o,St as p,kt as q,Ie as r,En as s,Wn as t,Hn as u,qn as v,Gn as w,co as x,fo as y,vo as z,ko as A,gn as B,Vo as C};