agwat.pas 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 agwat;
  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;
  33. type
  34. TWatInstrWriter = class;
  35. {# This is a derived class which is used to write
  36. Binaryen-styled assembler.
  37. }
  38. { TWatAssembler }
  39. { TWabtTextAssembler }
  40. TWabtTextAssembler=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: TWabtTextAssembler);
  72. procedure WriteInstruction(hp : tai); virtual;
  73. protected
  74. owner: TWabtTextAssembler;
  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. result:='0x'+hexstr(longint(t32bitarray(s)),8);
  132. end;
  133. function constdouble(d: double): ansistring;
  134. begin
  135. // force interpretation as double (since we write it out as an
  136. // integer, we never have to swap the endianess). We have to
  137. // include the sign separately because of the way Java parses
  138. // hex numbers (0x8000000000000000 is not a valid long)
  139. result:=hexstr(abs(int64(t64bitarray(d))),16);
  140. if int64(t64bitarray(d))<0 then
  141. result:='-'+result;
  142. result:='0dx'+result;
  143. end;
  144. function getopstr(const o:toper) : ansistring;
  145. var
  146. d: double;
  147. s: single;
  148. begin
  149. case o.typ of
  150. top_reg:
  151. // should have been translated into a memory location by the
  152. // register allocator)
  153. if (cs_no_regalloc in current_settings.globalswitches) then
  154. getopstr:=std_regname(o.reg)
  155. else
  156. internalerror(2010122803);
  157. top_const:
  158. str(o.val,result);
  159. top_ref:
  160. getopstr:=getreferencestring(o.ref^);
  161. top_single:
  162. begin
  163. result:=constsingle(o.sval);
  164. end;
  165. top_double:
  166. begin
  167. result:=constdouble(o.dval);
  168. end;
  169. {top_string:
  170. begin
  171. result:=constastr(o.pcval,o.pcvallen);
  172. end;
  173. top_wstring:
  174. begin
  175. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  176. end}
  177. else
  178. internalerror(2010122802);
  179. end;
  180. end;
  181. { TWabtTextAssembler }
  182. procedure TWabtTextAssembler.WriteOutGlobalInt32(const aname: string;
  183. val: integer; isconst: boolean);
  184. begin
  185. writer.AsmWrite(#9);
  186. writer.AsmWrite('(global $');
  187. writer.AsmWrite(aname);
  188. if not isconst then
  189. writer.AsmWrite(' (mut i32)')
  190. else
  191. writer.AsmWrite(' i32');
  192. writer.AsmWrite(' (i32.const ');
  193. writer.AsmWrite( tostr(val));
  194. writer.AsmWrite(')');
  195. writer.AsmWriteLn(')');
  196. end;
  197. procedure TWabtTextAssembler.WriteInstruction(hp: tai);
  198. var
  199. cpu : taicpu;
  200. i : integer;
  201. begin
  202. //writer.AsmWriteLn('instr');
  203. cpu := taicpu(hp);
  204. writer.AsmWrite(#9);
  205. writer.AsmWrite(wasm_op2str[cpu.opcode] );
  206. if (cpu.opcode = a_if) then
  207. writer.AsmWrite(' (result i32)'); //todo: this is a hardcode, but shouldn't
  208. cpu := taicpu(hp);
  209. if cpu.ops<>0 then
  210. begin
  211. for i:=0 to cpu.ops-1 do
  212. begin
  213. writer.AsmWrite(#9);
  214. if (cpu.opcode in AsmOp_LoadStore) and (cpu.oper[i]^.typ = top_ref) then
  215. writer.AsmWrite('offset='+tostr( cpu.oper[i]^.ref^.offset))
  216. else
  217. writer.AsmWrite(getopstr(cpu.oper[i]^));
  218. end;
  219. end;
  220. writer.AsmLn;
  221. end;
  222. procedure TWabtTextAssembler.WriteProcDef(pd: tprocdef; stub: Boolean; stubUnreachable: Boolean);
  223. var
  224. i : integer;
  225. begin
  226. if not assigned(tcpuprocdef(pd).exprasmlist) and
  227. not(po_abstractmethod in pd.procoptions) and
  228. ((pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  229. begin
  230. exit;
  231. end;
  232. writer.AsmWrite('(func ');
  233. writer.AsmWrite( GetWasmName( pd.mangledname ));
  234. //procsym.RealName ));
  235. //writer.AsmWriteln(MethodDefinition(pd));
  236. {if jvmtypeneedssignature(pd) then
  237. begin
  238. writer.AsmWrite('.signature "');
  239. writer.AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  240. writer.AsmWriteln('"');
  241. end;}
  242. writer.AsmLn;
  243. WriteProcParams(pd);
  244. WriteProcResult(pd);
  245. if not stub then begin
  246. //WriteTempAlloc(tcpuprocdef(pd).exprasmlist);
  247. WriteTree(tcpuprocdef(pd).exprasmlist);
  248. end else begin
  249. if stubUnreachable then
  250. writer.AsmWriteLn(#9#9'unreachable');
  251. end;
  252. writer.AsmWriteln(#9')');
  253. writer.AsmLn;
  254. end;
  255. procedure TWabtTextAssembler.WriteProcParams(pd: tprocdef);
  256. var
  257. i : integer;
  258. prm : tcpuparavarsym;
  259. begin
  260. if not Assigned(pd) or
  261. not Assigned(pd.paras) or
  262. (pd.paras.Count=0) then
  263. exit;
  264. for i:=0 to pd.paras.Count-1 do
  265. begin
  266. prm := tcpuparavarsym(pd.paras[i]);
  267. writer.AsmWrite(#9'(param'#9);
  268. case prm.paraloc[calleeside].Size of
  269. OS_8..OS_32, OS_S8..OS_S32:
  270. writer.AsmWrite('i32');
  271. OS_64, OS_S64:
  272. writer.AsmWrite('i64');
  273. OS_F32:
  274. writer.AsmWrite('f32');
  275. OS_F64:
  276. writer.AsmWrite('f64');
  277. else
  278. // unsupported calleeside parameter type
  279. Internalerror(2019093001);
  280. end;
  281. writer.AsmWrite(')');
  282. writer.AsmLn;
  283. end;
  284. end;
  285. procedure TWabtTextAssembler.WriteProcResult(pd: tprocdef);
  286. begin
  287. if not assigned(pd) or
  288. not Assigned(pd.returndef) or
  289. (pd.returndef.size = 0)
  290. then exit;
  291. writer.AsmWrite(#9'(result'#9);
  292. case pd.returndef.size of
  293. 1..4: writer.AsmWrite('i32');
  294. 8: writer.AsmWrite('i64');
  295. end;
  296. writer.AsmWrite(')');
  297. writer.AsmLn;
  298. end;
  299. procedure TWabtTextAssembler.WriteTree(p: TAsmList);
  300. var
  301. ch : char;
  302. hp : tai;
  303. hp1 : tailineinfo;
  304. s : ansistring;
  305. i,pos : longint;
  306. InlineLevel : longint;
  307. do_line : boolean;
  308. const
  309. WasmBasicTypeStr : array [TWasmBasicType] of string = ('i32','i64','f32','f64');
  310. begin
  311. if not assigned(p) then
  312. exit;
  313. InlineLevel:=0;
  314. { lineinfo is only needed for al_procedures (PFV) }
  315. do_line:=(cs_asm_source in current_settings.globalswitches);
  316. hp:=tai(p.first);
  317. while assigned(hp) do
  318. begin
  319. prefetch(pointer(hp.next)^);
  320. if not(hp.typ in SkipLineInfo) then
  321. begin
  322. hp1 := hp as tailineinfo;
  323. current_filepos:=hp1.fileinfo;
  324. { no line info for inlined code }
  325. if do_line and (inlinelevel=0) then
  326. begin
  327. { load infile }
  328. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  329. begin
  330. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  331. if assigned(infile) then
  332. begin
  333. { open only if needed !! }
  334. if (cs_asm_source in current_settings.globalswitches) then
  335. infile.open;
  336. end;
  337. { avoid unnecessary reopens of the same file !! }
  338. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  339. { be sure to change line !! }
  340. lastfileinfo.line:=-1;
  341. end;
  342. { write source }
  343. if (cs_asm_source in current_settings.globalswitches) and
  344. assigned(infile) then
  345. begin
  346. if (infile<>lastinfile) then
  347. begin
  348. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  349. if assigned(lastinfile) then
  350. lastinfile.close;
  351. end;
  352. if (hp1.fileinfo.line<>lastfileinfo.line) and
  353. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  354. begin
  355. if (hp1.fileinfo.line<>0) and
  356. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  357. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  358. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  359. { set it to a negative value !
  360. to make that is has been read already !! PM }
  361. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  362. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  363. end;
  364. end;
  365. lastfileinfo:=hp1.fileinfo;
  366. lastinfile:=infile;
  367. end;
  368. end;
  369. case hp.typ of
  370. ait_comment :
  371. Begin
  372. writer.AsmWrite(asminfo^.comment);
  373. writer.AsmWritePChar(tai_comment(hp).str);
  374. writer.AsmLn;
  375. End;
  376. ait_regalloc :
  377. begin
  378. if (cs_asm_regalloc in current_settings.globalswitches) then
  379. begin
  380. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  381. repeat
  382. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  383. if (hp.next=nil) or
  384. (tai(hp.next).typ<>ait_regalloc) or
  385. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  386. break;
  387. hp:=tai(hp.next);
  388. writer.AsmWrite(',');
  389. until false;
  390. writer.AsmWrite(' ');
  391. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  392. end;
  393. end;
  394. ait_tempalloc :
  395. begin
  396. if (cs_asm_tempalloc in current_settings.globalswitches) then
  397. begin
  398. {$ifdef EXTDEBUG}
  399. if assigned(tai_tempalloc(hp).problem) then
  400. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  401. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  402. else
  403. {$endif EXTDEBUG}
  404. end;
  405. end;
  406. ait_align :
  407. begin
  408. end;
  409. ait_section :
  410. begin
  411. end;
  412. ait_datablock :
  413. begin
  414. // internalerror(2010122701);
  415. end;
  416. ait_const:
  417. begin
  418. writer.AsmWriteln('constant');
  419. // internalerror(2010122702);
  420. end;
  421. ait_realconst :
  422. begin
  423. internalerror(2010122703);
  424. end;
  425. ait_string :
  426. begin
  427. pos:=0;
  428. for i:=1 to tai_string(hp).len do
  429. begin
  430. if pos=0 then
  431. begin
  432. writer.AsmWrite(#9'strconst: '#9'"');
  433. pos:=20;
  434. end;
  435. ch:=tai_string(hp).str[i-1];
  436. case ch of
  437. #0, {This can't be done by range, because a bug in FPC}
  438. #1..#31,
  439. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  440. '"' : s:='\"';
  441. '\' : s:='\\';
  442. else
  443. s:=ch;
  444. end;
  445. writer.AsmWrite(s);
  446. inc(pos,length(s));
  447. if (pos>line_length) or (i=tai_string(hp).len) then
  448. begin
  449. writer.AsmWriteLn('"');
  450. pos:=0;
  451. end;
  452. end;
  453. end;
  454. ait_label :
  455. begin
  456. // don't write any labels. Wasm don't support it
  457. // labels are only allowed with the respective block structures
  458. end;
  459. ait_symbol :
  460. begin
  461. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  462. begin
  463. end
  464. else
  465. begin
  466. writer.AsmWrite('data symbol: ');
  467. writer.AsmWriteln(tai_symbol(hp).sym.name);
  468. // internalerror(2010122706);
  469. end;
  470. end;
  471. ait_symbol_end :
  472. begin
  473. end;
  474. ait_instruction :
  475. begin
  476. WriteInstruction(hp);
  477. end;
  478. ait_force_line,
  479. ait_function_name : ;
  480. ait_cutobject :
  481. begin
  482. end;
  483. ait_marker :
  484. if tai_marker(hp).kind=mark_NoLineInfoStart then
  485. inc(InlineLevel)
  486. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  487. dec(InlineLevel);
  488. ait_directive :
  489. begin
  490. { the CPU directive is probably not supported by the JVM assembler,
  491. so it's commented out }
  492. //todo:
  493. writer.AsmWrite(asminfo^.comment);
  494. if tai_directive(hp).directive=asd_cpu then
  495. writer.AsmWrite(asminfo^.comment);
  496. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  497. if tai_directive(hp).name<>'' then
  498. writer.AsmWrite(tai_directive(hp).name);
  499. writer.AsmLn;
  500. end;
  501. ait_local :
  502. begin
  503. writer.AsmWrite(#9'(local ');
  504. if tai_local(hp).name <> '' then
  505. begin
  506. writer.AsmWrite(' ');
  507. writer.AsmWrite(tai_local(hp).name);
  508. writer.AsmWrite(' ');
  509. end;
  510. writer.AsmWrite( WasmBasicTypeStr[ tai_local(hp).bastyp ] );
  511. writer.AsmWrite(')');
  512. writer.AsmLn;
  513. end;
  514. else
  515. internalerror(2010122707);
  516. end;
  517. hp:=tai(hp.next);
  518. end;
  519. end;
  520. procedure TWabtTextAssembler.WriteAsmList;
  521. var
  522. hal : tasmlisttype;
  523. begin
  524. writer.MarkEmpty;
  525. writer.AsmWriteLn('(module ');
  526. writer.AsmWriteLn('(import "env" "memory" (memory 0)) ;;');
  527. WriteImports;
  528. WriteConstants(current_asmdata.asmlists[al_const]);
  529. WriteConstants(current_asmdata.asmlists[al_typedconsts]);
  530. //current_asmdata.CurrAsmList.labe
  531. { print all global variables }
  532. //current_asmdata.AsmSymbolDict
  533. if current_module.islibrary then
  534. begin
  535. writer.AsmWrite(#9'(global $__stack_top (mut i32) (i32.const ');
  536. writer.AsmWrite(tostr(globals.stacksize));
  537. writer.AsmWriteLn('))');
  538. end;
  539. WriteSymtableVarSyms(current_module.globalsymtable);
  540. WriteSymtableVarSyms(current_module.localsymtable);
  541. //writer.AsmLn;
  542. { print all global procedures/functions }
  543. WriteSymtableProcdefs(current_module.globalsymtable);
  544. WriteSymtableProcdefs(current_module.localsymtable);
  545. if current_module.islibrary then begin
  546. WriteExports(current_asmdata.asmlists[al_exports]);
  547. end else
  548. WriteUnitExports(current_module.globalsymtable);
  549. //WriteSymtableStructDefs(current_module.globalsymtable);
  550. //WriteSymtableStructDefs(current_module.localsymtable);
  551. //writer.decorator.LinePrefix := '';
  552. writer.AsmWriteLn(')');
  553. writer.AsmLn;
  554. end;
  555. function TWabtTextAssembler.DoAssemble: boolean;
  556. begin
  557. Result:=inherited DoAssemble;
  558. // the tool updates the symbol flags, so the linker
  559. // is capable of producing an executable
  560. if Result then
  561. RequotedExecuteProcess('wasmtool',' --symbolauto '+ObjFileName);
  562. end;
  563. constructor TWabtTextAssembler.CreateWithWriter(info: pasminfo;
  564. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  565. begin
  566. inherited CreateWithWriter(info, wr, freewriter, smart);
  567. end;
  568. procedure TWabtTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  569. var
  570. i : longint;
  571. def : tdef;
  572. begin
  573. if not assigned(st) then
  574. exit;
  575. for i:=0 to st.DefList.Count-1 do
  576. begin
  577. def:=tdef(st.DefList[i]);
  578. case def.typ of
  579. procdef :
  580. begin
  581. { methods are also in the static/globalsymtable of the unit
  582. -> make sure they are only written for the objectdefs that
  583. own them }
  584. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  585. (def.owner=st)) and
  586. not(df_generic in def.defoptions) and
  587. not (po_external in tprocdef(def).procoptions)
  588. then
  589. begin
  590. WriteProcDef(tprocdef(def));
  591. if assigned(tprocdef(def).localst) then
  592. WriteSymtableProcdefs(tprocdef(def).localst);
  593. end;
  594. end;
  595. else
  596. ;
  597. end;
  598. end;
  599. end;
  600. procedure TWabtTextAssembler.WriteSymtableVarSyms(st: TSymtable);
  601. var
  602. i : integer;
  603. sym : tsym;
  604. begin
  605. if not assigned(st) then
  606. exit;
  607. for i:=0 to st.SymList.Count-1 do
  608. begin
  609. sym:=tsym(st.SymList[i]);
  610. case sym.typ of
  611. staticvarsym:
  612. begin
  613. //WriteFieldSym(tabstractvarsym(sym));
  614. //if (sym.typ=staticvarsym) and
  615. // assigned(tstaticvarsym(sym).defaultconstsym) then
  616. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  617. WriteOutGlobalInt32(tcpustaticvarsym(sym).mangledname, dataofs);
  618. inc(dataofs, tcpustaticvarsym(sym).getsize);
  619. end;
  620. fieldvarsym:
  621. begin
  622. writer.AsmWriteLn(';; field');
  623. end;
  624. constsym:
  625. begin
  626. //if (sym.typ=staticvarsym) and
  627. // assigned(tstaticvarsym(sym).defaultconstsym) then
  628. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  629. //{ multiple procedures can have constants with the same name }
  630. //if not assigned(sym.owner.defowner) or
  631. // (tdef(sym.owner.defowner).typ<>procdef) then
  632. // WriteConstSym(tconstsym(sym));
  633. writer.AsmWriteLn(';; constant');
  634. end;
  635. {procsym:
  636. begin
  637. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  638. if not(df_generic in tprocdef(tprocsym(sym).procdeflist[j]).defoptions) then
  639. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  640. end;}
  641. else
  642. ;
  643. end;
  644. end;
  645. end;
  646. procedure TWabtTextAssembler.WriteTempAlloc(p: TAsmList);
  647. var
  648. hp: tai;
  649. tmp: array of tai_tempalloc;
  650. mx : integer;
  651. i : integer;
  652. begin
  653. if not assigned(p) then
  654. exit;
  655. mx := -1;
  656. hp:=tai(p.first);
  657. while assigned(hp) do
  658. begin
  659. //prefetch(pointer(hp.next)^);
  660. if (hp.typ = ait_tempalloc) and
  661. tai_tempalloc(hp).allocation and
  662. (tai_tempalloc(hp).temppos >= mx) then
  663. mx := tai_tempalloc(hp).temppos+1;
  664. hp:=tai(hp.next);
  665. end;
  666. if (mx <= 0) then exit; // no temp allocations used
  667. SetLength(tmp, mx);
  668. hp:=tai(p.first);
  669. while assigned(hp) do
  670. begin
  671. //prefetch(pointer(hp.next)^);
  672. if (hp.typ = ait_tempalloc) and
  673. (tai_tempalloc(hp).allocation) and
  674. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  675. begin
  676. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  677. dec(mx);
  678. if mx = 0 then break;
  679. end;
  680. hp:=tai(hp.next);
  681. end;
  682. for i:=0 to length(tmp)-1 do
  683. begin
  684. if tmp[i] = nil then continue;
  685. writer.AsmWrite(#9'(local'#9);
  686. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  687. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  688. writer.AsmWrite(')');
  689. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  690. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  691. writer.AsmLn;
  692. end;
  693. end;
  694. procedure TWabtTextAssembler.WriteExports(p: TAsmList);
  695. var
  696. hp: tai;
  697. x: tai_impexp;
  698. begin
  699. if not Assigned(p) then Exit;
  700. hp:=tai(p.First);
  701. if not Assigned(hp) then Exit;
  702. // writting out table, so wat2wasm can create reallocation symbols
  703. writer.AsmWrite(#9'(table 0 funcref)');
  704. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  705. while Assigned(hp) do begin
  706. case hp.typ of
  707. ait_importexport:
  708. begin
  709. x:=tai_impexp(hp);
  710. writer.AsmWrite(#9#9);
  711. writer.AsmWriteLn(GetWasmName(x.intname));
  712. end;
  713. end;
  714. hp := tai_impexp(hp.Next);
  715. end;
  716. writer.AsmWriteLn(#9') ');
  717. // writing export sections
  718. hp:=tai(p.First);
  719. while Assigned(hp) do begin
  720. case hp.typ of
  721. ait_importexport:
  722. begin
  723. x:=tai_impexp(hp);
  724. writer.AsmWrite(#9#9'(export "');
  725. writer.AsmWrite(x.extname);
  726. writer.AsmWrite('" (');
  727. case x.symstype of
  728. ie_Func: writer.AsmWrite('func');
  729. end;
  730. writer.AsmWrite(' ');
  731. writer.AsmWrite(GetWasmName(x.intname));
  732. writer.AsmWrite('))');
  733. writer.AsmLn;
  734. end;
  735. end;
  736. hp := tai_impexp(hp.Next);
  737. end;
  738. end;
  739. procedure TWabtTextAssembler.WriteUnitExports(st: TSymtable);
  740. var
  741. i : longint;
  742. def : tdef;
  743. begin
  744. if not assigned(st) then
  745. exit;
  746. writer.AsmWrite(#9'(table 0 funcref)');
  747. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  748. for i:=0 to st.DefList.Count-1 do
  749. begin
  750. def:=tdef(st.DefList[i]);
  751. case def.typ of
  752. procdef :
  753. begin
  754. { methods are also in the static/globalsymtable of the unit
  755. -> make sure they are only written for the objectdefs that
  756. own them }
  757. if
  758. not (po_external in tprocdef(def).procoptions)
  759. then
  760. begin
  761. writer.AsmWrite(#9#9'$');
  762. writer.AsmWriteLn(tprocdef(def).mangledname);
  763. end;
  764. end;
  765. else
  766. ;
  767. end;
  768. end;
  769. writer.AsmWriteLn(#9') ');
  770. end;
  771. procedure TWabtTextAssembler.WriteImports;
  772. var
  773. i : integer;
  774. proc : tprocdef;
  775. sym : tsym;
  776. j : integer;
  777. psym : tprocsym;
  778. begin
  779. for i:=0 to current_module.deflist.Count-1 do begin
  780. if tdef(current_module.deflist[i]).typ = procdef then begin
  781. proc := tprocdef(current_module.deflist[i]);
  782. if (po_external in proc.procoptions) and assigned(proc.import_dll) then begin
  783. writer.AsmWrite(#9'(import "');
  784. writer.AsmWrite(proc.import_dll^);
  785. writer.AsmWrite('" "');
  786. writer.AsmWrite(proc.import_name^);
  787. writer.AsmWrite('" ');
  788. WriteProcDef(proc);
  789. writer.AsmWriteLn(')');
  790. end;
  791. end;
  792. end;
  793. // any symbol used from another unit must be fully declared in .wat
  794. // (reference by symbol name only doesn't work in Wasm)
  795. // the entire entry should declared (as imported) symbol.
  796. // The wasm-import name (name of exernal module and name)
  797. // is not important, as the linker would be using the symbol name
  798. // while linking.
  799. for i:=0 to current_module.unitimportsyms.Count-1 do begin
  800. sym := tsym(current_module.unitimportsyms[i]);
  801. if sym.typ = procsym then begin
  802. psym := tprocsym(sym);
  803. if psym.ProcdefList.Count>0 then
  804. proc := tprocdef(psym.ProcdefList[0])
  805. else
  806. proc := nil;
  807. if proc<>nil then begin
  808. {writer.AsmWrite(#9'(import "_fpc_use" "');
  809. writer.AsmWrite(proc.mangledname);
  810. writer.AsmWrite('" ');}
  811. WriteProcDef(proc, true);
  812. //writer.AsmWrite(')');
  813. end;
  814. end;
  815. end;
  816. end;
  817. procedure TWabtTextAssembler.WriteOutPChar(p: pchar; ofs, len: integer);
  818. var
  819. i : integer;
  820. s : string;
  821. ch : char;
  822. begin
  823. for i:=ofs to ofs+len-1 do begin
  824. ch:=p[i];
  825. case ch of
  826. #0, {This can't be done by range, because a bug in FPC}
  827. #1..#31,
  828. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  829. '"' : s:='\"';
  830. '\' : s:='\\';
  831. else
  832. s:=ch;
  833. end;
  834. writer.AsmWrite(s);
  835. end;
  836. end;
  837. procedure TWabtTextAssembler.WriteConstString(lbl: tai_label;
  838. str: tai_string);
  839. var
  840. i : integer;
  841. ch : char;
  842. s : string;
  843. begin
  844. WriteOutGlobalInt32(lbl.labsym.Name, dataofs);
  845. // (data (get_global $test) "00")
  846. writer.AsmWrite(#9);
  847. writer.AsmWrite('(data (i32.const ');
  848. writer.AsmWrite(tostr(dataOfs));
  849. writer.AsmWrite(') "');
  850. // can be broken apart in multiple data() if needs to be
  851. WriteOutPChar(str.str, 0, str.len);
  852. writer.AsmWrite('"');
  853. writer.AsmWriteLn(') ;; value of '+ lbl.labsym.Name);
  854. inc(dataofs, str.len);
  855. end;
  856. procedure TWabtTextAssembler.WriteConstants(p: TAsmList);
  857. var
  858. i : integer;
  859. hp : tai;
  860. dt : tai;
  861. begin
  862. //WriteTree(p);
  863. hp:=tai(p.First);
  864. while Assigned(hp) do begin
  865. if (hp.typ = ait_label) then begin
  866. dt:=tai(hp.Next);
  867. if Assigned(dt) then begin
  868. case dt.typ of
  869. ait_string:
  870. begin
  871. WriteConstString(tai_label(hp), tai_string(dt));
  872. hp:=dt;
  873. end;
  874. end;
  875. end;
  876. end;
  877. hp:=tai(hp.Next);
  878. end;
  879. end;
  880. { TWatInstrWriter }
  881. constructor TWatInstrWriter.create(_owner: TWabtTextAssembler);
  882. begin
  883. inherited create;
  884. owner := _owner;
  885. end;
  886. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  887. begin
  888. end;
  889. const
  890. as_wasm_wabt_info : tasminfo =
  891. (
  892. id : as_wasm_wabt;
  893. idtxt : 'Wabt';
  894. asmbin : 'wat2wasm';
  895. asmcmd : '-r --no-canonicalize-leb128s -o $OBJ $EXTRAOPT $ASM';
  896. supported_targets : [system_wasm_wasm32];
  897. flags : [];
  898. labelprefix : 'L';
  899. comment : ';; ';
  900. dollarsign : '$';
  901. );
  902. initialization
  903. RegisterAssembler(as_wasm_wabt_info, TWabtTextAssembler);
  904. end.