cpupi.pas 40 KB

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