agwat.pas 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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_impexp;
  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_importexport:
  758. inc(cnt);
  759. end;
  760. hp := tai_impexp(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_importexport:
  771. begin
  772. x:=tai_impexp(hp);
  773. writer.AsmWrite(#9#9);
  774. writer.AsmWriteLn(GetWasmName(x.intname));
  775. end;
  776. end;
  777. hp := tai_impexp(hp.Next);
  778. end;
  779. writer.AsmWriteLn(#9') ');
  780. // writing export sections
  781. hp:=tai(p.First);
  782. while Assigned(hp) do begin
  783. case hp.typ of
  784. ait_importexport:
  785. begin
  786. x:=tai_impexp(hp);
  787. writer.AsmWrite(#9#9'(export "');
  788. writer.AsmWrite(x.extname);
  789. writer.AsmWrite('" (');
  790. case x.symstype of
  791. ie_Func: writer.AsmWrite('func');
  792. end;
  793. writer.AsmWrite(' ');
  794. writer.AsmWrite(GetWasmName(x.intname));
  795. writer.AsmWrite('))');
  796. writer.AsmLn;
  797. end;
  798. end;
  799. hp := tai_impexp(hp.Next);
  800. end;
  801. end;
  802. procedure TWabtTextAssembler.WriteUnitExports(st: TSymtable);
  803. var
  804. i : longint;
  805. def : tdef;
  806. begin
  807. if not assigned(st) then
  808. exit;
  809. writer.AsmWrite(#9'(table 0 funcref)');
  810. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  811. for i:=0 to st.DefList.Count-1 do
  812. begin
  813. def:=tdef(st.DefList[i]);
  814. case def.typ of
  815. procdef :
  816. begin
  817. { methods are also in the static/globalsymtable of the unit
  818. -> make sure they are only written for the objectdefs that
  819. own them }
  820. if
  821. not (po_external in tprocdef(def).procoptions)
  822. then
  823. begin
  824. writer.AsmWrite(#9#9'$');
  825. writer.AsmWriteLn(tprocdef(def).mangledname);
  826. end;
  827. end;
  828. else
  829. ;
  830. end;
  831. end;
  832. writer.AsmWriteLn(#9') ');
  833. end;
  834. procedure TWabtTextAssembler.WriteImports;
  835. var
  836. i : integer;
  837. proc : tprocdef;
  838. sym : tsym;
  839. j : integer;
  840. psym : tprocsym;
  841. begin
  842. for i:=0 to current_module.deflist.Count-1 do begin
  843. if tdef(current_module.deflist[i]).typ = procdef then begin
  844. proc := tprocdef(current_module.deflist[i]);
  845. if (po_external in proc.procoptions) and assigned(proc.import_dll) then begin
  846. writer.AsmWrite(#9'(import "');
  847. writer.AsmWrite(proc.import_dll^);
  848. writer.AsmWrite('" "');
  849. writer.AsmWrite(proc.import_name^);
  850. writer.AsmWrite('" ');
  851. WriteProcDef(proc);
  852. writer.AsmWriteLn(')');
  853. end;
  854. end;
  855. end;
  856. // any symbol used from another unit must be fully declared in .wat
  857. // (reference by symbol name only doesn't work in Wasm)
  858. // the entire entry should declared (as imported) symbol.
  859. // The wasm-import name (name of exernal module and name)
  860. // is not important, as the linker would be using the symbol name
  861. // while linking.
  862. for i:=0 to current_module.unitimportsyms.Count-1 do begin
  863. sym := tsym(current_module.unitimportsyms[i]);
  864. if sym.typ = procsym then begin
  865. psym := tprocsym(sym);
  866. if psym.ProcdefList.Count>0 then
  867. proc := tprocdef(psym.ProcdefList[0])
  868. else
  869. proc := nil;
  870. if proc<>nil then begin
  871. {writer.AsmWrite(#9'(import "_fpc_use" "');
  872. writer.AsmWrite(proc.mangledname);
  873. writer.AsmWrite('" ');}
  874. WriteProcDef(proc, true);
  875. //writer.AsmWrite(')');
  876. end;
  877. end;
  878. end;
  879. end;
  880. procedure TWabtTextAssembler.WriteOutPChar(p: pchar; ofs, len: integer);
  881. var
  882. i : integer;
  883. s : string;
  884. ch : char;
  885. begin
  886. for i:=ofs to ofs+len-1 do begin
  887. ch:=p[i];
  888. case ch of
  889. #0, {This can't be done by range, because a bug in FPC}
  890. #1..#31,
  891. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  892. '"' : s:='\"';
  893. '\' : s:='\\';
  894. else
  895. s:=ch;
  896. end;
  897. writer.AsmWrite(s);
  898. end;
  899. end;
  900. procedure TWabtTextAssembler.WriteConstString(lbl: tai_label;
  901. str: tai_string);
  902. var
  903. i : integer;
  904. ch : char;
  905. s : string;
  906. begin
  907. WriteOutGlobalInt32(lbl.labsym.Name, dataofs);
  908. // (data (get_global $test) "00")
  909. writer.AsmWrite(#9);
  910. writer.AsmWrite('(data (i32.const ');
  911. writer.AsmWrite(tostr(dataOfs));
  912. writer.AsmWrite(') "');
  913. // can be broken apart in multiple data() if needs to be
  914. WriteOutPChar(str.str, 0, str.len);
  915. writer.AsmWrite('"');
  916. writer.AsmWriteLn(') ;; value of '+ lbl.labsym.Name);
  917. inc(dataofs, str.len);
  918. end;
  919. procedure TWabtTextAssembler.WriteConstants(p: TAsmList);
  920. var
  921. i : integer;
  922. hp : tai;
  923. dt : tai;
  924. begin
  925. //WriteTree(p);
  926. hp:=tai(p.First);
  927. while Assigned(hp) do begin
  928. if (hp.typ = ait_label) then begin
  929. dt:=tai(hp.Next);
  930. if Assigned(dt) then begin
  931. case dt.typ of
  932. ait_string:
  933. begin
  934. WriteConstString(tai_label(hp), tai_string(dt));
  935. hp:=dt;
  936. end;
  937. end;
  938. end;
  939. end;
  940. hp:=tai(hp.Next);
  941. end;
  942. end;
  943. { TWatInstrWriter }
  944. constructor TWatInstrWriter.create(_owner: TWabtTextAssembler);
  945. begin
  946. inherited create;
  947. owner := _owner;
  948. end;
  949. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  950. begin
  951. end;
  952. const
  953. as_wasm_wabt_info : tasminfo =
  954. (
  955. id : as_wasm32_wabt;
  956. idtxt : 'WABT';
  957. asmbin : 'wasa';
  958. asmcmd : '-r --no-canonicalize-leb128s -o $OBJ $EXTRAOPT $ASM';
  959. supported_targets : [system_wasm32_wasm,system_wasm32_wasi];
  960. flags : [];
  961. labelprefix : 'L';
  962. labelmaxlen : -1;
  963. comment : ';; ';
  964. dollarsign : '$';
  965. );
  966. initialization
  967. RegisterAssembler(as_wasm_wabt_info, TWabtTextAssembler);
  968. end.