agwat.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. interface
  21. uses
  22. cclasses,systems, cgutils,
  23. globtype,globals,
  24. symconst,symbase,symdef,symsym, symtype,symcpu,
  25. aasmbase,aasmtai,aasmdata,aasmcpu,
  26. assemble
  27. ,cutils
  28. ,cpubase
  29. ,fmodule
  30. ,verbose, itcpuwasm;
  31. type
  32. TWatInstrWriter = class;
  33. {# This is a derived class which is used to write
  34. Binaryen-styled assembler.
  35. }
  36. { TWatAssembler }
  37. { TWabtTextAssembler }
  38. TWabtTextAssembler=class(texternalassembler)
  39. protected
  40. procedure WriteInstruction(hp: tai);
  41. procedure WriteProcDef(pd: tprocdef);
  42. procedure WriteProcParams(pd: tprocdef);
  43. procedure WriteProcResult(pd: tprocdef);
  44. procedure WriteSymtableProcdefs(st: TSymtable);
  45. procedure WriteTempAlloc(p:TAsmList);
  46. public
  47. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  48. procedure WriteTree(p:TAsmList);override;
  49. procedure WriteAsmList;override;
  50. end;
  51. {# This is the base class for writing instructions.
  52. The WriteInstruction() method must be overridden
  53. to write a single instruction to the assembler
  54. file.
  55. }
  56. { TBinaryenInstrWriter }
  57. { TWatInstrWriter }
  58. TWatInstrWriter = class
  59. constructor create(_owner: TWabtTextAssembler);
  60. procedure WriteInstruction(hp : tai); virtual;
  61. protected
  62. owner: TWabtTextAssembler;
  63. end;
  64. implementation
  65. type
  66. t64bitarray = array[0..7] of byte;
  67. t32bitarray = array[0..3] of byte;
  68. const
  69. line_length = 70;
  70. {****************************************************************************}
  71. { Support routines }
  72. {****************************************************************************}
  73. function fixline(s:string):string;
  74. {
  75. return s with all leading and ending spaces and tabs removed
  76. }
  77. var
  78. i,j,k : integer;
  79. begin
  80. i:=length(s);
  81. while (i>0) and (s[i] in [#9,' ']) do
  82. dec(i);
  83. j:=1;
  84. while (j<i) and (s[j] in [#9,' ']) do
  85. inc(j);
  86. for k:=j to i do
  87. if s[k] in [#0..#31,#127..#255] then
  88. s[k]:='.';
  89. fixline:=Copy(s,j,i-j+1);
  90. end;
  91. function GetWasmName(const st: TSymStr): ansistring;
  92. begin
  93. Result := '$'+st;
  94. Replace(Result, '(','');
  95. Replace(Result, ')','');
  96. end;
  97. function getreferencestring(var ref : treference) : ansistring;
  98. begin
  99. if (ref.arrayreftype<>art_none) or
  100. (ref.index<>NR_NO) then
  101. internalerror(2010122809);
  102. if assigned(ref.symbol) then
  103. begin
  104. // global symbol or field -> full type and name
  105. // ref.base can be <> NR_NO in case an instance field is loaded.
  106. // This register is not part of this instruction, it will have
  107. // been placed on the stack by the previous one.
  108. if (ref.offset<>0) then
  109. internalerror(2010122811);
  110. result:=GetWasmName(ref.symbol.name);
  111. end
  112. else
  113. begin
  114. // local symbol -> stack slot, stored in offset
  115. if ref.base<>NR_STACK_POINTER_REG then
  116. internalerror(2010122810);
  117. result:=tostr(ref.offset);
  118. end;
  119. end;
  120. function constsingle(s: single): ansistring;
  121. begin
  122. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  123. end;
  124. function constdouble(d: double): ansistring;
  125. begin
  126. // force interpretation as double (since we write it out as an
  127. // integer, we never have to swap the endianess). We have to
  128. // include the sign separately because of the way Java parses
  129. // hex numbers (0x8000000000000000 is not a valid long)
  130. result:=hexstr(abs(int64(t64bitarray(d))),16);
  131. if int64(t64bitarray(d))<0 then
  132. result:='-'+result;
  133. result:='0dx'+result;
  134. end;
  135. function getopstr(const o:toper) : ansistring;
  136. var
  137. d: double;
  138. s: single;
  139. begin
  140. case o.typ of
  141. top_reg:
  142. // should have been translated into a memory location by the
  143. // register allocator)
  144. if (cs_no_regalloc in current_settings.globalswitches) then
  145. getopstr:=std_regname(o.reg)
  146. else
  147. internalerror(2010122803);
  148. top_const:
  149. str(o.val,result);
  150. top_ref:
  151. getopstr:=getreferencestring(o.ref^);
  152. top_single:
  153. begin
  154. result:=constsingle(o.sval);
  155. end;
  156. top_double:
  157. begin
  158. result:=constdouble(o.dval);
  159. end;
  160. {top_string:
  161. begin
  162. result:=constastr(o.pcval,o.pcvallen);
  163. end;
  164. top_wstring:
  165. begin
  166. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  167. end}
  168. else
  169. internalerror(2010122802);
  170. end;
  171. end;
  172. { TWabtTextAssembler }
  173. procedure TWabtTextAssembler.WriteInstruction(hp: tai);
  174. var
  175. cpu : taicpu;
  176. i : integer;
  177. const
  178. ExplicitOffset = [a_i32_load, a_i32_store];
  179. begin
  180. //writer.AsmWriteLn('instr');
  181. //writeln('>',taicpu(hp).opcode);
  182. cpu := taicpu(hp);
  183. writer.AsmWrite(#9);
  184. writer.AsmWrite(wasm_op2str[cpu.opcode] );
  185. if (cpu.opcode = a_if) then
  186. writer.AsmWrite(' (result i32)'); //todo: this is a hardcode, but shouldn't
  187. cpu := taicpu(hp);
  188. if cpu.ops<>0 then
  189. begin
  190. for i:=0 to cpu.ops-1 do
  191. begin
  192. writer.AsmWrite(#9);
  193. if (cpu.oper[i]^.typ = top_ref) and
  194. (cpu.opcode in ExplicitOffset) then begin
  195. writer.AsmWrite('offset=');
  196. writer.AsmWrite(tostr(cpu.oper[i]^.ref^.offset));
  197. writer.AsmWrite(' ;;');
  198. writer.AsmWrite('alignment=');
  199. writer.AsmWrite(tostr(cpu.oper[i]^.ref^.alignment));
  200. end else
  201. writer.AsmWrite(getopstr(cpu.oper[i]^));
  202. end;
  203. end;
  204. writer.AsmLn;
  205. end;
  206. procedure TWabtTextAssembler.WriteProcDef(pd: tprocdef);
  207. var
  208. i : integer;
  209. begin
  210. if not assigned(tcpuprocdef(pd).exprasmlist) and
  211. not(po_abstractmethod in pd.procoptions) and
  212. (not is_javainterface(pd.struct) or
  213. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  214. begin
  215. //writeln('mordoy ne vyshel! ',pd.procsym.RealName );
  216. exit;
  217. end;
  218. writer.AsmWrite('(func ');
  219. writer.AsmWrite( GetWasmName( pd.procsym.RealName ));
  220. //writer.AsmWriteln(MethodDefinition(pd));
  221. {if jvmtypeneedssignature(pd) then
  222. begin
  223. writer.AsmWrite('.signature "');
  224. writer.AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  225. writer.AsmWriteln('"');
  226. end;}
  227. writer.AsmLn;
  228. WriteProcParams(tcpuprocdef(pd));
  229. WriteProcResult(tcpuprocdef(pd));
  230. WriteTempAlloc(tcpuprocdef(pd).exprasmlist);
  231. WriteTree(tcpuprocdef(pd).exprasmlist);
  232. writer.AsmWriteln(')');
  233. writer.AsmLn;
  234. end;
  235. procedure TWabtTextAssembler.WriteProcParams(pd: tprocdef);
  236. var
  237. i : integer;
  238. prm : tcpuparavarsym;
  239. begin
  240. if not Assigned(pd) or
  241. not Assigned(pd.paras) or
  242. (pd.paras.Count=0) then
  243. exit;
  244. for i:=0 to pd.paras.Count-1 do
  245. begin
  246. prm := tcpuparavarsym(pd.paras[i]);
  247. writer.AsmWrite(#9'(param'#9);
  248. case prm.getsize of
  249. 1..4: writer.AsmWrite('i32');
  250. 8: writer.AsmWrite('i64');
  251. end;
  252. writer.AsmWrite(')');
  253. writer.AsmLn;
  254. end;
  255. end;
  256. procedure TWabtTextAssembler.WriteProcResult(pd: tprocdef);
  257. begin
  258. if not assigned(pd) or
  259. not Assigned(pd.returndef) or
  260. (pd.returndef.size = 0)
  261. then exit;
  262. writer.AsmWrite(#9'(result'#9);
  263. case pd.returndef.size of
  264. 1..4: writer.AsmWrite('i32');
  265. 8: writer.AsmWrite('i64');
  266. end;
  267. writer.AsmWrite(')');
  268. writer.AsmLn;
  269. end;
  270. procedure TWabtTextAssembler.WriteTree(p: TAsmList);
  271. var
  272. ch : char;
  273. hp : tai;
  274. hp1 : tailineinfo;
  275. s : ansistring;
  276. i,pos : longint;
  277. InlineLevel : longint;
  278. do_line : boolean;
  279. begin
  280. if not assigned(p) then
  281. exit;
  282. InlineLevel:=0;
  283. { lineinfo is only needed for al_procedures (PFV) }
  284. do_line:=(cs_asm_source in current_settings.globalswitches);
  285. hp:=tai(p.first);
  286. while assigned(hp) do
  287. begin
  288. prefetch(pointer(hp.next)^);
  289. if not(hp.typ in SkipLineInfo) then
  290. begin
  291. hp1 := hp as tailineinfo;
  292. current_filepos:=hp1.fileinfo;
  293. { no line info for inlined code }
  294. if do_line and (inlinelevel=0) then
  295. begin
  296. { load infile }
  297. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  298. begin
  299. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  300. if assigned(infile) then
  301. begin
  302. { open only if needed !! }
  303. if (cs_asm_source in current_settings.globalswitches) then
  304. infile.open;
  305. end;
  306. { avoid unnecessary reopens of the same file !! }
  307. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  308. { be sure to change line !! }
  309. lastfileinfo.line:=-1;
  310. end;
  311. { write source }
  312. if (cs_asm_source in current_settings.globalswitches) and
  313. assigned(infile) then
  314. begin
  315. if (infile<>lastinfile) then
  316. begin
  317. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  318. if assigned(lastinfile) then
  319. lastinfile.close;
  320. end;
  321. if (hp1.fileinfo.line<>lastfileinfo.line) and
  322. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  323. begin
  324. if (hp1.fileinfo.line<>0) and
  325. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  326. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  327. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  328. { set it to a negative value !
  329. to make that is has been read already !! PM }
  330. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  331. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  332. end;
  333. end;
  334. lastfileinfo:=hp1.fileinfo;
  335. lastinfile:=infile;
  336. end;
  337. end;
  338. case hp.typ of
  339. ait_comment :
  340. Begin
  341. writer.AsmWrite(asminfo^.comment);
  342. writer.AsmWritePChar(tai_comment(hp).str);
  343. writer.AsmLn;
  344. End;
  345. ait_regalloc :
  346. begin
  347. if (cs_asm_regalloc in current_settings.globalswitches) then
  348. begin
  349. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  350. repeat
  351. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  352. if (hp.next=nil) or
  353. (tai(hp.next).typ<>ait_regalloc) or
  354. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  355. break;
  356. hp:=tai(hp.next);
  357. writer.AsmWrite(',');
  358. until false;
  359. writer.AsmWrite(' ');
  360. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  361. end;
  362. end;
  363. ait_tempalloc :
  364. begin
  365. if (cs_asm_tempalloc in current_settings.globalswitches) then
  366. begin
  367. {$ifdef EXTDEBUG}
  368. if assigned(tai_tempalloc(hp).problem) then
  369. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  370. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  371. else
  372. {$endif EXTDEBUG}
  373. end;
  374. end;
  375. ait_align :
  376. begin
  377. end;
  378. ait_section :
  379. begin
  380. end;
  381. ait_datablock :
  382. begin
  383. // internalerror(2010122701);
  384. end;
  385. ait_const:
  386. begin
  387. writer.AsmWriteln('constant');
  388. // internalerror(2010122702);
  389. end;
  390. ait_realconst :
  391. begin
  392. internalerror(2010122703);
  393. end;
  394. ait_string :
  395. begin
  396. pos:=0;
  397. for i:=1 to tai_string(hp).len do
  398. begin
  399. if pos=0 then
  400. begin
  401. writer.AsmWrite(#9'strconst: '#9'"');
  402. pos:=20;
  403. end;
  404. ch:=tai_string(hp).str[i-1];
  405. case ch of
  406. #0, {This can't be done by range, because a bug in FPC}
  407. #1..#31,
  408. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  409. '"' : s:='\"';
  410. '\' : s:='\\';
  411. else
  412. s:=ch;
  413. end;
  414. writer.AsmWrite(s);
  415. inc(pos,length(s));
  416. if (pos>line_length) or (i=tai_string(hp).len) then
  417. begin
  418. writer.AsmWriteLn('"');
  419. pos:=0;
  420. end;
  421. end;
  422. end;
  423. ait_label :
  424. begin
  425. if (tai_label(hp).labsym.is_used) then
  426. begin
  427. writer.AsmWrite(tai_label(hp).labsym.name);
  428. writer.AsmWriteLn(':');
  429. end;
  430. end;
  431. ait_symbol :
  432. begin
  433. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  434. begin
  435. end
  436. else
  437. begin
  438. writer.AsmWrite('data symbol: ');
  439. writer.AsmWriteln(tai_symbol(hp).sym.name);
  440. // internalerror(2010122706);
  441. end;
  442. end;
  443. ait_symbol_end :
  444. begin
  445. end;
  446. ait_instruction :
  447. begin
  448. WriteInstruction(hp);
  449. end;
  450. ait_force_line,
  451. ait_function_name : ;
  452. ait_cutobject :
  453. begin
  454. end;
  455. ait_marker :
  456. if tai_marker(hp).kind=mark_NoLineInfoStart then
  457. inc(InlineLevel)
  458. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  459. dec(InlineLevel);
  460. ait_directive :
  461. begin
  462. { the CPU directive is probably not supported by the JVM assembler,
  463. so it's commented out }
  464. //todo:
  465. writer.AsmWrite(asminfo^.comment);
  466. if tai_directive(hp).directive=asd_cpu then
  467. writer.AsmWrite(asminfo^.comment);
  468. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  469. if tai_directive(hp).name<>'' then
  470. writer.AsmWrite(tai_directive(hp).name);
  471. writer.AsmLn;
  472. end;
  473. else
  474. internalerror(2010122707);
  475. end;
  476. hp:=tai(hp.next);
  477. end;
  478. end;
  479. procedure TWabtTextAssembler.WriteAsmList;
  480. var
  481. hal : tasmlisttype;
  482. begin
  483. if current_module.is_unit then begin
  484. writer.AsmWriteLn('(module)');
  485. exit;
  486. end;
  487. writer.MarkEmpty;
  488. writer.AsmWriteLn('(module ');
  489. { print all global variables }
  490. //WriteSymtableVarSyms(current_module.globalsymtable);
  491. //WriteSymtableVarSyms(current_module.localsymtable);
  492. //writer.AsmLn;
  493. { print all global procedures/functions }
  494. WriteSymtableProcdefs(current_module.globalsymtable);
  495. WriteSymtableProcdefs(current_module.localsymtable);
  496. //WriteSymtableStructDefs(current_module.globalsymtable);
  497. //WriteSymtableStructDefs(current_module.localsymtable);
  498. //writer.decorator.LinePrefix := '';
  499. writer.AsmWriteLn(')');
  500. writer.AsmLn;
  501. end;
  502. constructor TWabtTextAssembler.CreateWithWriter(info: pasminfo;
  503. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  504. begin
  505. inherited CreateWithWriter(info, wr, freewriter, smart);
  506. end;
  507. procedure TWabtTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  508. var
  509. i : longint;
  510. def : tdef;
  511. begin
  512. if not assigned(st) then
  513. exit;
  514. for i:=0 to st.DefList.Count-1 do
  515. begin
  516. def:=tdef(st.DefList[i]);
  517. case def.typ of
  518. procdef :
  519. begin
  520. { methods are also in the static/globalsymtable of the unit
  521. -> make sure they are only written for the objectdefs that
  522. own them }
  523. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  524. (def.owner=st)) and
  525. not(df_generic in def.defoptions) then
  526. begin
  527. WriteProcDef(tprocdef(def));
  528. if assigned(tprocdef(def).localst) then
  529. WriteSymtableProcdefs(tprocdef(def).localst);
  530. end;
  531. end;
  532. else
  533. ;
  534. end;
  535. end;
  536. end;
  537. procedure TWabtTextAssembler.WriteTempAlloc(p: TAsmList);
  538. var
  539. hp: tai;
  540. tmp: array of tai_tempalloc;
  541. mx : integer;
  542. i : integer;
  543. begin
  544. if not assigned(p) then
  545. exit;
  546. mx := -1;
  547. hp:=tai(p.first);
  548. while assigned(hp) do
  549. begin
  550. //prefetch(pointer(hp.next)^);
  551. if (hp.typ = ait_tempalloc) and
  552. tai_tempalloc(hp).allocation and
  553. (tai_tempalloc(hp).temppos >= mx) then
  554. mx := tai_tempalloc(hp).temppos+1;
  555. hp:=tai(hp.next);
  556. end;
  557. if (mx <= 0) then exit; // no temp allocations used
  558. SetLength(tmp, mx);
  559. hp:=tai(p.first);
  560. while assigned(hp) do
  561. begin
  562. //prefetch(pointer(hp.next)^);
  563. if (hp.typ = ait_tempalloc) and
  564. (tai_tempalloc(hp).allocation) and
  565. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  566. begin
  567. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  568. dec(mx);
  569. if mx = 0 then break;
  570. end;
  571. hp:=tai(hp.next);
  572. end;
  573. for i:=0 to length(tmp)-1 do
  574. begin
  575. if tmp[i] = nil then continue;
  576. writer.AsmWrite(#9'(local'#9);
  577. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  578. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  579. writer.AsmWrite(')');
  580. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  581. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  582. writer.AsmLn;
  583. end;
  584. end;
  585. { TWatInstrWriter }
  586. constructor TWatInstrWriter.create(_owner: TWabtTextAssembler);
  587. begin
  588. inherited create;
  589. owner := _owner;
  590. end;
  591. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  592. begin
  593. end;
  594. const
  595. as_wasm_wabt_info : tasminfo =
  596. (
  597. id : as_wasm_wabt;
  598. idtxt : 'Wabt';
  599. asmbin : 'wat2wasm';
  600. asmcmd : '$ASM $EXTRAOPT';
  601. supported_targets : [system_wasm_wasm32];
  602. flags : [];
  603. labelprefix : 'L';
  604. comment : ';; ';
  605. dollarsign : '$';
  606. );
  607. initialization
  608. RegisterAssembler(as_wasm_wabt_info, TWabtTextAssembler);
  609. end.