agwat.pas 21 KB

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