agwasa.pas 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. {
  2. Copyright (c) 1998-2010 by the Free Pascal team
  3. This unit implements the WebAssembly text assembler
  4. The text is in S-expression format and should be consumable
  5. By either Binaryen or Wabt
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. ****************************************************************************
  18. }
  19. unit agwasa;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. cclasses,systems, cgutils,
  24. globtype,globals,
  25. symconst,symbase,symdef,symsym, symtype,symcpu,
  26. aasmbase,aasmtai,aasmdata,aasmcpu,
  27. assemble
  28. ,cutils
  29. ,cpubase, cgbase
  30. ,fmodule
  31. ,verbose, itcpuwasm
  32. ,cfileutl, tgcpu;
  33. type
  34. TWatInstrWriter = class;
  35. {# This is a derived class which is used to write
  36. Binaryen-styled assembler.
  37. }
  38. { TWatAssembler }
  39. { TWasaTextAssembler }
  40. TWasaTextAssembler=class(texternalassembler)
  41. protected
  42. dataofs : integer;
  43. procedure WriteOutGlobalInt32(const aname: string; val: integer; isconst: boolean = true);
  44. procedure WriteInstruction(hp: tai);
  45. procedure WriteProcDef(pd: tprocdef; stub: Boolean = false; stubUnreachable: Boolean = true);
  46. procedure WriteProcParams(pd: tprocdef);
  47. procedure WriteProcResult(pd: tprocdef);
  48. procedure WriteSymtableProcdefs(st: TSymtable);
  49. procedure WriteSymtableVarSyms(st: TSymtable);
  50. procedure WriteTempAlloc(p:TAsmList);
  51. procedure WriteExports(p: TAsmList);
  52. procedure WriteUnitExports(st: TSymtable);
  53. procedure WriteImports;
  54. procedure WriteOutPChar(p: pchar; ofs, len: integer);
  55. procedure WriteConstString(lbl: tai_label; str: tai_string);
  56. procedure WriteConstants(p: TAsmList);
  57. public
  58. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  59. procedure WriteTree(p:TAsmList);override;
  60. procedure WriteAsmList;override;
  61. Function DoAssemble:boolean;override;
  62. end;
  63. {# This is the base class for writing instructions.
  64. The WriteInstruction() method must be overridden
  65. to write a single instruction to the assembler
  66. file.
  67. }
  68. { TBinaryenInstrWriter }
  69. { TWatInstrWriter }
  70. TWatInstrWriter = class
  71. constructor create(_owner: TWasaTextAssembler);
  72. procedure WriteInstruction(hp : tai); virtual;
  73. protected
  74. owner: TWasaTextAssembler;
  75. end;
  76. implementation
  77. type
  78. t64bitarray = array[0..7] of byte;
  79. t32bitarray = array[0..3] of byte;
  80. const
  81. line_length = 70;
  82. {****************************************************************************}
  83. { Support routines }
  84. {****************************************************************************}
  85. function fixline(s:string):string;
  86. {
  87. return s with all leading and ending spaces and tabs removed
  88. }
  89. var
  90. i,j,k : integer;
  91. begin
  92. i:=length(s);
  93. while (i>0) and (s[i] in [#9,' ']) do
  94. dec(i);
  95. j:=1;
  96. while (j<i) and (s[j] in [#9,' ']) do
  97. inc(j);
  98. for k:=j to i do
  99. if s[k] in [#0..#31,#127..#255] then
  100. s[k]:='.';
  101. fixline:=Copy(s,j,i-j+1);
  102. end;
  103. function GetWasmName(const st: TSymStr): ansistring;
  104. begin
  105. Result := '$'+st;
  106. Replace(Result, '(','');
  107. Replace(Result, ')','');
  108. end;
  109. function getreferencestring(var ref : treference) : ansistring;
  110. begin
  111. if (ref.index<>NR_NO) then
  112. internalerror(2010122809);
  113. if assigned(ref.symbol) then
  114. begin
  115. // global symbol or field -> full type and name
  116. // ref.base can be <> NR_NO in case an instance field is loaded.
  117. // This register is not part of this instruction, it will have
  118. // been placed on the stack by the previous one.
  119. result:=GetWasmName(ref.symbol.name);
  120. end
  121. else
  122. begin
  123. // local symbol -> stack slot, stored in offset
  124. if ref.base<>NR_STACK_POINTER_REG then
  125. internalerror(2010122810);
  126. result:=tostr(ref.offset);
  127. end;
  128. end;
  129. function constsingle(s: single): ansistring;
  130. begin
  131. // wat2wasm is using strtof() internally
  132. str(s, result); //'0x'+hexstr(longint(t32bitarray(s)),8);
  133. end;
  134. function constdouble(d: double): ansistring;
  135. begin
  136. // force interpretation as double (since we write it out as an
  137. // integer, we never have to swap the endianess). We have to
  138. // include the sign separately because of the way Java parses
  139. // hex numbers (0x8000000000000000 is not a valid long)
  140. //result:=hexstr(abs(int64(t64bitarray(d))),16);
  141. //if int64(t64bitarray(d))<0 then
  142. // result:='-'+result;
  143. //result:='0dx'+result;
  144. str(d, result);
  145. end;
  146. function getopstr(const o:toper) : ansistring;
  147. var
  148. d: double;
  149. s: single;
  150. begin
  151. case o.typ of
  152. top_reg:
  153. // should have been translated into a memory location by the
  154. // register allocator)
  155. if (cs_no_regalloc in current_settings.globalswitches) then
  156. getopstr:=std_regname(o.reg)
  157. else
  158. internalerror(2010122803);
  159. top_const:
  160. str(o.val,result);
  161. top_ref:
  162. getopstr:=getreferencestring(o.ref^);
  163. top_single:
  164. begin
  165. result:=constsingle(o.sval);
  166. end;
  167. top_double:
  168. begin
  169. result:=constdouble(o.dval);
  170. end;
  171. {top_string:
  172. begin
  173. result:=constastr(o.pcval,o.pcvallen);
  174. end;
  175. top_wstring:
  176. begin
  177. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  178. end}
  179. else
  180. internalerror(2010122802);
  181. end;
  182. end;
  183. { TWasaTextAssembler }
  184. procedure TWasaTextAssembler.WriteOutGlobalInt32(const aname: string;
  185. val: integer; isconst: boolean);
  186. begin
  187. writer.AsmWrite(#9);
  188. writer.AsmWrite('(global $');
  189. writer.AsmWrite(aname);
  190. if not isconst then
  191. writer.AsmWrite(' (mut i32)')
  192. else
  193. writer.AsmWrite(' i32');
  194. writer.AsmWrite(' (i32.const ');
  195. writer.AsmWrite( tostr(val));
  196. writer.AsmWrite(')');
  197. writer.AsmWriteLn(')');
  198. end;
  199. procedure TWasaTextAssembler.WriteInstruction(hp: tai);
  200. var
  201. cpu : taicpu;
  202. i : integer;
  203. isprm : boolean;
  204. begin
  205. //writer.AsmWriteLn('instr');
  206. cpu := taicpu(hp);
  207. writer.AsmWrite(#9#9);
  208. writer.AsmWrite(wasm_op2str[cpu.opcode] );
  209. if (cpu.opcode = a_call_indirect) then begin
  210. // special wat2wasm syntax "call_indirect (type x)"
  211. writer.AsmWrite(#9);
  212. // todo: fix
  213. //isprm := true;
  214. //for i:=1 to length(cpu.typecode) do
  215. // if cpu.typecode[i]=':' then
  216. // isprm:=false
  217. // else begin
  218. // if isprm then writer.AsmWrite('(param ')
  219. // else writer.AsmWrite('(result ');
  220. // case cpu.typecode[i] of
  221. // 'i': writer.AsmWrite('i32');
  222. // 'I': writer.AsmWrite('i64');
  223. // 'f': writer.AsmWrite('f32');
  224. // 'F': writer.AsmWrite('f64');
  225. // end;
  226. // writer.AsmWrite(')');
  227. // end;
  228. writer.AsmLn;
  229. exit;
  230. end;
  231. if (cpu.opcode = a_if) then
  232. writer.AsmWrite(' (result i32)') //todo: this is a hardcode, but shouldn't
  233. else
  234. cpu := taicpu(hp);
  235. if cpu.ops<>0 then
  236. begin
  237. for i:=0 to cpu.ops-1 do
  238. begin
  239. writer.AsmWrite(#9);
  240. if (cpu.opcode in AsmOp_LoadStore) and (cpu.oper[i]^.typ = top_ref) then
  241. writer.AsmWrite('offset='+tostr( cpu.oper[i]^.ref^.offset))
  242. else
  243. writer.AsmWrite(getopstr(cpu.oper[i]^));
  244. end;
  245. end;
  246. if (cpu.opcode = a_call_indirect) then
  247. // special wat2wasm syntax "call_indirect (type x)"
  248. writer.AsmWrite(')');
  249. writer.AsmLn;
  250. end;
  251. procedure TWasaTextAssembler.WriteProcDef(pd: tprocdef; stub: Boolean; stubUnreachable: Boolean);
  252. var
  253. i : integer;
  254. begin
  255. if not assigned(tcpuprocdef(pd).exprasmlist) and
  256. not(po_abstractmethod in pd.procoptions) and
  257. ((pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  258. begin
  259. exit;
  260. end;
  261. writer.AsmWriteLn('');
  262. if stub and stubUnreachable then begin
  263. writer.AsmWriteLn(#9';;.weak');
  264. end;
  265. writer.AsmWrite(#9'(func ');
  266. writer.AsmWrite( GetWasmName( pd.mangledname ));
  267. //procsym.RealName ));
  268. //writer.AsmWriteln(MethodDefinition(pd));
  269. {if jvmtypeneedssignature(pd) then
  270. begin
  271. writer.AsmWrite('.signature "');
  272. writer.AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  273. writer.AsmWriteln('"');
  274. end;}
  275. writer.AsmLn;
  276. WriteProcParams(pd);
  277. WriteProcResult(pd);
  278. if not stub then begin
  279. //WriteTempAlloc(tcpuprocdef(pd).exprasmlist);
  280. WriteTree(tcpuprocdef(pd).exprasmlist);
  281. end else begin
  282. if stubUnreachable then
  283. writer.AsmWriteLn(#9#9'unreachable');
  284. end;
  285. writer.AsmWriteln(#9')');
  286. writer.AsmLn;
  287. end;
  288. procedure TWasaTextAssembler.WriteProcParams(pd: tprocdef);
  289. var
  290. i : integer;
  291. prm : tcpuparavarsym;
  292. begin
  293. if not Assigned(pd) or
  294. not Assigned(pd.paras) or
  295. (pd.paras.Count=0) then
  296. exit;
  297. for i:=0 to pd.paras.Count-1 do
  298. begin
  299. prm := tcpuparavarsym(pd.paras[i]);
  300. writer.AsmWrite(#9#9'(param'#9);
  301. case prm.paraloc[callerside].Size of
  302. OS_8..OS_32, OS_S8..OS_S32:
  303. writer.AsmWrite('i32');
  304. OS_64, OS_S64:
  305. writer.AsmWrite('i64');
  306. OS_F32:
  307. writer.AsmWrite('f32');
  308. OS_F64:
  309. writer.AsmWrite('f64');
  310. else
  311. // unsupported calleeside parameter type
  312. Internalerror(2019093001);
  313. end;
  314. writer.AsmWrite(')');
  315. writer.AsmLn;
  316. end;
  317. end;
  318. procedure TWasaTextAssembler.WriteProcResult(pd: tprocdef);
  319. var
  320. bt : TWasmBasicType;
  321. begin
  322. if not assigned(pd) or
  323. not Assigned(pd.returndef) or
  324. (pd.returndef.size = 0)
  325. then exit;
  326. if not defToWasmBasic(pd.returndef, bt) then
  327. bt := wbt_i32;
  328. writer.AsmWrite(#9#9'(result'#9);
  329. case bt of
  330. wbt_i64: writer.AsmWrite('i64');
  331. wbt_f32: writer.AsmWrite('f32');
  332. wbt_f64: writer.AsmWrite('f64');
  333. else
  334. writer.AsmWrite('i32');
  335. end;
  336. writer.AsmWrite(')');
  337. writer.AsmLn;
  338. end;
  339. procedure TWasaTextAssembler.WriteTree(p: TAsmList);
  340. var
  341. ch : char;
  342. hp : tai;
  343. hp1 : tailineinfo;
  344. s : ansistring;
  345. i,pos : longint;
  346. InlineLevel : longint;
  347. do_line : boolean;
  348. t: TWasmBasicType;
  349. const
  350. WasmBasicTypeStr : array [TWasmBasicType] of string = ('unknown','i32','i64','f32','f64','funcref','externref','v128');
  351. begin
  352. if not assigned(p) then
  353. exit;
  354. InlineLevel:=0;
  355. { lineinfo is only needed for al_procedures (PFV) }
  356. do_line:=(cs_asm_source in current_settings.globalswitches);
  357. hp:=tai(p.first);
  358. while assigned(hp) do
  359. begin
  360. prefetch(pointer(hp.next)^);
  361. if not(hp.typ in SkipLineInfo) then
  362. begin
  363. hp1 := hp as tailineinfo;
  364. current_filepos:=hp1.fileinfo;
  365. { no line info for inlined code }
  366. if do_line and (inlinelevel=0) then
  367. begin
  368. { load infile }
  369. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  370. begin
  371. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  372. if assigned(infile) then
  373. begin
  374. { open only if needed !! }
  375. if (cs_asm_source in current_settings.globalswitches) then
  376. infile.open;
  377. end;
  378. { avoid unnecessary reopens of the same file !! }
  379. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  380. { be sure to change line !! }
  381. lastfileinfo.line:=-1;
  382. end;
  383. { write source }
  384. if (cs_asm_source in current_settings.globalswitches) and
  385. assigned(infile) then
  386. begin
  387. if (infile<>lastinfile) then
  388. begin
  389. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  390. if assigned(lastinfile) then
  391. lastinfile.close;
  392. end;
  393. if (hp1.fileinfo.line<>lastfileinfo.line) and
  394. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  395. begin
  396. if (hp1.fileinfo.line<>0) and
  397. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  398. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  399. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  400. { set it to a negative value !
  401. to make that is has been read already !! PM }
  402. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  403. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  404. end;
  405. end;
  406. lastfileinfo:=hp1.fileinfo;
  407. lastinfile:=infile;
  408. end;
  409. end;
  410. case hp.typ of
  411. ait_comment :
  412. Begin
  413. writer.AsmWrite(asminfo^.comment);
  414. writer.AsmWritePChar(tai_comment(hp).str);
  415. writer.AsmLn;
  416. End;
  417. ait_regalloc :
  418. begin
  419. if (cs_asm_regalloc in current_settings.globalswitches) then
  420. begin
  421. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  422. repeat
  423. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  424. if (hp.next=nil) or
  425. (tai(hp.next).typ<>ait_regalloc) or
  426. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  427. break;
  428. hp:=tai(hp.next);
  429. writer.AsmWrite(',');
  430. until false;
  431. writer.AsmWrite(' ');
  432. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  433. end;
  434. end;
  435. ait_tempalloc :
  436. begin
  437. if (cs_asm_tempalloc in current_settings.globalswitches) then
  438. begin
  439. {$ifdef EXTDEBUG}
  440. if assigned(tai_tempalloc(hp).problem) then
  441. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  442. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  443. else
  444. {$endif EXTDEBUG}
  445. end;
  446. end;
  447. ait_align :
  448. begin
  449. end;
  450. ait_section :
  451. begin
  452. end;
  453. ait_datablock :
  454. begin
  455. // internalerror(2010122701);
  456. end;
  457. ait_const:
  458. begin
  459. writer.AsmWriteln('constant');
  460. // internalerror(2010122702);
  461. end;
  462. ait_realconst :
  463. begin
  464. internalerror(2010122703);
  465. end;
  466. ait_string :
  467. begin
  468. pos:=0;
  469. for i:=1 to tai_string(hp).len do
  470. begin
  471. if pos=0 then
  472. begin
  473. writer.AsmWrite(#9'strconst: '#9'"');
  474. pos:=20;
  475. end;
  476. ch:=tai_string(hp).str[i-1];
  477. case ch of
  478. #0, {This can't be done by range, because a bug in FPC}
  479. #1..#31,
  480. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  481. '"' : s:='\"';
  482. '\' : s:='\\';
  483. else
  484. s:=ch;
  485. end;
  486. writer.AsmWrite(s);
  487. inc(pos,length(s));
  488. if (pos>line_length) or (i=tai_string(hp).len) then
  489. begin
  490. writer.AsmWriteLn('"');
  491. pos:=0;
  492. end;
  493. end;
  494. end;
  495. ait_label :
  496. begin
  497. // don't write any labels. Wasm don't support it
  498. // labels are only allowed with the respective block structures
  499. end;
  500. ait_symbol :
  501. begin
  502. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  503. begin
  504. end
  505. else
  506. begin
  507. writer.AsmWrite('data symbol: ');
  508. writer.AsmWriteln(tai_symbol(hp).sym.name);
  509. // internalerror(2010122706);
  510. end;
  511. end;
  512. ait_symbol_end :
  513. begin
  514. end;
  515. ait_instruction :
  516. begin
  517. WriteInstruction(hp);
  518. end;
  519. ait_force_line,
  520. ait_function_name : ;
  521. ait_cutobject :
  522. begin
  523. end;
  524. ait_marker :
  525. if tai_marker(hp).kind=mark_NoLineInfoStart then
  526. inc(InlineLevel)
  527. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  528. dec(InlineLevel);
  529. ait_directive :
  530. begin
  531. { the CPU directive is probably not supported by the JVM assembler,
  532. so it's commented out }
  533. //todo:
  534. writer.AsmWrite(asminfo^.comment);
  535. if tai_directive(hp).directive=asd_cpu then
  536. writer.AsmWrite(asminfo^.comment);
  537. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  538. if tai_directive(hp).name<>'' then
  539. writer.AsmWrite(tai_directive(hp).name);
  540. writer.AsmLn;
  541. end;
  542. ait_local :
  543. begin
  544. for t in tai_local(hp).locals do
  545. begin
  546. writer.AsmWrite(#9#9'(local ');
  547. writer.AsmWrite( WasmBasicTypeStr[ t ] );
  548. writer.AsmWrite(')');
  549. writer.AsmLn;
  550. end;
  551. end;
  552. else
  553. internalerror(2010122707);
  554. end;
  555. hp:=tai(hp.next);
  556. end;
  557. end;
  558. procedure TWasaTextAssembler.WriteAsmList;
  559. var
  560. hal : tasmlisttype;
  561. begin
  562. writer.MarkEmpty;
  563. writer.AsmWriteLn('(module ');
  564. writer.AsmWriteLn('(import "env" "memory" (memory 0)) ;;');
  565. WriteImports;
  566. WriteConstants(current_asmdata.asmlists[al_const]);
  567. WriteConstants(current_asmdata.asmlists[al_typedconsts]);
  568. //current_asmdata.CurrAsmList.labe
  569. { print all global variables }
  570. //current_asmdata.AsmSymbolDict
  571. // for every unit __stack_top is a weak symbol
  572. // __stack_top is strong only for libraries or programs.
  573. if current_module.is_unit then
  574. writer.AsmWriteLn(#9';;.weak');
  575. writer.AsmWrite(#9'(global $__stack_top (mut i32) (i32.const ');
  576. writer.AsmWrite(tostr(globals.stacksize));
  577. writer.AsmWriteLn('))');
  578. WriteSymtableVarSyms(current_module.globalsymtable);
  579. WriteSymtableVarSyms(current_module.localsymtable);
  580. //writer.AsmLn;
  581. { print all global procedures/functions }
  582. WriteSymtableProcdefs(current_module.globalsymtable);
  583. WriteSymtableProcdefs(current_module.localsymtable);
  584. if current_module.islibrary then begin
  585. WriteExports(current_asmdata.asmlists[al_exports]);
  586. end else
  587. WriteUnitExports(current_module.globalsymtable);
  588. //WriteSymtableStructDefs(current_module.globalsymtable);
  589. //WriteSymtableStructDefs(current_module.localsymtable);
  590. //writer.decorator.LinePrefix := '';
  591. writer.AsmWriteLn(')');
  592. writer.AsmLn;
  593. end;
  594. function TWasaTextAssembler.DoAssemble: boolean;
  595. var
  596. t : tcmdstr;
  597. begin
  598. Result:=inherited DoAssemble;
  599. // the tool updates the symbol flags, so the linker
  600. // is capable of producing an executable
  601. if Result then
  602. if FindExe('wasmtool',true,t) then begin
  603. if current_module.is_unit then
  604. // making "common" global variables a week reference
  605. RequotedExecuteProcess(t,' --weak "$__stack_top" --symbolauto '+ObjFileName)
  606. else
  607. RequotedExecuteProcess(t,' --symbolauto '+ObjFileName)
  608. end
  609. else
  610. Message1(exec_e_util_not_found,'wasmtool');
  611. end;
  612. constructor TWasaTextAssembler.CreateWithWriter(info: pasminfo;
  613. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  614. begin
  615. inherited CreateWithWriter(info, wr, freewriter, smart);
  616. end;
  617. procedure TWasaTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  618. var
  619. i : longint;
  620. def : tdef;
  621. begin
  622. if not assigned(st) then
  623. exit;
  624. for i:=0 to st.DefList.Count-1 do
  625. begin
  626. def:=tdef(st.DefList[i]);
  627. case def.typ of
  628. procdef :
  629. begin
  630. { methods are also in the static/globalsymtable of the unit
  631. -> make sure they are only written for the objectdefs that
  632. own them }
  633. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  634. (def.owner=st)) and
  635. not(df_generic in def.defoptions) and
  636. not (po_external in tprocdef(def).procoptions)
  637. then
  638. begin
  639. WriteProcDef(tprocdef(def));
  640. if assigned(tprocdef(def).localst) then
  641. WriteSymtableProcdefs(tprocdef(def).localst);
  642. end;
  643. end;
  644. else
  645. ;
  646. end;
  647. end;
  648. end;
  649. procedure TWasaTextAssembler.WriteSymtableVarSyms(st: TSymtable);
  650. var
  651. i : integer;
  652. sym : tsym;
  653. begin
  654. if not assigned(st) then
  655. exit;
  656. for i:=0 to st.SymList.Count-1 do
  657. begin
  658. sym:=tsym(st.SymList[i]);
  659. case sym.typ of
  660. staticvarsym:
  661. begin
  662. //WriteFieldSym(tabstractvarsym(sym));
  663. //if (sym.typ=staticvarsym) and
  664. // assigned(tstaticvarsym(sym).defaultconstsym) then
  665. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  666. WriteOutGlobalInt32(tcpustaticvarsym(sym).mangledname, dataofs);
  667. inc(dataofs, tcpustaticvarsym(sym).getsize);
  668. end;
  669. fieldvarsym:
  670. begin
  671. writer.AsmWriteLn(';; field');
  672. end;
  673. constsym:
  674. begin
  675. //if (sym.typ=staticvarsym) and
  676. // assigned(tstaticvarsym(sym).defaultconstsym) then
  677. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  678. //{ multiple procedures can have constants with the same name }
  679. //if not assigned(sym.owner.defowner) or
  680. // (tdef(sym.owner.defowner).typ<>procdef) then
  681. // WriteConstSym(tconstsym(sym));
  682. writer.AsmWriteLn(';; constant');
  683. end;
  684. {procsym:
  685. begin
  686. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  687. if not(df_generic in tprocdef(tprocsym(sym).procdeflist[j]).defoptions) then
  688. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  689. end;}
  690. else
  691. ;
  692. end;
  693. end;
  694. end;
  695. procedure TWasaTextAssembler.WriteTempAlloc(p: TAsmList);
  696. var
  697. hp: tai;
  698. tmp: array of tai_tempalloc;
  699. mx : integer;
  700. i : integer;
  701. begin
  702. if not assigned(p) then
  703. exit;
  704. mx := -1;
  705. hp:=tai(p.first);
  706. while assigned(hp) do
  707. begin
  708. //prefetch(pointer(hp.next)^);
  709. if (hp.typ = ait_tempalloc) and
  710. tai_tempalloc(hp).allocation and
  711. (tai_tempalloc(hp).temppos >= mx) then
  712. mx := tai_tempalloc(hp).temppos+1;
  713. hp:=tai(hp.next);
  714. end;
  715. if (mx <= 0) then exit; // no temp allocations used
  716. SetLength(tmp, mx);
  717. hp:=tai(p.first);
  718. while assigned(hp) do
  719. begin
  720. //prefetch(pointer(hp.next)^);
  721. if (hp.typ = ait_tempalloc) and
  722. (tai_tempalloc(hp).allocation) and
  723. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  724. begin
  725. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  726. dec(mx);
  727. if mx = 0 then break;
  728. end;
  729. hp:=tai(hp.next);
  730. end;
  731. for i:=0 to length(tmp)-1 do
  732. begin
  733. if tmp[i] = nil then continue;
  734. writer.AsmWrite(#9'(local'#9);
  735. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  736. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  737. writer.AsmWrite(')');
  738. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  739. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  740. writer.AsmLn;
  741. end;
  742. end;
  743. procedure TWasaTextAssembler.WriteExports(p: TAsmList);
  744. var
  745. hp: tai;
  746. x: tai_export_name;
  747. cnt: integer;
  748. begin
  749. if not Assigned(p) then Exit;
  750. hp:=tai(p.First);
  751. if not Assigned(hp) then Exit;
  752. cnt := 0;
  753. while Assigned(hp) do begin
  754. case hp.typ of
  755. ait_export_name:
  756. inc(cnt);
  757. else
  758. ;
  759. end;
  760. hp := tai_export_name(hp.Next);
  761. end;
  762. // writting out table, so wat2wasm can create reallocation symbols
  763. writer.AsmWrite(#9'(table ');
  764. writer.AsmWrite(tostr(cnt));
  765. writer.AsmWrite(' anyfunc)');
  766. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  767. hp:=tai(p.First);
  768. while Assigned(hp) do begin
  769. case hp.typ of
  770. ait_export_name:
  771. begin
  772. x:=tai_export_name(hp);
  773. writer.AsmWrite(#9#9);
  774. writer.AsmWriteLn(GetWasmName(x.intname));
  775. end;
  776. else
  777. ;
  778. end;
  779. hp := tai_export_name(hp.Next);
  780. end;
  781. writer.AsmWriteLn(#9') ');
  782. // writing export sections
  783. hp:=tai(p.First);
  784. while Assigned(hp) do begin
  785. case hp.typ of
  786. ait_export_name:
  787. begin
  788. x:=tai_export_name(hp);
  789. writer.AsmWrite(#9#9'(export "');
  790. writer.AsmWrite(x.extname);
  791. writer.AsmWrite('" (');
  792. case x.symstype of
  793. ie_Func: writer.AsmWrite('func');
  794. else
  795. ;
  796. end;
  797. writer.AsmWrite(' ');
  798. writer.AsmWrite(GetWasmName(x.intname));
  799. writer.AsmWrite('))');
  800. writer.AsmLn;
  801. end;
  802. else
  803. ;
  804. end;
  805. hp := tai_export_name(hp.Next);
  806. end;
  807. end;
  808. procedure TWasaTextAssembler.WriteUnitExports(st: TSymtable);
  809. var
  810. i : longint;
  811. def : tdef;
  812. begin
  813. if not assigned(st) then
  814. exit;
  815. writer.AsmWrite(#9'(table 0 funcref)');
  816. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  817. for i:=0 to st.DefList.Count-1 do
  818. begin
  819. def:=tdef(st.DefList[i]);
  820. case def.typ of
  821. procdef :
  822. begin
  823. { methods are also in the static/globalsymtable of the unit
  824. -> make sure they are only written for the objectdefs that
  825. own them }
  826. if
  827. not (po_external in tprocdef(def).procoptions)
  828. then
  829. begin
  830. writer.AsmWrite(#9#9'$');
  831. writer.AsmWriteLn(tprocdef(def).mangledname);
  832. end;
  833. end;
  834. else
  835. ;
  836. end;
  837. end;
  838. writer.AsmWriteLn(#9') ');
  839. end;
  840. procedure TWasaTextAssembler.WriteImports;
  841. var
  842. i : integer;
  843. def : tdef;
  844. proc : tprocdef;
  845. sym : tsym;
  846. j : integer;
  847. psym : tprocsym;
  848. begin
  849. for i:=0 to current_module.deflist.Count-1 do begin
  850. def:=tdef(current_module.deflist[i]);
  851. { since commit 48986 deflist might have NIL entries }
  852. if assigned(def) and (def.typ=procdef) then begin
  853. proc := tprocdef(def);
  854. if (po_external in proc.procoptions) and assigned(proc.import_dll) then begin
  855. writer.AsmWrite(#9'(import "');
  856. writer.AsmWrite(proc.import_dll^);
  857. writer.AsmWrite('" "');
  858. writer.AsmWrite(proc.import_name^);
  859. writer.AsmWrite('" ');
  860. WriteProcDef(proc);
  861. writer.AsmWriteLn(')');
  862. end;
  863. end;
  864. end;
  865. // any symbol used from another unit must be fully declared in .wat
  866. // (reference by symbol name only doesn't work in Wasm)
  867. // the entire entry should declared (as imported) symbol.
  868. // The wasm-import name (name of exernal module and name)
  869. // is not important, as the linker would be using the symbol name
  870. // while linking.
  871. for i:=0 to current_module.unitimportsyms.Count-1 do begin
  872. sym := tsym(current_module.unitimportsyms[i]);
  873. if sym.typ = procsym then begin
  874. psym := tprocsym(sym);
  875. if psym.ProcdefList.Count>0 then
  876. proc := tprocdef(psym.ProcdefList[0])
  877. else
  878. proc := nil;
  879. if proc<>nil then begin
  880. {writer.AsmWrite(#9'(import "_fpc_use" "');
  881. writer.AsmWrite(proc.mangledname);
  882. writer.AsmWrite('" ');}
  883. WriteProcDef(proc, true);
  884. //writer.AsmWrite(')');
  885. end;
  886. end;
  887. end;
  888. end;
  889. procedure TWasaTextAssembler.WriteOutPChar(p: pchar; ofs, len: integer);
  890. var
  891. i : integer;
  892. s : string;
  893. ch : char;
  894. begin
  895. for i:=ofs to ofs+len-1 do begin
  896. ch:=p[i];
  897. case ch of
  898. #0, {This can't be done by range, because a bug in FPC}
  899. #1..#31,
  900. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  901. '"' : s:='\"';
  902. '\' : s:='\\';
  903. else
  904. s:=ch;
  905. end;
  906. writer.AsmWrite(s);
  907. end;
  908. end;
  909. procedure TWasaTextAssembler.WriteConstString(lbl: tai_label;
  910. str: tai_string);
  911. var
  912. i : integer;
  913. ch : char;
  914. s : string;
  915. begin
  916. WriteOutGlobalInt32(lbl.labsym.Name, dataofs);
  917. // (data (get_global $test) "00")
  918. writer.AsmWrite(#9);
  919. writer.AsmWrite('(data (i32.const ');
  920. writer.AsmWrite(tostr(dataOfs));
  921. writer.AsmWrite(') "');
  922. // can be broken apart in multiple data() if needs to be
  923. WriteOutPChar(str.str, 0, str.len);
  924. writer.AsmWrite('"');
  925. writer.AsmWriteLn(') ;; value of '+ lbl.labsym.Name);
  926. inc(dataofs, str.len);
  927. end;
  928. procedure TWasaTextAssembler.WriteConstants(p: TAsmList);
  929. var
  930. i : integer;
  931. hp : tai;
  932. dt : tai;
  933. begin
  934. //WriteTree(p);
  935. hp:=tai(p.First);
  936. while Assigned(hp) do begin
  937. if (hp.typ = ait_label) then begin
  938. dt:=tai(hp.Next);
  939. if Assigned(dt) then begin
  940. case dt.typ of
  941. ait_string:
  942. begin
  943. WriteConstString(tai_label(hp), tai_string(dt));
  944. hp:=dt;
  945. end;
  946. else
  947. ;
  948. end;
  949. end;
  950. end;
  951. hp:=tai(hp.Next);
  952. end;
  953. end;
  954. { TWatInstrWriter }
  955. constructor TWatInstrWriter.create(_owner: TWasaTextAssembler);
  956. begin
  957. inherited create;
  958. owner := _owner;
  959. end;
  960. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  961. begin
  962. end;
  963. const
  964. as_wasm_wasa_info : tasminfo =
  965. (
  966. id : as_wasm32_wasa;
  967. idtxt : 'WASA';
  968. asmbin : 'wasa';
  969. asmcmd : '-r --no-canonicalize-leb128s -o $OBJ $EXTRAOPT $ASM';
  970. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  971. flags : [];
  972. labelprefix : 'L';
  973. labelmaxlen : -1;
  974. comment : ';; ';
  975. dollarsign : '$';
  976. );
  977. initialization
  978. RegisterAssembler(as_wasm_wasa_info, TWasaTextAssembler);
  979. end.