agwat.pas 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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, 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. { 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. // 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. { TWabtTextAssembler }
  184. procedure TWabtTextAssembler.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 TWabtTextAssembler.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 TWabtTextAssembler.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 TWabtTextAssembler.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 TWabtTextAssembler.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 TWabtTextAssembler.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. const
  349. WasmBasicTypeStr : array [TWasmBasicType] of string = ('i32','i64','f32','f64');
  350. begin
  351. if not assigned(p) then
  352. exit;
  353. InlineLevel:=0;
  354. { lineinfo is only needed for al_procedures (PFV) }
  355. do_line:=(cs_asm_source in current_settings.globalswitches);
  356. hp:=tai(p.first);
  357. while assigned(hp) do
  358. begin
  359. prefetch(pointer(hp.next)^);
  360. if not(hp.typ in SkipLineInfo) then
  361. begin
  362. hp1 := hp as tailineinfo;
  363. current_filepos:=hp1.fileinfo;
  364. { no line info for inlined code }
  365. if do_line and (inlinelevel=0) then
  366. begin
  367. { load infile }
  368. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  369. begin
  370. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  371. if assigned(infile) then
  372. begin
  373. { open only if needed !! }
  374. if (cs_asm_source in current_settings.globalswitches) then
  375. infile.open;
  376. end;
  377. { avoid unnecessary reopens of the same file !! }
  378. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  379. { be sure to change line !! }
  380. lastfileinfo.line:=-1;
  381. end;
  382. { write source }
  383. if (cs_asm_source in current_settings.globalswitches) and
  384. assigned(infile) then
  385. begin
  386. if (infile<>lastinfile) then
  387. begin
  388. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  389. if assigned(lastinfile) then
  390. lastinfile.close;
  391. end;
  392. if (hp1.fileinfo.line<>lastfileinfo.line) and
  393. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  394. begin
  395. if (hp1.fileinfo.line<>0) and
  396. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  397. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  398. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  399. { set it to a negative value !
  400. to make that is has been read already !! PM }
  401. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  402. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  403. end;
  404. end;
  405. lastfileinfo:=hp1.fileinfo;
  406. lastinfile:=infile;
  407. end;
  408. end;
  409. case hp.typ of
  410. ait_comment :
  411. Begin
  412. writer.AsmWrite(asminfo^.comment);
  413. writer.AsmWritePChar(tai_comment(hp).str);
  414. writer.AsmLn;
  415. End;
  416. ait_regalloc :
  417. begin
  418. if (cs_asm_regalloc in current_settings.globalswitches) then
  419. begin
  420. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  421. repeat
  422. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  423. if (hp.next=nil) or
  424. (tai(hp.next).typ<>ait_regalloc) or
  425. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  426. break;
  427. hp:=tai(hp.next);
  428. writer.AsmWrite(',');
  429. until false;
  430. writer.AsmWrite(' ');
  431. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  432. end;
  433. end;
  434. ait_tempalloc :
  435. begin
  436. if (cs_asm_tempalloc in current_settings.globalswitches) then
  437. begin
  438. {$ifdef EXTDEBUG}
  439. if assigned(tai_tempalloc(hp).problem) then
  440. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  441. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  442. else
  443. {$endif EXTDEBUG}
  444. end;
  445. end;
  446. ait_align :
  447. begin
  448. end;
  449. ait_section :
  450. begin
  451. end;
  452. ait_datablock :
  453. begin
  454. // internalerror(2010122701);
  455. end;
  456. ait_const:
  457. begin
  458. writer.AsmWriteln('constant');
  459. // internalerror(2010122702);
  460. end;
  461. ait_realconst :
  462. begin
  463. internalerror(2010122703);
  464. end;
  465. ait_string :
  466. begin
  467. pos:=0;
  468. for i:=1 to tai_string(hp).len do
  469. begin
  470. if pos=0 then
  471. begin
  472. writer.AsmWrite(#9'strconst: '#9'"');
  473. pos:=20;
  474. end;
  475. ch:=tai_string(hp).str[i-1];
  476. case ch of
  477. #0, {This can't be done by range, because a bug in FPC}
  478. #1..#31,
  479. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  480. '"' : s:='\"';
  481. '\' : s:='\\';
  482. else
  483. s:=ch;
  484. end;
  485. writer.AsmWrite(s);
  486. inc(pos,length(s));
  487. if (pos>line_length) or (i=tai_string(hp).len) then
  488. begin
  489. writer.AsmWriteLn('"');
  490. pos:=0;
  491. end;
  492. end;
  493. end;
  494. ait_label :
  495. begin
  496. // don't write any labels. Wasm don't support it
  497. // labels are only allowed with the respective block structures
  498. end;
  499. ait_symbol :
  500. begin
  501. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  502. begin
  503. end
  504. else
  505. begin
  506. writer.AsmWrite('data symbol: ');
  507. writer.AsmWriteln(tai_symbol(hp).sym.name);
  508. // internalerror(2010122706);
  509. end;
  510. end;
  511. ait_symbol_end :
  512. begin
  513. end;
  514. ait_instruction :
  515. begin
  516. WriteInstruction(hp);
  517. end;
  518. ait_force_line,
  519. ait_function_name : ;
  520. ait_cutobject :
  521. begin
  522. end;
  523. ait_marker :
  524. if tai_marker(hp).kind=mark_NoLineInfoStart then
  525. inc(InlineLevel)
  526. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  527. dec(InlineLevel);
  528. ait_directive :
  529. begin
  530. { the CPU directive is probably not supported by the JVM assembler,
  531. so it's commented out }
  532. //todo:
  533. writer.AsmWrite(asminfo^.comment);
  534. if tai_directive(hp).directive=asd_cpu then
  535. writer.AsmWrite(asminfo^.comment);
  536. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  537. if tai_directive(hp).name<>'' then
  538. writer.AsmWrite(tai_directive(hp).name);
  539. writer.AsmLn;
  540. end;
  541. ait_local :
  542. begin
  543. writer.AsmWrite(#9#9'(local ');
  544. if tai_local(hp).name <> '' then
  545. begin
  546. writer.AsmWrite(' ');
  547. writer.AsmWrite(tai_local(hp).name);
  548. writer.AsmWrite(' ');
  549. end;
  550. writer.AsmWrite( WasmBasicTypeStr[ tai_local(hp).bastyp ] );
  551. writer.AsmWrite(')');
  552. writer.AsmLn;
  553. end;
  554. else
  555. internalerror(2010122707);
  556. end;
  557. hp:=tai(hp.next);
  558. end;
  559. end;
  560. procedure TWabtTextAssembler.WriteAsmList;
  561. var
  562. hal : tasmlisttype;
  563. begin
  564. writer.MarkEmpty;
  565. writer.AsmWriteLn('(module ');
  566. writer.AsmWriteLn('(import "env" "memory" (memory 0)) ;;');
  567. WriteImports;
  568. WriteConstants(current_asmdata.asmlists[al_const]);
  569. WriteConstants(current_asmdata.asmlists[al_typedconsts]);
  570. //current_asmdata.CurrAsmList.labe
  571. { print all global variables }
  572. //current_asmdata.AsmSymbolDict
  573. // for every unit __stack_top is a weak symbol
  574. // __stack_top is strong only for libraries or programs.
  575. if current_module.is_unit then
  576. writer.AsmWriteLn(#9';;.weak');
  577. writer.AsmWrite(#9'(global $__stack_top (mut i32) (i32.const ');
  578. writer.AsmWrite(tostr(globals.stacksize));
  579. writer.AsmWriteLn('))');
  580. WriteSymtableVarSyms(current_module.globalsymtable);
  581. WriteSymtableVarSyms(current_module.localsymtable);
  582. //writer.AsmLn;
  583. { print all global procedures/functions }
  584. WriteSymtableProcdefs(current_module.globalsymtable);
  585. WriteSymtableProcdefs(current_module.localsymtable);
  586. if current_module.islibrary then begin
  587. WriteExports(current_asmdata.asmlists[al_exports]);
  588. end else
  589. WriteUnitExports(current_module.globalsymtable);
  590. //WriteSymtableStructDefs(current_module.globalsymtable);
  591. //WriteSymtableStructDefs(current_module.localsymtable);
  592. //writer.decorator.LinePrefix := '';
  593. writer.AsmWriteLn(')');
  594. writer.AsmLn;
  595. end;
  596. function TWabtTextAssembler.DoAssemble: boolean;
  597. var
  598. t : tcmdstr;
  599. begin
  600. Result:=inherited DoAssemble;
  601. // the tool updates the symbol flags, so the linker
  602. // is capable of producing an executable
  603. if Result then
  604. if FindExe('wasmtool',true,t) then begin
  605. if current_module.is_unit then
  606. // making "common" global variables a week reference
  607. RequotedExecuteProcess(t,' --weak "$__stack_top" --symbolauto '+ObjFileName)
  608. else
  609. RequotedExecuteProcess(t,' --symbolauto '+ObjFileName)
  610. end
  611. else
  612. Message1(exec_e_util_not_found,'wasmtool');
  613. end;
  614. constructor TWabtTextAssembler.CreateWithWriter(info: pasminfo;
  615. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  616. begin
  617. inherited CreateWithWriter(info, wr, freewriter, smart);
  618. end;
  619. procedure TWabtTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  620. var
  621. i : longint;
  622. def : tdef;
  623. begin
  624. if not assigned(st) then
  625. exit;
  626. for i:=0 to st.DefList.Count-1 do
  627. begin
  628. def:=tdef(st.DefList[i]);
  629. case def.typ of
  630. procdef :
  631. begin
  632. { methods are also in the static/globalsymtable of the unit
  633. -> make sure they are only written for the objectdefs that
  634. own them }
  635. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  636. (def.owner=st)) and
  637. not(df_generic in def.defoptions) and
  638. not (po_external in tprocdef(def).procoptions)
  639. then
  640. begin
  641. WriteProcDef(tprocdef(def));
  642. if assigned(tprocdef(def).localst) then
  643. WriteSymtableProcdefs(tprocdef(def).localst);
  644. end;
  645. end;
  646. else
  647. ;
  648. end;
  649. end;
  650. end;
  651. procedure TWabtTextAssembler.WriteSymtableVarSyms(st: TSymtable);
  652. var
  653. i : integer;
  654. sym : tsym;
  655. begin
  656. if not assigned(st) then
  657. exit;
  658. for i:=0 to st.SymList.Count-1 do
  659. begin
  660. sym:=tsym(st.SymList[i]);
  661. case sym.typ of
  662. staticvarsym:
  663. begin
  664. //WriteFieldSym(tabstractvarsym(sym));
  665. //if (sym.typ=staticvarsym) and
  666. // assigned(tstaticvarsym(sym).defaultconstsym) then
  667. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  668. WriteOutGlobalInt32(tcpustaticvarsym(sym).mangledname, dataofs);
  669. inc(dataofs, tcpustaticvarsym(sym).getsize);
  670. end;
  671. fieldvarsym:
  672. begin
  673. writer.AsmWriteLn(';; field');
  674. end;
  675. constsym:
  676. begin
  677. //if (sym.typ=staticvarsym) and
  678. // assigned(tstaticvarsym(sym).defaultconstsym) then
  679. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  680. //{ multiple procedures can have constants with the same name }
  681. //if not assigned(sym.owner.defowner) or
  682. // (tdef(sym.owner.defowner).typ<>procdef) then
  683. // WriteConstSym(tconstsym(sym));
  684. writer.AsmWriteLn(';; constant');
  685. end;
  686. {procsym:
  687. begin
  688. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  689. if not(df_generic in tprocdef(tprocsym(sym).procdeflist[j]).defoptions) then
  690. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  691. end;}
  692. else
  693. ;
  694. end;
  695. end;
  696. end;
  697. procedure TWabtTextAssembler.WriteTempAlloc(p: TAsmList);
  698. var
  699. hp: tai;
  700. tmp: array of tai_tempalloc;
  701. mx : integer;
  702. i : integer;
  703. begin
  704. if not assigned(p) then
  705. exit;
  706. mx := -1;
  707. hp:=tai(p.first);
  708. while assigned(hp) do
  709. begin
  710. //prefetch(pointer(hp.next)^);
  711. if (hp.typ = ait_tempalloc) and
  712. tai_tempalloc(hp).allocation and
  713. (tai_tempalloc(hp).temppos >= mx) then
  714. mx := tai_tempalloc(hp).temppos+1;
  715. hp:=tai(hp.next);
  716. end;
  717. if (mx <= 0) then exit; // no temp allocations used
  718. SetLength(tmp, mx);
  719. hp:=tai(p.first);
  720. while assigned(hp) do
  721. begin
  722. //prefetch(pointer(hp.next)^);
  723. if (hp.typ = ait_tempalloc) and
  724. (tai_tempalloc(hp).allocation) and
  725. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  726. begin
  727. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  728. dec(mx);
  729. if mx = 0 then break;
  730. end;
  731. hp:=tai(hp.next);
  732. end;
  733. for i:=0 to length(tmp)-1 do
  734. begin
  735. if tmp[i] = nil then continue;
  736. writer.AsmWrite(#9'(local'#9);
  737. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  738. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  739. writer.AsmWrite(')');
  740. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  741. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  742. writer.AsmLn;
  743. end;
  744. end;
  745. procedure TWabtTextAssembler.WriteExports(p: TAsmList);
  746. var
  747. hp: tai;
  748. x: tai_export_name;
  749. cnt: integer;
  750. begin
  751. if not Assigned(p) then Exit;
  752. hp:=tai(p.First);
  753. if not Assigned(hp) then Exit;
  754. cnt := 0;
  755. while Assigned(hp) do begin
  756. case hp.typ of
  757. ait_export_name:
  758. inc(cnt);
  759. else
  760. ;
  761. end;
  762. hp := tai_export_name(hp.Next);
  763. end;
  764. // writting out table, so wat2wasm can create reallocation symbols
  765. writer.AsmWrite(#9'(table ');
  766. writer.AsmWrite(tostr(cnt));
  767. writer.AsmWrite(' anyfunc)');
  768. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  769. hp:=tai(p.First);
  770. while Assigned(hp) do begin
  771. case hp.typ of
  772. ait_export_name:
  773. begin
  774. x:=tai_export_name(hp);
  775. writer.AsmWrite(#9#9);
  776. writer.AsmWriteLn(GetWasmName(x.intname));
  777. end;
  778. else
  779. ;
  780. end;
  781. hp := tai_export_name(hp.Next);
  782. end;
  783. writer.AsmWriteLn(#9') ');
  784. // writing export sections
  785. hp:=tai(p.First);
  786. while Assigned(hp) do begin
  787. case hp.typ of
  788. ait_export_name:
  789. begin
  790. x:=tai_export_name(hp);
  791. writer.AsmWrite(#9#9'(export "');
  792. writer.AsmWrite(x.extname);
  793. writer.AsmWrite('" (');
  794. case x.symstype of
  795. ie_Func: writer.AsmWrite('func');
  796. else
  797. ;
  798. end;
  799. writer.AsmWrite(' ');
  800. writer.AsmWrite(GetWasmName(x.intname));
  801. writer.AsmWrite('))');
  802. writer.AsmLn;
  803. end;
  804. else
  805. ;
  806. end;
  807. hp := tai_export_name(hp.Next);
  808. end;
  809. end;
  810. procedure TWabtTextAssembler.WriteUnitExports(st: TSymtable);
  811. var
  812. i : longint;
  813. def : tdef;
  814. begin
  815. if not assigned(st) then
  816. exit;
  817. writer.AsmWrite(#9'(table 0 funcref)');
  818. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  819. for i:=0 to st.DefList.Count-1 do
  820. begin
  821. def:=tdef(st.DefList[i]);
  822. case def.typ of
  823. procdef :
  824. begin
  825. { methods are also in the static/globalsymtable of the unit
  826. -> make sure they are only written for the objectdefs that
  827. own them }
  828. if
  829. not (po_external in tprocdef(def).procoptions)
  830. then
  831. begin
  832. writer.AsmWrite(#9#9'$');
  833. writer.AsmWriteLn(tprocdef(def).mangledname);
  834. end;
  835. end;
  836. else
  837. ;
  838. end;
  839. end;
  840. writer.AsmWriteLn(#9') ');
  841. end;
  842. procedure TWabtTextAssembler.WriteImports;
  843. var
  844. i : integer;
  845. def : tdef;
  846. proc : tprocdef;
  847. sym : tsym;
  848. j : integer;
  849. psym : tprocsym;
  850. begin
  851. for i:=0 to current_module.deflist.Count-1 do begin
  852. def:=tdef(current_module.deflist[i]);
  853. { since commit 48986 deflist might have NIL entries }
  854. if assigned(def) and (def.typ=procdef) then begin
  855. proc := tprocdef(def);
  856. if (po_external in proc.procoptions) and assigned(proc.import_dll) then begin
  857. writer.AsmWrite(#9'(import "');
  858. writer.AsmWrite(proc.import_dll^);
  859. writer.AsmWrite('" "');
  860. writer.AsmWrite(proc.import_name^);
  861. writer.AsmWrite('" ');
  862. WriteProcDef(proc);
  863. writer.AsmWriteLn(')');
  864. end;
  865. end;
  866. end;
  867. // any symbol used from another unit must be fully declared in .wat
  868. // (reference by symbol name only doesn't work in Wasm)
  869. // the entire entry should declared (as imported) symbol.
  870. // The wasm-import name (name of exernal module and name)
  871. // is not important, as the linker would be using the symbol name
  872. // while linking.
  873. for i:=0 to current_module.unitimportsyms.Count-1 do begin
  874. sym := tsym(current_module.unitimportsyms[i]);
  875. if sym.typ = procsym then begin
  876. psym := tprocsym(sym);
  877. if psym.ProcdefList.Count>0 then
  878. proc := tprocdef(psym.ProcdefList[0])
  879. else
  880. proc := nil;
  881. if proc<>nil then begin
  882. {writer.AsmWrite(#9'(import "_fpc_use" "');
  883. writer.AsmWrite(proc.mangledname);
  884. writer.AsmWrite('" ');}
  885. WriteProcDef(proc, true);
  886. //writer.AsmWrite(')');
  887. end;
  888. end;
  889. end;
  890. end;
  891. procedure TWabtTextAssembler.WriteOutPChar(p: pchar; ofs, len: integer);
  892. var
  893. i : integer;
  894. s : string;
  895. ch : char;
  896. begin
  897. for i:=ofs to ofs+len-1 do begin
  898. ch:=p[i];
  899. case ch of
  900. #0, {This can't be done by range, because a bug in FPC}
  901. #1..#31,
  902. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  903. '"' : s:='\"';
  904. '\' : s:='\\';
  905. else
  906. s:=ch;
  907. end;
  908. writer.AsmWrite(s);
  909. end;
  910. end;
  911. procedure TWabtTextAssembler.WriteConstString(lbl: tai_label;
  912. str: tai_string);
  913. var
  914. i : integer;
  915. ch : char;
  916. s : string;
  917. begin
  918. WriteOutGlobalInt32(lbl.labsym.Name, dataofs);
  919. // (data (get_global $test) "00")
  920. writer.AsmWrite(#9);
  921. writer.AsmWrite('(data (i32.const ');
  922. writer.AsmWrite(tostr(dataOfs));
  923. writer.AsmWrite(') "');
  924. // can be broken apart in multiple data() if needs to be
  925. WriteOutPChar(str.str, 0, str.len);
  926. writer.AsmWrite('"');
  927. writer.AsmWriteLn(') ;; value of '+ lbl.labsym.Name);
  928. inc(dataofs, str.len);
  929. end;
  930. procedure TWabtTextAssembler.WriteConstants(p: TAsmList);
  931. var
  932. i : integer;
  933. hp : tai;
  934. dt : tai;
  935. begin
  936. //WriteTree(p);
  937. hp:=tai(p.First);
  938. while Assigned(hp) do begin
  939. if (hp.typ = ait_label) then begin
  940. dt:=tai(hp.Next);
  941. if Assigned(dt) then begin
  942. case dt.typ of
  943. ait_string:
  944. begin
  945. WriteConstString(tai_label(hp), tai_string(dt));
  946. hp:=dt;
  947. end;
  948. else
  949. ;
  950. end;
  951. end;
  952. end;
  953. hp:=tai(hp.Next);
  954. end;
  955. end;
  956. { TWatInstrWriter }
  957. constructor TWatInstrWriter.create(_owner: TWabtTextAssembler);
  958. begin
  959. inherited create;
  960. owner := _owner;
  961. end;
  962. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  963. begin
  964. end;
  965. const
  966. as_wasm_wabt_info : tasminfo =
  967. (
  968. id : as_wasm32_wabt;
  969. idtxt : 'WABT';
  970. asmbin : 'wasa';
  971. asmcmd : '-r --no-canonicalize-leb128s -o $OBJ $EXTRAOPT $ASM';
  972. supported_targets : [system_wasm32_embedded,system_wasm32_wasi];
  973. flags : [];
  974. labelprefix : 'L';
  975. labelmaxlen : -1;
  976. comment : ';; ';
  977. dollarsign : '$';
  978. );
  979. initialization
  980. RegisterAssembler(as_wasm_wabt_info, TWabtTextAssembler);
  981. end.