@gasm-compiler/core 0.4.0 → 0.5.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.
- package/README.md +38 -0
- package/dist/browser.d.ts +27 -3
- package/dist/browser.js +8 -8
- package/dist/chunk-MBWDLAL5.js +5 -0
- package/dist/chunk-TICBJF7F.js +9 -0
- package/dist/compiler.js +1 -1
- package/dist/{error_codes-Cdy_3FNo.d.ts → error_codes-5zCZDwFZ.d.ts} +108 -2
- package/dist/gasm_core_rs.wasm +0 -0
- package/dist/mod.d.ts +16 -78
- package/dist/mod.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-NQJKL2KQ.js +0 -9
- package/dist/chunk-R6SXLNEJ.js +0 -5
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
function R(t,e){let n=new Error(t);return n.name="CompileError",e&&(n.functionName=e.functionName,n.instructionName=e.instructionName,n.offset=e.offset,n.code=e.code),n}function Ui(t){return t instanceof Error&&t.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,atomic_fence:65027,i32_atomic_load:65040,i64_atomic_load:65041,i32_atomic_store:65047,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 v={ERR_MEMORY_COUNT:"ERR_MEMORY_COUNT",ERR_MEMORY_GROW:"ERR_MEMORY_GROW",ERR_TABLE_PRESENT:"ERR_TABLE_PRESENT",ERR_INDIRECT_CALL:"ERR_INDIRECT_CALL",ERR_START_FUNCTION:"ERR_START_FUNCTION",ERR_FUNCTION_IMPORT:"ERR_FUNCTION_IMPORT",ERR_NO_ENTRY_POINT:"ERR_NO_ENTRY_POINT",ERR_MUTABLE_GLOBAL:"ERR_MUTABLE_GLOBAL",ERR_MULTI_MEMORY:"ERR_MULTI_MEMORY",ERR_PASSIVE_SEGMENT:"ERR_PASSIVE_SEGMENT",ERR_WORKGROUP_MEMORY_SIZE:"ERR_WORKGROUP_MEMORY_SIZE",ERR_RECURSION:"ERR_RECURSION",ERR_NON_UNIFORM_BARRIER:"ERR_NON_UNIFORM_BARRIER",ERR_UNALIGNED_ACCESS:"ERR_UNALIGNED_ACCESS",ERR_OFFSET_OVERFLOW:"ERR_OFFSET_OVERFLOW",ERR_FUNCREF:"ERR_FUNCREF",ERR_EXTERNREF:"ERR_EXTERNREF",ERR_F64_DEMOTION_REQUIRED:"ERR_F64_DEMOTION_REQUIRED",ERR_ATOMIC_REGION_MISSING:"ERR_ATOMIC_REGION_MISSING",ERR_ATOMIC_REGION_UNALIGNED:"ERR_ATOMIC_REGION_UNALIGNED",ERR_ATOMIC_REGION_OVERFLOW:"ERR_ATOMIC_REGION_OVERFLOW",ERR_ATOMIC_REGION_UNKNOWN_ADDRESS:"ERR_ATOMIC_REGION_UNKNOWN_ADDRESS",ERR_UNSUPPORTED_INSTR:"ERR_UNSUPPORTED_INSTR",ERR_UNKNOWN_EXTENSION:"ERR_UNKNOWN_EXTENSION",ERR_DUPLICATE_EXTENSION:"ERR_DUPLICATE_EXTENSION",ERR_DUPLICATE_CUSTOM_SECTION:"ERR_DUPLICATE_CUSTOM_SECTION",ERR_DUPLICATE_WORKGROUP_SIZE:"ERR_DUPLICATE_WORKGROUP_SIZE",ERR_METADATA_SCHEMA:"ERR_METADATA_SCHEMA",ERR_PARSE:"ERR_PARSE",ERR_VALIDATION:"ERR_VALIDATION"},Wi=new Set([v.ERR_MEMORY_COUNT,v.ERR_MEMORY_GROW,v.ERR_TABLE_PRESENT,v.ERR_INDIRECT_CALL,v.ERR_START_FUNCTION,v.ERR_FUNCTION_IMPORT,v.ERR_NO_ENTRY_POINT,v.ERR_MUTABLE_GLOBAL,v.ERR_MULTI_MEMORY,v.ERR_PASSIVE_SEGMENT,v.ERR_WORKGROUP_MEMORY_SIZE,v.ERR_RECURSION,v.ERR_NON_UNIFORM_BARRIER,v.ERR_UNALIGNED_ACCESS,v.ERR_OFFSET_OVERFLOW,v.ERR_FUNCREF,v.ERR_EXTERNREF,v.ERR_F64_DEMOTION_REQUIRED,v.ERR_ATOMIC_REGION_MISSING,v.ERR_ATOMIC_REGION_UNALIGNED,v.ERR_ATOMIC_REGION_OVERFLOW,v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS,v.ERR_UNSUPPORTED_INSTR,v.ERR_UNKNOWN_EXTENSION,v.ERR_DUPLICATE_EXTENSION,v.ERR_DUPLICATE_CUSTOM_SECTION,v.ERR_DUPLICATE_WORKGROUP_SIZE,v.ERR_METADATA_SCHEMA]);var jn=new Set(["gasm:simd:1.0","gasm:relaxed-simd:1.0","gasm:atomics:1.0","gasm:sign-extension:1.0","gasm:nontrapping-fptoint:1.0","gasm:multi-value:1.0","gasm:math:1.0","gasm:demote-f64:1.0","gasm:relaxed-fp-minmax:1.0","gasm:bulk-memory:1.0","gasm:mutable-globals:1.0","gasm:workgroup-memory:1.0"]),Ee=class{constructor(e){this.bytes=e}offset=0;get done(){return this.offset>=this.bytes.length}readUleb(){let e=0,n=0;for(;this.offset<this.bytes.length;){let s=this.bytes[this.offset++];if(e|=(s&127)<<n,(s&128)===0)return e>>>0;if(n+=7,n>35)throw new Error("ULEB128 value is too large")}throw new Error("Unexpected end of custom section")}readString(){let e=this.readUleb();if(this.offset+e>this.bytes.length)throw new Error("Unexpected end of custom section string");let n=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,new TextDecoder().decode(n)}};function Re(t){let e=[],n=[],s=new Map,i,r=!1,o=!1;for(let c of t??[])try{if(c.name==="gasm.extensions"){if(r){e.push({code:v.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.extensions custom section"});continue}r=!0,Yn(c.data,n,e)}else if(c.name==="gasm.workgroup_size")Xn(c.data,s,e);else if(c.name==="gasm.atomic_region"){if(o){e.push({code:v.ERR_DUPLICATE_CUSTOM_SECTION,message:"Duplicate gasm.atomic_region custom section"});continue}o=!0,i=Zn(c.data,e)}}catch(u){e.push({code:v.ERR_PARSE,message:u instanceof Error?u.message:String(u)})}return{extensions:n,workgroupSizes:s,atomicRegion:i,diagnostics:e}}function Mt(t){let e=Re(t.customSections);t.extensions=e.extensions,t.workgroupSizes=e.workgroupSizes,t.atomicRegion=e.atomicRegion}function At(t,e){if(t.length<8||t[0]!==0||t[1]!==97||t[2]!==115||t[3]!==109)throw new Error("Invalid WebAssembly header");let n=[...new Set(e)].sort(),s=[...t.subarray(0,8)],i=8;for(;i<t.length;){let r=i,o=t[i++],c=Ft(t,i);i=c.nextOffset;let u=i,l=u+c.value;if(l>t.length)throw new Error("WebAssembly section exceeds module length");let d=!1;if(o===0){let f=Ft(t,u),p=f.nextOffset,g=p+f.value;if(g>l)throw new Error("WebAssembly custom section name exceeds section");d=new TextDecoder().decode(t.subarray(p,g))==="gasm.extensions"}d||s.push(...t.subarray(r,l)),i=l}if(n.length>0){let r=Bt("gasm.extensions"),o=n.flatMap(Bt),c=[...r,...o];s.push(0,...Ct(c.length),...c)}return new Uint8Array(s)}function Yn(t,e,n){let s=new Ee(t),i=new Set;for(;!s.done;){let r=s.readString();if(i.has(r)){n.push({code:v.ERR_DUPLICATE_EXTENSION,message:`Duplicate extension declaration: ${r}`});continue}i.add(r),e.push(r),jn.has(r)||n.push({code:v.ERR_UNKNOWN_EXTENSION,message:`Unknown Gasm extension: ${r}`})}}function Ft(t,e){let n=0,s=0,i=e;for(;i<t.length;){let r=t[i++];if(n|=(r&127)<<s,(r&128)===0)return{value:n>>>0,nextOffset:i};if(s+=7,s>35)throw new Error("ULEB128 value is too large")}throw new Error("Unexpected end of WebAssembly module")}function Ct(t){let e=[];do{let n=t&127;t>>>=7,t!==0&&(n|=128),e.push(n)}while(t!==0);return e}function Bt(t){let e=new TextEncoder().encode(t);return[...Ct(e.length),...e]}function Xn(t,e,n){let s=new Ee(t);for(;!s.done;){let i=s.readUleb(),r=s.readUleb(),o=s.readUleb(),c=s.readUleb();if(e.has(i)){n.push({code:v.ERR_DUPLICATE_WORKGROUP_SIZE,message:`Duplicate gasm.workgroup_size entry for function ${i}`});continue}e.set(i,[r,o,c])}}function Zn(t,e){let n=new Ee(t),s=n.readUleb(),i=n.readUleb(),r=n.readUleb();if(!n.done)throw new Error("Trailing bytes in gasm.atomic_region custom section");return(i%4!==0||r%4!==0)&&e.push({code:v.ERR_ATOMIC_REGION_UNALIGNED,message:"gasm.atomic_region offset and length must be 4-byte aligned"}),{memoryIndex:s,offset:i,length:r}}var Pe=class{view;offset=0;bytes;constructor(e){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}get pos(){return this.offset}set pos(e){this.offset=e}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++]}peekByte(){return this.bytes[this.offset]}readBytes(e){if(this.offset+e>this.bytes.length)throw R("Unexpected EOF",{offset:this.offset});let n=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,n}readUint32(){let e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}readF32(){let e=this.view.getFloat32(this.offset,!0);return this.offset+=4,e}readF64(){let e=this.view.getFloat64(this.offset,!0);return this.offset+=8,e}readVarUint32(){let e=0,n=0;for(;;){let s=this.readByte();if(e|=(s&127)<<n,(s&128)===0)break;n+=7}return e}readVarInt32(){let e=0,n=0,s;for(;s=this.readByte(),e|=(s&127)<<n,n+=7,(s&128)!==0;);return n<32&&(s&64)!==0&&(e|=-1<<n),e}readVarInt64(){let e=0n,n=0n,s;for(;s=this.readByte(),e|=BigInt(s&127)<<n,n+=7n,(s&128)!==0;);return n<64&&(s&64)!==0&&(e|=~0n<<n),e}readString(){let e=this.readVarUint32(),n=this.readBytes(e);return new TextDecoder("utf-8").decode(n)}readType(){let e=this.readByte();switch(e){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${e.toString(16)}`,{offset:this.offset-1})}}};function Le(t){let e=new Pe(t);if(e.readByte()!==0||e.readByte()!==97||e.readByte()!==115||e.readByte()!==109)return R("Invalid magic bytes",{offset:0});if(e.readByte()!==1||e.readByte()!==0||e.readByte()!==0||e.readByte()!==0)return R("Unsupported Wasm version",{offset:4});let n={types:[],functions:[],globals:[],memories:[],data:[],exports:[],imports:[],customSections:[],hasTableSection:!1,hasElementSection:!1},s=[];for(;!e.isEOF();){let i=e.readByte(),r=e.readVarUint32(),o=e.pos+r;switch(i){case 0:try{let c=e.readString(),u=e.readBytes(o-e.pos),l={name:c,data:u};n.customSections.push(l)}catch{e.pos=o}break;case 1:{let c=e.readVarUint32();for(let u=0;u<c;u++){if(e.readByte()!==96)throw R("Expected 0x60 for func type",{offset:e.pos-1});let d=e.readVarUint32(),f=[];for(let S=0;S<d;S++)f.push(e.readType());let p=e.readVarUint32(),g=[];for(let S=0;S<p;S++)g.push(e.readType());n.types.push({params:f,results:g})}}break;case 2:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readString(),d=e.readString(),f=e.readByte(),p={module:l,name:d,kind:"func"};switch(f){case 0:p.kind="func",p.typeIndex=e.readVarUint32();break;case 1:p.kind="table",e.readByte();{let S=e.readByte();e.readVarUint32(),S&1&&e.readVarUint32()}break;case 2:p.kind="mem";{let S=e.readByte();p.memoryMin=e.readVarUint32(),S&1&&(p.memoryMax=e.readVarUint32())}break;case 3:p.kind="global",p.globalType=e.readType(),p.globalMutable=e.readByte()===1;let g=n.globals.length;n.globals.push({kind:"import",index:g,module:l,name:d,type:p.globalType,mutable:p.globalMutable});break}n.imports.push(p)}}break;case 3:{let c=e.readVarUint32();for(let u=0;u<c;u++)s.push(e.readVarUint32())}break;case 4:n.hasTableSection=!0,e.pos=o;break;case 5:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readByte(),d=e.readVarUint32(),f=l&1?e.readVarUint32():void 0;n.memories.push({index:u,min:d,max:f})}}break;case 6:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readType(),d=e.readByte()===1,f=Ae(e),p=n.globals.length,g;if(f.length>=1){let S=f[0];(S.opcode===a.i32_const||S.opcode===a.f32_const||S.opcode===a.i64_const||S.opcode===a.f64_const)&&(g=S.immediates?.[0])}n.globals.push({kind:"definition",index:p,type:l,mutable:d,initExpr:f,initValue:g})}}break;case 7:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readString(),d=e.readByte(),f=e.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:e.pos})}n.exports.push({name:l,kind:p,index:f})}}break;case 8:{let c=e.readVarUint32();n.startFunctionIndex=c}break;case 9:n.hasElementSection=!0,e.pos=o;break;case 10:{let c=e.readVarUint32();s.length;for(let u=0;u<c;u++){let l=e.readVarUint32(),d=e.pos+l,f=s[u],p=n.types[f],g=e.readVarUint32(),S=[],y=0;for(let h=0;h<g;h++){let b=e.readVarUint32(),x=e.readType();for(let I=0;I<b;I++)S.push({index:y++,type:x,mutable:!0})}let k=Ae(e);n.functions.push({index:n.imports.filter(h=>h.kind==="func").length+u,params:p.params,results:p.results,locals:S,body:k}),e.pos!==d&&(e.pos=d)}}break;case 11:{let c=e.readVarUint32();for(let u=0;u<c;u++){let l=e.readVarUint32(),d="active",f=0,p=[];if(l===0)p=Ae(e);else if(l===1)d="passive";else if(l===2)f=e.readVarUint32(),p=Ae(e);else return R(`Unsupported data segment mode: ${l}`,{offset:e.pos});let g=e.readVarUint32(),S=e.readBytes(g);n.data.push({mode:d,memoryIndex:f,offset:p,data:S})}}break;default:e.pos=o;break}}return Mt(n),n}function Ae(t){let e=[],n=0;for(;;){let s=t.pos,i=t.readByte(),r,o={opcode:i,name:"",offset:s,immediates:[]},c=!1,u,l=!1,d=!1;if(i===253){let f=t.pos,p=t.readByte();(p&128)!==0&&t.peekByte()!==253&&t.peekByte()!==252?(t.pos=f,u=t.readVarUint32()):u=p,i=u<=255?64768|u:253<<16|u,o.opcode=i,c=!0}else i===252?(i=64512|t.readVarUint32(),o.opcode=i,l=!0):i===254&&(i=65024|t.readVarUint32(),o.opcode=i,d=!0);if(r=Kn(i),o.name=r,i===a.block||i===a.loop||i===a.if)n++;else if(i===11){if(n===0){e.push(o);break}n--}switch(i){case a.block:case a.loop:case a.if:{let f=t.readByte();o.immediates.push(f)}break;case a.br:case a.br_if:o.immediates.push(t.readVarUint32());break;case a.br_table:{let f=t.readVarUint32(),p=[];for(let g=0;g<f;g++)p.push(t.readVarUint32());p.push(t.readVarUint32()),o.immediates.push(p)}break;case a.call:case a.call_indirect:o.immediates.push(t.readVarUint32()),i===a.call_indirect&&o.immediates.push(t.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(t.readVarUint32());break;case a.i32_const:o.immediates.push(t.readVarInt32());break;case a.i64_const:o.immediates.push(t.readVarInt64());break;case a.f32_const:o.immediates.push(t.readF32());break;case a.f64_const:o.immediates.push(t.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:{let f=t.readVarUint32(),p=0;f>=64&&f<128&&(f-=64,p=t.readVarUint32()),o.immediates.push(f),o.immediates.push(t.readVarUint32()),p!==0&&o.immediates.push(p)}break;case 63:case 64:t.readByte();break}if(c)switch(u){case 12:o.immediates.push(Array.from(t.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(t.readByte());break;case 13:o.immediates.push(Array.from(t.readBytes(16)));break;case 0:o.immediates.push(t.readVarUint32()),o.immediates.push(t.readVarUint32());break;case 11:o.immediates.push(t.readVarUint32()),o.immediates.push(t.readVarUint32());break}if(l){let f=i&255;switch(i){case a.memory_init:o.immediates.push(t.readVarUint32()),t.readByte();break;case a.data_drop:o.immediates.push(t.readVarUint32());break;case a.memory_copy:t.readByte(),t.readByte();break;case a.memory_fill:t.readByte();break;case a.table_init:o.immediates.push(t.readVarUint32()),o.immediates.push(t.readVarUint32());break;case a.elem_drop:o.immediates.push(t.readVarUint32());break;case a.table_copy:o.immediates.push(t.readVarUint32()),o.immediates.push(t.readVarUint32());break;case a.table_grow:case a.table_size:case a.table_fill:o.immediates.push(t.readVarUint32());break}}if(d){let f=i&255;f>=16&&f<=78&&(o.immediates.push(t.readVarUint32()),o.immediates.push(t.readVarUint32()))}e.push(o)}return e}function Ue(t){return t?.name==="CompileError"}function Kn(t){let e=Object.entries(a).find(([,n])=>n===t);return e?e[0]:`0x${t.toString(16)}`}function Dt(t,e={}){try{if(e.strictConformance){let i=Re(t.customSections).diagnostics;if(i.length>0){let y=i[0];throw R(y.message,{code:y.code})}let r=new Set(t.extensions??[]),o=r.has("gasm:workgroup-memory:1.0"),c=r.has("gasm:mutable-globals:1.0"),u=r.has("gasm:bulk-memory:1.0"),l=r.has("gasm:atomics:1.0"),d=r.has("gasm:demote-f64:1.0"),f=t.memories.length,p=0;for(let y of t.imports){if(y.kind!=="mem")continue;if(y.module==="gasm"&&y.name==="workgroup_memory"&&o){if(p++,(y.memoryMax??y.memoryMin??0)>16*1024)throw R("Imported workgroup memory exceeds the portable 16 KiB limit (M011: ERR_WORKGROUP_MEMORY_SIZE)",{code:v.ERR_WORKGROUP_MEMORY_SIZE})}else f++}if(f===0)throw R("Module must declare exactly one primary memory (M001: ERR_MEMORY_COUNT)",{code:v.ERR_MEMORY_COUNT});if(f>1)throw R("Module must not declare more than one primary memory (M009: ERR_MULTI_MEMORY)",{code:v.ERR_MULTI_MEMORY});if(p>1)throw R("Module must not declare more than one workgroup memory import (M009: ERR_MULTI_MEMORY)",{code:v.ERR_MULTI_MEMORY});if(Jn(t,a.call_indirect))throw R("Invalid instruction: call_indirect",{code:v.ERR_INDIRECT_CALL});if(t.hasTableSection||t.hasElementSection||t.imports.some(y=>y.kind==="table")||t.exports.some(y=>y.kind==="table"))throw R("Tables and element segments are forbidden in Gasm v0.2 (M003: ERR_TABLE_PRESENT)",{code:v.ERR_TABLE_PRESENT});for(let y of t.imports)if(y.kind==="func"&&y.module!=="gasm")throw R(`Function import from "${y.module}" is forbidden; only "gasm" imports are allowed (M006: ERR_FUNCTION_IMPORT)`,{functionName:`${y.module}.${y.name}`,code:v.ERR_FUNCTION_IMPORT});for(let y of t.globals){if(y.kind==="import"&&y.mutable)throw R("Mutable imported globals are forbidden (M008: ERR_MUTABLE_GLOBAL)",{code:v.ERR_MUTABLE_GLOBAL});if(y.kind==="definition"&&y.mutable&&!c)throw R("Mutable globals require gasm:mutable-globals:1.0 (M008: ERR_MUTABLE_GLOBAL)",{code:v.ERR_MUTABLE_GLOBAL})}if(!u&&t.data.some(y=>y.mode==="passive"))throw R("Passive data segments require gasm:bulk-memory:1.0 (M010: ERR_PASSIVE_SEGMENT)",{code:v.ERR_PASSIVE_SEGMENT});es(t,l),rs(t,d);let g=t.imports.filter(y=>y.kind==="func").length;if(!t.exports.some(y=>{if(y.kind!=="func")return!1;let k=y.index;if(k<g){let b=t.imports.filter(x=>x.kind==="func")[k];if(b?.typeIndex!==void 0){let x=t.types[b.typeIndex];return x&&x.params.length===0&&x.results.length===0}return!1}let h=t.functions.find(b=>b.index===k);return h?h.params.length===0&&h.results.length===0:!1}))throw R("Module must export at least one () -> () function as an entry point (M007: ERR_NO_ENTRY_POINT)",{code:v.ERR_NO_ENTRY_POINT})}let n=new Set(t.extensions??[]).has("gasm:bulk-memory:1.0"),s=new Set(t.extensions??[]).has("gasm:atomics:1.0");for(let i of t.functions)Qn(t,i,n,s);if(ls(t),t.startFunctionIndex!==void 0)throw R("Start section not allowed",{functionName:"start",code:v.ERR_START_FUNCTION});return t}catch(n){if(ze(n))return n;throw n}}function ze(t){return t?.name==="CompileError"}function Qn(t,e,n=!1,s=!1){let i=[];for(let r of e.body){let o=(r.opcode&65280)===64768;if(r.opcode===a.call_indirect)throw R("Invalid instruction: call_indirect",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_INDIRECT_CALL});if(r.opcode===a.memory_grow)throw R(`Invalid instruction: ${r.name}`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_MEMORY_GROW});if(r.opcode>=208&&r.opcode<=210)throw R("Invalid instruction: Reference types not allowed",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(r.opcode===37||r.opcode===38)throw R("Invalid instruction: Table operations not allowed",{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(as(r.opcode,n))throw R(`Invalid instruction: ${r.name} not supported`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});if(cs(r.opcode)&&ss(t,e,r,i,s),os(r.opcode)){let c=r.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(r.opcode))throw R(`Invalid instruction: ${r.name} (only 32-bit and full 64-bit load/store allowed)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNSUPPORTED_INSTR});let l=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(r.opcode)?l=0:[a.i32_load16_s,a.i32_load16_u,a.i32_store16,a.i64_load16_s,a.i64_load16_u,a.i64_store16].includes(r.opcode)?l=1:[a.i64_load32_s,a.i64_load32_u,a.i64_store32].includes(r.opcode)?l=2:[a.i64_load,a.i64_store,a.f64_load,a.f64_store].includes(r.opcode)&&(l=3),c<l)throw R(`Misaligned memory access: ${r.name} (must be aligned)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_UNALIGNED_ACCESS});let d=r.immediates[1],f=c>=32?2**32:2**c;if(d!==void 0&&d+f-1>4294967295)throw R(`Memory access offset plus alignment overflows u32: ${r.name} (A003: ERR_OFFSET_OVERFLOW)`,{functionName:e.name||`func${e.index}`,instructionName:r.name,offset:r.offset,code:v.ERR_OFFSET_OVERFLOW})}r.opcode,a.loop,ns(i,r)}}function Jn(t,e){return t.functions.some(n=>n.body.some(s=>s.opcode===e))}function es(t,e){if(!e)return;if(!t.atomicRegion)throw R("gasm:atomics:1.0 requires a gasm.atomic_region custom section",{code:v.ERR_ATOMIC_REGION_MISSING});let n=t.atomicRegion;if(n.offset%4!==0||n.length%4!==0)throw R("gasm.atomic_region offset and length must be 4-byte aligned",{code:v.ERR_ATOMIC_REGION_UNALIGNED});let s=(ts(t,n.memoryIndex)??0)*65536;if(n.offset+n.length>s)throw R("gasm.atomic_region exceeds the declared memory minimum",{code:v.ERR_ATOMIC_REGION_OVERFLOW})}function ts(t,e){let n=0;for(let s of t.imports)if(s.kind==="mem"){if(n===e)return s.module==="gasm"&&s.name==="workgroup_memory"?void 0:s.memoryMin;n++}for(let s of t.memories){if(n===e)return s.min;n++}}function ns(t,e){switch(e.opcode){case a.i32_const:t.push(e.immediates[0]);return;case a.drop:t.pop();return;case a.i32_atomic_load:case a.i32_load:case a.i32_load8_s:case a.i32_load8_u:case a.i32_load16_s:case a.i32_load16_u:t.pop(),t.push(void 0);return;case a.i32_atomic_store:case a.i32_store:case a.i32_store8:case a.i32_store16:t.pop(),t.pop();return;case a.local_get:case a.global_get:t.push(void 0);return;case a.local_set:case a.global_set:t.pop();return;default:e.opcode===a.i32_eqz?(t.pop(),t.push(void 0)):(e.opcode>=a.i32_eq&&e.opcode<=a.i32_ge_u||e.opcode>=a.i32_add&&e.opcode<=a.i32_rotr)&&(t.pop(),t.pop(),t.push(void 0))}}function ss(t,e,n,s,i){if(!i||!us(n.opcode))throw R(`Invalid instruction: ${n.name} not supported`,{functionName:e.name||`func${e.index}`,instructionName:n.name,offset:n.offset,code:v.ERR_UNSUPPORTED_INSTR});if(!t.atomicRegion)throw R("Atomic instructions require a gasm.atomic_region custom section",{functionName:e.name||`func${e.index}`,instructionName:n.name,offset:n.offset,code:v.ERR_ATOMIC_REGION_MISSING});let r=is(n,s),o=n.immediates[1]??0;if(r===void 0)throw R("Atomic instruction address must resolve to the declared atomic region",{functionName:e.name||`func${e.index}`,instructionName:n.name,offset:n.offset,code:v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS});let c=r+o,u=t.atomicRegion;if(c<u.offset||c+4>u.offset+u.length)throw R("Atomic instruction address is outside the declared atomic region",{functionName:e.name||`func${e.index}`,instructionName:n.name,offset:n.offset,code:v.ERR_ATOMIC_REGION_UNKNOWN_ADDRESS})}function is(t,e){if(t.opcode===a.i32_atomic_load)return e.at(-1);if(t.opcode===a.i32_atomic_store)return e.at(-2)}function rs(t,e){let n=s=>{if(s==="funcref")throw R("funcref is forbidden in Gasm v0.2 (T001: ERR_FUNCREF)",{code:v.ERR_FUNCREF});if(s==="externref")throw R("externref is forbidden in Gasm v0.2 (T002: ERR_EXTERNREF)",{code:v.ERR_EXTERNREF});if(s==="f64"&&!e)throw R("f64 requires gasm:demote-f64:1.0 in Gasm v0.2 (T003: ERR_F64_DEMOTION_REQUIRED)",{code:v.ERR_F64_DEMOTION_REQUIRED})};for(let s of t.types){for(let i of s.params)n(i);for(let i of s.results)n(i)}for(let s of t.imports)s.kind==="global"&&s.globalType&&n(s.globalType);for(let s of t.globals)n(s.type);for(let s of t.functions){for(let i of s.params)n(i);for(let i of s.results)n(i);for(let i of s.locals)n(i.type)}}function os(t){return t>=40&&t<=62}function as(t,e){return(t&65280)!==64512||e&&t>=a.memory_init&&t<=a.memory_fill?!1:t>=a.memory_init}function cs(t){return(t&65280)===65024}function us(t){return t===a.i32_atomic_load||t===a.i32_atomic_store}function ls(t){let e=new Map;for(let r of t.functions){let o=new Set;for(let c of r.body)if(c.opcode===a.call){let u=c.immediates[0];o.add(u)}e.set(r.index,o)}let n=new Set,s=new Set;function i(r){n.add(r),s.add(r);let o=e.get(r);if(o){for(let c of o)if(n.has(c)){if(s.has(c))return!0}else if(i(c))return!0}return s.delete(r),!1}for(let r of t.functions)if(!n.has(r.index)&&i(r.index))throw R("Recursion detected",{functionName:r.name||`func${r.index}`,code:v.ERR_RECURSION})}var Ve=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 Tt(t,e){if(t!=="gasm")return!1;let n=Nt(e);return Ve.has(n)}function Nt(t){if(Ve.has(t))return t;let e=t.match(/^(.+)_v([234])f32(?:_v)?$/);if(e)return e[1];let n=t.match(/^(.+)_f32$/);return n&&Ve.has(n[1])?n[1]:t}function $e(t){let e=Nt(t);return Ve.get(e)}function $r(t){return $e(t)?.wgslBuiltin}function Ot(t){let e=t.match(/_v([234])f32(?:_v)?$/);return e?parseInt(e[1],10):4}function We(t){return/_v[234]f32(?:_v)?$/.test(t)}function Fr(t,e){let n=$e(t);if(!n)return!1;let s=["M0","M1","M2"],i=s.indexOf(n.level),r=s.indexOf(e);return i<=r}function Br(t){let e=["M0","M1","M2"],n=e.indexOf(t);return Array.from(Ve.values()).filter(s=>e.indexOf(s.level)<=n)}function Mr(t,e,n){let s=$e(t);if(!s)return`Unknown math intrinsic: ${t}`;if(We(t)){let r=s.wasmParams.map(c=>c==="f32"&&s.supportsVector?"v128":c),o=s.wasmResults.map(c=>c==="f32"&&s.supportsVector?"v128":c);if(e.length!==r.length)return`${t}: expected ${r.length} parameters, got ${e.length}`;if(n.length!==o.length)return`${t}: expected ${o.length} results, got ${n.length}`;for(let c=0;c<e.length;c++)if(e[c]!==r[c])return`${t}: parameter ${c} expected ${r[c]}, got ${e[c]}`;for(let c=0;c<n.length;c++)if(n[c]!==o[c])return`${t}: result ${c} expected ${o[c]}, got ${n[c]}`}else{if(e.length!==s.wasmParams.length)return`${t}: expected ${s.wasmParams.length} parameters, got ${e.length}`;if(n.length!==s.wasmResults.length)return`${t}: expected ${s.wasmResults.length} results, got ${n.length}`;for(let r=0;r<e.length;r++)if(e[r]!==s.wasmParams[r])return`${t}: parameter ${r} expected ${s.wasmParams[r]}, got ${e[r]}`;for(let r=0;r<n.length;r++)if(n[r]!==s.wasmResults[r])return`${t}: result ${r} expected ${s.wasmResults[r]}, got ${n[r]}`}}function Ge(t,e,n){let s=t.opcode;if(s.startsWith("i64.load")){ds(t,e,n);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=t.immediates[1],l=t.args[0];if(u!==0){let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[u]});let y=n.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.add",args:[l,S]}),l=y}let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=n.newU32Var();if(e.push({type:"instr",id:f,opcode:"i32.shr_u",args:[l,d]}),i){e.push({type:"instr",id:t.id,opcode:"wgsl.load_f32",args:[f]});return}let p=r||o,g=p?n.newVar("i32"):t.id;if(e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[f]}),!!p&&(r||o)){let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[3]});let y=n.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.and",args:[l,S]});let k=n.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.const",args:[],immediates:[8]});let h=n.newVar("i32");e.push({type:"instr",id:h,opcode:"i32.mul",args:[y,k]});let b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shr_u",args:[g,h]});let x=r?8:16,I=r?255:65535,V=n.newVar("i32");e.push({type:"instr",id:V,opcode:"i32.const",args:[],immediates:[I]});let O=c?n.newVar("i32"):t.id;if(e.push({type:"instr",id:O,opcode:"i32.and",args:[b,V]}),c){let U=32-x,N=n.newVar("i32");e.push({type:"instr",id:N,opcode:"i32.const",args:[],immediates:[U]});let W=n.newVar("i32");e.push({type:"instr",id:W,opcode:"i32.shl",args:[O,N]}),e.push({type:"instr",id:t.id,opcode:"i32.shr_s",args:[W,N]})}}}function ds(t,e,n){let s=t.opcode,i=t.immediates[1],r=t.args[0];if(t.id!==void 0&&n.changeVarType(t.id,"i32"),i!==0){let u=n.newVar("i32");e.push({type:"instr",id:u,opcode:"i32.const",args:[],immediates:[i]});let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.add",args:[r,u]}),r=l}let o=n.newVar("i32");e.push({type:"instr",id:o,opcode:"i32.const",args:[],immediates:[2]});let c=n.newU32Var();if(e.push({type:"instr",id:c,opcode:"i32.shr_u",args:[r,o]}),s==="i64.load"||s==="i64.load32_s"||s==="i64.load32_u")e.push({type:"instr",id:t.id,opcode:"wgsl.load_i32",args:[c]});else if(s==="i64.load8_s"||s==="i64.load8_u"){let u=n.newVar("i32");e.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=n.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[255]});let y=s==="i64.load8_s",k=y?n.newVar("i32"):t.id;if(e.push({type:"instr",id:k,opcode:"i32.and",args:[g,S]}),y){let h=n.newVar("i32");e.push({type:"instr",id:h,opcode:"i32.const",args:[],immediates:[24]});let b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shl",args:[k,h]}),e.push({type:"instr",id:t.id,opcode:"i32.shr_s",args:[b,h]})}}else if(s==="i64.load16_s"||s==="i64.load16_u"){let u=n.newVar("i32");e.push({type:"instr",id:u,opcode:"wgsl.load_i32",args:[c]});let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=n.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.shr_u",args:[u,p]});let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[65535]});let y=s==="i64.load16_s",k=y?n.newVar("i32"):t.id;if(e.push({type:"instr",id:k,opcode:"i32.and",args:[g,S]}),y){let h=n.newVar("i32");e.push({type:"instr",id:h,opcode:"i32.const",args:[],immediates:[16]});let b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.shl",args:[k,h]}),e.push({type:"instr",id:t.id,opcode:"i32.shr_s",args:[b,h]})}}}function qe(t,e,n){let s=t.opcode;if(s.startsWith("i64.store")){fs(t,e,n);return}let i=s==="f32.store",r=s==="i32.store8",o=s==="i32.store16",c=t.immediates[1],u=t.args[0],l=t.args[1];if(c!==0){let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[c]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.add",args:[u,p]}),u=g}let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.const",args:[],immediates:[2]});let f=n.newU32Var();if(e.push({type:"instr",id:f,opcode:"i32.shr_u",args:[u,d]}),r||o){let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.const",args:[],immediates:[3]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"i32.and",args:[u,p]});let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[8]});let y=n.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.mul",args:[g,S]});let k=n.newVar("i32");e.push({type:"instr",id:k,opcode:"wgsl.load_i32",args:[f]});let h=r?255:65535,b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.const",args:[],immediates:[h]});let x=n.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.shl",args:[b,y]});let I=n.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.const",args:[],immediates:[-1]});let V=n.newVar("i32");e.push({type:"instr",id:V,opcode:"i32.xor",args:[x,I]});let O=n.newVar("i32");e.push({type:"instr",id:O,opcode:"i32.and",args:[k,V]});let U=n.newVar("i32");e.push({type:"instr",id:U,opcode:"i32.and",args:[l,b]});let N=n.newVar("i32");e.push({type:"instr",id:N,opcode:"i32.shl",args:[U,y]});let W=n.newVar("i32");e.push({type:"instr",id:W,opcode:"i32.or",args:[O,N]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[f,W]})}else i?e.push({type:"instr",opcode:"wgsl.store_f32",args:[f,l]}):e.push({type:"instr",opcode:"wgsl.store_i32",args:[f,l]})}function fs(t,e,n){let s=t.opcode,i=t.immediates[1],r=t.args[0],o=t.args[1];if(i!==0){let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[i]});let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.add",args:[r,l]}),r=d}let c=n.newVar("i32");e.push({type:"instr",id:c,opcode:"i32.const",args:[],immediates:[2]});let u=n.newU32Var();if(e.push({type:"instr",id:u,opcode:"i32.shr_u",args:[r,c]}),s==="i64.store"||s==="i64.store32")e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,o]});else if(s==="i64.store8"){let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=n.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[255]});let y=n.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.shl",args:[S,p]});let k=n.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.const",args:[],immediates:[-1]});let h=n.newVar("i32");e.push({type:"instr",id:h,opcode:"i32.xor",args:[y,k]});let b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.and",args:[g,h]});let x=n.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.and",args:[o,S]});let I=n.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.shl",args:[x,p]});let V=n.newVar("i32");e.push({type:"instr",id:V,opcode:"i32.or",args:[b,I]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,V]})}else if(s==="i64.store16"){let l=n.newVar("i32");e.push({type:"instr",id:l,opcode:"i32.const",args:[],immediates:[3]});let d=n.newVar("i32");e.push({type:"instr",id:d,opcode:"i32.and",args:[r,l]});let f=n.newVar("i32");e.push({type:"instr",id:f,opcode:"i32.const",args:[],immediates:[8]});let p=n.newVar("i32");e.push({type:"instr",id:p,opcode:"i32.mul",args:[d,f]});let g=n.newVar("i32");e.push({type:"instr",id:g,opcode:"wgsl.load_i32",args:[u]});let S=n.newVar("i32");e.push({type:"instr",id:S,opcode:"i32.const",args:[],immediates:[65535]});let y=n.newVar("i32");e.push({type:"instr",id:y,opcode:"i32.shl",args:[S,p]});let k=n.newVar("i32");e.push({type:"instr",id:k,opcode:"i32.const",args:[],immediates:[-1]});let h=n.newVar("i32");e.push({type:"instr",id:h,opcode:"i32.xor",args:[y,k]});let b=n.newVar("i32");e.push({type:"instr",id:b,opcode:"i32.and",args:[g,h]});let x=n.newVar("i32");e.push({type:"instr",id:x,opcode:"i32.and",args:[o,S]});let I=n.newVar("i32");e.push({type:"instr",id:I,opcode:"i32.shl",args:[x,p]});let V=n.newVar("i32");e.push({type:"instr",id:V,opcode:"i32.or",args:[b,I]}),e.push({type:"instr",opcode:"wgsl.store_i32",args:[u,V]})}}function Pt(t){let e=t.functions.map(n=>ps(n));return{types:t.types,functions:e,globals:t.globals,memories:t.memories,data:t.data,exports:t.exports,imports:t.imports}}function ps(t){let n=new He(t).process(t.body);return{...t,body:n}}var He=class{func;nextVarId;constructor(e){this.func=e;let n=0;for(let s of e.vars.keys())s>n&&(n=s);this.nextVarId=n+1}newVar(e){let n=this.nextVarId++;return this.func.vars.set(n,{id:n,type:e}),n}newU32Var(){let e=this.nextVarId++;return this.func.vars.set(e,{id:e,type:"i32",emitAsU32:!0}),e}changeVarType(e,n){this.func.vars.get(e)&&this.func.vars.set(e,{id:e,type:n})}process(e){switch(e.kind){case"block":return{...e,children:e.children.map(n=>this.process(n))};case"loop":return{...e,body:this.process(e.body)};case"parallel_loop":return{...e,body:this.process(e.body),epilogue:e.epilogue?this.process(e.epilogue):void 0};case"if":return{...e,thenBranch:this.process(e.thenBranch),elseBranch:e.elseBranch?this.process(e.elseBranch):void 0};case"simple":return{...e,instructions:this.lowerInstructions(e.instructions)};default:return e}}lowerInstructions(e){let n=[];for(let s of e)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":Ge(s,n,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":qe(s,n,this);break;case"memory.size":this.lowerMemorySize(s,n);break;case"memory.grow":n.push(s);break;default:n.push(s)}return n}lowerMemorySize(e,n){let s=this.newVar("i32");n.push({type:"instr",id:s,opcode:"wgsl.buffer_length",args:[]});let i=this.newVar("i32");n.push({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[14]}),n.push({type:"instr",id:e.id,opcode:"i32.shr_u",args:[s,i]})}};function Lt(t){let e=t.functions.map(n=>ms(n));return{...t,functions:e}}function ms(t){let e=new je(t);if(t.inlinedExpressionMap)for(let[r,o]of t.inlinedExpressionMap)e.collectConstantFromInstruction(o);e.collectConstants(t.body);let n=e.optimize(t.body),s=new Map(t.vars);for(let[r,o]of e.newVars)s.set(r,o);let i=new Map(t.inlinedExpressionMap||[]);for(let[r,o]of e.constantValues)i.has(r)||i.set(r,{type:"instr",id:r,opcode:"i32.const",args:[],immediates:[o]});return{...t,body:n,vars:s,inlinedExpressionMap:i}}var je=class{func;constantValues=new Map;constantVarCache=new Map;usedVars=new Set;newVars=new Map;nextVarId;instructionsToRemove=new Set;replacementMap=new Map;constructor(e){this.func=e;let n=0;for(let s of e.vars.keys())s>n&&(n=s);this.nextVarId=n+1}collectConstants(e){switch(e.kind){case"block":for(let n of e.children)this.collectConstants(n);break;case"loop":this.collectConstants(e.body);break;case"parallel_loop":this.collectConstants(e.body),e.epilogue&&this.collectConstants(e.epilogue);break;case"if":this.collectConstants(e.thenBranch),e.elseBranch&&this.collectConstants(e.elseBranch);break;case"simple":for(let n of e.instructions)this.collectConstantFromInstruction(n);break}}collectConstantFromInstruction(e){if(e.id!==void 0){if(e.opcode==="i32.const"&&e.immediates&&e.immediates.length>0){let n=e.immediates[0];this.constantValues.set(e.id,n);let s=`i32:${n}`,i=this.constantVarCache.get(s);i!==void 0?(this.replacementMap.set(e.id,i),this.instructionsToRemove.add(e.id)):this.constantVarCache.set(s,e.id)}if(e.opcode==="i32.shr_u"||e.opcode==="i32.shr_s"){let n=e.args;if(n&&n.length>=2){let s=this.getReplacement(n[0]),i=this.getReplacement(n[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=e.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);this.constantValues.set(e.id,c)}}}}}getReplacement(e){let n=e;for(;this.replacementMap.has(n);)n=this.replacementMap.get(n);return n}updateArgs(e){return e.map(n=>this.getReplacement(n))}optimize(e){switch(e.kind){case"block":return{...e,children:e.children.map(n=>this.optimize(n))};case"loop":return{...e,body:this.optimize(e.body)};case"parallel_loop":return{...e,body:this.optimize(e.body),epilogue:e.epilogue?this.optimize(e.epilogue):void 0};case"if":{let n=this.getReplacement(e.condition);return{...e,condition:n,thenBranch:this.optimize(e.thenBranch),elseBranch:e.elseBranch?this.optimize(e.elseBranch):void 0}}case"simple":return{...e,instructions:this.optimizeInstructions(e.instructions)};case"return":{if(e.value!==void 0){let n=this.getReplacement(e.value);return{...e,value:n}}return e}default:return e}}optimizeInstructions(e){let n=[];for(let s of e){if(s.id!==void 0&&this.instructionsToRemove.has(s.id))continue;let i=this.tryConstantFold(s);if(i){n.push(i);continue}let r={...s,args:this.updateArgs(s.args)};n.push(r)}return n}tryConstantFold(e){if(e.id===void 0)return null;if(e.opcode==="i32.shr_u"||e.opcode==="i32.shr_s"){let n=e.args;if(n&&n.length>=2){let s=this.getReplacement(n[0]),i=this.getReplacement(n[1]),r=this.constantValues.get(s),o=this.constantValues.get(i);if(r!==void 0&&o!==void 0){let c=e.opcode==="i32.shr_u"?r>>>(o&31):r>>(o&31);return{type:"instr",id:e.id,opcode:"i32.const",args:[],immediates:[c]}}}}return null}};function Fe(){return{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function hs(t){let e=Fe(),n=_s(t);if(!n)return{module:t,dispatchInfo:e};let s=gs(n,t);if(s.parallelized){e=s.dispatchInfo;let i=t.functions.map(r=>r.index===n.index?s.func:r);return{module:{...t,functions:i},dispatchInfo:e}}return{module:t,dispatchInfo:e}}function _s(t){let e=t.exports.find(n=>n.name==="main"&&n.kind==="func");return e?t.functions.find(n=>n.index===e.index)??null:t.functions[0]??null}function gs(t,e){let n={func:t,parallelized:!1,dispatchInfo:Fe()},s=bs(t.body,t,e);if(!s)return n;let i=vs(t.body,s,t),r=64,o=s.upperBound;return{func:{...t,body:i,parallelLoopInfo:s},parallelized:!0,dispatchInfo:{workItemsX:o,workItemsY:1,workItemsZ:1,workgroupSizeX:r,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!0}}}function bs(t,e,n){let s=Gt(t,[],e,n);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 Gt(t,e,n,s){let i=[];if(t.kind==="block"){let r=[...e];for(let o of t.children){if(o.kind==="loop"){let c=Ut(o,r,n,s);c&&i.push(c)}o.kind==="block"&&i.push(...Gt(o,r,n,s)),r.push(o)}}else if(t.kind==="loop"){let r=Ut(t,e,n,s);r&&i.push(r)}return i}function Ut(t,e,n,s){let i=t.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=xs(r.condition,n,s);if(!o||!Ze(r.thenBranch,o.localIndex))return null;let u=new Set;if(ae(t.body,u),u.delete(o.localIndex),u.size>0){let l=new Set;ce(n.body,t,n.inlinedExpressionMap,l,new Set);for(let d of u)if(l.has(d))return null}return{loopLocalIndex:o.localIndex,upperBound:o.upperBound}}function ae(t,e){switch(t.kind){case"simple":for(let n of t.instructions)if(n.opcode==="local.set"||n.opcode==="local.tee"){let s=n.immediates?.[0];typeof s=="number"&&e.add(s)}return;case"block":for(let n of t.children)ae(n,e);return;case"loop":ae(t.body,e);return;case"parallel_loop":ae(t.body,e),t.epilogue&&ae(t.epilogue,e);return;case"if":ae(t.thenBranch,e),t.elseBranch&&ae(t.elseBranch,e);return;default:return}}function ce(t,e,n,s,i,r="before"){if(t===e)return"after";switch(t.kind){case"simple":if(r==="after")for(let o of t.instructions)qt(o,n,s,i);return r;case"block":for(let o of t.children)r=ce(o,e,n,s,i,r);return r;case"loop":return ce(t.body,e,n,s,i,r);case"parallel_loop":{let o=ce(t.body,e,n,s,i,r);return t.epilogue&&(o=ce(t.epilogue,e,n,s,i,o)),o}case"if":{r==="after"&&Ye(t.condition,n,s,i);let o=ce(t.thenBranch,e,n,s,i,r),c=t.elseBranch?ce(t.elseBranch,e,n,s,i,r):r;return o==="after"||c==="after"?"after":r}case"return":return r==="after"&&t.value!==void 0&&Ye(t.value,n,s,i),r;default:return r}}function qt(t,e,n,s){if(t.opcode==="local.get"||t.opcode==="local.tee"){let i=t.immediates?.[0];typeof i=="number"&&n.add(i)}for(let i of t.args)Ye(i,e,n,s)}function Ye(t,e,n,s){if(s.has(t))return;s.add(t);let i=e?.get(t);i&&qt(i,e,n,s)}function se(t,e){if(t.kind==="simple"){for(let n of t.instructions)if(n.id===e)return n}else if(t.kind==="block")for(let n of t.children){let s=se(n,e);if(s)return s}else{if(t.kind==="loop")return se(t.body,e);if(t.kind==="parallel_loop"){let n=se(t.body,e);if(n)return n;if(t.epilogue)return se(t.epilogue,e)}else if(t.kind==="if"){let n=se(t.thenBranch,e);if(n)return n;if(t.elseBranch)return se(t.elseBranch,e)}}return null}function xs(t,e,n){let s=e.inlinedExpressionMap?.get(t);if(!s||s.opcode!=="i32.lt_s"&&s.opcode!=="i32.lt_u")return null;let i=s.args[0],r=null,o=e.inlinedExpressionMap?.get(i);if(o&&o.opcode==="local.get")r=o.immediates?.[0];else{let l=se(e.body,i);l&&l.opcode==="local.get"&&(r=l.immediates?.[0])}if(r===null)return null;let c=s.args[1],u=Xe(c,e,n);return u===null||u<=0?null:{localIndex:r,upperBound:u}}function Xe(t,e,n){let s=e.inlinedExpressionMap?.get(t)??se(e.body,t);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=n.globals[i];return r&&r.kind==="definition"&&r.initValue!==void 0&&!Ss(i,n)&&typeof r.initValue=="number"?r.initValue:null}if(s.args&&s.args.length===2){let i=Xe(s.args[0],e,n);if(i===null)return null;let r=Xe(s.args[1],e,n);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 Ss(t,e){for(let n of e.functions)if(he(t,n.body))return!0;return!1}function he(t,e){switch(e.kind){case"simple":for(let n of e.instructions)if(n.opcode==="global.set"&&n.immediates?.[0]===t)return!0;return!1;case"block":return e.children.some(n=>he(t,n));case"loop":case"parallel_loop":return he(t,e.body)||(e.kind==="parallel_loop"&&e.epilogue?he(t,e.epilogue):!1);case"if":return he(t,e.thenBranch)||(e.elseBranch?he(t,e.elseBranch):!1);default:return!1}}function Ze(t,e){if(t.kind==="simple"){for(let n of t.instructions)if(ys(n,e))return!0}else if(t.kind==="block"){for(let n of t.children)if(Ze(n,e))return!0}return!1}function ys(t,e){return t.opcode==="local.set"&&t.immediates?.[0]===e}function vs(t,e,n){return Ht(t,{loopInfo:e,transformed:!1},!0)}function Ht(t,e,n){switch(t.kind){case"block":{let s=[];for(let i=0;i<t.children.length;i++){let r=t.children[i];if(r.kind==="loop"){if(!e.transformed&&n&&zt(r,e.loopInfo)){e.transformed=!0;let o=t.children.slice(i+1),c;o.length>0&&(c=o.length===1?o[0]:{kind:"block",children:o}),s.push(Is(r,e.loopInfo,c));break}s.push(r);continue}if(r.kind==="block"&&n&&!e.transformed){if(s.push(Ht(r,e,!0)),e.transformed){let o=t.children.slice(i+1);if(o.length>0){let c=s[s.length-1];jt(c,o)}break}}else s.push(r)}return{...t,children:s}}case"loop":return!e.transformed&&n&&zt(t,e.loopInfo)?(e.transformed=!0,ks(t,e.loopInfo)):t;case"if":return t;default:return t}}function Is(t,e,n){let s=Yt(t.body,e.loopLocalIndex);return{kind:"parallel_loop",loopInfo:e,body:s,epilogue:n}}function jt(t,e){if(t.kind==="parallel_loop"){let n=t.epilogue,s=[];n&&(n.kind==="block"?s.push(...n.children):s.push(n)),s.push(...e),t.epilogue=s.length===1?s[0]:{kind:"block",children:s};return}if(t.kind==="block"){for(let n of t.children)if(n.kind==="parallel_loop"||n.kind==="block"){jt(n,e);return}}}function zt(t,e){let n=t.body,s=null;if(n.kind==="block"){for(let i of n.children)if(i.kind==="if"){s=i;break}}else n.kind==="if"&&(s=n);return!s||s.kind!=="if"?!1:Ze(s.thenBranch,e.loopLocalIndex)}function ks(t,e){let n=Yt(t.body,e.loopLocalIndex);return{kind:"parallel_loop",loopInfo:e,body:n}}function Yt(t,e){if(t.kind==="block"&&t.children.length>0){let n=t.children[0];if(n.kind==="if")return Wt(n.thenBranch,e)}return t.kind==="if"?Wt(t.thenBranch,e):t}function Wt(t,e){if(t.kind==="block"){let s=t.children.filter(i=>!(i.kind==="block"&&i.children[i.children.length-1]?.kind==="continue"||i.kind==="continue")).map(i=>_e(i,e));return{...t,children:s}}return _e(t,e)}function _e(t,e){if(t.kind==="simple"){let n=t.instructions.filter(s=>!(s.opcode==="local.set"&&s.immediates?.[0]===e));return{...t,instructions:n}}return t.kind==="block"?{...t,children:t.children.map(n=>_e(n,e))}:t.kind==="if"?{...t,thenBranch:_e(t.thenBranch,e),elseBranch:t.elseBranch?_e(t.elseBranch,e):void 0}:t.kind==="loop"?{...t,body:_e(t.body,e)}:t}function ws(t){return t===!0?t="normal":t===!1&&(t="none"),{level:t,includeWasmOffsets:t==="detailed"||t==="verbose",includeSemanticInfo:t!=="none"&&t!=="minimal",includeIRInfo:t==="verbose",includeLanguageTag:t!=="none"}}function Es(t){let e=Xt(t,"name");if(!e)return null;let n={functionNames:new Map,localNames:new Map,globalNames:new Map,labelNames:new Map},s=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(;i<e.length;){let[r,o]=Y(e,i);i+=o;let[c,u]=Y(e,i);i+=u;let l=i+c;switch(r){case 0:{let[d,f]=ie(e,i);n.moduleName=d,i+=f}break;case 1:{let[d,f]=Y(e,i);i+=f;for(let p=0;p<d;p++){let[g,S]=Y(e,i);i+=S;let[y,k]=ie(e,i);i+=k,n.functionNames.set(g,y)}}break;case 2:{let[d,f]=Y(e,i);i+=f;for(let p=0;p<d;p++){let[g,S]=Y(e,i);i+=S;let[y,k]=Y(e,i);i+=k;let h=new Map;for(let b=0;b<y;b++){let[x,I]=Y(e,i);i+=I;let[V,O]=ie(e,i);i+=O,h.set(x,V)}n.localNames.set(g,h)}}break;case 7:{let[d,f]=Y(e,i);i+=f;for(let p=0;p<d;p++){let[g,S]=Y(e,i);i+=S;let[y,k]=ie(e,i);i+=k,n.globalNames.set(g,y)}}break;default:i=l;break}i<l&&(i=l)}return n}function Rs(t){let e=Xt(t,"producers");if(!e)return null;let n={},s=0,[i,r]=Y(e,s);s+=r;for(let o=0;o<i;o++){let[c,u]=ie(e,s);s+=u;let[l,d]=Y(e,s);s+=d;let f=[];for(let p=0;p<l;p++){let[g,S]=ie(e,s);s+=S;let[y,k]=ie(e,s);s+=k,f.push(y?`${g} ${y}`:g)}switch(c){case"language":n.languages=f;break;case"processed-by":n.processedBy=f;break;case"sdk":n.sdks=f;break}}return n}function Xt(t,e){if(t.length<8||(t[0]<<0|t[1]<<8|t[2]<<16|t[3]<<24)!==1836278016)return null;let s=8;for(;s<t.length;){let i=t[s++],[r,o]=Y(t,s);s+=o;let c=s+r;if(i===0){let[u,l]=ie(t,s);if(u===e)return t.subarray(s+l,c)}s=c}return null}function Y(t,e){let n=0,s=0,i=0;for(;;){let r=t[e+i];if(i++,n|=(r&127)<<s,(r&128)===0)break;s+=7}return[n,i]}function ie(t,e){let[n,s]=Y(t,e),i=t.subarray(e+s,e+s+n);return[new TextDecoder().decode(i),s+n]}function Vs(t,e,n){if(n?.languages)for(let s of n.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(n?.processedBy)for(let s of n.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(e)for(let s of e.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 e&&e.functionNames.size>0&&!n?"wat":"unknown"}function $s(t){let e=Es(t),n=Rs(t),s=Vs(t,e,n),i="low";return e&&(e.functionNames.size>0&&e.localNames.size>0?i="high":e.functionNames.size>0&&(i="medium")),{language:s,quality:i,functionNames:e?.functionNames??new Map,localNames:e?.localNames??new Map,globalNames:e?.globalNames??new Map,blockLabels:e?.labelNames??new Map,producers:n??void 0}}var Ke=class{options;debugInfo;constructor(e,n){this.options=n,this.debugInfo=$s(e)}getLanguage(){return this.debugInfo.language}getQuality(){return this.debugInfo.quality}generateHeaderComment(){if(this.options.level==="none")return null;let e=[];if(this.options.includeLanguageTag){let n=this.formatLanguageName(this.debugInfo.language);e.push(`Source Language: ${n}`)}return(this.options.level==="detailed"||this.options.level==="verbose")&&(e.push(`Debug Info: ${this.debugInfo.quality}`),this.debugInfo.producers?.processedBy&&e.push(`Processed By: ${this.debugInfo.producers.processedBy.join(", ")}`)),e.length>0?`// ${e.join(" | ")}`:null}commentForFunction(e,n){if(this.options.level==="none")return null;let s=[],i=this.debugInfo.functionNames.get(e),r=n||i||`func_${e}`;return s.push(`Function ${e}: "${r}"`),i&&i!==n&&i!==r&&s.push(`(debug: ${i})`),`// ${s.join(" ")}`}commentForVariable(e,n,s){if(this.options.level==="none"||this.options.level==="minimal")return null;let r=this.debugInfo.localNames.get(e)?.get(n);return r?` // ${r}${s?" (param)":""}`:null}commentForGlobal(e){if(this.options.level==="none"||this.options.level==="minimal")return null;let n=this.debugInfo.globalNames.get(e);return n?` // ${n}`:null}commentForInstruction(e,n){if(this.options.level==="none"||this.options.level==="minimal")return null;let s=[];if(s.push(`[WAT] ${e.opcode}`),e.opcode==="local.get"||e.opcode==="local.set"||e.opcode==="local.tee"){let i=e.immediates?.[0];if(i!==void 0){let o=this.debugInfo.localNames.get(n)?.get(i);o&&s.push(`(${o})`)}}if(e.opcode==="global.get"||e.opcode==="global.set"){let i=e.immediates?.[0];if(i!==void 0){let r=this.debugInfo.globalNames.get(i);r&&s.push(`(${r})`)}}return this.options.includeIRInfo&&e.id!==void 0&&s.push(`[IR] v${e.id}`),`// ${s.join(" ")}`}commentForStatement(e,n,s=0){if(this.options.level==="none")return null;let i=[];switch(e.kind){case"loop":i.push("[LOOP]"),e.label&&i.push(`${e.label}`);break;case"parallel_loop":i.push("[PARALLEL]");break;case"block":if(e.label)i.push(`[BLOCK] ${e.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(e){return this.options.level!=="detailed"&&this.options.level!=="verbose"?null:e?`// End: ${e}`:null}formatLanguageName(e){switch(e){case"wat":return"WAT (WebAssembly Text)";case"assemblyscript":return"AssemblyScript";case"c":return"C/C++";case"rust":return"Rust";default:return"Unknown"}}};function Zt(t,e){if(!e||e==="none")return null;let n=ws(e);return new Ke(t,n)}var C={"||":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"<":9,">":9,"<=":9,">=":9,"<<":10,">>":10,"+":11,"-":11,"*":12,"/":12,"%":12};var Kt={"+":1,"-":1,"*":1,"/":1,"%":1,"&":2,"|":2,"^":2,"<<":3,">>":3,"<":4,">":4,"<=":4,">=":4,"==":5,"!=":5,"&&":6,"||":6};function Fs(t,e,n,s){return t===0||e===0?!1:t===e?!!(t===2&&n&&s&&n!==s||t===3&&n&&s):t===1&&e===2||t===2&&e===1||t===1&&e===3||t===3&&e===1||t===2&&e===3||t===3&&e===2||t===4&&e===5||t===5&&e===4}var _=15;function Qt(t,e,n,s,i){if(s&&i){let r=Kt[s]??0,o=Kt[i]??0;if(Fs(r,o,s,i))return!0}return t>=_||t>e?!1:t<e?!0:n}function L(t,e,n=!1,s){return Qt(t.precedence,e,n,t.operator,s)?`(${t.code})`:t.code}function ge(t){switch(t){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 Qe(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;default:return}}function Je(t){for(let[e,n]of t.blocks)if(!(n.preds.length<2))for(let s=0;s<n.instructions.length;s++){let i=n.instructions[s];if(i.args&&i.args.includes(-1)){let r=Jt(t,e,n.preds);r!==-1&&(i.args=i.args.map(o=>o===-1?r:o))}}}function Jt(t,e,n){let s=[];for(let i of n){let r=t.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 et(t,e,n){let s=t.popStack(),i=t.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"]}[e];if(!u)throw new Error(`Unknown binary opcode: 0x${e.toString(16)}`);[o,r]=u;let l=t.newVar(r);t.addInstruction({type:"instr",id:l,opcode:o,args:[i,s],immediates:[]}),t.pushStack(l)}function tt(t,e,n){let s=t.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"]}[e];if(!r)throw new Error(`Unknown unary opcode: 0x${e.toString(16)}`);let[o,c]=r,u=t.newVar(c);t.addInstruction({type:"instr",id:u,opcode:o,args:[s],immediates:[]}),t.pushStack(u)}function nt(t,e,n){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[e];if(r){let[c,u]=r,l=t.popStack(),d=t.newVar(u);t.addInstruction({type:"instr",id:d,opcode:c,args:[l],immediates:n}),t.pushStack(d);return}let o=i[e];if(o){let c=t.popStack(),u=t.popStack();t.addInstruction({type:"instr",opcode:o,args:[u,c],immediates:n});return}if(e===a.memory_size){let c=t.newVar("i32");t.addInstruction({type:"instr",id:c,opcode:"memory.size",args:[],immediates:n}),t.pushStack(c);return}throw new Error(`Unknown memory opcode: 0x${e.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 st(t,e,n){if(e===m.v128_load){let f=t.popStack(),p=t.newVar("v128");t.addInstruction({type:"instr",id:p,opcode:"v128.load",args:[f],immediates:n}),t.pushStack(p);return}if(e===m.v128_store){let f=t.popStack(),p=t.popStack();t.addInstruction({type:"instr",opcode:"v128.store",args:[p,f],immediates:n});return}if(e===m.v128_const){let f=t.newVar("v128");t.addInstruction({type:"instr",id:f,opcode:"v128.const",args:[],immediates:n}),t.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[e]){let f=t.popStack(),p=t.newVar(s[e].resultType);t.addInstruction({type:"instr",id:p,opcode:s[e].opcode,args:[f],immediates:n}),t.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[e]){let f=t.popStack(),p=t.popStack(),g=t.newVar("v128");t.addInstruction({type:"instr",id:g,opcode:i[e],args:[p,f],immediates:n}),t.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[e]){let f=t.popStack(),p=t.newVar("v128");t.addInstruction({type:"instr",id:p,opcode:r[e],args:[f],immediates:[]}),t.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[e]){let f=t.popStack(),p=t.newVar("v128");t.addInstruction({type:"instr",id:p,opcode:o[e],args:[f],immediates:[]}),t.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[e]){let f=t.popStack(),p=t.popStack(),g=t.newVar("v128");t.addInstruction({type:"instr",id:g,opcode:c[e],args:[p,f],immediates:[]}),t.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[e]){let f=t.popStack(),p=t.popStack(),g=t.newVar("v128");t.addInstruction({type:"instr",id:g,opcode:u[e],args:[p,f],immediates:[]}),t.pushStack(g);return}if(e===m.v128_bitselect){let f=t.popStack(),p=t.popStack(),g=t.popStack(),S=t.newVar("v128");t.addInstruction({type:"instr",id:S,opcode:"v128.bitselect",args:[g,p,f],immediates:[]}),t.pushStack(S);return}if(e===m.v128_any_true){let f=t.popStack(),p=t.newVar("i32");t.addInstruction({type:"instr",id:p,opcode:"v128.any_true",args:[f],immediates:[]}),t.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[e]){let f=t.popStack(),p=t.newVar("i32");t.addInstruction({type:"instr",id:p,opcode:l[e],args:[f],immediates:[]}),t.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[e]){let f=t.popStack(),p=t.newVar("i32");t.addInstruction({type:"instr",id:p,opcode:d[e],args:[f],immediates:[]}),t.pushStack(p);return}if(e===m.i8x16_shuffle){let f=t.popStack(),p=t.popStack(),g=t.newVar("v128");t.addInstruction({type:"instr",id:g,opcode:"i8x16.shuffle",args:[p,f],immediates:n}),t.pushStack(g);return}if(e===m.i8x16_swizzle){let f=t.popStack(),p=t.popStack(),g=t.newVar("v128");t.addInstruction({type:"instr",id:g,opcode:"i8x16.swizzle",args:[p,f],immediates:[]}),t.pushStack(g);return}throw new Error(`Unknown SIMD opcode: 0x${e.toString(16)}`)}function it(t,e){let n=e.opcode;if(Ms(n))return et(t,n,e.immediates),!0;if(As(n))return tt(t,n,e.immediates),!0;if(Cs(n))return nt(t,n,e.immediates),!0;if(Ds(n))try{return st(t,n,e.immediates),!0}catch{return!1}switch(n){case a.local_get:{let s=e.immediates[0],i=Ts(t,s),r=t.newVar(i);return t.addInstruction({type:"instr",id:r,opcode:"local.get",args:[],immediates:[s]}),t.pushStack(r),!0}case a.local_set:{let s=e.immediates[0],i=t.popStack();return t.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),!0}case a.local_tee:{let s=e.immediates[0],i=t.popStack();return t.addInstruction({type:"instr",opcode:"local.set",args:[i],immediates:[s]}),t.pushStack(i),!0}case a.global_get:{let s=e.immediates[0],r=t.module.globals[s].type,o=t.newVar(r);return t.addInstruction({type:"instr",id:o,opcode:"global.get",args:[],immediates:[s]}),t.pushStack(o),!0}case a.global_set:{let s=e.immediates[0],i=t.popStack();return t.addInstruction({type:"instr",opcode:"global.set",args:[i],immediates:[s]}),!0}}switch(n){case a.i32_const:{let s=e.immediates[0],i=t.newVar("i32");return t.addInstruction({type:"instr",id:i,opcode:"i32.const",args:[],immediates:[s]}),t.pushStack(i),!0}case a.i64_const:{let s=e.immediates[0],i=t.newVar("i64");return t.addInstruction({type:"instr",id:i,opcode:"i64.const",args:[],immediates:[s]}),t.pushStack(i),!0}case a.f32_const:{let s=e.immediates[0],i=t.newVar("f32");return t.addInstruction({type:"instr",id:i,opcode:"f32.const",args:[],immediates:[s]}),t.pushStack(i),!0}case a.f64_const:{let s=e.immediates[0],i=t.newVar("f64");return t.addInstruction({type:"instr",id:i,opcode:"f64.const",args:[],immediates:[s]}),t.pushStack(i),!0}}if(n===a.return){if(t.funcResults.length>0){let s=t.popStack();t.addInstruction({type:"instr",opcode:"return",args:[s],immediates:[],synthetic:!1})}else t.addInstruction({type:"instr",opcode:"return",args:[],immediates:[],synthetic:!1});return!0}return!1}function Ms(t){return t===a.i32_add||t===a.i32_sub||t===a.i32_mul||t===a.i32_div_s||t===a.i32_div_u||t===a.i32_rem_s||t===a.i32_rem_u||t===a.i32_and||t===a.i32_or||t===a.i32_xor||t===a.i32_shl||t===a.i32_shr_s||t===a.i32_shr_u||t===a.i32_rotl||t===a.i32_rotr||t===a.i32_eq||t===a.i32_ne||t===a.i32_lt_s||t===a.i32_lt_u||t===a.i32_le_s||t===a.i32_le_u||t===a.i32_gt_s||t===a.i32_gt_u||t===a.i32_ge_s||t===a.i32_ge_u||t===a.i64_add||t===a.i64_sub||t===a.i64_mul||t===a.i64_div_s||t===a.i64_div_u||t===a.i64_rem_s||t===a.i64_rem_u||t===a.i64_and||t===a.i64_or||t===a.i64_xor||t===a.i64_shl||t===a.i64_shr_s||t===a.i64_shr_u||t===a.i64_rotl||t===a.i64_rotr||t===a.i64_eq||t===a.i64_ne||t===a.i64_lt_s||t===a.i64_lt_u||t===a.i64_le_s||t===a.i64_le_u||t===a.i64_gt_s||t===a.i64_gt_u||t===a.i64_ge_s||t===a.i64_ge_u||t===a.f32_add||t===a.f32_sub||t===a.f32_mul||t===a.f32_div||t===a.f32_min||t===a.f32_max||t===a.f32_copysign||t===a.f32_eq||t===a.f32_ne||t===a.f32_lt||t===a.f32_le||t===a.f32_gt||t===a.f32_ge||t===a.f64_add||t===a.f64_sub||t===a.f64_mul||t===a.f64_div||t===a.f64_min||t===a.f64_max||t===a.f64_copysign||t===a.f64_eq||t===a.f64_ne||t===a.f64_lt||t===a.f64_le||t===a.f64_gt||t===a.f64_ge}function As(t){return t===a.i32_clz||t===a.i32_ctz||t===a.i32_popcnt||t===a.i32_eqz||t===a.i64_clz||t===a.i64_ctz||t===a.i64_popcnt||t===a.i64_eqz||t===a.f32_abs||t===a.f32_neg||t===a.f32_sqrt||t===a.f32_ceil||t===a.f32_floor||t===a.f32_trunc||t===a.f32_nearest||t===a.f64_abs||t===a.f64_neg||t===a.f64_sqrt||t===a.f64_ceil||t===a.f64_floor||t===a.f64_trunc||t===a.f64_nearest||t===a.i32_wrap_i64||t===a.i64_extend_i32_s||t===a.i64_extend_i32_u||t===a.i32_trunc_f32_s||t===a.i32_trunc_f32_u||t===a.i32_trunc_f64_s||t===a.i32_trunc_f64_u||t===a.i64_trunc_f32_s||t===a.i64_trunc_f32_u||t===a.i64_trunc_f64_s||t===a.i64_trunc_f64_u||t===a.f32_convert_i32_s||t===a.f32_convert_i32_u||t===a.f32_convert_i64_s||t===a.f32_convert_i64_u||t===a.f32_demote_f64||t===a.f64_convert_i32_s||t===a.f64_convert_i32_u||t===a.f64_convert_i64_s||t===a.f64_convert_i64_u||t===a.f64_promote_f32||t===a.i32_reinterpret_f32||t===a.i64_reinterpret_f64||t===a.f32_reinterpret_i32||t===a.f64_reinterpret_i64||t===a.i32_trunc_sat_f32_s||t===a.i32_trunc_sat_f32_u||t===a.i32_trunc_sat_f64_s||t===a.i32_trunc_sat_f64_u||t===a.i64_trunc_sat_f32_s||t===a.i64_trunc_sat_f32_u||t===a.i64_trunc_sat_f64_s||t===a.i64_trunc_sat_f64_u}function Cs(t){return t===a.i32_load||t===a.i64_load||t===a.f32_load||t===a.f64_load||t===a.i32_load8_s||t===a.i32_load8_u||t===a.i32_load16_s||t===a.i32_load16_u||t===a.i64_load8_s||t===a.i64_load8_u||t===a.i64_load16_s||t===a.i64_load16_u||t===a.i64_load32_s||t===a.i64_load32_u||t===a.i32_store||t===a.i64_store||t===a.f32_store||t===a.f64_store||t===a.i32_store8||t===a.i32_store16||t===a.i64_store8||t===a.i64_store16||t===a.i64_store32||t===a.memory_size}function Ds(t){return(t&65280)===64768}function Ts(t,e){let n=t.funcParams.length;if(e<n)return t.funcParams[e];{let s=e-n;return t.funcLocals[s]}}function Ce(t,e){if(!t.currentFunc)return;let n=t.currentFunc.inlinedExpressionMap?.get(e);if(n&&n.opcode==="i32.const"&&n.immediates)return n.immediates[0]}function Ns(t){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(t)}function D(t,e){let n=t.resolveVarExpr(e);if(!t.currentFunc)return n;let s=t.currentFunc.inlinedExpressionMap?.get(e);if(s&&Ns(s.opcode)&&!n.code.startsWith("select(0i, 1i,"))return{code:`select(0i, 1i, ${n.code})`,precedence:_};let r=t.currentFunc.vars.get(e)?.type;return!r||r==="i32"?n:r==="f32"?{code:`bitcast<i32>(${n.code})`,precedence:_}:{code:`i32(${n.code})`,precedence:_}}function P(t,e){let n=t.resolveVarExpr(e);if(!t.currentFunc)return n;let i=t.currentFunc.vars.get(e)?.type;return i==="f32"||i==="f64"?n:!i||i==="i32"?{code:`bitcast<f32>(${n.code})`,precedence:_}:{code:`f32(${n.code})`,precedence:_}}function F(t,e){return D(t,e).code}function w(t,e){return P(t,e).code}function rt(t){switch(t){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 ot(t,e,n){let s=t.resolveVar(n);if(!t.currentFunc)return`local_${e} = ${s}`;let i,r=t.currentFunc.params.length;if(e<r)i=t.currentFunc.params[e];else if(t.currentFunc.locals&&e-r<t.currentFunc.locals.length)i=t.currentFunc.locals[e-r];else return`local_${e} = ${s}`;let c=t.currentFunc.vars.get(n)?.type||"i32",u=ge(c),l=ge(i);return u===l?l==="f32"&&c!=="f32"?`local_${e} = f32(${s})`:`local_${e} = ${s}`:u==="i32"&&l==="f32"||u==="f32"&&l==="i32"?`local_${e} = bitcast<${l}>(${s})`:`local_${e} = ${l}(${s})`}function q(t){let e=new Set;switch(t.kind){case"block":for(let n of t.children)for(let s of q(n))e.add(s);break;case"loop":for(let n of q(t.body))e.add(n);break;case"parallel_loop":for(let n of q(t.body))e.add(n);if(t.epilogue)for(let n of q(t.epilogue))e.add(n);break;case"if":for(let n of q(t.thenBranch))e.add(n);if(t.elseBranch)for(let n of q(t.elseBranch))e.add(n);break;case"simple":for(let n of t.instructions)n.id!==void 0&&e.add(n.id);break}return e}function X(t){let e=new Set;switch(t.kind){case"block":for(let n of t.children)for(let s of X(n))e.add(s);break;case"loop":for(let n of X(t.body))e.add(n);break;case"parallel_loop":for(let n of X(t.body))e.add(n);if(t.epilogue)for(let n of X(t.epilogue))e.add(n);break;case"if":e.add(t.condition);for(let n of X(t.thenBranch))e.add(n);if(t.elseBranch)for(let n of X(t.elseBranch))e.add(n);break;case"simple":for(let n of t.instructions)if(n.args)for(let s of n.args)s>=0&&e.add(s);break;case"return":t.value!==void 0&&e.add(t.value);break}return e}function K(t,e,n){switch(t.kind){case"block":{let s=q(t);for(let i of s)e.has(i)&&n.add(i);for(let i of t.children)K(i,e,n);break}case"loop":{let s=q(t.body);for(let i of s)e.has(i)&&n.add(i);K(t.body,e,n);break}case"parallel_loop":{let s=q(t.body);for(let i of s)e.has(i)&&n.add(i);if(K(t.body,e,n),t.epilogue){let i=q(t.epilogue);for(let r of i)e.has(r)&&n.add(r);K(t.epilogue,e,n)}break}case"if":{let s=q(t.thenBranch),i=t.elseBranch?q(t.elseBranch):new Set;for(let d of s)e.has(d)&&n.add(d);for(let d of i)e.has(d)&&n.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(t.thenBranch),c=t.elseBranch?r(t.elseBranch):new Set;for(let d of o)n.add(d);for(let d of c)n.add(d);let u=X(t.thenBranch),l=t.elseBranch?X(t.elseBranch):new Set;K(t.thenBranch,u,n),t.elseBranch&&K(t.elseBranch,l,n);break}case"simple":break}}function be(t,e=!1){switch(t.kind){case"return":case"break":case"continue":return!0;case"block":return t.children.length===0?!1:be(t.children[t.children.length-1],e);case"if":{let n=be(t.thenBranch,e),s=t.elseBranch?be(t.elseBranch,e):!1;return e&&(n||s)?!0:n&&s}case"simple":return t.instructions.length===0?!1:t.instructions.some(n=>n.opcode==="return"||n.opcode==="unreachable");case"loop":default:return!1}}function De(t){switch(t.kind){case"block":return t.children.length===0||t.children.every(e=>De(e));case"simple":return t.instructions.length===0;case"return":case"break":case"continue":case"loop":case"if":return!1;default:return!0}}function xe(t){switch(t.kind){case"return":return!0;case"block":return t.children.length===0?!1:t.children.some(e=>xe(e));case"if":return xe(t.thenBranch)&&(t.elseBranch?xe(t.elseBranch):!1);case"loop":case"break":case"continue":return!1;case"simple":return t.instructions.length===0?!1:t.instructions.some(e=>e.opcode==="return"||e.opcode==="unreachable");default:return!1}}function at(t){let e=new Set;function n(s){switch(s.kind){case"block":for(let i of s.children)n(i);break;case"loop":n(s.body);break;case"parallel_loop":n(s.body),s.epilogue&&n(s.epilogue);break;case"if":n(s.thenBranch),s.elseBranch&&n(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];e.add(r)}break;case"return":case"break":case"continue":break}}return n(t),e}function ct(t){let e=new Map;function n(s){switch(s.kind){case"block":for(let i of s.children)n(i);break;case"loop":n(s.body);break;case"parallel_loop":n(s.body),s.epilogue&&n(s.epilogue);break;case"if":n(s.thenBranch),s.elseBranch&&n(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=e.get(r)||0;e.set(r,o+1)}break;case"return":case"break":case"continue":break}}return n(t),e}function ut(t){function e(n,s=!1){switch(n.kind){case"loop":case"parallel_loop":return e((n.kind==="loop",n.body),!0)?!0:n.kind==="parallel_loop"&&n.epilogue?e(n.epilogue,s):!1;case"block":return n.children.some(c=>e(c,s));case"if":let r=e(n.thenBranch,s),o=n.elseBranch?e(n.elseBranch,s):!1;return r||o;case"simple":return s&&n.instructions.some(c=>c.opcode==="return"&&c.synthetic===!1);case"return":return!1;case"break":case"continue":default:return!1}}return e(t,!1)}function T(t,e,n){let s=C[t];if(s===void 0)return{code:`(${e.code} ${t} ${n.code})`,precedence:_};let i=L(e,s,!1,t),r=L(n,s,!0,t);return{code:`${i} ${t} ${r}`,precedence:s,operator:t}}function lt(t,e,n,s,i){switch(e){case"i32.const":{let r=s[0];return r===-2147483648?{code:"bitcast<i32>(2147483648u)",precedence:_}:{code:`${r}i`,precedence:_}}case"i32.add":return T("+",D(t,n[0]),D(t,n[1]));case"i32.sub":return T("-",D(t,n[0]),D(t,n[1]));case"i32.mul":return T("*",D(t,n[0]),D(t,n[1]));case"i32.div_s":return T("/",D(t,n[0]),D(t,n[1]));case"i32.div_u":return{code:`bitcast<i32>(bitcast<u32>(${F(t,n[0])}) / bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.rem_s":return T("%",D(t,n[0]),D(t,n[1]));case"i32.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${F(t,n[0])}) % bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.and":return T("&",D(t,n[0]),D(t,n[1]));case"i32.or":return T("|",D(t,n[0]),D(t,n[1]));case"i32.xor":return T("^",D(t,n[0]),D(t,n[1]));case"i32.shl":{let r=Ce(t,n[1]);if(r!==void 0&&r>=0&&r<=31){let u=D(t,n[0]);return{code:`${L(u,C["<<"],!1,"<<")} << ${r}u`,precedence:C["<<"],operator:"<<"}}let o=D(t,n[0]);return{code:`${L(o,C["<<"],!1,"<<")} << (bitcast<u32>(${F(t,n[1])}) & 31u)`,precedence:C["<<"],operator:"<<"}}case"i32.shr_s":{let r=Ce(t,n[1]);if(r!==void 0&&r>=0&&r<=31){let u=D(t,n[0]);return{code:`${L(u,C[">>"],!1,">>")} >> ${r}u`,precedence:C[">>"],operator:">>"}}let o=D(t,n[0]);return{code:`${L(o,C[">>"],!1,">>")} >> (bitcast<u32>(${F(t,n[1])}) & 31u)`,precedence:C[">>"],operator:">>"}}case"i32.shr_u":{let r=Ce(t,n[1]),o=D(t,n[0]),u=(i!==void 0?t.currentFunc?.vars.get(i):void 0)?.emitAsU32===!0,d=t.currentFunc?.vars.get(n[0])?.isNonNegative===!0,f=!o.code.startsWith("bitcast<u32>");if(r!==void 0&&r>=0&&r<=31){let g=o.precedence<_?`(${o.code})`:o.code;return u?d?{code:`u32(${g}) >> ${r}u`,precedence:C[">>"],operator:">>"}:{code:`bitcast<u32>(${g}) >> ${r}u`,precedence:C[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${g}) >> ${r}u)`,precedence:_}:f?{code:`bitcast<i32>(bitcast<u32>(${g}) >> ${r}u)`,precedence:_}:{code:`bitcast<i32>(${o.code} >> ${r}u)`,precedence:_}}let p=o.precedence<_?`(${o.code})`:o.code;return u?d?{code:`u32(${p}) >> (bitcast<u32>(${F(t,n[1])}) & 31u)`,precedence:C[">>"],operator:">>"}:{code:`bitcast<u32>(${p}) >> (bitcast<u32>(${F(t,n[1])}) & 31u)`,precedence:C[">>"],operator:">>"}:d?{code:`bitcast<i32>(u32(${p}) >> (bitcast<u32>(${F(t,n[1])}) & 31u))`,precedence:_}:{code:`bitcast<i32>(bitcast<u32>(${p}) >> (bitcast<u32>(${F(t,n[1])}) & 31u))`,precedence:_}}case"i32.rotl":{let r=`bitcast<u32>(${F(t,n[0])})`,o=`(bitcast<u32>(${F(t,n[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} << ${o}) | (${r} >> (32u - ${o}))))`,precedence:_}}case"i32.rotr":{let r=`bitcast<u32>(${F(t,n[0])})`,o=`(bitcast<u32>(${F(t,n[1])}) & 31u)`;return{code:`bitcast<i32>(((${r} >> ${o}) | (${r} << (32u - ${o}))))`,precedence:_}}case"i32.clz":return{code:`countLeadingZeros(${F(t,n[0])})`,precedence:_};case"i32.ctz":return{code:`countTrailingZeros(${F(t,n[0])})`,precedence:_};case"i32.popcnt":return{code:`countOneBits(${F(t,n[0])})`,precedence:_};default:return null}}function en(t,e,n,s,i){let r=lt(t,e,n,s,i);return r===null?null:r.precedence<_?`(${r.code})`:r.code}function dt(t,e,n){let s=(i,r,o)=>{let c=D(t,i),u=C[r];return L(c,u,o,r)};switch(e){case"i32.eq":return{code:`select(0i, 1i, ${s(n[0],"==",!1)} == ${s(n[1],"==",!0)})`,precedence:_};case"i32.ne":return{code:`select(0i, 1i, ${s(n[0],"!=",!1)} != ${s(n[1],"!=",!0)})`,precedence:_};case"i32.lt_s":return{code:`select(0i, 1i, ${s(n[0],"<",!1)} < ${s(n[1],"<",!0)})`,precedence:_};case"i32.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(t,n[0])}) < bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.gt_s":return{code:`select(0i, 1i, ${s(n[0],">",!1)} > ${s(n[1],">",!0)})`,precedence:_};case"i32.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${F(t,n[0])}) > bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.le_s":return{code:`select(0i, 1i, ${s(n[0],"<=",!1)} <= ${s(n[1],"<=",!0)})`,precedence:_};case"i32.le_u":return{code:`select(0i, 1i, bitcast<u32>(${F(t,n[0])}) <= bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.ge_s":return{code:`select(0i, 1i, ${s(n[0],">=",!1)} >= ${s(n[1],">=",!0)})`,precedence:_};case"i32.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${F(t,n[0])}) >= bitcast<u32>(${F(t,n[1])}))`,precedence:_};case"i32.eqz":return{code:`select(0i, 1i, ${s(n[0],"==",!1)} == 0i)`,precedence:_};default:return null}}function tn(t,e,n){let s=dt(t,e,n);return s===null?null:s.precedence<_?`(${s.code})`:s.code}function ft(t,e,n,s){switch(e){case"f32.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}f`,precedence:_}}case"f32.add":return T("+",P(t,n[0]),P(t,n[1]));case"f32.sub":return T("-",P(t,n[0]),P(t,n[1]));case"f32.mul":return T("*",P(t,n[0]),P(t,n[1]));case"f32.div":return T("/",P(t,n[0]),P(t,n[1]));case"f32.abs":return{code:`abs(${w(t,n[0])})`,precedence:_};case"f32.neg":{let i=P(t,n[0]);return{code:`-${L(i,14)}`,precedence:14}}case"f32.ceil":return{code:`ceil(${w(t,n[0])})`,precedence:_};case"f32.floor":return{code:`floor(${w(t,n[0])})`,precedence:_};case"f32.trunc":return{code:`trunc(${w(t,n[0])})`,precedence:_};case"f32.nearest":return{code:`round(${w(t,n[0])})`,precedence:_};case"f32.sqrt":return{code:`sqrt(${w(t,n[0])})`,precedence:_};case"f32.min":return{code:`min(${w(t,n[0])}, ${w(t,n[1])})`,precedence:_};case"f32.max":return{code:`max(${w(t,n[0])}, ${w(t,n[1])})`,precedence:_};case"f32.copysign":return{code:`bitcast<f32>((bitcast<u32>(${w(t,n[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${w(t,n[1])}) & 0x80000000u))`,precedence:_};default:return null}}function nn(t,e,n,s){let i=ft(t,e,n,s);return i===null?null:i.precedence<_?`(${i.code})`:i.code}function pt(t,e,n){switch(e){case"f32.eq":return{code:`select(0i, 1i, ${w(t,n[0])} == ${w(t,n[1])})`,precedence:_};case"f32.ne":return{code:`select(0i, 1i, ${w(t,n[0])} != ${w(t,n[1])})`,precedence:_};case"f32.lt":return{code:`select(0i, 1i, ${w(t,n[0])} < ${w(t,n[1])})`,precedence:_};case"f32.gt":return{code:`select(0i, 1i, ${w(t,n[0])} > ${w(t,n[1])})`,precedence:_};case"f32.le":return{code:`select(0i, 1i, ${w(t,n[0])} <= ${w(t,n[1])})`,precedence:_};case"f32.ge":return{code:`select(0i, 1i, ${w(t,n[0])} >= ${w(t,n[1])})`,precedence:_};default:return null}}function sn(t,e,n){let s=pt(t,e,n);return s===null?null:s.precedence<_?`(${s.code})`:s.code}function mt(t,e,n,s){switch(e){case"i64.const":{let i=s[0];return{code:`${BigInt.asIntN(32,i)}`,precedence:_}}case"i64.add":return T("+",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.sub":return T("-",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.mul":return T("*",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.div_s":return T("/",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.div_u":return{code:`bitcast<i32>(bitcast<u32>(${t.resolveVar(n[0])}) / bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.rem_s":return T("%",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.rem_u":return{code:`bitcast<i32>(bitcast<u32>(${t.resolveVar(n[0])}) % bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.and":return T("&",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.or":return T("|",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.xor":return T("^",t.resolveVarExpr(n[0]),t.resolveVarExpr(n[1]));case"i64.shl":{let i=t.resolveVarExpr(n[0]);return{code:`${L(i,C["<<"],!1,"<<")} << (bitcast<u32>(${t.resolveVar(n[1])}) & 31u)`,precedence:C["<<"],operator:"<<"}}case"i64.shr_s":{let i=t.resolveVarExpr(n[0]);return{code:`${L(i,C[">>"],!1,">>")} >> (bitcast<u32>(${t.resolveVar(n[1])}) & 31u)`,precedence:C[">>"],operator:">>"}}case"i64.shr_u":return{code:`bitcast<i32>(bitcast<u32>(${t.resolveVar(n[0])}) >> (bitcast<u32>(${t.resolveVar(n[1])}) & 31u))`,precedence:_};case"i64.rotl":{let i=`bitcast<u32>(${t.resolveVar(n[0])})`,r=`(bitcast<u32>(${t.resolveVar(n[1])}) & 31u)`;return{code:`bitcast<i32>((${i} << ${r}) | (${i} >> (32u - ${r})))`,precedence:_}}case"i64.rotr":{let i=`bitcast<u32>(${t.resolveVar(n[0])})`,r=`(bitcast<u32>(${t.resolveVar(n[1])}) & 31u)`;return{code:`bitcast<i32>((${i} >> ${r}) | (${i} << (32u - ${r})))`,precedence:_}}case"i64.clz":return{code:`countLeadingZeros(${t.resolveVar(n[0])})`,precedence:_};case"i64.ctz":return{code:`countTrailingZeros(${t.resolveVar(n[0])})`,precedence:_};case"i64.popcnt":return{code:`countOneBits(${t.resolveVar(n[0])})`,precedence:_};default:return null}}function rn(t,e,n,s){let i=mt(t,e,n,s);return i===null?null:i.precedence<_?`(${i.code})`:i.code}function ht(t,e,n){switch(e){case"i64.eq":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} == ${t.resolveVar(n[1])})`,precedence:_};case"i64.ne":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} != ${t.resolveVar(n[1])})`,precedence:_};case"i64.lt_s":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} < ${t.resolveVar(n[1])})`,precedence:_};case"i64.lt_u":return{code:`select(0i, 1i, bitcast<u32>(${t.resolveVar(n[0])}) < bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.gt_s":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} > ${t.resolveVar(n[1])})`,precedence:_};case"i64.gt_u":return{code:`select(0i, 1i, bitcast<u32>(${t.resolveVar(n[0])}) > bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.le_s":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} <= ${t.resolveVar(n[1])})`,precedence:_};case"i64.le_u":return{code:`select(0i, 1i, bitcast<u32>(${t.resolveVar(n[0])}) <= bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.ge_s":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} >= ${t.resolveVar(n[1])})`,precedence:_};case"i64.ge_u":return{code:`select(0i, 1i, bitcast<u32>(${t.resolveVar(n[0])}) >= bitcast<u32>(${t.resolveVar(n[1])}))`,precedence:_};case"i64.eqz":return{code:`select(0i, 1i, ${t.resolveVar(n[0])} == 0i)`,precedence:_};default:return null}}function on(t,e,n){let s=ht(t,e,n);return s===null?null:s.precedence<_?`(${s.code})`:s.code}function _t(t,e,n,s){switch(e){case"f64.const":{let r=s[0].toString();return!r.includes(".")&&!r.includes("e")&&(r+=".0"),{code:`${r}`,precedence:_}}case"f64.add":return T("+",P(t,n[0]),P(t,n[1]));case"f64.sub":return T("-",P(t,n[0]),P(t,n[1]));case"f64.mul":return T("*",P(t,n[0]),P(t,n[1]));case"f64.div":return T("/",P(t,n[0]),P(t,n[1]));case"f64.abs":return{code:`abs(${w(t,n[0])})`,precedence:_};case"f64.neg":{let i=P(t,n[0]);return{code:`-${L(i,14)}`,precedence:14}}case"f64.ceil":return{code:`ceil(${w(t,n[0])})`,precedence:_};case"f64.floor":return{code:`floor(${w(t,n[0])})`,precedence:_};case"f64.trunc":return{code:`trunc(${w(t,n[0])})`,precedence:_};case"f64.nearest":return{code:`round(${w(t,n[0])})`,precedence:_};case"f64.sqrt":return{code:`sqrt(${w(t,n[0])})`,precedence:_};case"f64.min":return{code:`min(${w(t,n[0])}, ${w(t,n[1])})`,precedence:_};case"f64.max":return{code:`max(${w(t,n[0])}, ${w(t,n[1])})`,precedence:_};case"f64.copysign":return{code:`bitcast<f32>((bitcast<u32>(${w(t,n[0])}) & 0x7FFFFFFFu) | (bitcast<u32>(${w(t,n[1])}) & 0x80000000u))`,precedence:_};default:return null}}function an(t,e,n,s){let i=_t(t,e,n,s);return i===null?null:i.precedence<_?`(${i.code})`:i.code}function gt(t,e,n){switch(e){case"f64.eq":return{code:`select(0i, 1i, ${w(t,n[0])} == ${w(t,n[1])})`,precedence:_};case"f64.ne":return{code:`select(0i, 1i, ${w(t,n[0])} != ${w(t,n[1])})`,precedence:_};case"f64.lt":return{code:`select(0i, 1i, ${w(t,n[0])} < ${w(t,n[1])})`,precedence:_};case"f64.gt":return{code:`select(0i, 1i, ${w(t,n[0])} > ${w(t,n[1])})`,precedence:_};case"f64.le":return{code:`select(0i, 1i, ${w(t,n[0])} <= ${w(t,n[1])})`,precedence:_};case"f64.ge":return{code:`select(0i, 1i, ${w(t,n[0])} >= ${w(t,n[1])})`,precedence:_};default:return null}}function cn(t,e,n){let s=gt(t,e,n);return s===null?null:s.precedence<_?`(${s.code})`:s.code}function bt(t,e,n){switch(e){case"i32.wrap_i64":return t.resolveVarExpr(n[0]);case"i64.extend_i32_s":return t.resolveVarExpr(n[0]);case"i64.extend_i32_u":return t.resolveVarExpr(n[0]);case"f32.convert_i32_s":return{code:`f32(${t.resolveVar(n[0])})`,precedence:_};case"f32.convert_i32_u":return{code:`f32(bitcast<u32>(${t.resolveVar(n[0])}))`,precedence:_};case"f32.convert_i64_s":return{code:`f32(${t.resolveVar(n[0])})`,precedence:_};case"f32.convert_i64_u":return{code:`f32(bitcast<u32>(${t.resolveVar(n[0])}))`,precedence:_};case"f64.convert_i32_s":return{code:`f32(${t.resolveVar(n[0])})`,precedence:_};case"f64.convert_i32_u":return{code:`f32(bitcast<u32>(${t.resolveVar(n[0])}))`,precedence:_};case"f64.convert_i64_s":return{code:`f32(${t.resolveVar(n[0])})`,precedence:_};case"f64.convert_i64_u":return{code:`f32(bitcast<u32>(${t.resolveVar(n[0])}))`,precedence:_};case"i32.trunc_f32_s":return{code:`i32(${t.resolveVar(n[0])})`,precedence:_};case"i32.trunc_f32_u":return{code:`bitcast<i32>(u32(${t.resolveVar(n[0])}))`,precedence:_};case"i64.trunc_f32_s":return{code:`i32(${t.resolveVar(n[0])})`,precedence:_};case"i64.trunc_f32_u":return{code:`bitcast<i32>(u32(${t.resolveVar(n[0])}))`,precedence:_};case"i64.trunc_f64_s":return{code:`i32(${t.resolveVar(n[0])})`,precedence:_};case"i64.trunc_f64_u":return{code:`bitcast<i32>(u32(${t.resolveVar(n[0])}))`,precedence:_};case"i32.trunc_f64_s":return{code:`i32(${t.resolveVar(n[0])})`,precedence:_};case"i32.trunc_f64_u":return{code:`bitcast<i32>(u32(${t.resolveVar(n[0])}))`,precedence:_};case"f32.demote_f64":return t.resolveVarExpr(n[0]);case"f64.promote_f32":return t.resolveVarExpr(n[0]);case"i32.reinterpret_f32":return{code:`bitcast<i32>(${t.resolveVar(n[0])})`,precedence:_};case"f32.reinterpret_i32":return{code:`bitcast<f32>(${t.resolveVar(n[0])})`,precedence:_};case"i64.reinterpret_f64":return{code:`bitcast<i32>(${t.resolveVar(n[0])})`,precedence:_};case"f64.reinterpret_i64":return{code:`bitcast<f32>(${t.resolveVar(n[0])})`,precedence:_};case"i32.trunc_sat_f32_s":return{code:`i32(trunc(${t.resolveVar(n[0])}))`,precedence:_};case"i32.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${t.resolveVar(n[0])})))`,precedence:_};case"i32.trunc_sat_f64_s":return{code:`i32(trunc(${t.resolveVar(n[0])}))`,precedence:_};case"i32.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${t.resolveVar(n[0])})))`,precedence:_};case"i64.trunc_sat_f32_s":return{code:`i32(trunc(${t.resolveVar(n[0])}))`,precedence:_};case"i64.trunc_sat_f32_u":return{code:`bitcast<i32>(u32(trunc(${t.resolveVar(n[0])})))`,precedence:_};case"i64.trunc_sat_f64_s":return{code:`i32(trunc(${t.resolveVar(n[0])}))`,precedence:_};case"i64.trunc_sat_f64_u":return{code:`bitcast<i32>(u32(trunc(${t.resolveVar(n[0])})))`,precedence:_};default:return null}}function un(t,e,n){let s=bt(t,e,n);return s===null?null:s.precedence<_?`(${s.code})`:s.code}function re(t,e){let n=t.currentFunc?.inlinedExpressionMap?.get(e);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?`${n.immediates[0]>>>0}u`:t.currentFunc?.vars.get(e)?.emitAsU32?`v${e}`:`bitcast<u32>(${F(t,e)})`}function ln(t,e,n){switch(e){case"wgsl.load_i32":{let s=re(t,n[0]);return t.inlineMemoryOps?`bitcast<i32>(memory[${s}])`:`wgsl_load_i32(${s})`}case"wgsl.load_f32":{let s=re(t,n[0]);return t.inlineMemoryOps?`bitcast<f32>(memory[${s}])`:`wgsl_load_f32(${s})`}case"wgsl.buffer_length":return"wgsl_buffer_length()";case"wgsl.load_vec3f":{let s=re(t,n[0]);return`vec3<f32>(bitcast<f32>(memory[${s}]), bitcast<f32>(memory[${s} + 1u]), bitcast<f32>(memory[${s} + 2u]))`}case"wgsl.load_vec4f":{let s=re(t,n[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 dn(t,e,n){switch(e){case"wgsl.store_i32":{let s=re(t,n[0]),i=F(t,n[1]);return t.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_i32(${s}, ${i});`}case"wgsl.store_f32":{let s=re(t,n[0]),i=t.resolveVar(n[1]);return t.inlineMemoryOps?`memory[${s}] = bitcast<u32>(${i});`:`wgsl_store_f32(${s}, ${i});`}case"wgsl.store_vec3f":{let s=re(t,n[0]),i=t.resolveVar(n[1]),r=t.resolveVar(n[2]),o=t.resolveVar(n[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=re(t,n[0]),i=t.resolveVar(n[1]),r=t.resolveVar(n[2]),o=t.resolveVar(n[3]),c=t.resolveVar(n[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 fn(t,e){let n=t[0];return e!==void 0&&n===e?"i32(_wgpu_global_idx)":`local_${n}`}function pn(t){return`global_${t[0]}`}function Os(t,e){if(!t.imports||!t.mathExtension)return null;let n=0;for(let s of t.imports)if(s.kind==="func"){if(n===e){if(Tt(s.module,s.name)){let i=$e(s.name);if(i){let r=We(s.name),o=r?Ot(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}n++}return null}function mn(t,e){let n=`bitcast<vec4<f32>>(${t})`;return e===2?`${n}.xy`:e===3?`${n}.xyz`:n}function hn(t,e){return e===4?`bitcast<vec4<u32>>(${t})`:e===3?`bitcast<vec4<u32>>(vec4<f32>(${t}, 0.0))`:e===2?`bitcast<vec4<u32>>(vec4<f32>(${t}, 0.0, 0.0))`:t}function _n(t,e,n){let s=n[0],r=Os(t,s);if(r){if(r.isVector&&r.vectorDim>0){let f=e.map((S,y)=>{let k=r.wasmParams[y];return k==="v128"||k==="f32"&&r.supportsVector?mn(t.resolveVar(S),r.vectorDim):t.resolveVar(S)}).join(", "),p=`${r.wgslBuiltin}(${f})`,g=r.wasmResults[0];return g==="v128"||g==="f32"&&r.supportsVector?hn(p,r.vectorDim):p}let l=e.map(d=>t.resolveVar(d)).join(", ");return`${r.wgslBuiltin}(${l})`}let c=t.functionNameMap?.get(s)??`func_${s}`,u=e.map(l=>t.resolveVar(l)).join(", ");return`${c}(${u})`}function gn(t,e,n){let s="i32";if(n!==void 0&&t.currentFunc){let c=t.currentFunc.vars.get(n);c&&(s=c.type)}let i=t.resolveVarExpr(e[2]),o=`(${L(i,C["!="],!1,"!=")} != 0)`;return s==="f32"||s==="f64"?`select(${w(t,e[0])}, ${w(t,e[1])}, ${o})`:s==="v128"?`select(${t.resolveVar(e[0])}, ${t.resolveVar(e[1])}, ${o})`:`select(${F(t,e[0])}, ${F(t,e[1])}, ${o})`}function bn(t,e){if(e.length>0){let n=e[0];return n>=0?`return ${t.resolveVar(n)};`:"return 0i;"}return"return;"}function xt(t,e,n){if(e.length===0)return"0i";let s=t.currentFunc?.vars.get(n);return s?.type==="f32"||s?.type==="f64"?w(t,e[0]):s?.type==="v128"?t.resolveVar(e[0]):F(t,e[0])}function xn(t,e){let s=`(bitcast<u32>(${t.resolveVar(e[0])}) >> 2u)`;return`vec4<u32>(memory[${s}], memory[${s} + 1u], memory[${s} + 2u], memory[${s} + 3u])`}function Sn(t,e){let n=t.resolveVar(e[0]),s=t.resolveVar(e[1]),i=`(bitcast<u32>(${n}) >> 2u)`;return[`memory[${i}] = ${s}.x;`,`memory[${i} + 1u] = ${s}.y;`,`memory[${i} + 2u] = ${s}.z;`,`memory[${i} + 3u] = ${s}.w;`]}function yn(t){let e;if(Array.isArray(t[0]))e=t[0];else if(t.length===16&&typeof t[0]=="number")e=t;else return console.warn("v128.const has invalid immediates:",t),"vec4<u32>(0u, 0u, 0u, 0u)";if(e.length!==16)return console.warn("v128.const has invalid length:",e.length),"vec4<u32>(0u, 0u, 0u, 0u)";let n=[];for(let s=0;s<4;s++){let i=0;for(let r=0;r<4;r++)i|=e[s*4+r]<<r*8;n.push(i>>>0)}return`vec4<u32>(${n.map(s=>`${s}u`).join(", ")})`}function vn(t,e,n){switch(e){case"i32x4.add":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${t.resolveVar(n[0])}) + bitcast<vec4<i32>>(${t.resolveVar(n[1])})))`;case"i32x4.sub":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${t.resolveVar(n[0])}) - bitcast<vec4<i32>>(${t.resolveVar(n[1])})))`;case"i32x4.mul":return`bitcast<vec4<u32>>((bitcast<vec4<i32>>(${t.resolveVar(n[0])}) * bitcast<vec4<i32>>(${t.resolveVar(n[1])})))`;case"i32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`})`;case"i32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`}))`;case"i32x4.min_s":{let s=`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<i32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"i32x4.min_u":return`min(${t.resolveVar(n[0])}, ${t.resolveVar(n[1])})`;case"i32x4.max_s":{let s=`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<i32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"i32x4.max_u":return`max(${t.resolveVar(n[0])}, ${t.resolveVar(n[1])})`;default:return null}}function Te(t){let e=[];for(let n=0;n<4;n++){let s=[];for(let i=0;i<4;i++){let r=n*4+i;i===0?s.push(`(u32(${t[r]}) & 0xFFu)`):s.push(`((u32(${t[r]}) & 0xFFu) << ${i*8}u)`)}e.push(`(${s.join(" | ")})`)}return`vec4<u32>(${e.join(", ")})`}function Be(t){let e=[];for(let n=0;n<4;n++){let s=`(u32(${t[n*2]}) & 0xFFFFu)`,i=`((u32(${t[n*2+1]}) & 0xFFFFu) << 16u)`;e.push(`(${s} | ${i})`)}return`vec4<u32>(${e.join(", ")})`}function Ps(t,e,n){let s=t.resolveVar(n[0]),i=n.length>1?t.resolveVar(n[1]):null;switch(e){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 Te(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 Te(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 Te(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 Te(r)}default:return null}}function Ls(t,e,n){let s=t.resolveVar(n[0]),i=n.length>1?t.resolveVar(n[1]):null;switch(e){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 Be(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 Be(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 Be(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 Be(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 Be(r)}default:return null}}function Us(t,e,n){let s=t.resolveVar(n[0]),i=t.resolveVar(n[1]);switch(e){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})`,S=`select(0u, 0xFFu, ${p} == ${g})`;l===0?u.push(S):u.push(`(${S} << ${d}u)`)}r.push(`(${u.join(" | ")})`)}return`vec4<u32>(${r.join(", ")})`}default:return null}}function zs(t,e,n){let s=t.resolveVar(n[0]),i=t.resolveVar(n[1]);switch(e){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 In(t,e,n){switch(e){case"v128.and":return`(${t.resolveVar(n[0])} & ${t.resolveVar(n[1])})`;case"v128.or":return`(${t.resolveVar(n[0])} | ${t.resolveVar(n[1])})`;case"v128.xor":return`(${t.resolveVar(n[0])} ^ ${t.resolveVar(n[1])})`;case"v128.not":return`(~${t.resolveVar(n[0])})`;case"v128.andnot":return`(${t.resolveVar(n[0])} & ~${t.resolveVar(n[1])})`;case"v128.bitselect":{let s=t.resolveVar(n[0]),i=t.resolveVar(n[1]),r=t.resolveVar(n[2]);return`((${s} & ${r}) | (${i} & ~${r}))`}default:return null}}function kn(t,e,n){let s=(i,r)=>{let o=r?`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`:t.resolveVar(n[0]),c=r?`bitcast<vec4<i32>>(${t.resolveVar(n[1])})`:t.resolveVar(n[1]);return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${o} ${i} ${c}))`};switch(e){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>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} == ${r}))`}case"f32x4.ne":{let i=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} != ${r}))`}case"f32x4.lt":{let i=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} < ${r}))`}case"f32x4.gt":{let i=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} > ${r}))`}case"f32x4.le":{let i=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(select(vec4<i32>(0), vec4<i32>(-1), ${i} <= ${r}))`}case"f32x4.ge":{let i=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,r=`bitcast<vec4<f32>>(${t.resolveVar(n[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>(${t.resolveVar(n[0])}.x), bitcast<f32>(${t.resolveVar(n[0])}.z))`,r=`vec2<f32>(bitcast<f32>(${t.resolveVar(n[1])}.x), bitcast<f32>(${t.resolveVar(n[1])}.z))`,c={"f64x2.eq":"==","f64x2.ne":"!=","f64x2.lt":"<","f64x2.gt":">","f64x2.le":"<=","f64x2.ge":">="}[e],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 Ws(t,e,n){switch(e){case"f32x4.add":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(${s} + ${i})`}case"f32x4.sub":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(${s} - ${i})`}case"f32x4.mul":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(${s} * ${i})`}case"f32x4.div":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(${s} / ${i})`}case"f32x4.min":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.max":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.pmin":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(min(${s}, ${i}))`}case"f32x4.pmax":{let s=`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`,i=`bitcast<vec4<f32>>(${t.resolveVar(n[1])})`;return`bitcast<vec4<u32>>(max(${s}, ${i}))`}case"f32x4.abs":return`bitcast<vec4<u32>>(abs(${`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`}))`;case"f32x4.neg":return`bitcast<vec4<u32>>(-${`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`})`;case"f32x4.sqrt":return`bitcast<vec4<u32>>(sqrt(${`bitcast<vec4<f32>>(${t.resolveVar(n[0])})`}))`;case"f32x4.convert_i32x4_s":return`bitcast<vec4<u32>>(vec4<f32>(${`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`}))`;case"f32x4.convert_i32x4_u":return`bitcast<vec4<u32>>(vec4<f32>(${t.resolveVar(n[0])}))`;default:return null}}function Gs(t,e,n){switch(e){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>(${t.resolveVar(n[0])}.x), bitcast<f32>(${t.resolveVar(n[0])}.z))`,i=`vec2<f32>(bitcast<f32>(${t.resolveVar(n[1])}.x), bitcast<f32>(${t.resolveVar(n[1])}.z))`,o={"f64x2.add":"+","f64x2.sub":"-","f64x2.mul":"*","f64x2.div":"/","f64x2.min":"min","f64x2.max":"max","f64x2.pmin":"min","f64x2.pmax":"max"}[e],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>(${t.resolveVar(n[0])}.x), bitcast<f32>(${t.resolveVar(n[0])}.z))`,r={"f64x2.abs":"abs","f64x2.neg":"-","f64x2.sqrt":"sqrt"}[e],o;return r==="-"?o=`(-${s})`:o=`${r}(${s})`,`vec4<u32>(bitcast<u32>(${o}.x), 0u, bitcast<u32>(${o}.y), 0u)`}default:return null}}function wn(t,e,n){switch(e){case"i32x4.shl":{let s=`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`,r=`vec4<u32>(${`u32(${t.resolveVar(n[1])})`})`;return`bitcast<vec4<u32>>(${s} << ${r})`}case"i32x4.shr_s":{let s=`bitcast<vec4<i32>>(${t.resolveVar(n[0])})`,r=`vec4<u32>(${`u32(${t.resolveVar(n[1])})`})`;return`bitcast<vec4<u32>>(${s} >> ${r})`}case"i32x4.shr_u":{let s=t.resolveVar(n[0]),r=`vec4<u32>(${`u32(${t.resolveVar(n[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 t.resolveVar(n[0]);default:return null}}function En(t,e,n,s){switch(e){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=`((${t.resolveVar(n[0])}.${o} >> ${c}u) & 0xFFu)`;return e.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=`((${t.resolveVar(n[0])}.${o} >> ${c}u) & 0xFFFFu)`;return e.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>(${t.resolveVar(n[0])}.${r[i]})`}case"i64x2.extract_lane":return s[0]===0?`bitcast<i64>(vec2<u32>(${t.resolveVar(n[0])}.x, ${t.resolveVar(n[0])}.y))`:`bitcast<i64>(vec2<u32>(${t.resolveVar(n[0])}.z, ${t.resolveVar(n[0])}.w))`;case"f32x4.extract_lane":{let i=s[0],r=["x","y","z","w"];return`bitcast<f32>(${t.resolveVar(n[0])}.${r[i]})`}case"f64x2.extract_lane":return s[0]===0?`bitcast<f32>(${t.resolveVar(n[0])}.x)`:`bitcast<f32>(${t.resolveVar(n[0])}.z)`;default:return null}}function Rn(t,e,n,s){switch(e){case"i8x16.replace_lane":case"i16x8.replace_lane":{let i=s[0]%4,r=t.resolveVar(n[0]),o=`bitcast<u32>(${t.resolveVar(n[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=t.resolveVar(n[0]),o=`bitcast<u32>(${t.resolveVar(n[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=t.resolveVar(n[0]),o=`bitcast<vec2<u32>>(${t.resolveVar(n[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=t.resolveVar(n[0]),o=`bitcast<u32>(${t.resolveVar(n[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=t.resolveVar(n[0]),o=`bitcast<u32>(${t.resolveVar(n[1])})`;return i===0?`vec4<u32>(${o}, 0u, ${r}.z, ${r}.w)`:`vec4<u32>(${r}.x, ${r}.y, ${o}, 0u)`}default:return null}}function Vn(t,e,n){switch(e){case"i32x4.splat":{let s=`bitcast<u32>(${t.resolveVar(n[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i16x8.splat":case"i8x16.splat":{let s=`bitcast<u32>(${t.resolveVar(n[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"i64x2.splat":{let s=`bitcast<vec2<u32>>(${t.resolveVar(n[0])})`;return`vec4<u32>(${s}.x, ${s}.y, ${s}.x, ${s}.y)`}case"f32x4.splat":{let s=`bitcast<u32>(${t.resolveVar(n[0])})`;return`vec4<u32>(${s}, ${s}, ${s}, ${s})`}case"f64x2.splat":{let s=`bitcast<u32>(${t.resolveVar(n[0])})`;return`vec4<u32>(${s}, 0u, ${s}, 0u)`}default:return null}}function $n(t,e,n){switch(e){case"v128.any_true":return`select(0i, 1i, any(${t.resolveVar(n[0])} != vec4<u32>(0u)))`;case"i8x16.all_true":{let s=t.resolveVar(n[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=t.resolveVar(n[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>>(${t.resolveVar(n[0])})`} != vec4<i32>(0)))`;case"i8x16.bitmask":{let s=t.resolveVar(n[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=t.resolveVar(n[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>>(${t.resolveVar(n[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(t,e,n,s){let i=vn(t,e,n);return i!==null||(i=Ps(t,e,n),i!==null)||(i=Ls(t,e,n),i!==null)||(i=Us(t,e,n),i!==null)||(i=zs(t,e,n),i!==null)||(i=Ws(t,e,n),i!==null)||(i=Gs(t,e,n),i!==null)||(i=In(t,e,n),i!==null)||(i=kn(t,e,n),i!==null)||(i=wn(t,e,n),i!==null)||s&&(i=En(t,e,n,s),i!==null||(i=Rn(t,e,n,s),i!==null)||(i=qs(t,e,n,s),i!==null))||(i=Vn(t,e,n),i!==null)||(i=$n(t,e,n),i!==null)?i:null}function qs(t,e,n,s){switch(e){case"i8x16.shuffle":return t.resolveVar(n[0]);case"i8x16.swizzle":return t.resolveVar(n[0]);default:return null}}function St(t,e,n,s,i){let r=en(t,e,n,s,i);if(r!==null)return{expression:r,handled:!0};if(r=tn(t,e,n),r!==null)return{expression:r,handled:!0};if(r=nn(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=sn(t,e,n),r!==null)return{expression:r,handled:!0};if(r=rn(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=on(t,e,n),r!==null)return{expression:r,handled:!0};if(r=an(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=cn(t,e,n),r!==null)return{expression:r,handled:!0};if(r=un(t,e,n),r!==null)return{expression:r,handled:!0};if(e==="wgsl.extract_f32"&&s&&s.length>0){let c=["x","y","z","w"],u=s[0];return{expression:`${t.resolveVar(n[0])}.${c[u]}`,handled:!0}}if(r=ln(t,e,n),r!==null)return{expression:r,handled:!0};let o=dn(t,e,n);if(o!==null)return{statements:[o],handled:!0};if(r=Fn(t,e,n,s),r!==null)return{expression:r,handled:!0};if(e==="v128.load")return{expression:xn(t,n),handled:!0};if(e==="v128.const")return{expression:yn(s),handled:!0};if(e==="v128.store")return{statements:Sn(t,n),handled:!0};if(e==="local.get"){let c=s[0],u=t.currentFunc?.params.length||0,l=t.currentFunc?.immutableParams||new Set;return c<u&&l.has(c)?{expression:`p${c}`,handled:!0}:{expression:fn(s,t.parallelLoopLocalIndex),handled:!0}}if(e==="global.get")return{expression:pn(s),handled:!0};if(e==="call")return{expression:_n(t,n,s),handled:!0};if(e==="select")return{expression:gn(t,n,i),handled:!0};if(e==="return"){let c=bn(t,n);if(c!==null)return{statements:[c],handled:!0}}return{handled:!1}}function Bn(t,e,n,s,i){let r=lt(t,e,n,s,i);if(r!==null)return{expression:r,handled:!0};if(r=dt(t,e,n),r!==null)return{expression:r,handled:!0};if(r=ft(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=pt(t,e,n),r!==null)return{expression:r,handled:!0};if(r=mt(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=ht(t,e,n),r!==null)return{expression:r,handled:!0};if(r=_t(t,e,n,s),r!==null)return{expression:r,handled:!0};if(r=gt(t,e,n),r!==null)return{expression:r,handled:!0};if(r=bt(t,e,n),r!==null)return{expression:r,handled:!0};let o=St(t,e,n,s,i);return o.handled&&o.expression!==void 0?{expression:{code:o.expression,precedence:_},handled:!0}:o.handled&&o.statements!==void 0?{statements:o.statements,handled:!0}:{handled:!1}}var js="0.5.0",Ys="2026-06-12";function Mn(t){let e=t.replace(/^\$/,"");return e=e.replace(/[^a-zA-Z0-9_]/g,"_"),/^[0-9]/.test(e)&&(e=`_${e}`),e.length===0&&(e="_unnamed"),e}function Va(t){let e=t.functions.map(s=>Zs(s,t));for(let s of e)Je(s);let n=t.globals;return{types:t.types,functions:e,globals:n,memories:t.memories,data:t.data,exports:t.exports,imports:t.imports,startFunctionIndex:t.startFunctionIndex}}function An(t){let e="select(0i, 1i, ";if(!t.startsWith(e)||!t.endsWith(")"))return null;let n=t.slice(e.length,-1),s=0;for(let i of n)if(i==="("?s++:i===")"&&s--,s<0)return null;return s!==0?null:n}function Ba(t,e={},n,s){return new vt(t,e,n,s).generate()}var vt=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(e,n,s,i){this.module=e,this.options=n,this.dispatchInfo=i||Fe(),this.imports=e.imports,this.types=e.types,this.mathExtension=n.mathExtension,this.buildFunctionNameMap();let r=n.stripComments||n.releaseMode;n.sourceMapping&&s&&!r&&(this.sourceMapper=Zt(s,n.sourceMapping))}buildFunctionNameMap(){let e=this.module.exports.some(n=>n.kind==="func"&&n.name==="main");for(let n of this.module.functions)this.functionNameMap.set(n.index,n.name?Mn(n.name):`func_${n.index}`);for(let n of this.module.exports)if(n.kind==="func"){let s=Mn(n.name);if(s==="main"&&e)continue;this.functionNameMap.set(n.index,s)}}get inlineMemoryOps(){return this.options.inlineMemoryOps||!1}hasF32MemoryOps(){for(let e of this.module.functions)if(this.statementHasOpcode(e.body,"wgsl.load_f32")||this.statementHasOpcode(e.body,"wgsl.store_f32"))return!0;return!1}statementHasOpcode(e,n){switch(e.kind){case"simple":return e.instructions.some(s=>s.opcode===n);case"block":return e.children.some(s=>this.statementHasOpcode(s,n));case"loop":return this.statementHasOpcode(e.body,n);case"if":return this.statementHasOpcode(e.thenBranch,n)||(e.elseBranch?this.statementHasOpcode(e.elseBranch,n):!1);case"parallel_loop":return this.statementHasOpcode(e.body,n)||(e.epilogue?this.statementHasOpcode(e.epilogue,n):!1);default:return!1}}resolveVar(e){return this.resolveVarExpr(e).code}resolveVarExpr(e){if(this.currentFunc?.inlinedExpressionMap?.has(e)){let n=this.currentFunc.inlinedExpressionMap.get(e),s=Bn(this,n.opcode,n.args||[],n.immediates,n.id);if(s.expression)return s.expression}return{code:`v${e}`,precedence:_}}generate(){if(this.emit("// Gasm Compiler Generated WGSL"),this.emit(`// Compiler Version: ${js}`),this.emit(`// Build Date: ${Ys}`),this.emit(`// Generated: ${new Date().toISOString()}`),this.options.compilerMetadata&&this.emit(`// Metadata: ${this.options.compilerMetadata}`),this.sourceMapper){let n=this.sourceMapper.generateHeaderComment();n&&this.emit(n)}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 n of this.module.globals){let s=Q(n.type);if(n.kind==="import")n.module==="gasm"?this.emit(`var<private> global_${n.index}: ${s}; // gasm.${n.name}`):this.emit(`var<private> global_${n.index}: ${s}; // import ${n.module}.${n.name}`);else{let i="";if(n.initValue!==void 0){if(s==="i32"||s==="i64")i=` = ${n.initValue}i`;else if(s==="f32"){let r=n.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}f`}else if(s==="f64"){let r=n.initValue.toString();!r.includes(".")&&!r.includes("e")&&(r+=".0"),i=` = ${r}`}}this.emit(`var<private> global_${n.index}: ${s}${i};`)}}this.dispatchInfo.isParallelized&&this.emit("var<private> _wgpu_global_idx: u32 = 0u;"),this.emit("");for(let n of this.module.functions)this.emitFunction(n),this.emit("");let e=this.module.exports.find(n=>n.kind==="func"&&n.name==="main");if(e){let n=this.options.specVersion==="0.2"?64:1,s=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeX:this.options.workgroupSize?.[0]||n,i=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeY:this.options.workgroupSize?.[1]||1,r=this.dispatchInfo.isParallelized?this.dispatchInfo.workgroupSizeZ:this.options.workgroupSize?.[2]||1;this.emit(`@compute @workgroup_size(${s}, ${i}, ${r})`),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 c of this.module.globals)if(c.kind==="import"&&c.module==="gasm"){let u=c.name.endsWith("_x")?".x":c.name.endsWith("_y")?".y":c.name.endsWith("_z")?".z":"";c.name.startsWith("global_invocation_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(global_id${u});`):c.name.startsWith("local_invocation_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(local_id${u});`):c.name.startsWith("workgroup_id")&&u?this.emit(`global_${c.index} = bitcast<i32>(workgroup_id${u});`):c.name.startsWith("num_workgroups")&&u&&this.emit(`global_${c.index} = bitcast<i32>(num_workgroups${u});`)}let o=this.functionNameMap.get(e.index)??`func_${e.index}`;this.emit(`${o}();`),this.popIndent(),this.emit("}")}return this.output.join(`
|
|
2
|
+
`)}emitFunction(e){this.currentFunc=e,this.predeclaredVars=new Set,this.emittedVars=new Set;let n=this.functionNameMap.get(e.index)??e.name??`func_${e.index}`,s=e.params.map((d,f)=>`p${f}: ${Q(d)}`).join(", "),i=e.results.length>0?` -> ${Q(e.results[0])}`:"";if(this.sourceMapper){let d=this.module.exports.find(p=>p.kind==="func"&&p.index===e.index),f=this.sourceMapper.commentForFunction(e.index,d?.name);f&&this.emit(f)}if(this.emit(`fn ${n}(${s})${i} {`),this.pushIndent(),this.usingUnifiedReturn=Xs(e.body),this.usingUnifiedReturn&&(this.emit("var _has_returned_internal: bool = false;"),e.results.length>0)){let d=Q(e.results[0]),f=this.getDefaultValue(e.results[0]);this.emit(`var _return_value_internal: ${d} = ${f};`)}let r=e.params.length,o=e.immutableParams||new Set,c=at(e.body),u=ct(e.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(e.locals)for(let d=0;d<e.locals.length;d++){let f=r+d;if(!c.has(f))continue;let p=e.locals[d];this.emit(`var local_${f}: ${Q(p)};`)}else this.emit("// Warning: locals type info missing");let l=X(e.body);if(K(e.body,l,this.predeclaredVars),this.predeclaredVars.size>0)for(let d of this.predeclaredVars){if(e.inlinedExpressionMap?.has(d))continue;let f=e.vars.get(d),p=f?.emitAsU32?"u32":f?Q(f.type):"i32";this.emit(`var v${d}: ${p};`)}if(this.emitStatementFlattened(e.body),e.results.length>0&&!this.endsWithReturn(e.body)){let d=this.getDefaultValue(e.results[0]);this.emit(`return ${d};`)}this.popIndent(),this.emit("}"),this.currentFunc=null}endsWithReturn(e){return xe(e)}getDefaultValue(e){return rt(e)}isEmptyStatement(e){return De(e)}hasExplicitTerminator(e,n=!1){return be(e,n)}collectDefinedVars(e){return q(e)}collectUsedVars(e){return X(e)}analyzeVarsForPredeclaration(e,n=new Set){K(e,n,this.predeclaredVars)}ensureI32(e){return F(this,e)}ensureF32(e){return w(this,e)}generateLocalAssignment(e,n){return ot(this,e,n)}emitStatementFlattened(e,n=!0){if(e.kind==="block"&&e.children.length===1&&!e.label)this.emitStatementFlattened(e.children[0],n);else if(e.kind==="block"&&!e.label)for(let s=0;s<e.children.length;s++){let i=e.children[s],r=s===e.children.length-1;if(this.emitStatement(i,r&&n),this.hasExplicitTerminator(i,!1))break}else this.emitStatement(e,n)}negateComparison(e){let n=/^(.+?)\s*(<=|>=|<|>|==|!=)\s*(.+)$/,s=e.match(n);if(!s)return null;let[,i,r,o]=s,u={"<":">=","<=":">",">":"<=",">=":"<","==":"!=","!=":"=="}[r];return u?`${i} ${u} ${o}`:null}emitStatement(e,n=!0){switch(e.kind){case"block":let i=e.children.length===1&&!e.label?e.children[0]:null;if(i&&(i.kind==="block"||i.kind==="loop"||i.kind==="if"||i.kind==="simple"))this.emitStatement(i,n);else{if(this.sourceMapper&&e.label){let c=this.sourceMapper.commentForStatement(e,this.currentFunc?.index??0);c&&this.emit(c)}this.emit("{"),this.pushIndent();for(let c=0;c<e.children.length;c++){let u=e.children[c],l=c===e.children.length-1;if(this.emitStatement(u,l),this.hasExplicitTerminator(u,!1))break}if(this.popIndent(),this.emit("}"),this.sourceMapper&&e.label){let c=this.sourceMapper.commentForEndBlock(e.label);c&&this.emit(c)}}break;case"loop":if(this.sourceMapper){let c=this.sourceMapper.commentForStatement(e,this.currentFunc?.index??0);c&&this.emit(c)}e.label,this.emit("loop {"),this.pushIndent(),this.loopDepth++;let o=this.inParallelLoopDirect;if(this.inParallelLoopDirect=!1,this.emitStatementFlattened(e.body,!0),this.inParallelLoopDirect=o,this.loopDepth--,this.popIndent(),this.emit("}"),this.sourceMapper&&e.label){let c=this.sourceMapper.commentForEndBlock(e.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(e.thenBranch),u=!e.elseBranch||this.isEmptyStatement(e.elseBranch);if(c&&u)break;let l=this.hasExplicitTerminator(e.thenBranch,!1),d=e.elseBranch?this.hasExplicitTerminator(e.elseBranch,!1):!1,f=this.loopDepth>0||this.inParallelLoopDirect&&this.loopDepth>0,p=n&&this.loopDepth>0&&!this.inParallelLoopDirect,g=c&&!u&&e.elseBranch,S,y=this.currentFunc?.vars.get(e.condition),k=this.resolveVarExpr(e.condition);if(y?.type==="v128")S=`any(${k.code} != vec4<u32>(0u))`,g&&(S=`!${S}`);else{let b=An(k.code),x;b||(x=this.booleanVarExpressions.get(e.condition));let I;if(b){let V=b,O=/^v(\d+) == 0i$/,U=V.match(O);if(U){let N=parseInt(U[1],10),W=this.booleanVarExpressions.get(N);W&&(I=W,I=this.negateComparison(I)||`!(${I})`)}I||(I=V)}else x&&(I=x);if(I)if(g){let V=this.negateComparison(I);V?S=V:S=`!(${I})`}else S=I;else{let V=L(k,C["!="],!1,"!=");g?S=`${V} == 0`:S=`${V} != 0`}}if(g){this.emit(`if (${S}) {`),this.pushIndent(),this.emitStatementFlattened(e.elseBranch,!0),this.popIndent(),this.emit("}");break}this.emit(`if (${S}) {`),this.pushIndent(),this.emitStatementFlattened(e.thenBranch,!0),p&&!l&&d&&this.emit("break;"),this.popIndent();let h=p&&!d&&l;e.elseBranch&&(!this.isEmptyStatement(e.elseBranch)||h)?(this.emit("} else {"),this.pushIndent(),this.emitStatementFlattened(e.elseBranch,!0),h&&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=e.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(e.body,!0),this.popIndent(),this.emit("}"),this.parallelLoopLocalIndex=void 0,this.inParallelLoopDirect=u,e.epilogue&&(this.emit("// [PARALLEL] Epilogue: runs on single invocation"),this.emit("if (_wgpu_global_idx == 0u) {"),this.pushIndent(),this.emitStatementFlattened(e.epilogue,!0),this.popIndent(),this.emit("}"));break}case"simple":for(let c of e.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?(e.value!==void 0&&this.emit(`_return_value_internal = v${e.value};`),this.emit("_has_returned_internal = true;"),this.emit("break;")):e.value!==void 0?this.emit(`return v${e.value};`):this.emit("return;");break}}emitInstruction(e){if(this.sourceMapper){let c=this.sourceMapper.commentForInstruction(e,this.currentFunc?.index??0);c&&this.emit(c)}if(e.args){for(let c of e.args)if(!this.currentFunc?.inlinedExpressionMap?.has(c)&&c>=0&&!this.emittedVars.has(c)&&!this.predeclaredVars.has(c)&&(console.warn(`ERROR: Instruction ${e.opcode} references undefined variable v${c}`),console.warn(` Instruction defines: v${e.id}`),console.warn(` Args: [${e.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=Q(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 n=e.opcode;if(n==="return"&&this.loopDepth>0&&this.usingUnifiedReturn){if(e.args&&e.args.length>0){let c=e.args[0],u=this.resolveVar(c);this.emit(`_return_value_internal = ${u};`)}this.emit("_has_returned_internal = true;"),this.emit("break;");return}switch(n){case"global.set":{let c=e.immediates[0],u=e.args[0],l=Q(this.module.globals[c].type),f=this.currentFunc?.vars.get(u)?.type||"i32",p=Q(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=e.immediates[0],u=e.args[0],l=this.generateLocalAssignment(c,u);this.emit(`${l};`);return}case"local.tee":{let c=e.immediates[0],u=e.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(e.id!==void 0&&e.args.length>0){if(!this.predeclaredVars.has(e.id)&&!this.emittedVars.has(e.id)){console.warn(`WARNING: assign instruction for v${e.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(e.id),d=l?Q(l.type):"i32";this.emit(`var v${e.id}: ${d}; // EMERGENCY: Should have been predeclared`),this.predeclaredVars.add(e.id)}this.emittedVars.add(e.id);let c=`v${e.id} = `,u=xt(this,e.args,e.id);this.emit(`${c}${u};`)}return}}let i=St(this,n,e.args||[],e.immediates,e.id);if(i.handled){if(i.statements){for(let c of i.statements)this.emit(c);return}if(i.expression!==void 0){if(e.id!==void 0&&this.currentFunc?.inlinedExpressionMap?.has(e.id))return;if(e.id!==void 0&&typeof i.expression=="string"){let u=An(i.expression);u!==null&&this.booleanVarExpressions.set(e.id,u)}let c="";if(e.id!==void 0&&(this.predeclaredVars.has(e.id)?c=`v${e.id} = `:c=`let v${e.id} = `,this.emittedVars.add(e.id)),n==="local.tee"){let u=e.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(e.id!==void 0){if(this.currentFunc?.inlinedExpressionMap?.has(e.id))return;this.predeclaredVars.has(e.id)?r=`v${e.id} = `:r=`let v${e.id} = `,this.emittedVars.add(e.id)}let o=`/* unhandled: ${n} */ 0`;r?this.emit(`${r}${o};`):o&&this.emit(`${o};`)}emit(e){this.output.push(" ".repeat(this.indent)+e)}pushIndent(){this.indent++}popIndent(){this.indent--}},Q=ge,yt=Qe;var Xs=ut,It=class{module;func;ssa;currentBlockId;stack=[];controlStack=[];constructor(e,n){this.func=e,this.module=n,this.ssa={index:e.index,name:e.name,params:e.params,results:e.results,locals:e.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 e.params)this.ssa.vars.set(s,{id:s,type:i}),s++;for(let i of e.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 e of this.func.body)this.controlStack[this.controlStack.length-1].unreachable&&e.opcode!==a.end&&e.opcode!==a.else||this.processInstruction(e);return this.ssa}processInstruction(e){let n=e.opcode;switch(n){case a.block:{let i=this.newBlock(),r=this.newBlock();this.addBranch(r),this.switchBlock(r);let o=e.immediates[0],c=yt(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=e.immediates[0],c=yt(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=e.immediates[0],l=yt(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=e.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=e.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=e.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=e.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=e.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=e.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=e.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=e.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"local.set",args:[r],immediates:[i]});break}case a.global_get:{let i=e.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=e.immediates[0],r=this.popStack();this.addInstruction({type:"instr",opcode:"global.set",args:[r],immediates:[i]});break}case a.local_tee:{let i=e.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=e.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=n===a.f32_load?"f32":"i32",o=this.newVar(r);this.addInstruction({type:"instr",id:o,opcode:e.name.replace(/_/g,"."),args:[i],immediates:e.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:e.name.replace(/_/g,"."),args:[r,i],immediates:e.immediates});break}case a.memory_size:{let i=this.newVar("i32");this.addInstruction({type:"instr",id:i,opcode:"memory.size",args:[],immediates:e.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:e.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:e.immediates});break}case 64780:{let i=this.newVar("v128");this.addInstruction({type:"instr",id:i,opcode:"v128.const",args:[],immediates:e.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:e.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:e.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=it(this.getSSAContext(),e)}}newVar(e){let n=this.ssa.nextVarId++;return this.ssa.vars.set(n,{id:n,type:e}),n}blocktypeToValueType(e){switch(e){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(e){let n=this.func.params.length;if(e<n)return this.func.params[e];let s=e-n;return s<this.func.locals.length?this.func.locals[s].type:"i32"}newBlock(){let e=this.ssa.nextBlockId++;return this.ssa.blocks.set(e,{id:e,instructions:[],preds:[],succs:[]}),e}switchBlock(e){this.currentBlockId=e}addBranch(e){this.addInstruction({type:"instr",opcode:"br",args:[],immediates:[e]});let n=this.getBlock(e);n&&(this.getBlock(this.currentBlockId).succs.push(e),n.preds.push(this.currentBlockId))}addInstruction(e){this.getBlock(this.currentBlockId).instructions.push(e)}getBlock(e){return this.ssa.blocks.get(e)}pushStack(e){this.stack.push(e)}popStack(){return this.stack.length===0?-1:this.stack.pop()}peekStack(e=0){let n=this.stack.length-1-e;return n<0?-1:this.stack[n]}getSSAContext(){return{module:this.module,funcParams:this.func.params,funcLocals:this.func.locals.map(e=>e.type),funcResults:this.func.results,pushStack:e=>this.pushStack(e),popStack:()=>this.popStack(),peekStack:e=>this.peekStack(e??0),newVar:e=>this.newVar(e),addInstruction:e=>this.addInstruction(e)}}getCurrentFrame(){return this.controlStack[this.controlStack.length-1]}};function Zs(t,e){return new It(t,e).convert()}function z(){return{min:-1/0,max:1/0,isNonNegative:!1,knownZeroBits:0,knownOneBits:0}}function Cn(t){return{min:t,max:t,isNonNegative:t>=0,knownZeroBits:~t,knownOneBits:t}}function Ks(t=1/0){return{min:0,max:t,isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}function Se(t,e,n){switch(t){case"i32.and":{if(n.min===n.max){let s=n.min;return{min:0,max:s,isNonNegative:!0,knownZeroBits:~s,knownOneBits:0}}return z()}case"i32.add":return e.min===-1/0||n.min===-1/0?z():{min:e.min+n.min,max:e.max===1/0||n.max===1/0?1/0:e.max+n.max,isNonNegative:e.isNonNegative&&n.isNonNegative,knownZeroBits:0,knownOneBits:0};case"i32.sub":return e.min===-1/0||n.max===1/0?z():{min:e.max===1/0?-1/0:e.min-n.max,max:e.max===1/0||n.min===-1/0?1/0:e.max-n.min,isNonNegative:!1,knownZeroBits:0,knownOneBits:0};case"i32.mul":{if(e.min===-1/0||n.min===-1/0)return z();let s=[e.min*n.min,e.min*(n.max===1/0?Number.MAX_SAFE_INTEGER:n.max),(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max)*n.min,(e.max===1/0?Number.MAX_SAFE_INTEGER:e.max)*(n.max===1/0?Number.MAX_SAFE_INTEGER:n.max)];return{min:Math.min(...s),max:Math.max(...s),isNonNegative:e.isNonNegative&&n.isNonNegative,knownZeroBits:0,knownOneBits:0}}case"i32.shr_u":{if(n.min===n.max&&e.max!==1/0){let s=n.min;return{min:0,max:Math.floor(e.max/Math.pow(2,s)),isNonNegative:!0,knownZeroBits:0,knownOneBits:0}}return Ks()}default:return z()}}function Pa(t,e={}){let n=t.functions.map(s=>new kt(s,t,e).run());return{...t,functions:n}}var kt=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(e,n,s={}){this.func=e,this.module=n,this.options=s}run(){this.metrics.varsBefore=this.func.vars.size,this.metrics.instructionsBefore=this.countInstructions();let e=0,n=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(),e++;while(this.changed&&e<n);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 e=0;for(let n of this.func.blocks.values())e+=n.instructions.length;return e}logMetrics(){let e=this.func.name||`func_${this.func.index}`;console.log(`[Optimizer] ${e}:`),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 e=!1;for(let n of this.func.blocks.values())for(let s of n.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")&&(e=!0)}if(e&&this.module)for(let n=0;n<this.module.globals.length;n++){let s=this.module.globals[n];(s.kind!=="definition"||s.mutable)&&this.mutatedGlobals.add(n)}}analyzeValueRanges(){this.valueRanges.clear();for(let e of this.func.blocks.values())for(let n of e.instructions){if(n.id===void 0)continue;let s=n.id,i;switch(n.opcode){case"i32.const":{let r=n.immediates[0];i=Cn(r);break}case"i32.and":{let r=this.resolveAlias(n.args[0]),o=this.resolveAlias(n.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=Se("i32.and",c,u);break}case"i32.add":{let r=this.resolveAlias(n.args[0]),o=this.resolveAlias(n.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=Se("i32.add",c,u);break}case"i32.sub":{let r=this.resolveAlias(n.args[0]),o=this.resolveAlias(n.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=Se("i32.sub",c,u);break}case"i32.mul":{let r=this.resolveAlias(n.args[0]),o=this.resolveAlias(n.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=Se("i32.mul",c,u);break}case"i32.shr_u":{let r=this.resolveAlias(n.args[0]),o=this.resolveAlias(n.args[1]),c=this.valueRanges.get(r)||z(),u=this.valueRanges.get(o)||z();i=Se("i32.shr_u",c,u);break}default:i=z()}this.valueRanges.set(s,i)}for(let[e,n]of this.valueRanges)if(n.isNonNegative){let s=this.func.vars.get(e);s&&(s.isNonNegative=!0)}}analyze(){this.usageCounts.clear(),this.varDefinitions.clear();for(let[n]of this.func.vars)this.usageCounts.set(n,0);let e=n=>{if(n.id!==void 0){let s=this.varDefinitions.get(n.id)||[];s.push(n),this.varDefinitions.set(n.id,s)}if(n.args){for(let s of n.args)if(s>=0){let i=this.usageCounts.get(s)||0;this.usageCounts.set(s,i+1)}}};for(let[n,s]of this.func.blocks)for(let i of s.instructions)e(i);if(this.func.inlinedExpressionMap)for(let n of this.func.inlinedExpressionMap.values())e(n)}resolveAlias(e){let n=e,s=0;for(;this.aliasMap.has(n)&&s<100;)n=this.aliasMap.get(n),s++;return n}performConstantFolding(){for(let e of this.func.blocks.values()){let n=[];for(let s=0;s<e.instructions.length;s++){let i=e.instructions[s];if(i.args&&(i.args=i.args.map(o=>this.resolveAlias(o))),this.isConst(i.opcode)){n.push(i);continue}let r=this.tryFold(i);r===null?n.push(i):typeof r=="object"?(i.id!==void 0&&(r.id=i.id),n.push(r),this.changed=!0):i.id!==void 0&&(this.aliasMap.set(i.id,r),this.changed=!0)}e.instructions=n}}performCopyPropagation(){let e=new Set;for(let[n,s]of this.varDefinitions)s.length===1&&e.add(n);for(let n of this.func.blocks.values()){let s=[];for(let i of n.instructions){if(i.opcode==="assign"&&i.args?.length===1&&i.id!==void 0&&e.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)}n.instructions=s}}performCSE(){for(let e of this.func.blocks.values()){let n=new Map,s=new Set,i=new Set,r=[];for(let o of e.instructions){if(o.opcode==="local.set"||o.opcode==="local.tee"){let l=o.immediates?.[0];l!==void 0&&(s.add(l),this.invalidateDependentExpressions(n,"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(n,"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=n.get(c);if(u!==void 0){this.aliasMap.set(o.id,u),this.metrics.commonSubexprsEliminated++,this.changed=!0;continue}n.set(c,o.id),r.push(o)}e.instructions=r}}invalidateDependentExpressions(e,n,s){let i=`${n}::${s}`,r=[];for(let o of e.keys())o.includes(i)&&r.push(o);for(let o of r)e.delete(o)}createExprSignature(e){let n=e.args?.map(s=>this.resolveAlias(s))||[];return this.isCommutativeOp(e.opcode)&&n.sort((s,i)=>s-i),`${e.opcode}:${n.join(",")}:${JSON.stringify(e.immediates||[])}`}isCommutativeOp(e){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(e)}performInlining(){this.func.inlinedExpressionMap||(this.func.inlinedExpressionMap=new Map);let e=new Set;for(let[n,s]of this.usageCounts){if(this.func.inlinedExpressionMap?.has(n))continue;let i=this.varDefinitions.get(n);if(i&&i.length===1){let r=i[0];if(this.isConst(r.opcode)){this.func.inlinedExpressionMap.set(n,r),e.add(n),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(n,r),e.add(n),this.metrics.expressionsInlined++,this.changed=!0;continue}if(s===1&&!this.isSafeToInlineLocalGet(n,o)||s!==1)continue}this.func.inlinedExpressionMap.set(n,r),e.add(n),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(n,o)&&(this.func.inlinedExpressionMap.set(n,r),e.add(n),this.metrics.expressionsInlined++,this.changed=!0);continue}}if(s===1&&this.isPureOp(r.opcode)){this.func.inlinedExpressionMap.set(n,r),e.add(n),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(n,r),e.add(n),this.metrics.expressionsInlined++,this.changed=!0)}}if(e.size>0)for(let n of this.func.blocks.values()){let s=[];for(let i of n.instructions)i.id!==void 0&&e.has(i.id)||s.push(i);n.instructions=s}}isCheapToInline(e){if(!e.args||e.args.length===0)return!0;for(let n of e.args){let s=this.resolveAlias(n),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(e,n){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===e&&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]===n){let o=r.args?.[0];if(o!==void 0&&this.usesVar(o,e,s,i)&&(this.usageCounts.get(e)||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]===n)return!1}return this.isLocalNeverWrittenInReachableBlocks(s,n)}usesVar(e,n,s,i){for(let r=i+1;r<s.instructions.length;r++){let o=s.instructions[r];if(o.id===e){if(o.args?.includes(n))return!0;for(let c of o.args||[])if(this.usesVar(c,n,s,i))return!0;return!1}}return!1}isLocalNeverWrittenInReachableBlocks(e,n){let s=new Set,i=[...e.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]===n)return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSafeToInlineGlobalGet(e,n){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===e&&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]===n||o.opcode==="call"||o.opcode==="call_indirect")return!1}return this.isGlobalNeverWrittenInReachableBlocks(s,n)}isGlobalNeverWrittenInReachableBlocks(e,n){let s=new Set,i=[...e.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]===n||c.opcode==="call"||c.opcode==="call_indirect")return!1;for(let c of o.succs||[])s.has(c)||i.push(c)}}return!0}isSimpleInlinable(e){let n=e.opcode;if(this.isConst(n))return!0;if(n.startsWith("i32.")||n.startsWith("i64.")||n.startsWith("f32.")||n.startsWith("f64."))return!(n.includes("load")||n.includes("store"));if(n==="local.get")return!0;if(n==="global.get"){let s=e.immediates?.[0];return!(s!==void 0&&this.mutatedGlobals.has(s))}return n==="select"}performBooleanCanonicalization(){for(let e of this.func.blocks.values()){let n=[];for(let s of e.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:[]};n.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:[]};n.push(u),this.metrics.booleansCanonized++,this.changed=!0;continue}}n.push(s)}e.instructions=n}}getSingleDef(e){let n=this.varDefinitions.get(e);return n&&n.length===1?n[0]:null}isDefinitelyBoolean(e){let n=this.getSingleDef(e);if(!n)return!1;let s=n.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"&&n.args?.length===3){let i=this.getSingleDef(this.resolveAlias(n.args[0])),r=this.getSingleDef(this.resolveAlias(n.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 e=r=>r>0&&(r&r-1)===0,n=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&&e(g)){let k=n(g),h=this.func.nextVarId++;this.func.vars.set(h,{id:h,type:"i32"});let b={type:"instr",id:h,opcode:"i32.const",args:[],immediates:[k]};o.push(b);let x={type:"instr",id:c.id,opcode:"i32.shr_u",args:[l,h],immediates:[]};o.push(x),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.div_s"&&g!==null&&e(g)){let k=n(g),h=g-1,b=s(31);o.push(b.instr);let x=i("i32.shr_s",l,b.varId);o.push(x.instr);let I=s(h);o.push(I.instr);let V=i("i32.and",x.varId,I.varId);o.push(V.instr);let O=i("i32.add",l,V.varId);o.push(O.instr);let U=s(k);o.push(U.instr);let N={type:"instr",id:c.id,opcode:"i32.shr_s",args:[O.varId,U.varId],immediates:[]};o.push(N),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_u"&&g!==null&&e(g)){let k=g-1,h=this.func.nextVarId++;this.func.vars.set(h,{id:h,type:"i32"});let b={type:"instr",id:h,opcode:"i32.const",args:[],immediates:[k]};o.push(b);let x={type:"instr",id:c.id,opcode:"i32.and",args:[l,h],immediates:[]};o.push(x),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.rem_s"&&g!==null&&e(g)){let k=n(g),h=g-1;if(this.valueRanges.get(l)?.isNonNegative===!0){let $=this.func.nextVarId++;this.func.vars.set($,{id:$,type:"i32"});let B={type:"instr",id:$,opcode:"i32.const",args:[],immediates:[h]};o.push(B);let A={type:"instr",id:c.id,opcode:"i32.and",args:[l,$],immediates:[]};o.push(A),this.metrics.strengthReductions++,this.changed=!0;continue}let I=s(31);o.push(I.instr);let V=i("i32.shr_s",l,I.varId);o.push(V.instr);let O=s(h);o.push(O.instr);let U=i("i32.and",V.varId,O.varId);o.push(U.instr);let N=i("i32.add",l,U.varId);o.push(N.instr);let W=s(k);o.push(W.instr);let J=i("i32.shr_s",N.varId,W.varId);o.push(J.instr);let ee=s(k);o.push(ee.instr);let ne=i("i32.shl",J.varId,ee.varId);o.push(ne.instr);let Ie={type:"instr",id:c.id,opcode:"i32.sub",args:[l,ne.varId],immediates:[]};o.push(Ie),this.metrics.strengthReductions++,this.changed=!0;continue}if(u==="i32.mul"&&g!==null&&e(g)){let k=n(g),h=this.func.nextVarId++;this.func.vars.set(h,{id:h,type:"i32"});let b={type:"instr",id:h,opcode:"i32.const",args:[],immediates:[k]};o.push(b);let x={type:"instr",id:c.id,opcode:"i32.shl",args:[l,h],immediates:[]};o.push(x),this.metrics.strengthReductions++,this.changed=!0;continue}let S=this.getSingleDef(l),y=S&&S.opcode==="i32.const"?S.immediates[0]:null;if(u==="i32.mul"&&y!==null&&e(y)){let k=n(y),h=this.func.nextVarId++;this.func.vars.set(h,{id:h,type:"i32"});let b={type:"instr",id:h,opcode:"i32.const",args:[],immediates:[k]};o.push(b);let x={type:"instr",id:c.id,opcode:"i32.shl",args:[d,h],immediates:[]};o.push(x),this.metrics.strengthReductions++,this.changed=!0;continue}o.push(c)}r.instructions=o}}performDCE(){let e=new Set,n=[],s=i=>{let r=this.resolveAlias(i);r>=0&&!e.has(r)&&(e.add(r),n.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(;n.length>0;){let i=n.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&&e.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 e=new Map;for(let n of this.func.blocks.values())for(let s of n.instructions)if(s.opcode==="local.get"){let i=s.immediates?.[0];i!==void 0&&e.set(i,(e.get(i)||0)+1)}for(let n of this.func.blocks.values()){let s=[];for(let i of n.instructions){if(i.opcode==="local.set"||i.opcode==="local.tee"){let r=i.immediates?.[0];if(r!==void 0&&(e.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)}n.instructions=s}}performBlockFlattening(){let e=this.func.blocks,n=!0;for(;n;){n=!1;let s=Array.from(e.keys()).sort((i,r)=>i-r);for(let i of s){let r=e.get(i);if(r&&r.succs.length===1){let o=r.succs[0];if(o===r.id)continue;let c=e.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=e.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])}}}e.delete(o),this.changed=!0,n=!0,this.metrics.blocksFlattened++}}}}}performLocalLoadStoreForwarding(){for(let e of this.func.blocks.values()){let n=new Map,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&&i.args&&i.args.length>0){let o=this.resolveAlias(i.args[0]);n.set(r,o)}}if(i.opcode==="local.get"&&i.id!==void 0){let r=i.immediates?.[0];if(r!==void 0&&n.has(r)){let o=n.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)}e.instructions=s}}hasSideEffects(e){let n=e.opcode;return!!(n==="br"||n==="br_if"||n==="return"||n==="unreachable"||n==="call"||n.includes("store")||n.includes("memory.grow")||n==="local.set"||n==="local.tee"||e.id===void 0)}isConst(e){return e==="i32.const"||e==="i64.const"||e==="f32.const"||e==="f64.const"||e==="v128.const"}tryFold(e){let n=[],s=!0;if(e.args)for(let i of e.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:n.push(c)}else s=!1;if(s&&e.args&&e.args.length>0){let i=e.opcode;if(i.startsWith("i32."))return this.foldI32(e,n);if(i.startsWith("f32."))return this.foldF32(e,n);if(i.startsWith("i32x4.")||i.startsWith("f32x4.")||i==="v128.const")return this.foldSIMD(e,n)}if(e.opcode==="f32.mul"&&e.args&&e.args.length===2)for(let i=0;i<2;i++){let r=this.resolveAlias(e.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:e.id,opcode:"f32.const",args:[],immediates:[0]}}return this.tryIdentityReduction(e)}tryIdentityReduction(e){if(!e.args||e.args.length<2)return null;let n=e.opcode,s=this.resolveAlias(e.args[0]),i=this.resolveAlias(e.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(n==="i32.add"){if(l(u)===0)return s;if(l(c)===0)return i}else if(n==="i32.sub"){if(l(u)===0)return s}else if(n==="i32.mul"){if(l(u)===1)return s;if(l(c)===1)return i}else if(n==="i32.and"){if(l(u)===-1)return s;if(l(c)===-1)return i}else if(n==="i32.or"){if(l(u)===0)return s;if(l(c)===0)return i}else if(n==="i32.xor"){if(l(u)===0)return s;if(l(c)===0)return i}else if(n==="i32.shl"||n==="i32.shr_s"||n==="i32.shr_u"){if(l(u)===0)return s}else if(n==="f32.add"){if(d(u)===0)return s;if(d(c)===0)return i}else if(n==="f32.sub"){if(d(u)===0)return s}else if(n==="f32.mul"){if(d(u)===1)return s;if(d(c)===1)return i}else if(n==="f32.div"){if(d(u)===1)return s}else if(n==="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(n==="f64.sub"){if((p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===0)return s}else if(n==="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(n==="f64.div"&&(p=>p&&p.opcode==="f64.const"?p.immediates[0]:null)(u)===1)return s;return null}foldI32(e,n){let s=n[0].immediates[0],i=n.length>1?n[1].immediates[0]:0,r=null;switch(e.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:e.id,opcode:"i32.const",args:[],immediates:[r]}:null}foldF32(e,n){let s=n[0].immediates[0],i=n.length>1?n[1].immediates[0]:0,r=null;switch(e.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?e.opcode.includes("eq")||e.opcode.includes("lt")||e.opcode.includes("gt")||e.opcode.includes("le")||e.opcode.includes("ne")?{type:"instr",id:e.id,opcode:"i32.const",args:[],immediates:[r]}:{type:"instr",id:e.id,opcode:"f32.const",args:[],immediates:[r]}:null}foldSIMD(e,n){let s=e.opcode,i=r=>r.opcode==="v128.const"?r.immediates:null;if(s==="i32x4.splat"){if(n.length>0&&n[0].opcode==="i32.const"){let r=n[0].immediates[0],o=new Int32Array([r,r,r,r]);return{type:"instr",id:e.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(n.length<2)return null;let r=i(n[0]),o=i(n[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:e.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((e,n)=>e.bodyBlocks.size-n.bodyBlocks.size);for(let e of this.loops)this.hoistLoopInvariants(e)}}computeDominators(){this.dominators.clear();let e=this.func.blocks,n=this.func.entryBlock,s=new Set(e.keys());for(let r of e.keys())r===n?this.dominators.set(r,new Set([n])):this.dominators.set(r,new Set(s));let i=!0;for(;i;){i=!1;for(let[r,o]of e){if(r===n)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(e,n){let s=this.dominators.get(n);return s?s.has(e):!1}detectLoops(){this.loops=[];let e=this.func.blocks;for(let[n,s]of e)for(let i of s.succs)if(this.dominates(i,n)){let r=this.collectNaturalLoop(i,n);r&&this.loops.push(r)}}collectNaturalLoop(e,n){let s=new Set([e]),i=new Set,r=new Set([n]),o=[n];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(e);if(u){for(let l of u.preds)if(!s.has(l)){c=l;break}}return{headerBlock:e,bodyBlocks:s,exitBlocks:i,backedgeBlocks:r,preheaderBlock:c}}hoistLoopInvariants(e){if(!e.preheaderBlock)return;let n=this.func.blocks.get(e.preheaderBlock);if(!n)return;let s=new Set;for(let l of e.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 e.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,e,s,i)&&(i.add(f.id),this.canHoist(f)&&r.push({blockId:l,instr:f}),o=!0))}}if(r.length===0)return;let c=n.instructions.length;if(c>0){let l=n.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}n.instructions.splice(c,0,...u)}isLoopInvariant(e,n,s,i){if(this.isConst(e.opcode))return!0;if(e.opcode==="local.get"){let r=e.immediates?.[0];return!this.mutatedLocals.has(r)}if(e.opcode==="global.get"){let r=e.immediates?.[0];return!this.mutatedGlobals.has(r)}if(!this.isPureOp(e.opcode))return!1;if(!e.args||e.args.length===0)return!0;for(let r of e.args){let o=this.resolveAlias(r);if(s.has(o)&&!i.has(o))return!1}return!0}canHoist(e){if(this.hasSideEffects(e))return!1;if(e.opcode==="local.get"){let n=e.immediates?.[0];if(this.mutatedLocals.has(n))return!1}if(e.opcode==="global.get"){let n=e.immediates?.[0];if(this.mutatedGlobals.has(n))return!1}return!0}isPureOp(e){return this.isConst(e)?!0:e.startsWith("i32.")||e.startsWith("i64.")||e.startsWith("f32.")||e.startsWith("f64.")?!(e.includes("load")||e.includes("store")):e==="local.get"||e==="global.get"||e==="select"?!0:e.startsWith("i8x16.")||e.startsWith("i16x8.")||e.startsWith("i32x4.")||e.startsWith("i64x2.")||e.startsWith("f32x4.")||e.startsWith("f64x2.")||e.startsWith("v128.")?!(e.includes("load")||e.includes("store")):!1}};function Ua(t){let e=t.functions.map(n=>Qs(n));return{types:t.types,functions:e,globals:t.globals,memories:t.memories,data:t.data,exports:t.exports,imports:t.imports}}function Qs(t){let n=new wt(t).process();return{index:t.index,name:t.name,params:t.params,results:t.results,locals:t.locals,vars:t.vars,body:n,immutableParams:t.immutableParams,inlinedExpressionMap:t.inlinedExpressionMap}}var wt=class{func;blocks;dominators=new Map;immediateDominator=new Map;constructor(e){this.func=e,this.blocks=e.blocks}process(){this.calculateDominators();let e=new Set(this.blocks.keys()),n=this.getReachable(this.func.entryBlock);if(this.func.index===3){let s=`Func ${this.func.name||this.func.index}: Blocks ${n.size}
|
|
3
|
+
`;for(let i of n){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(n,this.func.entryBlock)}calculateDominators(){let e=Array.from(this.blocks.keys()),n=this.func.entryBlock;for(let i of e)i===n?this.dominators.set(i,new Set([i])):this.dominators.set(i,new Set(e));let s=!0;for(;s;){s=!1;for(let i of e){if(i===n)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(e){let n=new Set,s=[e];for(;s.length>0;){let i=s.pop();if(n.has(i))continue;n.add(i);let r=this.blocks.get(i);if(r)for(let o of r.succs)s.push(o)}return n}reloop(e,n,s,i){if(!e.has(n))return{kind:"simple",instructions:[]};let r=this.blocks.get(n),o=(h,b)=>{if(s===void 0||b===s)return[];if(e.has(h))return[];let x=this.blocks.get(h);if(!x)return[];if(x.preds.length!==1||x.preds[0]!==b)return[];let I=x.instructions[x.instructions.length-1];return!I||I.opcode!=="br"?[]:x.instructions.filter(V=>V.opcode!=="br"&&V.opcode!=="br_if"&&V.opcode!=="return"&&V.opcode!=="unreachable")},u=s===n?[]:r.preds.filter(h=>e.has(h)&&this.dominators.get(h)?.has(n));if(u.length>0){let h=new Set,b=[...u];for(h.add(n);b.length>0;){let $=b.pop();if(!h.has($)&&e.has($)){h.add($);let B=this.blocks.get($);for(let A of B.preds)b.push(A)}}let x=new Set;for(let $ of h){let B=this.blocks.get($);for(let A of B.succs)if(e.has(A)&&!h.has(A)&&A!==n){let G=B.instructions[B.instructions.length-1];G&&(G.opcode==="br"||G.opcode==="br_if")&&G.immediates?.[0]===A?x.add(A):this.blocks.get(A).succs.length===0||x.add(A)}}let I=!0;for(;I;){I=!1;for(let $ of e)if(!h.has($)){if(x.has($))continue;let B=this.blocks.get($),A=B.preds.some(te=>h.has(te)),G=B.succs.length===0||B.succs.every(te=>h.has(te)||te===n?!0:s!==void 0&&te===s?!1:!e.has(te));A&&G&&(h.add($),I=!0)}}let V=`loop_${n}`,O=r.preds;r.preds=r.preds.filter($=>!u.includes($));let U=this.reloop(h,n,n);r.preds=O;let N=new Set,W="";for(let $ of h){let B=this.blocks.get($),A=B.instructions.map(G=>G.opcode).join(",");W+=`Block ${$}: Succs [${B.succs.join(",")}] Preds [${B.preds.join(",")}] Instrs [${A}]
|
|
5
|
+
`;for(let G of B.succs)e.has(G)&&!h.has(G)&&G!==n&&N.add(G)}let J=new Set;for(let $ of e)h.has($)||J.add($);let ee,ne=!1;if(N.size>0)for(let $ of N){let B=this.blocks.get($);if(B&&B.preds.length>0){ne=!0;break}}if(ne&&N.size>0){let $=N.values().next().value;$!==void 0&&(ee=this.reloop(J,$,s,i))}return{kind:"block",children:[{kind:"loop",body:U,label:V},...ee?[ee]:[]]}}let l=s!==void 0&&r.succs.some(h=>h===s);if(r.succs.length===2&&!l){let h=r.succs[0],b=r.succs[1],x=-1;for(let I=r.instructions.length-1;I>=0;I--){let V=r.instructions[I];if(V.opcode==="br_if"){x=V.args[0];break}V.opcode!=="br"&&V.opcode}if(x!==-1){let I=E=>{if(s===void 0)return!1;if(E===s)return!0;let M=this.blocks.get(E);return M&&M.succs.length===1&&M.succs[0]===s?M.instructions.every(j=>j.opcode==="br"||j.opcode==="nop"):!1},V=s!==void 0&&I(h),O=s!==void 0&&I(b);if(V&&!O){let E=r.instructions.filter(M=>M.opcode!=="br"&&M.opcode!=="br_if");return{kind:"block",children:[...E.length>0?[{kind:"simple",instructions:E}]:[],{kind:"if",condition:x,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}}]}}if(O&&!V){let E=r.instructions.filter(M=>M.opcode!=="br"&&M.opcode!=="br_if");return{kind:"block",children:[...E.length>0?[{kind:"simple",instructions:E}]:[],{kind:"if",condition:x,thenBranch:{kind:"break",label:""},elseBranch:{kind:"continue",label:""}}]}}let U=s!==void 0&&!e.has(h)&&e.has(b),N=s!==void 0&&!e.has(b)&&e.has(h);if(U){let E=r.instructions.filter(we=>we.opcode!=="br"&&we.opcode!=="br_if"),M=this.reloop(e,b,s,i),H=o(h,n),j=H.length>0?{kind:"block",children:[{kind:"simple",instructions:H},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...E.length>0?[{kind:"simple",instructions:E}]:[],{kind:"if",condition:x,thenBranch:j},M]}}if(N){let E=r.instructions.filter(we=>we.opcode!=="br"&&we.opcode!=="br_if"),M=this.reloop(e,h,s,i),H=o(b,n),j=H.length>0?{kind:"block",children:[{kind:"simple",instructions:H},{kind:"break",label:""}]}:{kind:"break",label:""};return{kind:"block",children:[...E.length>0?[{kind:"simple",instructions:E}]:[],{kind:"if",condition:x,thenBranch:M,elseBranch:j}]}}let W=this.blocks.get(h),J=this.blocks.get(b),ee=W?new Set(W.succs):new Set,ne=J?new Set(J.succs):new Set,Ie=[...ee].filter(E=>ne.has(E)),$,B,A,G=ne.has(h),te=ee.has(b);if(G)e.has(h)?$=new Set(this.getReachableInSet(h,e,s)):$=new Set,B=new Set,A=new Set([b]);else if(te)$=new Set(this.getReachableInSet(b,e,s)),B=new Set([h]),A=new Set;else if(Ie.length>0)$=new Set(this.getReachableInSet(Ie[0],e,s)),B=new Set([h]),A=new Set([b]);else{let E=this.getReachableInSet(h,e,s),M=this.getReachableInSet(b,e,s),H=[...E].filter(j=>M.has(j));$=new Set(H),B=new Set([...E].filter(j=>!$.has(j)&&this.blocks.has(j))),A=new Set([...M].filter(j=>!$.has(j)&&this.blocks.has(j)))}let Et=s!==void 0&&(h===s||b===s||!e.has(h)||!e.has(b))&&!(e.has(h)&&e.has(b)),ue,ke;if(Et)ke=!0,ue=!0;else{let E=!e.has(h),M=!e.has(b);ue=!$.has(b)&&A.size>0||M,ke=!$.has(h)&&B.size>0||E}let le=null,de=new Set;if(!ke)de.add(h);else for(let E of B){let M=this.blocks.get(E);if(M)for(let H of M.succs)$.has(H)&&de.add(H)}if(!ue)de.add(b);else for(let E of A){let M=this.blocks.get(E);if(M)for(let H of M.succs)$.has(H)&&de.add(H)}if(de.size>0){let E=de.values().next().value;E!==void 0&&(le=E)}let fe,pe,qn=ke&&B.size===0,Hn=ue&&A.size===0,me=(E,M)=>E.length===0?M:{kind:"block",children:[{kind:"simple",instructions:E},M]},Rt=E=>E===s||E===i?[]:o(E,n);if(qn){let E=Rt(h);h===s?fe=me(E,{kind:"continue",label:""}):h===i?fe=me(E,{kind:"simple",instructions:[]}):fe=me(E,{kind:"break",label:""})}else ke?fe=this.reloop(B,h,s,le||i):fe={kind:"simple",instructions:[]};if(Hn){let E=Rt(b);b===s?pe=me(E,{kind:"continue",label:""}):b===i?pe=me(E,{kind:"simple",instructions:[]}):pe=me(E,{kind:"break",label:""})}else ue?pe=this.reloop(A,b,s,le||i):pe=void 0;let Vt=le!==s&&le!==null&&$.size>0?this.reloop($,le,s,i):void 0,$t=r.instructions.filter(E=>E.opcode!=="br"&&E.opcode!=="br_if");return{kind:"block",children:[...$t.length>0?[{kind:"simple",instructions:$t}]:[],{kind:"if",condition:x,thenBranch:fe,elseBranch:pe},...Vt?[Vt]:[]]}}else console.log(`Failed to find condVar for block ${n} despite having 2 succs and br_if?`)}let d=[],f=[],p=!1;for(let h of r.instructions)if(h.opcode==="br"){let b=h.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||e.has(b)||(f.push({kind:"break",label:""}),s===void 0&&(p=!0))}else if(h.opcode==="br_if"){let b=h.immediates[0],x=h.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:x,thenBranch:{kind:"continue",label:""},elseBranch:{kind:"break",label:""}});else if(!(i!==void 0&&b===i)){if(s!==void 0&&!e.has(b))d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:x,thenBranch:{kind:"break",label:""}});else if(!e.has(b)&&s===void 0)d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0),f.push({kind:"if",condition:x,thenBranch:{kind:"break",label:""}}),p=!0;else if(e.has(b)){d.length>0&&(f.push({kind:"simple",instructions:[...d]}),d.length=0);let I=this.reloop(e,b,s);f.push({kind:"if",condition:x,thenBranch:I})}}}else d.push(h);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 S=r.succs.filter(h=>e.has(h)&&(s===void 0||h!==s)),y=new Set;r.instructions.forEach(h=>{h.opcode==="br_if"&&y.add(h.immediates[0])});let k=S.filter(h=>!y.has(h));if(k.length>0){let h=k[0];if(h!==n){let b=this.reloop(e,h,s);return{kind:"block",children:f.length>0?[g,b]:[b]}}}else if(r.succs.length===1){let h=r.succs[0],b=s!==void 0&&h===s,x=f.some(I=>I.kind==="continue"||I.kind==="break"||I.kind==="return")||d.some(I=>I.opcode==="return"||I.opcode==="unreachable");if(e.has(h)&&!b&&!x){let I=this.reloop(e,h,s);return{kind:"block",children:f.length>0?[g,I]:[I]}}}return g}getReachableInSet(e,n,s){let i=new Set;if(!n.has(e)||s!==void 0&&e===s)return i;let r=[e];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)n.has(u)&&(s===void 0||u!==s)&&r.push(u)}return i}leadsToBackEdge(e,n,s){if(e===n)return!0;if(!s.has(e))return!1;let i=new Set,r=[e];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===n)return!0;s.has(u)&&r.push(u)}}return!1}};var Wa="0.1",Ga="0.2",qa="0.2",Js;function ye(t){return t?.specVersion??Js??"0.2"}function Dn(t){return ye(t)==="0.2"}function Ne(){return{advisories:[],warnings:[],errors:[],demotions:[],featuresUsed:{usesF64:!1,usesI64:!1,usesF64Memory:!1,usesI64Memory:!1,usesSimdF64x2:!1,usesSimdI64x2:!1,usesSimdEmulation:!1}}}function Ha(t){for(let e of[...t.advisories,...t.warnings,...t.errors])e.recovery??=ti(e);return t}function ei(){return{f64:"allow",i64:"deny"}}function Tn(t){let e=ei(),n=t?.demotionPolicy;return{f64:n?.f64??e.f64,i64:n?.i64??e.i64}}function ti(t){switch(t.code){case"ERR_F64_DEMOTION_REQUIRED":return{action:"add_extension",extension:"gasm:demote-f64:1.0"};case"ERR_MUTABLE_GLOBAL":return t.message.toLowerCase().includes("imported")?{action:"refactor_source"}:{action:"add_extension",extension:"gasm:mutable-globals:1.0"};case"ERR_SIMD_EXTENSION_REQUIRED":return{action:"add_extension",extension:"gasm:simd:1.0"};case"ERR_RELAXED_SIMD_EXTENSION_REQUIRED":return{action:"add_extension",extension:"gasm:relaxed-simd:1.0"};case"ERR_PASSIVE_SEGMENT":return{action:"add_extension",extension:"gasm:bulk-memory:1.0"};case"ERR_F64_DEMOTION_DENIED":return{action:"set_demotion_policy",demotionPolicy:{f64:"allow"}};case"ERR_I64_UNSUPPORTED":case"ERR_I64_MEMORY_UNSUPPORTED":case"ERR_I64_CONST_OUT_OF_RANGE":return{action:"set_demotion_policy",demotionPolicy:{i64:"allow-lossy"}};default:return}}function ve(t){return(t&65280)===64768}function ni(t){return t&255}var si=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]),Nn=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]),On=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]),ii=new Set([a.f64_load,a.f64_store]),ri=new Set([20,33,34,71,72,73,74,75,76,236,237,239,240,241,242,243,244,245,246,247]),oi=new Set([18,29,30,192,193,195,196,203,204,205,206,209,213,214,215,216,217,218,219]);function ai(t){let e=t.params.includes("i64")||t.results.includes("i64")||t.locals.some(c=>c.type==="i64"),n=e,s=!1,i=!1,r=!1,o=e;for(let c=0;c<t.body.length;c++){let u=t.body[c];if(!ve(u.opcode)){if(u.opcode===a.i64_const){let l=t.body[c+1];if(l&&ve(l.opcode))continue}if(On.has(u.opcode)){n=!0,s=!0,o=!0;continue}if(Nn.has(u.opcode)&&(n=!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<t.body.length;c++){let u=t.body[c];if(ve(u.opcode)||!Nn.has(u.opcode)&&!On.has(u.opcode))continue;if(u.opcode===a.i64_const){let d=t.body[c+1];if(d&&ve(d.opcode))continue}u.opcode===a.i64_const||u.opcode===a.i32_wrap_i64||(i=!0)}return{usesI64:n,usesI64Memory:s,usesI64ParamOrResultOrLocal:e,hasDisallowedI64Op:i,hasI64ConstOutOfRange:r,usesAnyScalarI64:o}}function ci(t){let e=t.params.includes("f64")||t.results.includes("f64")||t.locals.some(r=>r.type==="f64"),n=e,s=!1,i=e;for(let r of t.body)if(!ve(r.opcode)){if(ii.has(r.opcode)){n=!0,s=!0,i=!0;continue}si.has(r.opcode)&&(n=!0,i=!0)}return{usesF64:n,usesF64Memory:s,usesF64ParamOrResultOrLocal:e,usesAnyScalarF64:i}}function ui(t){let e=!1,n=!1,s=!1;for(let i of t.body){if(!ve(i.opcode))continue;let r=ni(i.opcode);ri.has(r)&&(e=!0),oi.has(r)&&(n=!0)}return{usesSimdF64x2:e,usesSimdI64x2:n,usesSimdEmulation:s}}function Pn(t,e){let n=Ne(),s=Tn(e),i=Dn(e),r=new Set,o=new Set;for(let c of t.functions){let u=c.index,l=c.name??`func_${u}`,d=ai(c),f=ci(c),p=ui(c);n.featuresUsed.usesI64||=d.usesI64,n.featuresUsed.usesI64Memory||=d.usesI64Memory,n.featuresUsed.usesF64||=f.usesF64,n.featuresUsed.usesF64Memory||=f.usesF64Memory,n.featuresUsed.usesSimdF64x2||=p.usesSimdF64x2,n.featuresUsed.usesSimdI64x2||=p.usesSimdI64x2,n.featuresUsed.usesSimdEmulation||=p.usesSimdEmulation,(f.usesF64||p.usesSimdF64x2)&&(f.usesF64Memory?n.errors.push({severity:"error",code:"ERR_F64_MEMORY_UNSUPPORTED",message:`Function ${l} uses f64 load/store; memory encoding for f64 is not defined.`,functionIndex:u,functionName:l}):s.f64==="deny"?n.errors.push({severity:"error",code:"ERR_F64_DEMOTION_DENIED",message:`Function ${l} uses f64; demotion to f32 is denied by policy.`,functionIndex:u,functionName:l}):r.has(u)||(n.warnings.push({severity:"warning",code:"WARN_F64_DEMOTED",message:`Function ${l} uses f64; lowering to f32 (precision loss).`,functionIndex:u,functionName:l}),n.demotions.push({kind:"f64->f32",functionIndex:u,functionName:l}),r.add(u))),!i&&(s.i64==="deny"?(d.usesI64Memory&&n.errors.push({severity:"error",code:"ERR_I64_MEMORY_UNSUPPORTED",message:`Function ${l} uses i64 load/store; memory encoding for i64 is not defined. Enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l}),d.usesI64ParamOrResultOrLocal&&n.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${l} uses scalar i64 parameters/results/locals; i64 is unsupported by default.`,functionIndex:u,functionName:l}),d.hasI64ConstOutOfRange&&n.errors.push({severity:"error",code:"ERR_I64_CONST_OUT_OF_RANGE",message:`Function ${l} uses i64.const outside signed i32 range; enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l}),d.hasDisallowedI64Op&&n.errors.push({severity:"error",code:"ERR_I64_UNSUPPORTED",message:`Function ${l} uses scalar i64 operations; enable lossy i64 demotion to allow.`,functionIndex:u,functionName:l})):d.usesAnyScalarI64&&(o.has(u)||(n.warnings.push({severity:"warning",code:"WARN_I64_DEMOTED_LOSSY",message:`Function ${l} uses i64; lowering to i32 (lossy, modulo 2^32). Shift operations are masked to 31 bits, changing semantics for shift amounts >= 32.`,functionIndex:u,functionName:l}),n.demotions.push({kind:"i64->i32-lossy",functionIndex:u,functionName:l}),o.add(u))))}if(e.warningsAsErrors&&n.warnings.length>0)for(let c of n.warnings)n.errors.push({severity:"error",code:"ERR_WARNINGS_AS_ERRORS",message:c.message,functionIndex:c.functionIndex,functionName:c.functionName});return{diagnostics:n,policy:s}}function Qa(t){return t?{workItemsX:t.workItemsX,workItemsY:t.workItemsY,workItemsZ:t.workItemsZ,workgroupSizeX:t.workgroupSizeX,workgroupSizeY:t.workgroupSizeY,workgroupSizeZ:t.workgroupSizeZ,isParallelized:t.isParallelized}:{workItemsX:1,workItemsY:1,workItemsZ:1,workgroupSizeX:1,workgroupSizeY:1,workgroupSizeZ:1,isParallelized:!1}}function Ja(t){let e=Ne();return e.errors.push(...t.map(n=>({severity:"error",code:n.code,message:n.message,functionName:n.functionName??void 0}))),e}var li=new Set(["global_invocation_id_x","global_invocation_id_y","global_invocation_id_z","local_invocation_id_x","local_invocation_id_y","local_invocation_id_z","workgroup_id_x","workgroup_id_y","workgroup_id_z","num_workgroups_x","num_workgroups_y","num_workgroups_z"]);function Oe(t){let e=[{group:0,binding:0,kind:"storage",rw:"read_write",role:"memory",wgslName:"memory"}],n=1,s=0;for(let o of t.imports){if(o.kind!=="global")continue;let c=s++;o.module==="gasm"&&li.has(o.name)||e.push({group:0,binding:n++,kind:"uniform",role:"imported_global",wasmName:`${o.module}.${o.name}`,wgslName:`global_${c}`,type:fi(o.globalType)})}return new Set(t.extensions??[]).has("gasm:mutable-globals:1.0")&&t.globals.some(o=>o.kind==="definition"&&o.mutable)&&e.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"mutable_globals",wgslName:"mutable_globals"}),t.atomicRegion&&e.push({group:0,binding:n++,kind:"storage",rw:"read_write",role:"atomic_region",wgslName:"atomic_region",atomic:!0}),di(e),e}function di(t){let e=new Set;for(let n of t){let s=`${n.group}:${n.binding}`;if(e.has(s))throw new Error(`Duplicate Gasm binding: ${s}`);e.add(s)}}function fi(t){if(t==="i32"||t==="i64"||t==="f32"||t==="f64")return t;if(t==="v128")return"vec4<u32>"}function rc(t,e={}){let n=Oe(t),s=n.find(l=>l.role==="atomic_region"),i=yi(t),r={specVersion:ye(e.options),extensions:[...t.extensions??[]],memory:{sizeBytes:_i(t),atomicRegion:Si(t.atomicRegion,s)},entryPoints:Un(t).map(l=>({name:l.name,wgslName:pi(l.name),workgroupSize:hi(t,l.index,e)})),bindings:n,dataSegments:i.memorySegments},o=gi(t);o!==void 0&&(r.memory.workgroupMemoryBytes=o),i.atomicSegments.length>0&&(r.atomicDataSegments=i.atomicSegments);let c=t.data.map((l,d)=>({segment:l,index:d})).filter(({segment:l})=>l.mode==="passive").map(({segment:l,index:d})=>Ii(l,d));c.length>0&&(r.passiveDataSegments=c);let u=bi(t);return u.length>0&&(r.mutableGlobals=u),r}function oc(t){let e=[],n=oe(t);if(!n)return{valid:!1,errors:["metadata must be an object"]};let s=["specVersion","extensions","memory","entryPoints","bindings","dataSegments"];for(let f of s)f in n||e.push(`missing required property: ${f}`);for(let f of Object.keys(n))[...s,"mutableGlobals","passiveDataSegments","atomicDataSegments","extras"].includes(f)||e.push(`unexpected property: ${f}`);n.specVersion!=="0.1"&&n.specVersion!=="0.2"&&e.push("specVersion must be 0.1 or 0.2"),Array.isArray(n.extensions)||e.push("extensions must be an array"),oe(n.memory)||e.push("memory must be an object"),(!Array.isArray(n.entryPoints)||n.entryPoints.length===0)&&e.push("entryPoints must be a non-empty array"),Array.isArray(n.bindings)||e.push("bindings must be an array"),Array.isArray(n.dataSegments)||e.push("dataSegments must be an array");let i=Array.isArray(n.bindings)?n.bindings:[],r=new Set;for(let f of i){let p=oe(f);if(!p){e.push("binding must be an object");continue}Z(p.group)||e.push("binding.group invalid"),Z(p.binding)||e.push("binding.binding invalid"),typeof p.kind!="string"&&e.push("binding.kind invalid"),typeof p.role!="string"&&e.push("binding.role invalid");let g=`${p.group}:${p.binding}`;r.has(g)&&e.push(`duplicate binding: ${g}`),r.add(g)}let o=Array.isArray(n.entryPoints)?n.entryPoints:[];for(let f of o){let p=oe(f);if(!p){e.push("entryPoint must be an object");continue}(typeof p.name!="string"||p.name.length===0)&&e.push("entryPoint.name invalid"),(typeof p.wgslName!="string"||p.wgslName.length===0)&&e.push("entryPoint.wgslName invalid"),(!Array.isArray(p.workgroupSize)||p.workgroupSize.length!==3||!p.workgroupSize.every(g=>Ei(g)))&&e.push("entryPoint.workgroupSize invalid")}let c=oe(n.memory);c&&!Z(c.sizeBytes)&&e.push("memory.sizeBytes invalid"),c&&"workgroupMemoryBytes"in c&&!Z(c.workgroupMemoryBytes)&&e.push("memory.workgroupMemoryBytes invalid");let u=Array.isArray(n.dataSegments)?n.dataSegments:[];for(let f of u){let p=oe(f);if(!p){e.push("dataSegment must be an object");continue}Z(p.memory)||e.push("dataSegment.memory invalid"),Z(p.offset)||e.push("dataSegment.offset invalid"),Z(p.byteLength)||e.push("dataSegment.byteLength invalid"),typeof p.dataB64!="string"&&e.push("dataSegment.dataB64 invalid")}let l=Array.isArray(n.passiveDataSegments)?n.passiveDataSegments:[];for(let f of l){let p=oe(f);if(!p){e.push("passiveDataSegment must be an object");continue}Z(p.index)||e.push("passiveDataSegment.index invalid"),Z(p.byteLength)||e.push("passiveDataSegment.byteLength invalid"),typeof p.dataB64!="string"&&e.push("passiveDataSegment.dataB64 invalid"),typeof p.dropped!="boolean"&&e.push("passiveDataSegment.dropped invalid")}let d=Array.isArray(n.atomicDataSegments)?n.atomicDataSegments:[];for(let f of d){let p=oe(f);if(!p){e.push("atomicDataSegment must be an object");continue}Z(p.memory)||e.push("atomicDataSegment.memory invalid"),Z(p.offset)||e.push("atomicDataSegment.offset invalid"),Z(p.byteLength)||e.push("atomicDataSegment.byteLength invalid"),typeof p.dataB64!="string"&&e.push("atomicDataSegment.dataB64 invalid")}return e.length===0?{valid:!0}:{valid:!1,errors:e}}function ac(t,e){let n=[...t.extensions??[]].sort(),s=[...e.extensions].sort();Ln(n,s,"extensions");for(let[i,r]of t.workgroupSizes??new Map){let o=Un(t).find(u=>u.index===i);if(!o)continue;let c=e.entryPoints.find(u=>u.name===o.name);if(!c)throw new Error(`metadata missing entry point ${o.name}`);Ln(r,c.workgroupSize,"workgroupSize")}if(t.atomicRegion){let i=e.memory.atomicRegion;if(!i)throw new Error("metadata missing atomicRegion");Ri(t.atomicRegion,i)}}function Un(t){return t.exports.filter(e=>{if(e.kind!=="func")return!1;let n=mi(t,e.index);return!!n&&n.params.length===0&&n.results.length===0})}function pi(t){let e=wi(t);return e==="main"?"main":`${e}_entry`}function cc(t,e){return!!e.workgroupSize&&(t.workgroupSizes?.size??0)>0}function mi(t,e){let n=t.imports.filter(i=>i.kind==="func");if(e<n.length){let i=n[e].typeIndex;return i===void 0?void 0:t.types[i]}let s=t.functions.find(i=>i.index===e);if(s)return{params:s.params,results:s.results}}function hi(t,e,n){if(n.options?.workgroupSize)return n.options.workgroupSize;let s=t.workgroupSizes?.get(e);if(s)return s;let i=n.dispatchInfo;return i?.isParallelized?[i.workgroupSizeX,i.workgroupSizeY,i.workgroupSizeZ]:ye(n.options)==="0.2"?[64,1,1]:[1,1,1]}function _i(t){let e=t.memories[0];return e?e.min*65536:(t.imports.find(s=>s.kind==="mem"&&!(s.module==="gasm"&&s.name==="workgroup_memory"))?.memoryMin??0)*65536}function gi(t){if(!new Set(t.extensions??[]).has("gasm:workgroup-memory:1.0"))return;let n=t.imports.find(s=>s.kind==="mem"&&s.module==="gasm"&&s.name==="workgroup_memory");if(n)return n.memoryMax??n.memoryMin??0}function bi(t){if(!(t.extensions??[]).includes("gasm:mutable-globals:1.0"))return[];let e=[],n=0;for(let s of t.globals){if(s.kind!=="definition"||!s.mutable)continue;let i=xi(s.type);e.push({index:s.index,type:s.type,offset:n,byteLength:i,...s.initValue!==void 0?{initialValue:s.initValue.toString()}:{}}),n+=i}return e}function xi(t){return t==="i64"||t==="f64"?8:4}function Si(t,e){return t?{offset:t.offset,length:t.length,binding:{group:e?.group??0,binding:e?.binding??0}}:null}function yi(t){let e=[],n=[];for(let s of t.data)s.mode==="active"&&vi(s,t.atomicRegion).forEach(i=>{i.atomic?n.push(i.metadata):e.push(i.metadata)});return{memorySegments:e,atomicSegments:n}}function vi(t,e){let n=ki(t.offset);if(!e||t.memoryIndex!==e.memoryIndex)return[Me(t,n,t.data,!1)];let s=n+t.data.length,i=e.offset,r=e.offset+e.length,o=[];if(n<Math.min(s,i)){let l=Math.min(s,i);o.push(Me(t,n,t.data.subarray(0,l-n),!1))}let c=Math.max(n,i),u=Math.min(s,r);if(c<u&&o.push(Me(t,c,t.data.subarray(c-n,u-n),!0)),Math.max(n,r)<s){let l=Math.max(n,r);o.push(Me(t,l,t.data.subarray(l-n),!1))}return o.length===0&&o.push(Me(t,n,t.data,!1)),o}function Me(t,e,n,s){return{atomic:s,metadata:{memory:t.memoryIndex,offset:e,byteLength:n.length,dataB64:zn(n)}}}function Ii(t,e){return{index:e,byteLength:t.data.length,dataB64:zn(t.data),dropped:!1}}function ki(t){let n=t.find(s=>s.opcode===a.i32_const)?.immediates[0];return typeof n=="number"?n:0}function zn(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function wi(t){let e="";for(let n=0;n<t.length;n++){let s=t[n],i=s==="_"||/[A-Za-z]/.test(s)||n>0&&/[0-9]/.test(s);e+=i?s:"_"}return(e.length===0||/^[0-9]/.test(e))&&(e=`_${e}`),e}function oe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Z(t){return Number.isInteger(t)&&t>=0}function Ei(t){return Number.isInteger(t)&&t>=1}function Ln(t,e,n){if(JSON.stringify(t)!==JSON.stringify(e))throw new Error(`${n} mismatch: ${JSON.stringify(t)} != ${JSON.stringify(e)}`)}function Ri(t,e){if(t.offset!==e.offset||t.length!==e.length)throw new Error("atomicRegion mismatch")}var Vi={f64:"allow",i64:"allow-lossy"},$i={f64:"deny",i64:"deny"};function gc(t,e={}){let n=e.mode??"integrator",s=n==="integrator"&&(e.patchWasm??!0),i=Fi(n,e),r=[],o=[],c=Le(t);if(Ue(c))return o.push({severity:"error",code:c.code??v.ERR_PARSE,message:c.message,functionName:c.functionName,instructionName:c.instructionName,offset:c.offset}),Oi(t,i,r,o);let u=c;Mi(u,o);let l=new Set(u.extensions??[]),d=u.globals.some(x=>x.kind==="definition"&&x.mutable);n==="integrator"&&i.specVersion==="0.2"&&d&&!l.has("gasm:mutable-globals:1.0")&&(i.specVersion="0.1",r.push({severity:"advisory",code:"GASM_ADVISORY_MUTABLE_GLOBALS_V01_COMPAT",message:'Mutable defined globals detected; selected specVersion "0.1" for per-invocation private semantics.',recovery:{action:"refactor_source"}}));let f=Bi(u,i),p=new Set(l);for(let x of f){if(p.add(x.extension),l.has(x.extension))continue;let I={action:"add_extension",extension:x.extension};n==="strict"?o.push({severity:"error",code:x.code,message:x.message,recovery:I}):r.push({severity:"advisory",code:"GASM_ADVISORY_EXTENSION_ADDED",message:`Added required extension ${x.extension}.`,recovery:I})}Ai(u,i,o);let g=[...p].sort(),S=t;if(s)try{S=At(t,g)}catch(x){o.push({severity:"error",code:v.ERR_PARSE,message:x instanceof Error?x.message:String(x)})}let y=u,k=n==="integrator"&&!s&&f.some(x=>!l.has(x.extension));if(s&&o.length===0){let x=Le(S);Ue(x)?o.push({severity:"error",code:x.code??v.ERR_PARSE,message:x.message}):y=x}else y.extensions=g;if(o.length===0&&!k){let x=Dt(y,{strictConformance:i.specVersion==="0.2"||i.strictConformance});ze(x)&&o.push({severity:"error",code:x.code??v.ERR_VALIDATION,message:x.message,functionName:x.functionName,instructionName:x.instructionName,offset:x.offset})}let h=Oe(y),b=h.some(x=>x.role==="mutable_globals")?Ni(y):void 0;return{wasmBytes:S,compileOptions:i,bindings:h,...b?{mutableGlobalsInit:b}:{},extensions:g,advisories:r,errors:o}}function Fi(t,e){let{mode:n,patchWasm:s,...i}=e,r=t==="integrator"?Vi:$i;return{...i,specVersion:e.specVersion??"0.2",demotionPolicy:{...r,...e.demotionPolicy}}}function Bi(t,e){if(e.specVersion!=="0.2")return[];let n=new Map,s=r=>{n.set(r.extension,r)},i=t.functions.flatMap(r=>r.body);return(Wn(t,"f64")||i.some(Ci))&&s({extension:"gasm:demote-f64:1.0",code:v.ERR_F64_DEMOTION_REQUIRED,message:"f64 usage requires gasm:demote-f64:1.0 in Gasm v0.2."}),t.globals.some(r=>r.kind==="definition"&&r.mutable)&&s({extension:"gasm:mutable-globals:1.0",code:v.ERR_MUTABLE_GLOBAL,message:"Mutable globals require gasm:mutable-globals:1.0 in Gasm v0.2."}),(Wn(t,"v128")||i.some(r=>Di(r.opcode)))&&s({extension:"gasm:simd:1.0",code:"ERR_SIMD_EXTENSION_REQUIRED",message:"SIMD usage requires gasm:simd:1.0 in Gasm v0.2."}),i.some(r=>Ti(r.opcode))&&s({extension:"gasm:relaxed-simd:1.0",code:"ERR_RELAXED_SIMD_EXTENSION_REQUIRED",message:"Relaxed SIMD usage requires gasm:relaxed-simd:1.0 in Gasm v0.2."}),(t.data.some(r=>r.mode==="passive")||i.some(r=>r.opcode>=a.memory_init&&r.opcode<=a.memory_fill))&&s({extension:"gasm:bulk-memory:1.0",code:v.ERR_PASSIVE_SEGMENT,message:"Bulk memory usage requires gasm:bulk-memory:1.0."}),i.some(r=>(r.opcode&65280)===65024)&&s({extension:"gasm:atomics:1.0",code:v.ERR_UNSUPPORTED_INSTR,message:"Atomic instructions require gasm:atomics:1.0."}),t.imports.some(r=>r.kind==="mem"&&r.module==="gasm"&&r.name==="workgroup_memory")&&s({extension:"gasm:workgroup-memory:1.0",code:v.ERR_MULTI_MEMORY,message:"The gasm.workgroup_memory import requires gasm:workgroup-memory:1.0."}),e.mathExtension&&s({extension:"gasm:math:1.0",code:"ERR_MATH_EXTENSION_REQUIRED",message:"The math extension option requires gasm:math:1.0."}),i.some(r=>r.opcode>=a.i32_extend8_s&&r.opcode<=a.i64_extend32_s)&&s({extension:"gasm:sign-extension:1.0",code:"ERR_SIGN_EXTENSION_REQUIRED",message:"Sign-extension instructions require gasm:sign-extension:1.0."}),i.some(r=>r.opcode>=a.i32_trunc_sat_f32_s&&r.opcode<=a.i64_trunc_sat_f64_u)&&s({extension:"gasm:nontrapping-fptoint:1.0",code:"ERR_NONTRAPPING_FPTOINT_REQUIRED",message:"Non-trapping float-to-int instructions require gasm:nontrapping-fptoint:1.0."}),t.types.some(r=>r.results.length>1)&&s({extension:"gasm:multi-value:1.0",code:"ERR_MULTI_VALUE_EXTENSION_REQUIRED",message:"Multi-value function types require gasm:multi-value:1.0."}),[...n.values()].sort((r,o)=>r.extension.localeCompare(o.extension))}function Mi(t,e){for(let n of Re(t.customSections).diagnostics)e.push({severity:"error",code:n.code,message:n.message})}function Ai(t,e,n){let s=Pn(t,e);for(let i of s.diagnostics.errors)n.push({...i,recovery:i.code==="ERR_F64_DEMOTION_DENIED"?{action:"set_demotion_policy",demotionPolicy:{f64:"allow"}}:i.code.startsWith("ERR_I64")?{action:"set_demotion_policy",demotionPolicy:{i64:"allow-lossy"}}:i.recovery})}function Wn(t,e){return t.types.some(n=>n.params.includes(e)||n.results.includes(e))||t.globals.some(n=>n.type===e)||t.functions.some(n=>n.params.includes(e)||n.results.includes(e)||n.locals.some(s=>s.type===e))}function Ci(t){return t.name.startsWith("f64.")||t.opcode===a.f32_demote_f64||t.opcode===a.f64_promote_f32||t.opcode===a.i32_trunc_f64_s||t.opcode===a.i32_trunc_f64_u||t.opcode===a.i64_trunc_f64_s||t.opcode===a.i64_trunc_f64_u||t.opcode===a.f64_convert_i32_s||t.opcode===a.f64_convert_i32_u||t.opcode===a.f64_convert_i64_s||t.opcode===a.f64_convert_i64_u}function Di(t){return(t&65280)===64768||t>>>16===253}function Ti(t){return t>>>16===253&&(t&65535)>=256}function Ni(t){let e=t.globals.filter(o=>o.kind==="definition"&&o.mutable);if(e.length===0)return;let n=e.reduce((o,c)=>o+Gn(c.type),0),s=new ArrayBuffer(n),i=new DataView(s),r=0;for(let o of e){let c=o.initValue??0;switch(o.type){case"i32":i.setInt32(r,Number(c),!0);break;case"f32":i.setFloat32(r,Number(c),!0);break;case"i64":i.setBigInt64(r,BigInt(c),!0);break;case"f64":i.setFloat64(r,Number(c),!0);break}r+=Gn(o.type)}return{byteLength:n,data:new Uint32Array(s)}}function Gn(t){return t==="i64"||t==="f64"?8:4}function Oi(t,e,n,s){return{wasmBytes:t,compileOptions:e,bindings:[],extensions:[],advisories:n,errors:s}}function Sc(t){let e=t.gasm_core_rs_version_major,n=t.gasm_core_rs_smoke_compile,s=t.gasm_core_rs_alloc,i=t.gasm_core_rs_dealloc,r=t.gasm_core_rs_compile,o=t.gasm_core_rs_result_ptr,c=t.gasm_core_rs_result_len,u=t.memory;if(typeof e!="function"||typeof n!="function"||typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof o!="function"||typeof c!="function"||!(u instanceof WebAssembly.Memory))throw new Error("Invalid gasm-core-rs Wasm exports");let l=()=>{let d=o(),f=c(),p=new TextDecoder().decode(new Uint8Array(u.buffer,d,f));return JSON.parse(p)};return{versionMajor:()=>e(),smokeCompile:d=>n(d),compile:(d,f={})=>{let p=s(d.length);try{new Uint8Array(u.buffer,p,d.length).set(d);let g=ye(f)==="0.2"?2:1,S=f.strictConformance?1:0,y=f.inlineMemoryOps?1:0,k=f.optimize===!1?0:1,h=f.vectorPromotion?1:0;return r(p,d.length,g,S,y,k,h),l()}finally{i(p,d.length)}}}}export{R as a,Ui as b,a as c,v as d,Le as e,Ue as f,Dt as g,ze as h,Ve as i,Tt as j,$e as k,$r as l,Ot as m,Fr as n,Br as o,Mr as p,Pt as q,Lt as r,Fe as s,hs as t,Es as u,Rs as v,Vs as w,$s as x,Zt as y,Va as z,Ba as A,Pa as B,Ua as C,Wa as D,Ga as E,qa as F,ye as G,Dn as H,Ne as I,Ha as J,Pn as K,Sc as L,Qa as M,Ja as N,Oe as O,rc as P,oc as Q,ac as R,pi as S,cc as T,gc as U};
|