agllvmmc.pas 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. {
  2. Copyright (c) 1998-2020 by the Free Pascal team
  3. This unit implements the llvm-mc ("llvm machine code playground")
  4. assembler writer for WebAssembly
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit agllvmmc;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. systems,cgutils,
  23. globtype,globals,
  24. symbase,symdef,symtype,symconst,symcpu,
  25. aasmbase,aasmtai,aasmdata,aasmcpu,
  26. assemble,aggas;
  27. type
  28. { TLLVMMachineCodePlaygroundAssembler }
  29. TLLVMMachineCodePlaygroundAssembler=class(TGNUassembler)
  30. protected
  31. procedure WriteProcDef(pd: tprocdef);
  32. procedure WriteSymtableProcdefs(st: TSymtable);
  33. procedure WriteImports;
  34. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  35. public
  36. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  37. procedure WriteAsmList;override;
  38. end;
  39. { TWASM32InstrWriter }
  40. TWASM32InstrWriter = class(TCPUInstrWriter)
  41. procedure WriteInstruction(hp : tai);override;
  42. end;
  43. implementation
  44. uses
  45. cutils,
  46. fmodule,finput,
  47. itcpugas,
  48. cpubase,
  49. hlcgobj,hlcgcpu,
  50. verbose;
  51. { TLLVMMachineCodePlaygroundAssembler }
  52. procedure TLLVMMachineCodePlaygroundAssembler.WriteProcDef(pd: tprocdef);
  53. begin
  54. if not assigned(tcpuprocdef(pd).exprasmlist) and
  55. not(po_abstractmethod in pd.procoptions) and
  56. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  57. exit;
  58. writer.AsmWriteLn(asminfo^.comment+'WriteProcDef('+pd.mangledname+')');
  59. WriteTree(tcpuprocdef(pd).exprasmlist);
  60. writer.AsmWriteLn(asminfo^.comment+'WriteProcDef('+pd.mangledname+') done');
  61. end;
  62. procedure TLLVMMachineCodePlaygroundAssembler.WriteSymtableProcdefs(st: TSymtable);
  63. var
  64. i : longint;
  65. def : tdef;
  66. begin
  67. if not assigned(st) then
  68. exit;
  69. for i:=0 to st.DefList.Count-1 do
  70. begin
  71. def:=tdef(st.DefList[i]);
  72. case def.typ of
  73. procdef :
  74. begin
  75. { methods are also in the static/globalsymtable of the unit
  76. -> make sure they are only written for the objectdefs that
  77. own them }
  78. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  79. (def.owner=st)) and
  80. not(df_generic in def.defoptions) then
  81. begin
  82. WriteProcDef(tprocdef(def));
  83. if assigned(tprocdef(def).localst) then
  84. WriteSymtableProcdefs(tprocdef(def).localst);
  85. end;
  86. end;
  87. else
  88. ;
  89. end;
  90. end;
  91. end;
  92. procedure TLLVMMachineCodePlaygroundAssembler.WriteImports;
  93. var
  94. i : integer;
  95. proc : tprocdef;
  96. list : TAsmList;
  97. begin
  98. for i:=0 to current_module.deflist.Count-1 do
  99. if tdef(current_module.deflist[i]).typ = procdef then
  100. begin
  101. proc := tprocdef(current_module.deflist[i]);
  102. if (po_external in proc.procoptions) and assigned(proc.import_dll) then
  103. begin
  104. //WriteProcDef(proc);
  105. list:=TAsmList.Create;
  106. thlcgwasm(hlcg).g_procdef(list,proc);
  107. WriteTree(list);
  108. list.free;
  109. writer.AsmWrite(#9'.import_module'#9);
  110. writer.AsmWrite(proc.mangledname);
  111. writer.AsmWrite(', ');
  112. writer.AsmWriteLn(proc.import_dll^);
  113. writer.AsmWrite(#9'.import_name'#9);
  114. writer.AsmWrite(proc.mangledname);
  115. writer.AsmWrite(', ');
  116. writer.AsmWriteLn(proc.import_name^);
  117. end;
  118. end;
  119. end;
  120. function TLLVMMachineCodePlaygroundAssembler.sectionname(atype: TAsmSectiontype; const aname: string; aorder: TAsmSectionOrder): string;
  121. begin
  122. if atype=sec_fpc then
  123. atype:=sec_data;
  124. Result:=inherited sectionname(atype, aname, aorder)+',"",@';
  125. end;
  126. constructor TLLVMMachineCodePlaygroundAssembler.CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  127. begin
  128. inherited;
  129. InstrWriter:=TWASM32InstrWriter.create(self);
  130. end;
  131. procedure TLLVMMachineCodePlaygroundAssembler.WriteAsmList;
  132. begin
  133. inherited;
  134. { print all global procedures/functions }
  135. WriteSymtableProcdefs(current_module.globalsymtable);
  136. WriteSymtableProcdefs(current_module.localsymtable);
  137. writer.AsmWriteLn(#9'.globaltype'#9+STACK_POINTER_SYM+', i32');
  138. WriteImports;
  139. end;
  140. { TWASM32InstrWriter }
  141. procedure TWASM32InstrWriter.WriteInstruction(hp: tai);
  142. function getreferencestring(var ref : treference) : ansistring;
  143. begin
  144. if assigned(ref.symbol) then
  145. begin
  146. // global symbol or field -> full type and name
  147. // ref.base can be <> NR_NO in case an instance field is loaded.
  148. // This register is not part of this instruction, it will have
  149. // been placed on the stack by the previous one.
  150. result:=ref.symbol.name;
  151. if ref.base<>NR_NO then
  152. result:=result+'+'+std_regname(ref.base);
  153. if ref.index<>NR_NO then
  154. result:=result+'+'+std_regname(ref.index);
  155. if ref.offset>0 then
  156. result:=result+'+'+tostr(ref.offset)
  157. else if ref.offset<0 then
  158. result:=result+tostr(ref.offset);
  159. end
  160. else
  161. begin
  162. // local symbol -> stack slot, stored in offset
  163. result:='';
  164. if (ref.base<>NR_STACK_POINTER_REG) and (ref.base<>NR_NO) then
  165. result:=std_regname(ref.base);
  166. if ref.index<>NR_NO then
  167. if result<>'' then
  168. result:=result+'+'+std_regname(ref.index)
  169. else
  170. result:=std_regname(ref.index);
  171. if ref.offset>0 then
  172. begin
  173. if result<>'' then
  174. result:=result+'+'+tostr(ref.offset)
  175. else
  176. result:=tostr(ref.offset);
  177. end
  178. else if ref.offset<0 then
  179. result:=result+tostr(ref.offset);
  180. if result='' then
  181. result:='0';
  182. end;
  183. end;
  184. function constsingle(s: single): ansistring;
  185. begin
  186. // wat2wasm is using strtof() internally
  187. str(s, result); //'0x'+hexstr(longint(t32bitarray(s)),8);
  188. end;
  189. function constdouble(d: double): ansistring;
  190. begin
  191. // force interpretation as double (since we write it out as an
  192. // integer, we never have to swap the endianess). We have to
  193. // include the sign separately because of the way Java parses
  194. // hex numbers (0x8000000000000000 is not a valid long)
  195. //result:=hexstr(abs(int64(t64bitarray(d))),16);
  196. //if int64(t64bitarray(d))<0 then
  197. // result:='-'+result;
  198. //result:='0dx'+result;
  199. str(d, result);
  200. end;
  201. function getopstr(const o:toper) : ansistring;
  202. var
  203. d: double;
  204. s: single;
  205. begin
  206. case o.typ of
  207. top_reg:
  208. // should have been translated into a memory location by the
  209. // register allocator)
  210. if (cs_no_regalloc in current_settings.globalswitches) then
  211. getopstr:=std_regname(o.reg)
  212. else
  213. internalerror(2010122803);
  214. top_const:
  215. str(o.val,result);
  216. top_ref:
  217. getopstr:=getreferencestring(o.ref^);
  218. top_single:
  219. begin
  220. result:=constsingle(o.sval);
  221. end;
  222. top_double:
  223. begin
  224. result:=constdouble(o.dval);
  225. end;
  226. {top_string:
  227. begin
  228. result:=constastr(o.pcval,o.pcvallen);
  229. end;
  230. top_wstring:
  231. begin
  232. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  233. end}
  234. else
  235. internalerror(2010122802);
  236. end;
  237. end;
  238. var
  239. cpu : taicpu;
  240. i : integer;
  241. isprm : boolean;
  242. writer: TExternalAssemblerOutputFile;
  243. begin
  244. writer:=owner.writer;
  245. cpu := taicpu(hp);
  246. writer.AsmWrite(#9#9);
  247. writer.AsmWrite(gas_op2str[cpu.opcode]);
  248. if (cpu.opcode = a_call_indirect) then begin
  249. // special wat2wasm syntax "call_indirect (type x)"
  250. writer.AsmWrite(#9);
  251. isprm := true;
  252. for i:=1 to length(cpu.typecode) do
  253. if cpu.typecode[i]=':' then
  254. isprm:=false
  255. else begin
  256. if isprm then writer.AsmWrite('(param ')
  257. else writer.AsmWrite('(result ');
  258. case cpu.typecode[i] of
  259. 'i': writer.AsmWrite('i32');
  260. 'I': writer.AsmWrite('i64');
  261. 'f': writer.AsmWrite('f32');
  262. 'F': writer.AsmWrite('f64');
  263. end;
  264. writer.AsmWrite(')');
  265. end;
  266. writer.AsmLn;
  267. exit;
  268. end;
  269. if (cpu.opcode = a_if) then
  270. writer.AsmWrite(' (result i32)') //todo: this is a hardcode, but shouldn't
  271. else
  272. cpu := taicpu(hp);
  273. if cpu.ops<>0 then
  274. begin
  275. for i:=0 to cpu.ops-1 do
  276. begin
  277. writer.AsmWrite(#9);
  278. writer.AsmWrite(getopstr(cpu.oper[i]^));
  279. end;
  280. end;
  281. if (cpu.opcode = a_call_indirect) then
  282. // special wat2wasm syntax "call_indirect (type x)"
  283. writer.AsmWrite(')');
  284. writer.AsmLn;
  285. end;
  286. const
  287. as_wasm32_llvm_mc_info : tasminfo =
  288. (
  289. id : as_wasm32_llvm_mc;
  290. idtxt : 'LLVM-MC';
  291. asmbin : 'llvm-mc';
  292. asmcmd : '--assemble --arch=wasm32 --filetype=obj -o $OBJ $EXTRAOPT $ASM';
  293. supported_targets : [system_wasm32_wasm,system_wasm32_wasi];
  294. flags : [];
  295. labelprefix : '.L';
  296. labelmaxlen : -1;
  297. comment : '# ';
  298. dollarsign : '$';
  299. );
  300. initialization
  301. RegisterAssembler(as_wasm32_llvm_mc_info,TLLVMMachineCodePlaygroundAssembler);
  302. end.