cpupi.pas 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. {
  2. Copyright (c) 2002-2010 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the CPU specific part of tprocinfo
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit cpupi;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. cutils,globtype,aasmdata,aasmcpu,aasmtai,
  22. procinfo,cpubase,cpuinfo, symtype,aasmbase,cgbase,
  23. psub, cclasses;
  24. type
  25. { tcpuprocinfo }
  26. tcpuprocinfo=class(tcgprocinfo)
  27. private
  28. FFirstFreeLocal: Integer;
  29. FAllocatedLocals: array of TWasmBasicType;
  30. function ConvertBranchTargetNumbersToLabels(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  31. function ConvertIfToBrIf(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  32. function ConvertLoopToBr(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  33. function StripBlockInstructions(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  34. { used for allocating locals during the postprocess_code stage (i.e. after register allocation) }
  35. function AllocWasmLocal(wbt: TWasmBasicType): Integer;
  36. public
  37. { label to the nearest local exception handler }
  38. CurrRaiseLabel : tasmlabel;
  39. constructor create(aparent: tprocinfo); override;
  40. function calc_stackframe_size : longint;override;
  41. procedure setup_eh; override;
  42. procedure generate_exit_label(list: tasmlist); override;
  43. procedure postprocess_code; override;
  44. procedure set_first_temp_offset;override;
  45. end;
  46. implementation
  47. uses
  48. systems,verbose,globals,tgcpu,cgexcept,
  49. tgobj,paramgr,symconst,symdef,symtable,symcpu,cgutils,pass_2,parabase,
  50. fmodule,hlcgobj,hlcgcpu,defutil,itcpugas;
  51. {*****************************************************************************
  52. twasmexceptionstatehandler_noexceptions
  53. *****************************************************************************}
  54. type
  55. { twasmexceptionstatehandler_noexceptions }
  56. twasmexceptionstatehandler_noexceptions = class(tcgexceptionstatehandler)
  57. class procedure get_exception_temps(list:TAsmList;var t:texceptiontemps); override;
  58. class procedure unget_exception_temps(list:TAsmList;const t:texceptiontemps); override;
  59. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  60. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  61. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  62. end;
  63. class procedure twasmexceptionstatehandler_noexceptions.get_exception_temps(list:TAsmList;var t:texceptiontemps);
  64. begin
  65. if not assigned(exceptionreasontype) then
  66. exceptionreasontype:=search_system_proc('fpc_setjmp').returndef;
  67. reference_reset(t.envbuf,0,[]);
  68. reference_reset(t.jmpbuf,0,[]);
  69. tg.gethltemp(list,exceptionreasontype,exceptionreasontype.size,tt_persistent,t.reasonbuf);
  70. end;
  71. class procedure twasmexceptionstatehandler_noexceptions.unget_exception_temps(list:TAsmList;const t:texceptiontemps);
  72. begin
  73. tg.ungettemp(list,t.reasonbuf);
  74. end;
  75. class procedure twasmexceptionstatehandler_noexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  76. begin
  77. exceptstate.exceptionlabel:=nil;
  78. exceptstate.oldflowcontrol:=flowcontrol;
  79. exceptstate.finallycodelabel:=nil;
  80. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  81. end;
  82. class procedure twasmexceptionstatehandler_noexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  83. begin
  84. end;
  85. class procedure twasmexceptionstatehandler_noexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  86. begin
  87. list.Concat(tai_comment.Create(strpnew('TODO: handle_nested_exception')));
  88. end;
  89. {*****************************************************************************
  90. twasmexceptionstatehandler_jsexceptions
  91. *****************************************************************************}
  92. type
  93. twasmexceptionstatehandler_jsexceptions = class(tcgexceptionstatehandler)
  94. class procedure get_exception_temps(list:TAsmList;var t:texceptiontemps); override;
  95. class procedure unget_exception_temps(list:TAsmList;const t:texceptiontemps); override;
  96. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  97. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  98. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  99. end;
  100. class procedure twasmexceptionstatehandler_jsexceptions.get_exception_temps(list:TAsmList;var t:texceptiontemps);
  101. begin
  102. if not assigned(exceptionreasontype) then
  103. exceptionreasontype:=search_system_proc('fpc_setjmp').returndef;
  104. reference_reset(t.envbuf,0,[]);
  105. reference_reset(t.jmpbuf,0,[]);
  106. tg.gethltemp(list,exceptionreasontype,exceptionreasontype.size,tt_persistent,t.reasonbuf);
  107. end;
  108. class procedure twasmexceptionstatehandler_jsexceptions.unget_exception_temps(list:TAsmList;const t:texceptiontemps);
  109. begin
  110. tg.ungettemp(list,t.reasonbuf);
  111. end;
  112. class procedure twasmexceptionstatehandler_jsexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  113. begin
  114. exceptstate.exceptionlabel:=nil;
  115. exceptstate.oldflowcontrol:=flowcontrol;
  116. exceptstate.finallycodelabel:=nil;
  117. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  118. end;
  119. class procedure twasmexceptionstatehandler_jsexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  120. begin
  121. end;
  122. class procedure twasmexceptionstatehandler_jsexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  123. begin
  124. list.Concat(tai_comment.Create(strpnew('TODO: handle_nested_exception')));
  125. end;
  126. {*****************************************************************************
  127. twasmexceptionstatehandler_nativeexceptions
  128. *****************************************************************************}
  129. type
  130. { twasmexceptionstatehandler_nativeexceptions }
  131. twasmexceptionstatehandler_nativeexceptions = class(tcgexceptionstatehandler)
  132. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  133. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  134. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  135. { start of an "on" (catch) block }
  136. class procedure begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister); override;
  137. { end of an "on" (catch) block }
  138. class procedure end_catch(list: TAsmList); override;
  139. end;
  140. class procedure twasmexceptionstatehandler_nativeexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  141. begin
  142. exceptstate.exceptionlabel:=nil;
  143. exceptstate.oldflowcontrol:=flowcontrol;
  144. exceptstate.finallycodelabel:=nil;
  145. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  146. end;
  147. class procedure twasmexceptionstatehandler_nativeexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  148. begin
  149. end;
  150. class procedure twasmexceptionstatehandler_nativeexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  151. begin
  152. Message1(parser_f_unsupported_feature,'nested exception');
  153. end;
  154. class procedure twasmexceptionstatehandler_nativeexceptions.begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister);
  155. var
  156. pd: tprocdef;
  157. href2: treference;
  158. fpc_catches_res,
  159. paraloc1: tcgpara;
  160. exceptloc: tlocation;
  161. indirect: boolean;
  162. otherunit: boolean;
  163. begin
  164. paraloc1.init;
  165. otherunit:=findunitsymtable(excepttype.owner).moduleid<>findunitsymtable(current_procinfo.procdef.owner).moduleid;
  166. indirect:=(tf_supports_packages in target_info.flags) and
  167. (target_info.system in systems_indirect_var_imports) and
  168. (cs_imported_data in current_settings.localswitches) and
  169. otherunit;
  170. { send the vmt parameter }
  171. pd:=search_system_proc('fpc_catches');
  172. reference_reset_symbol(href2, current_asmdata.RefAsmSymbol(excepttype.vmt_mangledname, AT_DATA, indirect), 0, sizeof(pint), []);
  173. if otherunit then
  174. current_module.add_extern_asmsym(excepttype.vmt_mangledname, AB_EXTERNAL, AT_DATA);
  175. paramanager.getcgtempparaloc(list, pd, 1, paraloc1);
  176. hlcg.a_loadaddr_ref_cgpara(list, excepttype.vmt_def, href2, paraloc1);
  177. paramanager.freecgpara(list, paraloc1);
  178. fpc_catches_res:=hlcg.g_call_system_proc(list, pd, [@paraloc1], nil);
  179. location_reset(exceptloc, LOC_REGISTER, def_cgsize(fpc_catches_res.def));
  180. exceptloc.register:=hlcg.getaddressregister(list, fpc_catches_res.def);
  181. hlcg.gen_load_cgpara_loc(list, fpc_catches_res.def, fpc_catches_res, exceptloc, true);
  182. { is it this catch? }
  183. thlcgwasm(hlcg).a_cmp_const_reg_stack(list, fpc_catches_res.def, OC_NE, 0, exceptloc.register);
  184. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_if));
  185. thlcgwasm(hlcg).decstack(current_asmdata.CurrAsmList,1);
  186. paraloc1.done;
  187. exceptlocdef:=fpc_catches_res.def;
  188. exceptlocreg:=exceptloc.register;
  189. end;
  190. class procedure twasmexceptionstatehandler_nativeexceptions.end_catch(list: TAsmList);
  191. begin
  192. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_end_if));
  193. end;
  194. {*****************************************************************************
  195. twasmexceptionstatehandler_bfexceptions
  196. *****************************************************************************}
  197. type
  198. { twasmexceptionstatehandler_bfexceptions }
  199. twasmexceptionstatehandler_bfexceptions = class(tcgexceptionstatehandler)
  200. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  201. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  202. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  203. { start of an "on" (catch) block }
  204. class procedure begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister); override;
  205. { end of an "on" (catch) block }
  206. class procedure end_catch(list: TAsmList); override;
  207. end;
  208. class procedure twasmexceptionstatehandler_bfexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  209. begin
  210. exceptstate.exceptionlabel:=nil;
  211. exceptstate.oldflowcontrol:=flowcontrol;
  212. exceptstate.finallycodelabel:=nil;
  213. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  214. end;
  215. class procedure twasmexceptionstatehandler_bfexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  216. begin
  217. end;
  218. class procedure twasmexceptionstatehandler_bfexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  219. begin
  220. Message1(parser_f_unsupported_feature,'nested exception');
  221. end;
  222. class procedure twasmexceptionstatehandler_bfexceptions.begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister);
  223. var
  224. pd: tprocdef;
  225. href2: treference;
  226. fpc_catches_res,
  227. paraloc1: tcgpara;
  228. exceptloc: tlocation;
  229. indirect: boolean;
  230. otherunit: boolean;
  231. begin
  232. paraloc1.init;
  233. otherunit:=findunitsymtable(excepttype.owner).moduleid<>findunitsymtable(current_procinfo.procdef.owner).moduleid;
  234. indirect:=(tf_supports_packages in target_info.flags) and
  235. (target_info.system in systems_indirect_var_imports) and
  236. (cs_imported_data in current_settings.localswitches) and
  237. otherunit;
  238. { send the vmt parameter }
  239. pd:=search_system_proc('fpc_catches');
  240. reference_reset_symbol(href2, current_asmdata.RefAsmSymbol(excepttype.vmt_mangledname, AT_DATA, indirect), 0, sizeof(pint), []);
  241. if otherunit then
  242. current_module.add_extern_asmsym(excepttype.vmt_mangledname, AB_EXTERNAL, AT_DATA);
  243. paramanager.getcgtempparaloc(list, pd, 1, paraloc1);
  244. hlcg.a_loadaddr_ref_cgpara(list, excepttype.vmt_def, href2, paraloc1);
  245. paramanager.freecgpara(list, paraloc1);
  246. fpc_catches_res:=hlcg.g_call_system_proc(list, pd, [@paraloc1], nil);
  247. location_reset(exceptloc, LOC_REGISTER, def_cgsize(fpc_catches_res.def));
  248. exceptloc.register:=hlcg.getaddressregister(list, fpc_catches_res.def);
  249. hlcg.gen_load_cgpara_loc(list, fpc_catches_res.def, fpc_catches_res, exceptloc, true);
  250. { is it this catch? }
  251. thlcgwasm(hlcg).a_cmp_const_reg_stack(list, fpc_catches_res.def, OC_NE, 0, exceptloc.register);
  252. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_if));
  253. thlcgwasm(hlcg).decstack(current_asmdata.CurrAsmList,1);
  254. paraloc1.done;
  255. exceptlocdef:=fpc_catches_res.def;
  256. exceptlocreg:=exceptloc.register;
  257. end;
  258. class procedure twasmexceptionstatehandler_bfexceptions.end_catch(list: TAsmList);
  259. begin
  260. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_end_if));
  261. end;
  262. {*****************************************************************************
  263. twasmblockitem
  264. *****************************************************************************}
  265. type
  266. { twasmblockitem }
  267. twasmblockitem = class(TLinkedListItem)
  268. blockstart: taicpu;
  269. elseinstr: taicpu;
  270. constructor Create(ablockstart: taicpu);
  271. end;
  272. constructor twasmblockitem.Create(ablockstart: taicpu);
  273. begin
  274. blockstart:=ablockstart;
  275. end;
  276. {*****************************************************************************
  277. twasmblockstack
  278. *****************************************************************************}
  279. type
  280. { twasmblockstack }
  281. twasmblockstack = class(tlinkedlist)
  282. end;
  283. {*****************************************************************************
  284. tcpuprocinfo
  285. *****************************************************************************}
  286. function tcpuprocinfo.ConvertBranchTargetNumbersToLabels(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  287. var
  288. instr: taicpu;
  289. bl: taicpu_wasm_structured_instruction;
  290. l: TAsmLabel;
  291. begin
  292. result.typ:=amfrtNoChange;
  293. if ai.typ<>ait_instruction then
  294. exit;
  295. instr:=taicpu(ai);
  296. if not (instr.opcode in [a_br,a_br_if]) then
  297. exit;
  298. if instr.ops<>1 then
  299. internalerror(2023101601);
  300. if instr.oper[0]^.typ<>top_const then
  301. exit;
  302. bl:=blockstack[instr.oper[0]^.val];
  303. l:=bl.getlabel;
  304. instr.loadsymbol(0,l,0);
  305. end;
  306. function tcpuprocinfo.ConvertIfToBrIf(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  307. begin
  308. result.typ:=amfrtNoChange;
  309. if (ai.typ=ait_wasm_structured_instruction) and (ai is tai_wasmstruc_if) then
  310. begin
  311. result.typ:=amfrtNewList;
  312. result.newlist:=TAsmList.Create;
  313. tai_wasmstruc_if(ai).ConvertToBrIf(result.newlist,@AllocWasmLocal);
  314. end;
  315. end;
  316. function tcpuprocinfo.ConvertLoopToBr(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  317. begin
  318. result.typ:=amfrtNoChange;
  319. if (ai.typ=ait_wasm_structured_instruction) and (ai is tai_wasmstruc_loop) then
  320. begin
  321. result.typ:=amfrtNewList;
  322. result.newlist:=TAsmList.Create;
  323. tai_wasmstruc_loop(ai).ConvertToBr(result.newlist);
  324. end;
  325. end;
  326. function tcpuprocinfo.StripBlockInstructions(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  327. var
  328. instr: taicpu;
  329. begin
  330. result.typ:=amfrtNoChange;
  331. if ai.typ<>ait_instruction then
  332. exit;
  333. instr:=taicpu(ai);
  334. if instr.opcode in [a_block,a_end_block] then
  335. result.typ:=amfrtDeleteAi;
  336. end;
  337. function tcpuprocinfo.AllocWasmLocal(wbt: TWasmBasicType): Integer;
  338. begin
  339. SetLength(FAllocatedLocals,Length(FAllocatedLocals)+1);
  340. FAllocatedLocals[High(FAllocatedLocals)]:=wbt;
  341. result:=High(FAllocatedLocals)+FFirstFreeLocal;
  342. end;
  343. constructor tcpuprocinfo.create(aparent: tprocinfo);
  344. begin
  345. inherited create(aparent);
  346. if ts_wasm_bf_exceptions in current_settings.targetswitches then
  347. current_asmdata.getjumplabel(CurrRaiseLabel);
  348. end;
  349. function tcpuprocinfo.calc_stackframe_size: longint;
  350. begin
  351. { the stack frame in WebAssembly should always have a 16-byte alignment }
  352. Result:=Align(inherited calc_stackframe_size,16);
  353. end;
  354. procedure tcpuprocinfo.setup_eh;
  355. begin
  356. if ts_wasm_native_exceptions in current_settings.targetswitches then
  357. cexceptionstatehandler:=twasmexceptionstatehandler_nativeexceptions
  358. else if ts_wasm_js_exceptions in current_settings.targetswitches then
  359. cexceptionstatehandler:=twasmexceptionstatehandler_jsexceptions
  360. else if ts_wasm_no_exceptions in current_settings.targetswitches then
  361. cexceptionstatehandler:=twasmexceptionstatehandler_noexceptions
  362. else if ts_wasm_bf_exceptions in current_settings.targetswitches then
  363. cexceptionstatehandler:=twasmexceptionstatehandler_bfexceptions
  364. else
  365. internalerror(2021091701);
  366. end;
  367. procedure tcpuprocinfo.generate_exit_label(list: tasmlist);
  368. begin
  369. list.concat(taicpu.op_none(a_end_block));
  370. inherited generate_exit_label(list);
  371. end;
  372. procedure tcpuprocinfo.postprocess_code;
  373. function findfirst_tai_functype(asmlist: TAsmList): tai_functype;
  374. var
  375. hp: tai;
  376. begin
  377. result:=nil;
  378. if not assigned(asmlist) then
  379. exit;
  380. hp:=tai(asmlist.first);
  381. while assigned(hp) do
  382. begin
  383. if hp.typ=ait_functype then
  384. begin
  385. result:=tai_functype(hp);
  386. exit;
  387. end;
  388. hp:=tai(hp.Next);
  389. end;
  390. end;
  391. procedure replace_local_frame_pointer(asmlist: TAsmList);
  392. var
  393. hp: tai;
  394. instr: taicpu;
  395. l: Integer;
  396. begin
  397. if not assigned(asmlist) then
  398. exit;
  399. hp:=tai(asmlist.first);
  400. while assigned(hp) do
  401. begin
  402. if hp.typ=ait_instruction then
  403. begin
  404. instr:=taicpu(hp);
  405. for l:=0 to instr.ops-1 do
  406. if (instr.oper[l]^.typ=top_reg) and (instr.oper[l]^.reg=NR_LOCAL_FRAME_POINTER_REG) then
  407. instr.loadref(l,tcpuprocdef(current_procinfo.procdef).frame_pointer_ref);
  408. end;
  409. hp:=tai(hp.Next);
  410. end;
  411. end;
  412. function FindNextInstruction(hp: tai): taicpu;
  413. begin
  414. result:=nil;
  415. if not assigned(hp) then
  416. exit;
  417. repeat
  418. hp:=tai(hp.next);
  419. until not assigned(hp) or (hp.typ=ait_instruction);
  420. if assigned(hp) then
  421. result:=taicpu(hp);
  422. end;
  423. procedure resolve_labels_pass1(asmlist: TAsmList);
  424. var
  425. hp: tai;
  426. lastinstr, nextinstr: taicpu;
  427. cur_nesting_depth: longint;
  428. lbl: tai_label;
  429. blockstack: twasmblockstack;
  430. cblock: twasmblockitem;
  431. begin
  432. blockstack:=twasmblockstack.create;
  433. cur_nesting_depth:=0;
  434. lastinstr:=nil;
  435. hp:=tai(asmlist.first);
  436. while assigned(hp) do
  437. begin
  438. case hp.typ of
  439. ait_instruction:
  440. begin
  441. lastinstr:=taicpu(hp);
  442. case lastinstr.opcode of
  443. a_block,
  444. a_loop,
  445. a_if,
  446. a_try:
  447. begin
  448. blockstack.Concat(twasmblockitem.create(lastinstr));
  449. inc(cur_nesting_depth);
  450. end;
  451. a_else:
  452. begin
  453. cblock:=twasmblockitem(blockstack.Last);
  454. if (cblock=nil) or
  455. (cblock.blockstart.opcode<>a_if) or
  456. assigned(cblock.elseinstr) then
  457. Message1(parser_f_unsupported_feature,'misplaced a_else');
  458. cblock.elseinstr:=lastinstr;
  459. end;
  460. a_end_block,
  461. a_end_loop,
  462. a_end_if,
  463. a_end_try:
  464. begin
  465. dec(cur_nesting_depth);
  466. if cur_nesting_depth<0 then
  467. Message1(parser_f_unsupported_feature,'negative nesting level');
  468. cblock:=twasmblockitem(blockstack.GetLast);
  469. if (cblock=nil) or
  470. ((cblock.blockstart.opcode=a_block) and (lastinstr.opcode<>a_end_block)) or
  471. ((cblock.blockstart.opcode=a_loop) and (lastinstr.opcode<>a_end_loop)) or
  472. ((cblock.blockstart.opcode=a_if) and (lastinstr.opcode<>a_end_if)) or
  473. ((cblock.blockstart.opcode=a_try) and (lastinstr.opcode<>a_end_try)) then
  474. Message1(parser_f_unsupported_feature,'incompatible nesting level');
  475. cblock.free;
  476. end;
  477. else
  478. ;
  479. end;
  480. end;
  481. ait_label:
  482. begin
  483. lbl:=tai_label(hp);
  484. lbl.labsym.nestingdepth:=-1;
  485. nextinstr:=FindNextInstruction(hp);
  486. if assigned(nextinstr) and (nextinstr.opcode in [a_end_block,a_end_try,a_end_if]) then
  487. lbl.labsym.nestingdepth:=cur_nesting_depth
  488. else if assigned(lastinstr) and (lastinstr.opcode=a_loop) then
  489. lbl.labsym.nestingdepth:=cur_nesting_depth
  490. else if assigned(lastinstr) and (lastinstr.opcode in [a_end_block,a_end_try,a_end_if]) then
  491. lbl.labsym.nestingdepth:=cur_nesting_depth+1
  492. else if assigned(nextinstr) and (nextinstr.opcode=a_loop) then
  493. lbl.labsym.nestingdepth:=cur_nesting_depth+1;
  494. end;
  495. else
  496. ;
  497. end;
  498. hp:=tai(hp.Next);
  499. end;
  500. if cur_nesting_depth<>0 then
  501. Message1(parser_f_unsupported_feature,'unbalanced nesting level');
  502. blockstack.free;
  503. end;
  504. function resolve_labels_pass2(asmlist: TAsmList): Boolean;
  505. var
  506. hp: tai;
  507. instr: taicpu;
  508. hlabel: tasmsymbol;
  509. cur_nesting_depth: longint;
  510. begin
  511. Result:=true;
  512. cur_nesting_depth:=0;
  513. hp:=tai(asmlist.first);
  514. while assigned(hp) do
  515. begin
  516. if hp.typ=ait_instruction then
  517. begin
  518. instr:=taicpu(hp);
  519. case instr.opcode of
  520. a_block,
  521. a_loop,
  522. a_if,
  523. a_try:
  524. inc(cur_nesting_depth);
  525. a_end_block,
  526. a_end_loop,
  527. a_end_if,
  528. a_end_try:
  529. begin
  530. dec(cur_nesting_depth);
  531. if cur_nesting_depth<0 then
  532. Message1(parser_f_unsupported_feature,'negative nesting level');
  533. end;
  534. a_br,
  535. a_br_if:
  536. begin
  537. if instr.ops<>1 then
  538. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong operand count');
  539. if instr.oper[0]^.typ=top_ref then
  540. begin
  541. if not assigned(instr.oper[0]^.ref^.symbol) then
  542. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong ref operand');
  543. if (instr.oper[0]^.ref^.base<>NR_NO) or
  544. (instr.oper[0]^.ref^.index<>NR_NO) or
  545. (instr.oper[0]^.ref^.offset<>0) then
  546. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong ref type');
  547. if (instr.oper[0]^.ref^.symbol.nestingdepth<>-1) and
  548. (cur_nesting_depth>=instr.oper[0]^.ref^.symbol.nestingdepth) then
  549. instr.loadconst(0,cur_nesting_depth-instr.oper[0]^.ref^.symbol.nestingdepth)
  550. else
  551. begin
  552. result:=false;
  553. hlabel:=tasmsymbol(instr.oper[0]^.ref^.symbol);
  554. asmlist.insertafter(tai_comment.create(strpnew('Unable to find destination of label '+hlabel.name)),hp);
  555. end;
  556. end;
  557. end;
  558. else
  559. ;
  560. end;
  561. end;
  562. hp:=tai(hp.Next);
  563. end;
  564. if cur_nesting_depth<>0 then
  565. Message1(parser_f_unsupported_feature,'unbalanced nesting level');
  566. end;
  567. function resolve_labels_simple(asmlist: TAsmList): Boolean;
  568. begin
  569. if not assigned(asmlist) then
  570. exit(true);
  571. resolve_labels_pass1(asmlist);
  572. result:=resolve_labels_pass2(asmlist);
  573. end;
  574. procedure resolve_labels_via_state_machine(asmlist: TAsmList);
  575. var
  576. blocks: TFPHashObjectList;
  577. curr_block, tmplist: TAsmList;
  578. hp, hpnext: tai;
  579. block_nr, machine_state, target_block_index: Integer;
  580. state_machine_loop_start_label, state_machine_exit: TAsmLabel;
  581. begin
  582. blocks:=TFPHashObjectList.Create;
  583. curr_block:=TAsmList.Create;
  584. blocks.Add('.start',curr_block);
  585. repeat
  586. hp:=tai(asmlist.First);
  587. if assigned(hp) then
  588. begin
  589. asmlist.Remove(hp);
  590. if hp.typ=ait_label then
  591. begin
  592. curr_block:=TAsmList.Create;
  593. blocks.Add(tai_label(hp).labsym.Name,curr_block);
  594. end;
  595. curr_block.Concat(hp);
  596. end;
  597. until not assigned(hp);
  598. { asmlist is now empty }
  599. asmlist.Concat(tai_comment.Create(strpnew('labels resolved via state machine')));
  600. machine_state:=AllocWasmLocal(wbt_i32);
  601. asmlist.Concat(tai_comment.Create(strpnew('machine state is in local '+tostr(machine_state))));
  602. asmlist.Concat(taicpu.op_const(a_i32_const,0));
  603. asmlist.Concat(taicpu.op_const(a_local_set,machine_state));
  604. asmlist.Concat(taicpu.op_none(a_block));
  605. asmlist.Concat(taicpu.op_none(a_loop));
  606. current_asmdata.getjumplabel(state_machine_loop_start_label);
  607. asmlist.concat(tai_label.create(state_machine_loop_start_label));
  608. current_asmdata.getjumplabel(state_machine_exit);
  609. for block_nr:=0 to blocks.Count-1 do
  610. asmlist.Concat(taicpu.op_none(a_block));
  611. for block_nr:=0 to blocks.Count-1 do
  612. begin
  613. { TODO: this sequence can be replaced with a single br_table instruction }
  614. asmlist.Concat(taicpu.op_const(a_local_get,machine_state));
  615. asmlist.Concat(taicpu.op_const(a_i32_const,block_nr));
  616. asmlist.Concat(taicpu.op_none(a_i32_eq));
  617. asmlist.Concat(taicpu.op_const(a_br_if,block_nr));
  618. end;
  619. asmlist.Concat(taicpu.op_none(a_unreachable));
  620. tmplist:=TAsmList.Create;
  621. for block_nr:=0 to blocks.Count-1 do
  622. begin
  623. asmlist.Concat(taicpu.op_none(a_end_block));
  624. asmlist.Concat(tai_comment.Create(strpnew('block '+tostr(block_nr)+' for label '+blocks.NameOfIndex(block_nr))));
  625. curr_block:=TAsmList(blocks[block_nr]);
  626. hp:=tai(curr_block.First);
  627. while assigned(hp) do
  628. begin
  629. hpnext:=tai(hp.next);
  630. if (hp.typ=ait_instruction) and (taicpu(hp).opcode in [a_br,a_br_if]) and
  631. (taicpu(hp).ops=1) and
  632. (taicpu(hp).oper[0]^.typ=top_ref) and
  633. assigned(taicpu(hp).oper[0]^.ref^.symbol) then
  634. begin
  635. target_block_index:=blocks.FindIndexOf(taicpu(hp).oper[0]^.ref^.symbol.Name);
  636. curr_block.InsertBefore(tai_comment.Create(strpnew(
  637. 'branch '+gas_op2str[taicpu(hp).opcode]+
  638. ' '+taicpu(hp).oper[0]^.ref^.symbol.Name+
  639. ' target_block_index='+tostr(target_block_index))),hp);
  640. if target_block_index<>-1 then
  641. begin
  642. tmplist.Clear;
  643. if taicpu(hp).opcode=a_br_if then
  644. tmplist.Concat(taicpu.op_none(a_if));
  645. tmplist.Concat(taicpu.op_const(a_i32_const,target_block_index));
  646. tmplist.Concat(taicpu.op_const(a_local_set,machine_state));
  647. tmplist.Concat(taicpu.op_sym(a_br,state_machine_loop_start_label));
  648. if taicpu(hp).opcode=a_br_if then
  649. tmplist.Concat(taicpu.op_none(a_end_if));
  650. curr_block.insertListAfter(hp,tmplist);
  651. curr_block.Remove(hp);
  652. end;
  653. end;
  654. hp:=hpnext;
  655. end;
  656. if block_nr<(blocks.Count-1) then
  657. begin
  658. curr_block.Concat(taicpu.op_const(a_i32_const,block_nr+1));
  659. curr_block.Concat(taicpu.op_const(a_local_set,machine_state));
  660. curr_block.Concat(taicpu.op_sym(a_br,state_machine_loop_start_label));
  661. end
  662. else
  663. curr_block.Concat(taicpu.op_sym(a_br,state_machine_exit));
  664. asmlist.concatList(curr_block);
  665. end;
  666. tmplist.Free;
  667. asmlist.Concat(taicpu.op_none(a_end_loop));
  668. asmlist.Concat(taicpu.op_none(a_end_block));
  669. asmlist.concat(tai_label.create(state_machine_exit));
  670. end;
  671. procedure filter_start_exit_code(asmlist: TAsmList; out entry_code, proc_body, exit_code: TAsmList);
  672. var
  673. hp, hpnext, hpprev: tai;
  674. begin
  675. entry_code:=TAsmList.Create;
  676. proc_body:=TAsmList.Create;
  677. exit_code:=TAsmList.Create;
  678. repeat
  679. hp:=tai(asmlist.First);
  680. if assigned(hp) then
  681. begin
  682. hpnext:=tai(hp.next);
  683. if (hp.typ=ait_instruction) and (taicpu(hp).opcode=a_block) then
  684. break;
  685. asmlist.Remove(hp);
  686. entry_code.Concat(hp);
  687. hp:=hpnext;
  688. end;
  689. until not assigned(hp);
  690. repeat
  691. hp:=tai(asmlist.Last);
  692. if assigned(hp) then
  693. begin
  694. hpprev:=tai(hp.Previous);
  695. if (hp.typ=ait_instruction) and (taicpu(hp).opcode=a_end_block) then
  696. break;
  697. asmlist.Remove(hp);
  698. exit_code.Insert(hp);
  699. hp:=hpprev;
  700. end;
  701. until not assigned(hp);
  702. proc_body.insertList(asmlist);
  703. end;
  704. procedure resolve_labels_complex(var asmlist: TAsmList);
  705. var
  706. l2, entry_code, proc_body, exit_code: TAsmList;
  707. begin
  708. filter_start_exit_code(asmlist,entry_code,proc_body,exit_code);
  709. asmlist.Free;
  710. asmlist:=proc_body;
  711. proc_body:=nil;
  712. l2:=TAsmList.Create;
  713. wasm_convert_to_structured_asmlist(asmlist,l2);
  714. asmlist.Free;
  715. asmlist:=l2;
  716. map_structured_asmlist(asmlist,@ConvertBranchTargetNumbersToLabels);
  717. map_structured_asmlist(asmlist,@ConvertIfToBrIf);
  718. map_structured_asmlist(asmlist,@ConvertLoopToBr);
  719. l2:=TAsmList.Create;
  720. wasm_convert_to_flat_asmlist(asmlist,l2);
  721. asmlist.Free;
  722. asmlist:=l2;
  723. map_structured_asmlist(asmlist,@StripBlockInstructions);
  724. resolve_labels_via_state_machine(asmlist);
  725. asmlist.insertList(entry_code);
  726. entry_code.free;
  727. asmlist.concatList(exit_code);
  728. exit_code.free;
  729. if not resolve_labels_simple(asmlist) then
  730. internalerror(2023102101);
  731. end;
  732. function prepare_locals: TAsmList;
  733. var
  734. local: tai_local;
  735. first: Boolean;
  736. l : TWasmLocal;
  737. begin
  738. result:=TAsmList.create;
  739. local:=nil;
  740. first:=true;
  741. l:=ttgwasm(tg).localvars.first;
  742. FFirstFreeLocal:=Length(findfirst_tai_functype(aktproccode).functype.params);
  743. while Assigned(l) do
  744. begin
  745. local:=tai_local.create(l.typ);
  746. local.first:=first;
  747. first:=false;
  748. result.Concat(local);
  749. l:=l.nextseq;
  750. Inc(FFirstFreeLocal);
  751. end;
  752. end;
  753. procedure add_extra_allocated_locals(localslist: TAsmList);
  754. var
  755. t: TWasmBasicType;
  756. begin
  757. for t in FAllocatedLocals do
  758. localslist.Concat(tai_local.create(t));
  759. end;
  760. procedure insert_localslist(destlist,localslist: TAsmList);
  761. begin
  762. if assigned(localslist) then
  763. begin
  764. tai_local(localslist.Last).last:=true;
  765. destlist.insertListAfter(findfirst_tai_functype(destlist),localslist);
  766. end;
  767. end;
  768. var
  769. localslist: TAsmList;
  770. labels_resolved: Boolean;
  771. begin
  772. localslist:=prepare_locals;
  773. replace_local_frame_pointer(aktproccode);
  774. labels_resolved:=resolve_labels_simple(aktproccode);
  775. {$ifndef DEBUG_WASM_GOTO}
  776. if not labels_resolved then
  777. {$endif DEBUG_WASM_GOTO}
  778. resolve_labels_complex(aktproccode);
  779. add_extra_allocated_locals(localslist);
  780. insert_localslist(aktproccode,localslist);
  781. localslist.Free;
  782. inherited postprocess_code;
  783. end;
  784. procedure tcpuprocinfo.set_first_temp_offset;
  785. var
  786. sz : integer;
  787. i : integer;
  788. sym: tsym;
  789. begin
  790. {
  791. Stackframe layout:
  792. sp:
  793. <incoming parameters>
  794. sp+first_temp_offset:
  795. <locals>
  796. <temp>
  797. }
  798. procdef.init_paraloc_info(calleeside);
  799. sz := procdef.calleeargareasize;
  800. tg.setfirsttemp(sz);
  801. end;
  802. initialization
  803. cprocinfo:=tcpuprocinfo;
  804. end.