@gasm-compiler/core 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as ee,B as te,C as ne,a as w,c as q,d as P,e as D,f as U,g as N,i as z,j as W,m as R,o as j,p as H,q as J,r as K,s as Q,x as X,y as Y,z as Z}from"./chunk-OJJM3SJ5.js";import{a as g}from"./chunk-STDXBN5E.js";import{resolve as de}from"path";import{stat as fe,readFile as De,writeFile as ze,unlink as We,mkdir as Ge}from"fs/promises";import{spawn as Te}from"child_process";import{dirname as qe}from"path";function re(e){let r=e.functions.map(n=>!("parallelLoopInfo"in n)||!n.parallelLoopInfo?n:he(n));return{...e,functions:r}}function he(e){let r=e.parallelLoopInfo.loopLocalIndex,{writes:n}=ge(e.body,r);if(n>0){let t=$(e.body,r);return{...e,body:t}}return e}function ge(e,r){let n=0,t=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===r&&n++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===r&&t++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:n,writes:t}}function $(e,r){switch(e.kind){case"simple":{if(!e.instructions)return e;let n=e.instructions.filter(t=>!((t.opcode==="local.set"||t.opcode==="local.tee")&&t.immediates?.[0]===r));return n.length===0?{kind:"block",children:[]}:{...e,instructions:n}}case"block":{let n=e.children.map(t=>$(t,r)).filter(t=>!ye(t));return{...e,children:n}}case"loop":return{...e,body:$(e.body,r)};case"if":return{...e,thenBranch:$(e.thenBranch,r),elseBranch:e.elseBranch?$(e.elseBranch,r):void 0};case"parallel_loop":return{...e,body:$(e.body,r),epilogue:e.epilogue?$(e.epilogue,r):void 0};case"return":case"break":case"continue":return e}}function ye(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function oe(e){let r=e.functions.map(n=>be(n));return{...e,functions:r}}function be(e){let r=k(e.body,e);return{...e,body:r}}function k(e,r){switch(e.kind){case"loop":{let n=Se(e.body),t=[],o=ie(e.body,n,t,r);return t.length===0?{...e,body:k(e.body,r)}:{kind:"block",children:[{kind:"simple",instructions:t},{...e,body:k(o,r)}],label:void 0}}case"block":return{...e,children:e.children.map(n=>k(n,r))};case"if":return{...e,thenBranch:k(e.thenBranch,r),elseBranch:e.elseBranch?k(e.elseBranch,r):void 0};case"simple":return e;default:return e}}function Se(e){let r=new Set;function n(t){if(t.kind==="simple"&&t.instructions){for(let o of t.instructions)if(o.id!==void 0&&r.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];r.add(-s-1)}}t.kind==="block"&&t.children.forEach(n),t.kind==="loop"&&n(t.body),t.kind==="if"&&(n(t.thenBranch),t.elseBranch&&n(t.elseBranch))}return n(e),r}function ie(e,r,n,t){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)we(i,r,s)?(n.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>ie(s,r,n,t));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function we(e,r,n){if(!Ie(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(r.has(o))return!1}if(e.args){for(let t of e.args)if(r.has(t))return!1}return!0}function Ie(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","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","i64.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","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function se(e){for(let r of e.functions)ve(r);return e}function ve(e){x(e.body,e)}function x(e,r){switch(e.kind){case"simple":$e(e,r);break;case"block":for(let n of e.children)x(n,r);break;case"loop":x(e.body,r);break;case"if":x(e.thenBranch,r),e.elseBranch&&x(e.elseBranch,r);break;case"parallel_loop":x(e.body,r),e.epilogue&&x(e.epilogue,r);break}}function $e(e,r){let n=_e(e.instructions,r);n.length>0&&ke(e,r,n);let t=Ae(e.instructions,r);t.length>0&&Ee(e,r,t)}function ae(e,r){let n=O(e,r);if(!n)return null;if(n.opcode==="i32.shr_u"&&n.args.length===2){if(L(n.args[1],r)!==2)return null;let o=n.args[0];return xe(o,r)}return Me(e,r)}function xe(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0&&t%4===0)return{baseVar:n.args[0],wordOffset:t/4};let o=L(n.args[0],r);return o!==null&&o>=0&&o%4===0?{baseVar:n.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function Me(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0)return{baseVar:n.args[0],wordOffset:t}}return{baseVar:e,wordOffset:0}}function O(e,r){if(r.inlinedExpressionMap){let n=r.inlinedExpressionMap.get(e);if(n)return n}return M(r.body,e)}function M(e,r){switch(e.kind){case"simple":for(let n of e.instructions)if(n.id===r)return n;return null;case"block":for(let n of e.children){let t=M(n,r);if(t)return t}return null;case"loop":return M(e.body,r);case"if":{let n=M(e.thenBranch,r);return n||(e.elseBranch?M(e.elseBranch,r):null)}case"parallel_loop":{let n=M(e.body,r);return n||(e.epilogue?M(e.epilogue,r):null)}default:return null}}function L(e,r){let n=O(e,r);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?n.immediates[0]:null}function _e(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,valueArgs:d.map(h=>h.valueArg),components:p})}a=c+1}}return n}function Ae(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,resultVars:d.map(h=>h.resultVar),components:p})}a=c+1}}return n}function ce(e,r){if(e.length<3)return!1;let n=Math.min(...e),t=Math.max(...e),o=e.length*4;if(t-n>=o)return!1;for(let s=n;s<=t;s++)if(r[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function ke(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[t.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...t.valueArgs],synthetic:!0},a=[...t.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function Ee(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of r.vars.keys())d>s&&(s=d);let i=s+1;r.vars.set(i,{id:i,type:"v128"});let a=e.instructions[t.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=t.resultVars.map((d,m)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[m],synthetic:!0})),p=[...t.instrIndices].sort((d,m)=>d-m);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function ue(e,r){let n={valid:!0,mathImports:[],errors:[],requiredLevel:null},t=r===!0||r==="M0"||r==="M1"||r==="M2",o=r===!0?"M2":r==="M0"||r==="M1"||r==="M2"?r:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!z(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){n.errors.push(w(`Math import ${a.name} has no type index`,{functionName:a.name})),n.valid=!1;continue}let p=e.types[u];if(!p){n.errors.push(w(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),n.valid=!1;continue}let d=W(a.name);if(!d){n.errors.push(w(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),n.valid=!1;continue}let m={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(n.mathImports.push(m),(n.requiredLevel===null||s.indexOf(d.level)>s.indexOf(n.requiredLevel))&&(n.requiredLevel=d.level),!t){n.errors.push(w(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),n.valid=!1;continue}if(o&&!R(a.name,o)){n.errors.push(w(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),n.valid=!1;continue}let h=j(a.name,p.params,p.results);h&&(n.errors.push(w(h,{functionName:a.name})),n.valid=!1)}return n}var le={};for(let[e,r]of Object.entries(q))le[r]=e.replace(/_/g,".");function Ve(e){let r=[];r.push("(module");for(let t of e.memories)r.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of e.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let o=e.types[t.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");r.push(` (import "${t.module}" "${t.name}" (func ${s}${i?" "+i:""}))`)}}let n=new Set;for(let t of e.globals){if(t.kind==="import")continue;let o=t.mutable?"(mut ":"",s=t.mutable?")":"",i="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?i=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(i=`${t.type}.const ${t.initValue}`)),r.push(` (global $${t.index} ${o}${t.type}${s} ${i?`(${i})`:""})`)}for(let t of e.data){let o=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=t.data.length>32?"...":"";r.push(` (data (i32.const ${t.memoryIndex}) "${o}${s}") ;; ${t.data.length} bytes`)}for(let t of e.functions)r.push(""),r.push(...Ce(t,e));if(e.exports.length>0){r.push("");for(let t of e.exports)t.kind==="func"?r.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?r.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&r.push(` (export "${t.name}" (global ${t.index}))`)}return e.startFunctionIndex!==void 0&&r.push(` (start $${e.startFunctionIndex})`),r.push(")"),r.join(`
|
|
1
|
+
import{A as ee,B as te,C as ne,a as w,c as q,d as P,e as D,f as U,g as N,i as z,j as W,m as R,o as j,p as H,q as J,r as K,s as Q,x as X,y as Y,z as Z}from"./chunk-4VQ2UHPG.js";import{a as g}from"./chunk-STDXBN5E.js";import{resolve as de}from"path";import{stat as fe,readFile as De,writeFile as ze,unlink as We,mkdir as Ge}from"fs/promises";import{spawn as Te}from"child_process";import{dirname as qe}from"path";function re(e){let r=e.functions.map(n=>!("parallelLoopInfo"in n)||!n.parallelLoopInfo?n:he(n));return{...e,functions:r}}function he(e){let r=e.parallelLoopInfo.loopLocalIndex,{writes:n}=ge(e.body,r);if(n>0){let t=$(e.body,r);return{...e,body:t}}return e}function ge(e,r){let n=0,t=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===r&&n++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===r&&t++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:n,writes:t}}function $(e,r){switch(e.kind){case"simple":{if(!e.instructions)return e;let n=e.instructions.filter(t=>!((t.opcode==="local.set"||t.opcode==="local.tee")&&t.immediates?.[0]===r));return n.length===0?{kind:"block",children:[]}:{...e,instructions:n}}case"block":{let n=e.children.map(t=>$(t,r)).filter(t=>!ye(t));return{...e,children:n}}case"loop":return{...e,body:$(e.body,r)};case"if":return{...e,thenBranch:$(e.thenBranch,r),elseBranch:e.elseBranch?$(e.elseBranch,r):void 0};case"parallel_loop":return{...e,body:$(e.body,r),epilogue:e.epilogue?$(e.epilogue,r):void 0};case"return":case"break":case"continue":return e}}function ye(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function oe(e){let r=e.functions.map(n=>be(n));return{...e,functions:r}}function be(e){let r=k(e.body,e);return{...e,body:r}}function k(e,r){switch(e.kind){case"loop":{let n=Se(e.body),t=[],o=ie(e.body,n,t,r);return t.length===0?{...e,body:k(e.body,r)}:{kind:"block",children:[{kind:"simple",instructions:t},{...e,body:k(o,r)}],label:void 0}}case"block":return{...e,children:e.children.map(n=>k(n,r))};case"if":return{...e,thenBranch:k(e.thenBranch,r),elseBranch:e.elseBranch?k(e.elseBranch,r):void 0};case"simple":return e;default:return e}}function Se(e){let r=new Set;function n(t){if(t.kind==="simple"&&t.instructions){for(let o of t.instructions)if(o.id!==void 0&&r.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];r.add(-s-1)}}t.kind==="block"&&t.children.forEach(n),t.kind==="loop"&&n(t.body),t.kind==="if"&&(n(t.thenBranch),t.elseBranch&&n(t.elseBranch))}return n(e),r}function ie(e,r,n,t){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)we(i,r,s)?(n.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>ie(s,r,n,t));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function we(e,r,n){if(!Ie(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(r.has(o))return!1}if(e.args){for(let t of e.args)if(r.has(t))return!1}return!0}function Ie(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","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","i64.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","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function se(e){for(let r of e.functions)ve(r);return e}function ve(e){x(e.body,e)}function x(e,r){switch(e.kind){case"simple":$e(e,r);break;case"block":for(let n of e.children)x(n,r);break;case"loop":x(e.body,r);break;case"if":x(e.thenBranch,r),e.elseBranch&&x(e.elseBranch,r);break;case"parallel_loop":x(e.body,r),e.epilogue&&x(e.epilogue,r);break}}function $e(e,r){let n=_e(e.instructions,r);n.length>0&&ke(e,r,n);let t=Ae(e.instructions,r);t.length>0&&Ee(e,r,t)}function ae(e,r){let n=O(e,r);if(!n)return null;if(n.opcode==="i32.shr_u"&&n.args.length===2){if(L(n.args[1],r)!==2)return null;let o=n.args[0];return xe(o,r)}return Me(e,r)}function xe(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0&&t%4===0)return{baseVar:n.args[0],wordOffset:t/4};let o=L(n.args[0],r);return o!==null&&o>=0&&o%4===0?{baseVar:n.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function Me(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0)return{baseVar:n.args[0],wordOffset:t}}return{baseVar:e,wordOffset:0}}function O(e,r){if(r.inlinedExpressionMap){let n=r.inlinedExpressionMap.get(e);if(n)return n}return M(r.body,e)}function M(e,r){switch(e.kind){case"simple":for(let n of e.instructions)if(n.id===r)return n;return null;case"block":for(let n of e.children){let t=M(n,r);if(t)return t}return null;case"loop":return M(e.body,r);case"if":{let n=M(e.thenBranch,r);return n||(e.elseBranch?M(e.elseBranch,r):null)}case"parallel_loop":{let n=M(e.body,r);return n||(e.epilogue?M(e.epilogue,r):null)}default:return null}}function L(e,r){let n=O(e,r);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?n.immediates[0]:null}function _e(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,valueArgs:d.map(h=>h.valueArg),components:p})}a=c+1}}return n}function Ae(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,resultVars:d.map(h=>h.resultVar),components:p})}a=c+1}}return n}function ce(e,r){if(e.length<3)return!1;let n=Math.min(...e),t=Math.max(...e),o=e.length*4;if(t-n>=o)return!1;for(let s=n;s<=t;s++)if(r[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function ke(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[t.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...t.valueArgs],synthetic:!0},a=[...t.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function Ee(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of r.vars.keys())d>s&&(s=d);let i=s+1;r.vars.set(i,{id:i,type:"v128"});let a=e.instructions[t.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=t.resultVars.map((d,m)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[m],synthetic:!0})),p=[...t.instrIndices].sort((d,m)=>d-m);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function ue(e,r){let n={valid:!0,mathImports:[],errors:[],requiredLevel:null},t=r===!0||r==="M0"||r==="M1"||r==="M2",o=r===!0?"M2":r==="M0"||r==="M1"||r==="M2"?r:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!z(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){n.errors.push(w(`Math import ${a.name} has no type index`,{functionName:a.name})),n.valid=!1;continue}let p=e.types[u];if(!p){n.errors.push(w(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),n.valid=!1;continue}let d=W(a.name);if(!d){n.errors.push(w(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),n.valid=!1;continue}let m={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(n.mathImports.push(m),(n.requiredLevel===null||s.indexOf(d.level)>s.indexOf(n.requiredLevel))&&(n.requiredLevel=d.level),!t){n.errors.push(w(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),n.valid=!1;continue}if(o&&!R(a.name,o)){n.errors.push(w(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),n.valid=!1;continue}let h=j(a.name,p.params,p.results);h&&(n.errors.push(w(h,{functionName:a.name})),n.valid=!1)}return n}var le={};for(let[e,r]of Object.entries(q))le[r]=e.replace(/_/g,".");function Ve(e){let r=[];r.push("(module");for(let t of e.memories)r.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of e.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let o=e.types[t.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");r.push(` (import "${t.module}" "${t.name}" (func ${s}${i?" "+i:""}))`)}}let n=new Set;for(let t of e.globals){if(t.kind==="import")continue;let o=t.mutable?"(mut ":"",s=t.mutable?")":"",i="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?i=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(i=`${t.type}.const ${t.initValue}`)),r.push(` (global $${t.index} ${o}${t.type}${s} ${i?`(${i})`:""})`)}for(let t of e.data){let o=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=t.data.length>32?"...":"";r.push(` (data (i32.const ${t.memoryIndex}) "${o}${s}") ;; ${t.data.length} bytes`)}for(let t of e.functions)r.push(""),r.push(...Ce(t,e));if(e.exports.length>0){r.push("");for(let t of e.exports)t.kind==="func"?r.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?r.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&r.push(` (export "${t.name}" (global ${t.index}))`)}return e.startFunctionIndex!==void 0&&r.push(` (start $${e.startFunctionIndex})`),r.push(")"),r.join(`
|
|
2
2
|
`)}function Ce(e,r){let n=[],t=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(n.push(` (func $${e.index} ${t}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)n.push(` (local ${a} (;${c}x;))`)}let s=Be(e.body,2);return n.push(...s),n.push(" )"),n}function Be(e,r){let n=[],t=" ".repeat(r);for(let o of e){let s=Le(o,r);n.push(`${t}${s}`)}return n}function Le(e,r){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:n,immediates:t}=e,o=le[n]||`unknown_0x${n.toString(16)}`;if(!t||t.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${t[0]}`;case"global.get":case"global.set":return`${o} $${t[0]}`;case"i32.const":case"i64.const":return`${o} ${t[0]}`;case"f32.const":case"f64.const":return`${o} ${t[0]}`;case"call":return`${o} $${t[0]}`;case"call_indirect":return`${o} (type ${t[0]})`;case"br":case"br_if":return`${o} ${t[0]}`;case"br_table":let s=t[0].join(" "),i=t[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=t[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let c=t[0],u=t[1],p=[];return u!==0&&p.push(`offset=${u}`),c!==void 0&&p.push(`align=${1<<c}`),`${o}${p.length>0?" "+p.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=t[0],m=t[1],h=[];return m!==0&&h.push(`offset=${m}`),d!==void 0&&h.push(`align=${1<<d}`),`${o}${h.length>0?" "+h.join(" "):""}`}if(o.includes("const")){let d=t.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${t[0]}`:`${o}${t.length>0?" "+t.join(" "):""}`}return`${o}${t.length>0?" "+t.join(" "):""}`}}var it=globalThis.gpu,Oe=globalThis.navigator?.gpu,G=class{constructor(r={}){this.config=r}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let r=await Oe?.requestAdapter?.();if(!r)throw new g("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await r.requestDevice?.(),!this.device)throw new g("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(r){throw r instanceof g?r:new g(`GPU initialization failed: ${r instanceof Error?r.message:String(r)}`,"compilation",String(r))}}createBuffer(r,n,t){if(!this.device)throw new g("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:r,size:n.byteLength,usage:t});return this.queue.writeBuffer(o,0,n.buffer,n.byteOffset,n.byteLength),o}async readBuffer(r,n,t){if(!this.device||!this.queue)throw new g("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(n/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(r,0,s,0,Math.min(n,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new g(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return t==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():t==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:t}}async execute(r,n,t,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new g("Device initialization failed","compilation");try{let c;try{let l=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:r,label:l});let f=await c.getCompilationInfo?.();if(f&&f.messages.length>0){let y=f.messages.filter(b=>b.type==="error");if(y.length>0){let b=y.map(I=>`${I.message} at ${I.lineNum}:${I.linePos}`).join("; ");throw new g(`WGSL compilation failed: ${b}`,"compilation")}}}catch(l){throw l instanceof g?l:new g(`Failed to create shader module: ${l instanceof Error?l.message:String(l)}`,"compilation",String(l))}let u=[],p=0,d=new Map,m=Object.entries(n).sort((l,f)=>l[0]==="memory"?-1:f[0]==="memory"?1:l[0].localeCompare(f[0]));for(let[l,{data:f,type:y}]of m){let b=this.createBuffer(`input_${l}`,f,140);d.set(l,b),u.push({binding:p++,resource:{buffer:b}})}let h=new Map,v=new Map;for(let l of t){if(d.has(l)){let me=d.get(l),T=n[l];h.set(l,me),v.set(l,{size:T.data.byteLength,type:T.type});continue}let f=o.outputBuffers?.[l]??{type:"f32",size:1},y=f.size??1,b=y*4,I=this.device.createBuffer({label:`output_${l}`,size:b,usage:132}),A;f.type==="f32"?A=new Float32Array(y).fill(0):f.type==="i32"?A=new Int32Array(y).fill(0):A=new Uint32Array(y).fill(0),this.queue.writeBuffer(I,0,A.buffer,A.byteOffset,A.byteLength),h.set(l,I),v.set(l,{size:b,type:f.type}),u.push({binding:p++,resource:{buffer:I}})}let _=Object.keys(n).length,E=this.device.createBindGroupLayout({entries:u.map((l,f)=>{let y=f===0&&n.memory!==void 0,b=f>=_;return{binding:f,visibility:4,buffer:{type:!y&&!b?"read-only-storage":"storage"}}})}),S=this.device.createBindGroup({layout:E,entries:u}),V=this.device.createPipelineLayout({bindGroupLayouts:[E]}),C;try{C=this.device.createComputePipeline({layout:V,compute:{module:c,entryPoint:"main"}})}catch(l){throw new g(`Failed to create compute pipeline: ${l instanceof Error?l.message:String(l)}`,"binding",String(l))}try{let l=this.device.createCommandEncoder(),f=l.beginComputePass();f.setPipeline(C),f.setBindGroup(0,S),f.dispatchWorkgroups(i[0],i[1],i[2]),f.end(),this.queue.submit([l.finish()])}catch(l){throw new g(`Compute shader dispatch failed: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}let B={};try{for(let l of t){let f=h.get(l),y=v.get(l);if(!f||!y)throw new g(`Output buffer "${l}" not found`,"readback");B[l]=await this.readBuffer(f,y.size,y.type)}}catch(l){throw l instanceof g?l:new g(`Failed to read back results: ${l instanceof Error?l.message:String(l)}`,"readback",String(l))}finally{let l=new Set;d.forEach(f=>{f.destroy(),l.add(f)}),h.forEach(f=>{l.has(f)||f.destroy()})}return B}catch(c){throw c instanceof g?c:new g(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(r=>r.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function F(e,r={}){let n=te(),t=P(e);if(D(t))return n.errors.push({severity:"error",code:"ERR_PARSE",message:t.message,functionName:t.functionName}),{ok:!1,diagnostics:n};let o=t,s=U(o,{strictConformance:r.strictConformance});if(N(s))return n.errors.push({severity:"error",code:"ERR_VALIDATION",message:s.message,functionName:s.functionName}),{ok:!1,diagnostics:n};let i=s;if(r.mathExtension){let m=ue(o,r.mathExtension);if(!m.valid){for(let h of m.errors)n.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:h.message,functionName:h.functionName});return{ok:!1,diagnostics:n}}}let a=ne(i,r);if(n.warnings.push(...a.diagnostics.warnings),n.errors.push(...a.diagnostics.errors),n.demotions.push(...a.diagnostics.demotions),n.featuresUsed=a.diagnostics.featuresUsed,n.errors.length>0)return{ok:!1,diagnostics:n};let c=X(i);r.optimize!==!1&&(c=Z(c,{verbose:r.verbose??!1}));let u=ee(c);u=H(u),r.optimize!==!1&&(u=J(u)),r.vectorPromotion&&(u=se(u));let p=K();if(r.optimize!==!1){let m=Q(u);u=m.module,p=m.dispatchInfo,u=re(u),u=oe(u)}return{ok:!0,wgsl:Y(u,r,e,p),diagnostics:n,dispatchInfo:p}}function Lt(e,r={}){let n=F(e,r);if(!n.ok){let t=n.diagnostics.errors[0];throw w(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code})}return n.wgsl}function pe(e,r){for(let n of e.warnings){let t=n.functionName?` (${n.functionName})`:"";console.error(`warning${t}: ${n.message}`)}if(r&&e.demotions.length>0){let n=new Map;for(let o of e.demotions)n.set(o.kind,(n.get(o.kind)??0)+1);let t=[...n.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${t.join(", ")}`)}}function Ue(e,r){return new Promise(n=>{let t=Te(e,r,{stdio:["ignore","pipe","pipe"]}),o="",s="";t.stdout.on("data",i=>{o+=String(i)}),t.stderr.on("data",i=>{s+=String(i)}),t.on("close",i=>{n({success:i===0,stdout:o,stderr:s})}),t.on("error",i=>{n({success:!1,stdout:o,stderr:`${s}
|
|
3
3
|
${i.message}`})})})}async function Fe(e,r={}){let{output:n,verbose:t=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=r;try{t&&console.log(`[1/4] Validating input file: ${e}`);let u=de(e);if(!(await fe(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let m=u.replace(/\.(as|ts)$/,".wasm");if(d)t&&console.log("[2/4] Input is WASM, skipping compilation..."),m=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let S=await Ne(),{success:V,stdout:C,stderr:B}=await Ue(S,[u,"-o",m]);if(!V)throw new Error(`AssemblyScript compilation failed:
|
|
4
4
|
${B}`);t&&C&&console.log(C)}t&&console.log("[3/4] Reading WASM binary...");let h=await De(m);t&&(console.log(` WASM size: ${h.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let v={};i&&(v.f64="deny"),a&&(v.i64="allow-lossy");let _=F(h,{optimize:s,demotionPolicy:v,warningsAsErrors:c});if(pe(_.diagnostics,t),!_.ok){let S=_.diagnostics.errors[0];throw new Error(S?.message??"Compilation failed")}let E=_.wgsl;if(n){let S=de(n),V=qe(S);await Ge(V,{recursive:!0}),await ze(S,E,"utf-8"),console.log(t?`
|
package/dist/compiler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b}from"./chunk-
|
|
1
|
+
import{c as a,d as b}from"./chunk-IK2QX46I.js";import"./chunk-4VQ2UHPG.js";import"./chunk-G6YRZSKB.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
|
package/dist/mod.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as n,b as r,c as s,d as t,e as u,f as v}from"./chunk-
|
|
1
|
+
import{a as n,b as r,c as s,d as t,e as u,f as v}from"./chunk-IK2QX46I.js";import{b as a,d as b,e as c,h as d,i as e,j as f,k as g,l as h,n as i,t as j,u as k,v as l,w as m}from"./chunk-4VQ2UHPG.js";import{a as q}from"./chunk-G6YRZSKB.js";import{a as o,b as p}from"./chunk-STDXBN5E.js";export{q as BrowserGPUExecutor,r as DenoGPUExecutor,o as ExecutionError,d as MATH_INTRINSICS,v as compile,s as compileAssemblyScriptToWGSL,t as compileWasmToWGSL,u as compileWithDiagnostics,l as detectSourceLanguage,n as disassembleToWAT,m as extractDebugInfo,i as getIntrinsicsAtLevel,f as getMathSpec,h as getVectorDimension,g as getWgslMapping,a as isCompileError,p as isExecutionError,e as isMathIntrinsic,c as isParseError,j as parseNamesSection,k as parseProducersSection,b as parseWasmModule};
|