psub.pas 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl, Daniel Mantione
  3. Does the parsing and codegeneration at subroutine level
  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 psub;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. globals,
  22. node,nbas,
  23. symdef,procinfo,optdfa;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure CreateInlineInfo;
  28. { returns the node which is the start of the user code, this is needed by the dfa }
  29. function GetUserCode: tnode;
  30. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  31. procedure add_entry_exit_code;
  32. procedure setup_tempgen;
  33. public
  34. { code for the subroutine as tree }
  35. code : tnode;
  36. { positions in the tree for init/final }
  37. entry_asmnode,
  38. loadpara_asmnode,
  39. exitlabel_asmnode,
  40. stackcheck_asmnode,
  41. init_asmnode : tasmnode;
  42. temps_finalized : boolean;
  43. dfabuilder : TDFABuilder;
  44. destructor destroy;override;
  45. function calc_stackframe_size : longint;override;
  46. procedure printproc(pass:string);
  47. procedure generate_code;
  48. procedure generate_code_tree;
  49. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  50. procedure resetprocdef;
  51. procedure add_to_symtablestack;
  52. procedure remove_from_symtablestack;
  53. procedure parse_body;
  54. function has_assembler_child : boolean;
  55. end;
  56. procedure printnode_reset;
  57. { reads the declaration blocks }
  58. procedure read_declarations(islibrary : boolean);
  59. { reads declarations in the interface part of a unit }
  60. procedure read_interface_declarations;
  61. { reads any routine in the implementation, or a non-method routine
  62. declaration in the interface (depending on whether or not parse_only is
  63. true) }
  64. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef;isgeneric:boolean);
  65. { parses only the body of a non nested routine; needs a correctly setup pd }
  66. procedure read_proc_body(pd:tprocdef);
  67. procedure import_external_proc(pd:tprocdef);
  68. implementation
  69. uses
  70. sysutils,
  71. { common }
  72. cutils, cmsgs,
  73. { global }
  74. globtype,tokens,verbose,comphook,constexp,
  75. systems,cpubase,aasmbase,aasmtai,aasmdata,
  76. { symtable }
  77. symconst,symbase,symsym,symtype,symtable,defutil,defcmp,symcreat,
  78. paramgr,
  79. fmodule,
  80. { pass 1 }
  81. nutils,ngenutil,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  82. pass_1,
  83. {$ifdef state_tracking}
  84. nstate,
  85. {$endif state_tracking}
  86. { pass 2 }
  87. {$ifndef NOPASS2}
  88. pass_2,
  89. {$endif}
  90. { parser }
  91. scanner,gendef,
  92. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,pparautl,
  93. { codegen }
  94. tgobj,cgbase,cgobj,hlcgobj,hlcgcpu,dbgbase,
  95. {$ifdef llvm}
  96. { override create_hlcodegen from hlcgcpu }
  97. hlcgllvm,
  98. {$endif}
  99. ncgutil,
  100. optbase,
  101. opttail,
  102. optcse,
  103. optloop,
  104. optconstprop,
  105. optdeadstore,
  106. optloadmodifystore,
  107. optutils
  108. {$if defined(arm)}
  109. ,cpuinfo
  110. {$endif arm}
  111. {$ifndef NOOPT}
  112. ,aopt
  113. {$endif}
  114. ;
  115. function checknodeinlining(procdef: tprocdef): boolean;
  116. procedure _no_inline(const reason: TMsgStr);
  117. begin
  118. include(procdef.implprocoptions,pio_inline_not_possible);
  119. Message1(parser_n_not_supported_for_inline,reason);
  120. Message(parser_h_inlining_disabled);
  121. end;
  122. var
  123. i : integer;
  124. currpara : tparavarsym;
  125. begin
  126. result := false;
  127. { this code will never be used (only specialisations can be inlined),
  128. and moreover contains references to defs that are not stored in the
  129. ppu file }
  130. if df_generic in current_procinfo.procdef.defoptions then
  131. exit;
  132. if pi_has_assembler_block in current_procinfo.flags then
  133. begin
  134. _no_inline('assembler');
  135. exit;
  136. end;
  137. if (pi_has_global_goto in current_procinfo.flags) or
  138. (pi_has_interproclabel in current_procinfo.flags) then
  139. begin
  140. _no_inline('global goto');
  141. exit;
  142. end;
  143. if pi_has_nested_exit in current_procinfo.flags then
  144. begin
  145. _no_inline('nested exit');
  146. exit;
  147. end;
  148. if pi_calls_c_varargs in current_procinfo.flags then
  149. begin
  150. _no_inline('called C-style varargs functions');
  151. exit;
  152. end;
  153. { the compiler cannot handle inherited in inlined subroutines because
  154. it tries to search for self in the symtable, however, the symtable
  155. is not available }
  156. if pi_has_inherited in current_procinfo.flags then
  157. begin
  158. _no_inline('inherited');
  159. exit;
  160. end;
  161. if pio_nested_access in procdef.implprocoptions then
  162. begin
  163. _no_inline('access to local from nested scope');
  164. exit;
  165. end;
  166. { We can't support inlining for procedures that have nested
  167. procedures because the nested procedures use a fixed offset
  168. for accessing locals in the parent procedure (PFV) }
  169. if current_procinfo.has_nestedprocs then
  170. begin
  171. _no_inline('nested procedures');
  172. exit;
  173. end;
  174. for i:=0 to procdef.paras.count-1 do
  175. begin
  176. currpara:=tparavarsym(procdef.paras[i]);
  177. case currpara.vardef.typ of
  178. formaldef :
  179. begin
  180. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  181. begin
  182. _no_inline('formal parameter');
  183. exit;
  184. end;
  185. end;
  186. arraydef :
  187. begin
  188. if is_array_of_const(currpara.vardef) or
  189. is_variant_array(currpara.vardef) then
  190. begin
  191. _no_inline('array of const');
  192. exit;
  193. end;
  194. { open arrays might need re-basing of the index, i.e. if you pass
  195. an array[1..10] as open array, you have to add 1 to all index operations
  196. if you directly inline it }
  197. if is_open_array(currpara.vardef) then
  198. begin
  199. _no_inline('open array');
  200. exit;
  201. end;
  202. end;
  203. end;
  204. end;
  205. result:=true;
  206. end;
  207. {****************************************************************************
  208. PROCEDURE/FUNCTION BODY PARSING
  209. ****************************************************************************}
  210. procedure initializedefaultvars(p:TObject;arg:pointer);
  211. var
  212. b : tblocknode;
  213. begin
  214. if tsym(p).typ<>localvarsym then
  215. exit;
  216. with tabstractnormalvarsym(p) do
  217. begin
  218. if (vo_is_default_var in varoptions) and (vardef.size>0) then
  219. begin
  220. b:=tblocknode(arg);
  221. b.left:=cstatementnode.create(
  222. ccallnode.createintern('fpc_zeromem',
  223. ccallparanode.create(
  224. cordconstnode.create(vardef.size,sizeuinttype,false),
  225. ccallparanode.create(
  226. caddrnode.create_internal(
  227. cloadnode.create(tsym(p),tsym(p).owner)),
  228. nil
  229. )
  230. )
  231. ),
  232. b.left);
  233. end;
  234. end;
  235. end;
  236. procedure initializevars(p:TObject;arg:pointer);
  237. var
  238. b : tblocknode;
  239. begin
  240. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  241. exit;
  242. with tabstractnormalvarsym(p) do
  243. begin
  244. if assigned(defaultconstsym) then
  245. begin
  246. b:=tblocknode(arg);
  247. b.left:=cstatementnode.create(
  248. cassignmentnode.create(
  249. cloadnode.create(tsym(p),tsym(p).owner),
  250. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  251. b.left);
  252. end
  253. else
  254. initializedefaultvars(p,arg);
  255. end;
  256. end;
  257. procedure check_finalize_paras(p:TObject;arg:pointer);
  258. begin
  259. if (tsym(p).typ=paravarsym) then
  260. begin
  261. if tparavarsym(p).needs_finalization then
  262. begin
  263. include(current_procinfo.flags,pi_needs_implicit_finally);
  264. include(current_procinfo.flags,pi_do_call);
  265. end;
  266. if (tparavarsym(p).varspez in [vs_value,vs_out]) and
  267. (cs_create_pic in current_settings.moduleswitches) and
  268. (tf_pic_uses_got in target_info.flags) and
  269. is_rtti_managed_type(tparavarsym(p).vardef) then
  270. include(current_procinfo.flags,pi_needs_got);
  271. end;
  272. end;
  273. procedure check_finalize_locals(p:TObject;arg:pointer);
  274. begin
  275. { include the result: it needs to be finalized in case an exception }
  276. { occurs }
  277. if (tsym(p).typ=localvarsym) and
  278. (tlocalvarsym(p).refs>0) and
  279. is_managed_type(tlocalvarsym(p).vardef) then
  280. begin
  281. include(current_procinfo.flags,pi_needs_implicit_finally);
  282. include(current_procinfo.flags,pi_do_call);
  283. if is_rtti_managed_type(tlocalvarsym(p).vardef) and
  284. (cs_create_pic in current_settings.moduleswitches) and
  285. (tf_pic_uses_got in target_info.flags) then
  286. include(current_procinfo.flags,pi_needs_got);
  287. end;
  288. end;
  289. function block(islibrary : boolean) : tnode;
  290. var
  291. oldfilepos: tfileposinfo;
  292. begin
  293. { parse const,types and vars }
  294. read_declarations(islibrary);
  295. { do we have an assembler block without the po_assembler?
  296. we should allow this for Delphi compatibility (PFV) }
  297. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  298. include(current_procinfo.procdef.procoptions,po_assembler);
  299. { Handle assembler block different }
  300. if (po_assembler in current_procinfo.procdef.procoptions) then
  301. begin
  302. block:=assembler_block;
  303. exit;
  304. end;
  305. {Unit initialization?.}
  306. if (
  307. assigned(current_procinfo.procdef.localst) and
  308. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  309. (current_module.is_unit or islibrary)
  310. ) then
  311. begin
  312. if (token=_END) then
  313. begin
  314. consume(_END);
  315. { We need at least a node, else the entry/exit code is not
  316. generated and thus no PASCALMAIN symbol which we need (PFV) }
  317. if islibrary then
  318. block:=cnothingnode.create
  319. else
  320. block:=nil;
  321. end
  322. else
  323. begin
  324. if token=_INITIALIZATION then
  325. begin
  326. { The library init code is already called and does not
  327. need to be in the initfinal table (PFV) }
  328. block:=statement_block(_INITIALIZATION);
  329. end
  330. else if token=_FINALIZATION then
  331. begin
  332. { when a unit has only a finalization section, we can come to this
  333. point when we try to read the nonh existing initalization section
  334. so we've to check if we are really try to parse the finalization }
  335. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  336. block:=statement_block(_FINALIZATION)
  337. else
  338. block:=nil;
  339. end
  340. else
  341. block:=statement_block(_BEGIN);
  342. end;
  343. end
  344. else
  345. begin
  346. { parse routine body }
  347. block:=statement_block(_BEGIN);
  348. { initialized variables }
  349. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  350. begin
  351. { initialization of local variables with their initial
  352. values: part of function entry }
  353. oldfilepos:=current_filepos;
  354. current_filepos:=current_procinfo.entrypos;
  355. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  356. current_filepos:=oldfilepos;
  357. end
  358. else if current_procinfo.procdef.localst.symtabletype=staticsymtable then
  359. begin
  360. { for program and unit initialization code we also need to
  361. initialize the local variables used of Default() }
  362. oldfilepos:=current_filepos;
  363. current_filepos:=current_procinfo.entrypos;
  364. current_procinfo.procdef.localst.SymList.ForEachCall(@initializedefaultvars,block);
  365. current_filepos:=oldfilepos;
  366. end;
  367. if assigned(current_procinfo.procdef.parentfpstruct) then
  368. begin
  369. { we only do this after the code has been parsed because
  370. otherwise for-loop counters moved to the struct cause
  371. errors; we still do it nevertheless to prevent false
  372. "unused" symbols warnings and to assist debug info
  373. generation }
  374. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  375. { finish the parentfpstruct (add padding, ...) }
  376. finish_parentfpstruct(current_procinfo.procdef);
  377. end;
  378. end;
  379. end;
  380. {****************************************************************************
  381. PROCEDURE/FUNCTION COMPILING
  382. ****************************************************************************}
  383. procedure printnode_reset;
  384. begin
  385. assign(printnodefile,treelogfilename);
  386. {$push}{$I-}
  387. rewrite(printnodefile);
  388. {$pop}
  389. if ioresult<>0 then
  390. begin
  391. Comment(V_Error,'Error creating '+treelogfilename);
  392. exit;
  393. end;
  394. close(printnodefile);
  395. end;
  396. procedure add_label_init(p:TObject;arg:pointer);
  397. begin
  398. if tstoredsym(p).typ=labelsym then
  399. begin
  400. addstatement(tstatementnode(arg^),
  401. cifnode.create(caddnode.create(equaln,
  402. ccallnode.createintern('fpc_setjmp',
  403. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  404. cordconstnode.create(1,sinttype,true))
  405. ,cgotonode.create(tlabelsym(p)),nil)
  406. );
  407. end;
  408. end;
  409. function generate_bodyentry_block:tnode;
  410. var
  411. srsym : tsym;
  412. para : tcallparanode;
  413. call : tcallnode;
  414. newstatement : tstatementnode;
  415. def : tabstractrecorddef;
  416. begin
  417. result:=internalstatements(newstatement);
  418. if assigned(current_structdef) then
  419. begin
  420. { a constructor needs a help procedure }
  421. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  422. begin
  423. if is_class(current_structdef) or
  424. (
  425. is_objectpascal_helper(current_structdef) and
  426. is_class(tobjectdef(current_structdef).extendeddef)
  427. ) then
  428. begin
  429. if is_objectpascal_helper(current_structdef) then
  430. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  431. else
  432. def:=current_structdef;
  433. srsym:=search_struct_member(def,'NEWINSTANCE');
  434. if assigned(srsym) and
  435. (srsym.typ=procsym) then
  436. begin
  437. { if vmt=1 then newinstance }
  438. addstatement(newstatement,cifnode.create(
  439. caddnode.create_internal(equaln,
  440. ctypeconvnode.create_internal(
  441. load_vmt_pointer_node,
  442. voidpointertype),
  443. cpointerconstnode.create(1,voidpointertype)),
  444. cassignmentnode.create(
  445. ctypeconvnode.create_internal(
  446. load_self_pointer_node,
  447. voidpointertype),
  448. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  449. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  450. [],nil)),
  451. nil));
  452. end
  453. else
  454. internalerror(200305108);
  455. end
  456. else
  457. if is_object(current_structdef) then
  458. begin
  459. { parameter 3 : vmt_offset }
  460. { parameter 2 : address of pointer to vmt,
  461. this is required to allow setting the vmt to -1 to indicate
  462. that memory was allocated }
  463. { parameter 1 : self pointer }
  464. para:=ccallparanode.create(
  465. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  466. ccallparanode.create(
  467. ctypeconvnode.create_internal(
  468. load_vmt_pointer_node,
  469. voidpointertype),
  470. ccallparanode.create(
  471. ctypeconvnode.create_internal(
  472. load_self_pointer_node,
  473. voidpointertype),
  474. nil)));
  475. addstatement(newstatement,cassignmentnode.create(
  476. ctypeconvnode.create_internal(
  477. load_self_pointer_node,
  478. voidpointertype),
  479. ccallnode.createintern('fpc_help_constructor',para)));
  480. end
  481. else
  482. if is_javaclass(current_structdef) or
  483. ((target_info.system in systems_jvm) and
  484. is_record(current_structdef)) then
  485. begin
  486. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  487. not current_procinfo.ConstructorCallingConstructor then
  488. begin
  489. { call inherited constructor }
  490. if is_javaclass(current_structdef) then
  491. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  492. else
  493. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  494. if assigned(srsym) and
  495. (srsym.typ=procsym) then
  496. begin
  497. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  498. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  499. addstatement(newstatement,call);
  500. end
  501. else
  502. internalerror(2011010312);
  503. end;
  504. end
  505. else
  506. if not is_record(current_structdef) and
  507. not (
  508. is_objectpascal_helper(current_structdef) and
  509. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  510. ) then
  511. internalerror(200305103);
  512. { if self=nil then exit
  513. calling fail instead of exit is useless because
  514. there is nothing to dispose (PFV) }
  515. if is_class_or_object(current_structdef) then
  516. addstatement(newstatement,cifnode.create(
  517. caddnode.create(equaln,
  518. load_self_pointer_node,
  519. cnilnode.create),
  520. cexitnode.create(nil),
  521. nil));
  522. end;
  523. { maybe call BeforeDestruction for classes }
  524. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  525. is_class(current_structdef) then
  526. begin
  527. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  528. if assigned(srsym) and
  529. (srsym.typ=procsym) then
  530. begin
  531. { if vmt>0 then beforedestruction }
  532. addstatement(newstatement,cifnode.create(
  533. caddnode.create(gtn,
  534. ctypeconvnode.create_internal(
  535. load_vmt_pointer_node,ptrsinttype),
  536. ctypeconvnode.create_internal(
  537. cnilnode.create,ptrsinttype)),
  538. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  539. nil));
  540. end
  541. else
  542. internalerror(200305104);
  543. end;
  544. end;
  545. if m_non_local_goto in current_settings.modeswitches then
  546. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  547. end;
  548. function generate_bodyexit_block:tnode;
  549. var
  550. srsym : tsym;
  551. para : tcallparanode;
  552. newstatement : tstatementnode;
  553. oldlocalswitches: tlocalswitches;
  554. begin
  555. result:=internalstatements(newstatement);
  556. if assigned(current_structdef) then
  557. begin
  558. { Don't test self and the vmt here. The reason is that }
  559. { a constructor already checks whether these are valid }
  560. { before. Further, in case of TThread the thread may }
  561. { free the class instance right after AfterConstruction }
  562. { has been called, so it may no longer be valid (JM) }
  563. oldlocalswitches:=current_settings.localswitches;
  564. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  565. { a destructor needs a help procedure }
  566. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  567. begin
  568. if is_class(current_structdef) then
  569. begin
  570. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  571. if assigned(srsym) and
  572. (srsym.typ=procsym) then
  573. begin
  574. { if self<>0 and vmt<>0 then freeinstance }
  575. addstatement(newstatement,cifnode.create(
  576. caddnode.create(andn,
  577. caddnode.create(unequaln,
  578. load_self_pointer_node,
  579. cnilnode.create),
  580. caddnode.create(unequaln,
  581. ctypeconvnode.create(
  582. load_vmt_pointer_node,
  583. voidpointertype),
  584. cpointerconstnode.create(0,voidpointertype))),
  585. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  586. nil));
  587. end
  588. else
  589. internalerror(200305108);
  590. end
  591. else
  592. if is_object(current_structdef) then
  593. begin
  594. { finalize object data, but only if not in inherited call }
  595. if is_managed_type(current_structdef) then
  596. begin
  597. addstatement(newstatement,cifnode.create(
  598. caddnode.create(unequaln,
  599. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  600. cnilnode.create),
  601. cnodeutils.finalize_data_node(load_self_node),
  602. nil));
  603. end;
  604. { parameter 3 : vmt_offset }
  605. { parameter 2 : pointer to vmt }
  606. { parameter 1 : self pointer }
  607. para:=ccallparanode.create(
  608. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  609. ccallparanode.create(
  610. ctypeconvnode.create_internal(
  611. load_vmt_pointer_node,
  612. voidpointertype),
  613. ccallparanode.create(
  614. ctypeconvnode.create_internal(
  615. load_self_pointer_node,
  616. voidpointertype),
  617. nil)));
  618. addstatement(newstatement,
  619. ccallnode.createintern('fpc_help_destructor',para));
  620. end
  621. else if is_javaclass(current_structdef) then
  622. begin
  623. { nothing to do }
  624. end
  625. else
  626. internalerror(200305105);
  627. end;
  628. current_settings.localswitches:=oldlocalswitches;
  629. end;
  630. end;
  631. {****************************************************************************
  632. TCGProcInfo
  633. ****************************************************************************}
  634. destructor tcgprocinfo.destroy;
  635. begin
  636. code.free;
  637. inherited destroy;
  638. end;
  639. function tcgprocinfo.calc_stackframe_size:longint;
  640. begin
  641. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  642. end;
  643. procedure tcgprocinfo.printproc(pass:string);
  644. begin
  645. assign(printnodefile,treelogfilename);
  646. {$push}{$I-}
  647. append(printnodefile);
  648. if ioresult<>0 then
  649. rewrite(printnodefile);
  650. {$pop}
  651. if ioresult<>0 then
  652. begin
  653. Comment(V_Error,'Error creating '+treelogfilename);
  654. exit;
  655. end;
  656. writeln(printnodefile);
  657. writeln(printnodefile,'*******************************************************************************');
  658. writeln(printnodefile, pass);
  659. writeln(printnodefile,procdef.fullprocname(false));
  660. writeln(printnodefile,'*******************************************************************************');
  661. printnode(printnodefile,code);
  662. close(printnodefile);
  663. end;
  664. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  665. var
  666. oldlocalswitches: tlocalswitches;
  667. srsym: tsym;
  668. constructionblock,
  669. exceptblock,
  670. newblock: tblocknode;
  671. newstatement: tstatementnode;
  672. pd: tprocdef;
  673. constructionsuccessful: tlocalvarsym;
  674. begin
  675. if assigned(procdef.struct) and
  676. (procdef.proctypeoption=potype_constructor) then
  677. begin
  678. withexceptblock:=
  679. withexceptblock and
  680. not(target_info.system in systems_garbage_collected_managed_types);
  681. { Don't test self and the vmt here. See generate_bodyexit_block }
  682. { why (JM) }
  683. oldlocalswitches:=current_settings.localswitches;
  684. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  685. { call AfterConstruction for classes }
  686. constructionsuccessful:=nil;
  687. if is_class(procdef.struct) then
  688. begin
  689. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[],false);
  690. procdef.localst.insert(constructionsuccessful,false);
  691. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  692. if not assigned(srsym) or
  693. (srsym.typ<>procsym) then
  694. internalerror(200305106);
  695. current_filepos:=entrypos;
  696. constructionblock:=internalstatements(newstatement);
  697. { initialise constructionsuccessful with -1, indicating that
  698. the construction was not successful and hence
  699. beforedestruction should not be called if a destructor is
  700. called from the constructor }
  701. addstatement(newstatement,cassignmentnode.create(
  702. cloadnode.create(constructionsuccessful,procdef.localst),
  703. genintconstnode(-1))
  704. );
  705. { first execute all constructor code. If no exception
  706. occurred then we will execute afterconstruction,
  707. otherwise we won't (the exception will jump over us) }
  708. addstatement(newstatement,tocode);
  709. current_filepos:=exitpos;
  710. { if implicit finally node wasn't created, then exit label and
  711. finalization code must be handled here and placed before
  712. afterconstruction }
  713. if not ((pi_needs_implicit_finally in flags) and
  714. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  715. begin
  716. include(tocode.flags,nf_block_with_exit);
  717. if procdef.proctypeoption<>potype_exceptfilter then
  718. addstatement(newstatement,cfinalizetempsnode.create);
  719. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  720. temps_finalized:=true;
  721. end;
  722. { construction successful -> beforedestruction should be called
  723. if an exception happens now }
  724. addstatement(newstatement,cassignmentnode.create(
  725. cloadnode.create(constructionsuccessful,procdef.localst),
  726. genintconstnode(1))
  727. );
  728. { Self can be nil when fail is called }
  729. { if self<>nil and vmt<>nil then afterconstruction }
  730. addstatement(newstatement,cifnode.create(
  731. caddnode.create(andn,
  732. caddnode.create(unequaln,
  733. load_self_node,
  734. cnilnode.create),
  735. caddnode.create(unequaln,
  736. load_vmt_pointer_node,
  737. cnilnode.create)),
  738. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  739. nil));
  740. tocode:=constructionblock;
  741. end;
  742. if withexceptblock and (procdef.struct.typ=objectdef) then
  743. begin
  744. { Generate the implicit "fail" code for a constructor (destroy
  745. in case an exception happened) }
  746. pd:=tobjectdef(procdef.struct).find_destructor;
  747. { this will always be the case for classes, since tobject has
  748. a destructor }
  749. if assigned(pd) or is_object(procdef.struct) then
  750. begin
  751. current_filepos:=exitpos;
  752. exceptblock:=internalstatements(newstatement);
  753. { first free the instance if non-nil }
  754. if assigned(pd) then
  755. { if vmt<>0 then call destructor }
  756. addstatement(newstatement,
  757. cifnode.create(
  758. caddnode.create(unequaln,
  759. load_vmt_pointer_node,
  760. cnilnode.create),
  761. { cnf_create_failed -> don't call BeforeDestruction }
  762. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  763. nil))
  764. else
  765. { object without destructor, call 'fail' helper }
  766. addstatement(newstatement,
  767. ccallnode.createintern('fpc_help_fail',
  768. ccallparanode.create(
  769. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  770. ccallparanode.create(
  771. ctypeconvnode.create_internal(
  772. load_vmt_pointer_node,
  773. voidpointertype),
  774. ccallparanode.create(
  775. ctypeconvnode.create_internal(
  776. load_self_pointer_node,
  777. voidpointertype),
  778. nil))))
  779. );
  780. { then re-raise the exception }
  781. addstatement(newstatement,craisenode.create(nil,nil,nil));
  782. current_filepos:=entrypos;
  783. newblock:=internalstatements(newstatement);
  784. { try
  785. tocode
  786. except
  787. exceptblock
  788. end
  789. }
  790. addstatement(newstatement,ctryexceptnode.create(
  791. tocode,
  792. nil,
  793. exceptblock));
  794. tocode:=newblock;
  795. end;
  796. end;
  797. current_settings.localswitches:=oldlocalswitches;
  798. end;
  799. end;
  800. procedure tcgprocinfo.add_entry_exit_code;
  801. var
  802. finalcode,
  803. bodyentrycode,
  804. bodyexitcode,
  805. wrappedbody,
  806. newblock : tnode;
  807. codestatement,
  808. newstatement : tstatementnode;
  809. oldfilepos : tfileposinfo;
  810. is_constructor: boolean;
  811. begin
  812. is_constructor:=assigned(procdef.struct) and
  813. (procdef.proctypeoption=potype_constructor);
  814. oldfilepos:=current_filepos;
  815. { Generate code/locations used at start of proc }
  816. current_filepos:=entrypos;
  817. entry_asmnode:=casmnode.create_get_position;
  818. loadpara_asmnode:=casmnode.create_get_position;
  819. stackcheck_asmnode:=casmnode.create_get_position;
  820. init_asmnode:=casmnode.create_get_position;
  821. bodyentrycode:=generate_bodyentry_block;
  822. { Generate code/locations used at end of proc }
  823. current_filepos:=exitpos;
  824. exitlabel_asmnode:=casmnode.create_get_position;
  825. temps_finalized:=false;
  826. bodyexitcode:=generate_bodyexit_block;
  827. { Generate procedure by combining init+body+final,
  828. depending on the implicit finally we need to add
  829. an try...finally...end wrapper }
  830. current_filepos:=entrypos;
  831. newblock:=internalstatements(newstatement);
  832. { initialization is common for all cases }
  833. addstatement(newstatement,loadpara_asmnode);
  834. addstatement(newstatement,stackcheck_asmnode);
  835. addstatement(newstatement,entry_asmnode);
  836. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  837. addstatement(newstatement,init_asmnode);
  838. if assigned(procdef.parentfpinitblock) then
  839. begin
  840. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  841. begin
  842. { could be an asmn in case of a pure assembler procedure,
  843. but those shouldn't access nested variables }
  844. addstatement(newstatement,procdef.parentfpinitblock);
  845. end
  846. else
  847. procdef.parentfpinitblock.free;
  848. procdef.parentfpinitblock:=nil;
  849. end;
  850. addstatement(newstatement,bodyentrycode);
  851. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  852. (pi_needs_implicit_finally in flags) and
  853. { but it's useless in init/final code of units }
  854. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  855. not(target_info.system in systems_garbage_collected_managed_types) then
  856. begin
  857. { Any result of managed type must be returned in parameter }
  858. if is_managed_type(procdef.returndef) and
  859. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  860. (not is_class(procdef.returndef)) then
  861. InternalError(2013121301);
  862. { Generate special exception block only needed when
  863. implicit finaly is used }
  864. current_filepos:=exitpos;
  865. { Generate code that will be in the try...finally }
  866. finalcode:=internalstatements(codestatement);
  867. if procdef.proctypeoption<>potype_exceptfilter then
  868. addstatement(codestatement,cfinalizetempsnode.create);
  869. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  870. temps_finalized:=true;
  871. current_filepos:=entrypos;
  872. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  873. { afterconstruction must be called after finalizetemps, because it
  874. has to execute after the temps have been finalised in case of a
  875. refcounted class (afterconstruction decreases the refcount
  876. without freeing the instance if the count becomes nil, while
  877. the finalising of the temps can free the instance) }
  878. maybe_add_constructor_wrapper(wrappedbody,true);
  879. addstatement(newstatement,wrappedbody);
  880. addstatement(newstatement,exitlabel_asmnode);
  881. addstatement(newstatement,bodyexitcode);
  882. { set flag the implicit finally has been generated }
  883. include(flags,pi_has_implicit_finally);
  884. end
  885. else
  886. begin
  887. { constructors need destroy-on-exception code even if they don't
  888. have managed variables/temps }
  889. maybe_add_constructor_wrapper(code,
  890. cs_implicit_exceptions in current_settings.moduleswitches);
  891. current_filepos:=entrypos;
  892. addstatement(newstatement,code);
  893. current_filepos:=exitpos;
  894. if assigned(nestedexitlabel) then
  895. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  896. addstatement(newstatement,exitlabel_asmnode);
  897. addstatement(newstatement,bodyexitcode);
  898. if not is_constructor then
  899. begin
  900. if procdef.proctypeoption<>potype_exceptfilter then
  901. addstatement(newstatement,cfinalizetempsnode.create);
  902. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  903. temps_finalized:=true;
  904. end;
  905. end;
  906. if not temps_finalized then
  907. begin
  908. current_filepos:=exitpos;
  909. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  910. end;
  911. do_firstpass(newblock);
  912. code:=newblock;
  913. current_filepos:=oldfilepos;
  914. end;
  915. procedure clearrefs(p:TObject;arg:pointer);
  916. begin
  917. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  918. if tabstractvarsym(p).refs>1 then
  919. tabstractvarsym(p).refs:=1;
  920. end;
  921. procedure translate_registers(p:TObject;list:pointer);
  922. begin
  923. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  924. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  925. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  926. begin
  927. if not(cs_no_regalloc in current_settings.globalswitches) then
  928. begin
  929. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  930. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  931. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  932. end;
  933. end;
  934. end;
  935. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(riscv32) or defined(riscv64)}
  936. const
  937. exception_flags: array[boolean] of tprocinfoflags = (
  938. [],
  939. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  940. );
  941. {$endif}
  942. procedure tcgprocinfo.setup_tempgen;
  943. begin
  944. tg:=tgobjclass.create;
  945. {$if defined(i386) or defined(x86_64) or defined(arm)}
  946. {$if defined(arm)}
  947. { frame and stack pointer must be always the same on arm thumb so it makes no
  948. sense to fiddle with a frame pointer }
  949. if GenerateThumbCode then
  950. begin
  951. framepointer:=NR_STACK_POINTER_REG;
  952. tg.direction:=1;
  953. end
  954. else
  955. {$endif defined(arm)}
  956. begin
  957. { try to strip the stack frame }
  958. { set the framepointer to esp if:
  959. - no assembler directive, those are handled in assembler_block
  960. in pstatment.pas (for cases not caught by the Delphi
  961. exception below)
  962. - no exceptions are used
  963. - no pushes are used/esp modifications, could be:
  964. * outgoing parameters on the stack on non-fixed stack target
  965. * incoming parameters on the stack
  966. * open arrays
  967. - no inline assembler
  968. or
  969. - Delphi mode
  970. - assembler directive
  971. - no pushes are used/esp modifications, could be:
  972. * outgoing parameters on the stack
  973. * incoming parameters on the stack
  974. * open arrays
  975. - no local variables
  976. - stack frame cannot be optimized if using Win64 SEH
  977. (at least with the current state of our codegenerator).
  978. }
  979. if ((po_assembler in procdef.procoptions) and
  980. (m_delphi in current_settings.modeswitches) and
  981. { localst at main_program_level is a staticsymtable }
  982. (procdef.localst.symtablelevel<>main_program_level) and
  983. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  984. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  985. not(cs_generate_stackframes in current_settings.localswitches) and
  986. not(cs_profile in current_settings.moduleswitches) and
  987. not(po_assembler in procdef.procoptions) and
  988. not ((pi_has_stackparameter in flags)
  989. {$ifndef arm} { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  990. with fixed stack. On ARM it fails, see bug #25050 }
  991. and (not paramanager.use_fixed_stack)
  992. {$endif arm}
  993. ) and
  994. ((flags*([pi_has_assembler_block,pi_is_assembler,
  995. pi_needs_stackframe]+
  996. exception_flags[(target_info.cpu=cpu_i386)
  997. {$ifndef DISABLE_WIN64_SEH}
  998. or (target_info.system=system_x86_64_win64)
  999. {$endif DISABLE_WIN64_SEH}
  1000. ]))=[])
  1001. )
  1002. then
  1003. begin
  1004. { we need the parameter info here to determine if the procedure gets
  1005. parameters on the stack
  1006. calling generate_parameter_info doesn't hurt but it costs time
  1007. (necessary to init para_stack_size)
  1008. }
  1009. generate_parameter_info;
  1010. if not(procdef.stack_tainting_parameter(calleeside)) and
  1011. not(has_assembler_child) and (para_stack_size=0) then
  1012. begin
  1013. { Only need to set the framepointer }
  1014. framepointer:=NR_STACK_POINTER_REG;
  1015. tg.direction:=1;
  1016. end
  1017. {$if defined(arm)}
  1018. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1019. in case parameters are passed on the stack.
  1020. However, the draw back is, if the estimation fails, compilation will break later on
  1021. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1022. multipass compilation of subroutines must be supported
  1023. }
  1024. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1025. not(has_assembler_child) then
  1026. begin
  1027. { Only need to set the framepointer }
  1028. framepointer:=NR_STACK_POINTER_REG;
  1029. tg.direction:=1;
  1030. include(flags,pi_estimatestacksize);
  1031. set_first_temp_offset;
  1032. procdef.has_paraloc_info:=callnoside;
  1033. generate_parameter_info;
  1034. exit;
  1035. end;
  1036. {$endif defined(arm)}
  1037. end;
  1038. end;
  1039. {$endif defined(x86) or defined(arm)}
  1040. { set the start offset to the start of the temp area in the stack }
  1041. set_first_temp_offset;
  1042. end;
  1043. function tcgprocinfo.has_assembler_child : boolean;
  1044. var
  1045. hp : tprocinfo;
  1046. begin
  1047. result:=false;
  1048. hp:=get_first_nestedproc;
  1049. while assigned(hp) do
  1050. begin
  1051. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1052. begin
  1053. result:=true;
  1054. exit;
  1055. end;
  1056. hp:=tprocinfo(hp.next);
  1057. end;
  1058. end;
  1059. procedure tcgprocinfo.generate_code_tree;
  1060. var
  1061. hpi : tcgprocinfo;
  1062. begin
  1063. { generate code for this procedure }
  1064. generate_code;
  1065. { process nested procedures }
  1066. hpi:=tcgprocinfo(get_first_nestedproc);
  1067. while assigned(hpi) do
  1068. begin
  1069. hpi.generate_code_tree;
  1070. hpi:=tcgprocinfo(hpi.next);
  1071. end;
  1072. resetprocdef;
  1073. end;
  1074. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1075. which can be called by OS during stack unwind. This resembles nested procedures,
  1076. but finalizer procedures do not have their own local variables and work directly
  1077. with the stack frame of parent. In particular, the tempgen must be shared, so
  1078. 1) finalizer procedure is able to finalize temps of the parent,
  1079. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1080. allocated in stack frame of parent, so second-level finalizer procedures are
  1081. not needed.
  1082. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1083. procedure (after the parent) and have to do it inline.
  1084. This is called by platform-specific tryfinallynodes during pass2.
  1085. Here we put away the codegen (which carries the register allocator state), process
  1086. the 'nested' procedure, then restore previous cg and continue processing the parent
  1087. procedure. generate_code() will create another cg, but not another tempgen because
  1088. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1089. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1090. var
  1091. saved_cg: tcg;
  1092. saved_hlcg: thlcgobj;
  1093. {$ifdef cpu64bitalu}
  1094. saved_cg128 : tcg128;
  1095. {$else cpu64bitalu}
  1096. saved_cg64 : tcg64;
  1097. {$endif cpu64bitalu}
  1098. begin
  1099. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1100. InternalError(201201141);
  1101. { flush code generated this far }
  1102. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1103. { save the codegen }
  1104. saved_cg:=cg;
  1105. saved_hlcg:=hlcg;
  1106. cg:=nil;
  1107. hlcg:=nil;
  1108. {$ifdef cpu64bitalu}
  1109. saved_cg128:=cg128;
  1110. cg128:=nil;
  1111. {$else cpu64bitalu}
  1112. saved_cg64:=cg64;
  1113. cg64:=nil;
  1114. {$endif cpu64bitalu}
  1115. nestedpi.generate_code;
  1116. { prevents generating code the second time when processing nested procedures }
  1117. nestedpi.resetprocdef;
  1118. cg:=saved_cg;
  1119. hlcg:=saved_hlcg;
  1120. {$ifdef cpu64bitalu}
  1121. cg128:=saved_cg128;
  1122. {$else cpu64bitalu}
  1123. cg64:=saved_cg64;
  1124. {$endif cpu64bitalu}
  1125. add_reg_instruction_hook:[email protected]_reg_instruction;
  1126. end;
  1127. procedure TCGProcinfo.CreateInlineInfo;
  1128. begin
  1129. new(procdef.inlininginfo);
  1130. procdef.inlininginfo^.code:=code.getcopy;
  1131. procdef.inlininginfo^.flags:=flags;
  1132. { The blocknode needs to set an exit label }
  1133. if procdef.inlininginfo^.code.nodetype=blockn then
  1134. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1135. procdef.has_inlininginfo:=true;
  1136. end;
  1137. procedure searchthreadvar(p: TObject; arg: pointer);
  1138. var
  1139. i : longint;
  1140. pd : tprocdef;
  1141. begin
  1142. case tsym(p).typ of
  1143. staticvarsym :
  1144. begin
  1145. { local (procedure or unit) variables only need finalization
  1146. if they are used
  1147. }
  1148. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1149. ((tstaticvarsym(p).refs>0) or
  1150. { global (unit) variables always need finalization, since
  1151. they may also be used in another unit
  1152. }
  1153. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1154. (
  1155. (tstaticvarsym(p).varspez<>vs_const) or
  1156. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1157. ) and
  1158. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1159. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1160. is_managed_type(tstaticvarsym(p).vardef) then
  1161. include(current_procinfo.flags,pi_uses_threadvar);
  1162. end;
  1163. procsym :
  1164. begin
  1165. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1166. begin
  1167. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1168. if assigned(pd.localst) and
  1169. (pd.procsym=tprocsym(p)) and
  1170. (pd.localst.symtabletype<>staticsymtable) then
  1171. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1172. end;
  1173. end;
  1174. end;
  1175. end;
  1176. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1177. begin
  1178. if nf_usercode_entry in n.flags then
  1179. begin
  1180. pnode(arg)^:=n;
  1181. result:=fen_norecurse_true
  1182. end
  1183. else
  1184. result:=fen_false;
  1185. end;
  1186. function TCGProcinfo.GetUserCode : tnode;
  1187. var
  1188. n : tnode;
  1189. begin
  1190. n:=nil;
  1191. foreachnodestatic(code,@searchusercode,@n);
  1192. if not(assigned(n)) then
  1193. internalerror(2013111004);
  1194. result:=n;
  1195. end;
  1196. procedure tcgprocinfo.generate_code;
  1197. procedure check_for_threadvars_in_initfinal;
  1198. begin
  1199. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1200. begin
  1201. { this is also used for initialization of variables in a
  1202. program which does not have a globalsymtable }
  1203. if assigned(current_module.globalsymtable) then
  1204. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1205. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1206. end;
  1207. end;
  1208. var
  1209. old_current_procinfo : tprocinfo;
  1210. oldmaxfpuregisters : longint;
  1211. oldfilepos : tfileposinfo;
  1212. old_current_structdef : tabstractrecorddef;
  1213. templist : TAsmList;
  1214. headertai : tai;
  1215. i : integer;
  1216. {RedoDFA : boolean;}
  1217. procedure delete_marker(anode: tasmnode);
  1218. var
  1219. ai: tai;
  1220. begin
  1221. if assigned(anode) then
  1222. begin
  1223. ai:=anode.currenttai;
  1224. if assigned(ai) then
  1225. begin
  1226. aktproccode.remove(ai);
  1227. ai.free;
  1228. anode.currenttai:=nil;
  1229. end;
  1230. end;
  1231. end;
  1232. begin
  1233. { the initialization procedure can be empty, then we
  1234. don't need to generate anything. When it was an empty
  1235. procedure there would be at least a blocknode }
  1236. if not assigned(code) then
  1237. exit;
  1238. { We need valid code }
  1239. if Errorcount<>0 then
  1240. exit;
  1241. { No code can be generated for generic template }
  1242. if (df_generic in procdef.defoptions) then
  1243. internalerror(200511152);
  1244. { For regular procedures the RA and Tempgen shall not be available yet,
  1245. but exception filters reuse Tempgen of parent }
  1246. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1247. internalerror(200309201);
  1248. old_current_procinfo:=current_procinfo;
  1249. oldfilepos:=current_filepos;
  1250. old_current_structdef:=current_structdef;
  1251. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1252. current_procinfo:=self;
  1253. current_filepos:=entrypos;
  1254. current_structdef:=procdef.struct;
  1255. { store start of user code, it must be a block node, it will be used later one to
  1256. check variable lifeness }
  1257. include(code.flags,nf_usercode_entry);
  1258. { add wrapping code if necessary (initialization of typed constants on
  1259. some platforms, initing of local variables and out parameters with
  1260. trashing values, ...) }
  1261. { init/final code must be wrapped later (after code for main proc body
  1262. has been generated) }
  1263. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1264. code:=cnodeutils.wrap_proc_body(procdef,code);
  1265. { automatic inlining? }
  1266. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1267. { inlining not turned off? }
  1268. (cs_do_inline in current_settings.localswitches) and
  1269. not(po_noinline in procdef.procoptions) and
  1270. { no inlining yet? }
  1271. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1272. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1273. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1274. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1275. (not(procdef.proccalloption in [pocall_safecall])) and
  1276. { rough approximation if we should auto inline }
  1277. (node_count(code)<=10) then
  1278. begin
  1279. { Can we inline this procedure? }
  1280. if checknodeinlining(procdef) then
  1281. begin
  1282. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1283. include(procdef.procoptions,po_inline);
  1284. CreateInlineInfo;
  1285. end;
  1286. end;
  1287. templist:=TAsmList.create;
  1288. { add parast/localst to symtablestack }
  1289. add_to_symtablestack;
  1290. { clear register count }
  1291. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1292. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1293. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1294. if (procdef.localst.symtablelevel=main_program_level) and
  1295. (not current_module.is_unit) then
  1296. begin
  1297. include(flags,pi_do_call);
  1298. { the main program never returns due to the do_exit call }
  1299. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1300. include(procdef.procoptions,po_noreturn);
  1301. end;
  1302. { set implicit_finally flag when there are locals/paras to be finalized }
  1303. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1304. begin
  1305. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1306. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1307. end;
  1308. {$ifdef SUPPORT_SAFECALL}
  1309. { set implicit_finally flag for if procedure is safecall }
  1310. if (tf_safecall_exceptions in target_info.flags) and
  1311. (procdef.proccalloption=pocall_safecall) then
  1312. include(flags, pi_needs_implicit_finally);
  1313. {$endif}
  1314. { firstpass everything }
  1315. flowcontrol:=[];
  1316. do_firstpass(code);
  1317. {$if defined(i386) or defined(i8086)}
  1318. if node_resources_fpu(code)>0 then
  1319. include(flags,pi_uses_fpu);
  1320. {$endif i386 or i8086}
  1321. { Print the node to tree.log }
  1322. if paraprintnodetree=1 then
  1323. printproc( 'after the firstpass');
  1324. { do this before adding the entry code else the tail recursion recognition won't work,
  1325. if this causes troubles, it must be if'ed
  1326. }
  1327. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1328. (pi_is_recursive in flags) then
  1329. do_opttail(code,procdef);
  1330. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1331. do_optconstpropagate(code);
  1332. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1333. { creating dfa is not always possible }
  1334. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1335. begin
  1336. dfabuilder:=TDFABuilder.Create;
  1337. dfabuilder.createdfainfo(code);
  1338. include(flags,pi_dfaavailable);
  1339. { when life info is available, we can give more sophisticated warning about uninitialized
  1340. variables ...
  1341. ... but not for the finalization section of a unit, we would need global dfa to handle
  1342. it properly }
  1343. if potype_unitfinalize<>procdef.proctypeoption then
  1344. { iterate through life info of the first node }
  1345. for i:=0 to dfabuilder.nodemap.count-1 do
  1346. begin
  1347. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1348. begin
  1349. { do not warn for certain parameters: }
  1350. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1351. { do not warn about parameters passed by var }
  1352. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1353. { function result is passed by var but it must be initialized }
  1354. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1355. { do not warn about initialized hidden parameters }
  1356. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1357. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1358. end
  1359. else
  1360. begin
  1361. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1362. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1363. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1364. end;
  1365. end;
  1366. end;
  1367. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1368. do_optdeadstoreelim(code);
  1369. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1370. { our induction variable strength reduction doesn't like
  1371. for loops with more than one entry }
  1372. and not(pi_has_label in flags) then
  1373. begin
  1374. {RedoDFA:=}OptimizeInductionVariables(code);
  1375. end;
  1376. if (cs_opt_remove_emtpy_proc in current_settings.optimizerswitches) and
  1377. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1378. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1379. procdef.isempty:=true;
  1380. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1381. require a tls register, so check for such variables }
  1382. check_for_threadvars_in_initfinal;
  1383. { add implicit entry and exit code }
  1384. add_entry_exit_code;
  1385. if cs_opt_nodecse in current_settings.optimizerswitches then
  1386. do_optcse(code);
  1387. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1388. do_optloadmodifystore(code);
  1389. { only do secondpass if there are no errors }
  1390. if (ErrorCount=0) then
  1391. begin
  1392. create_hlcodegen;
  1393. if (procdef.proctypeoption<>potype_exceptfilter) then
  1394. setup_tempgen;
  1395. { Create register allocator, must come after framepointer is known }
  1396. hlcg.init_register_allocators;
  1397. generate_parameter_info;
  1398. { allocate got register if needed }
  1399. allocate_got_register(aktproccode);
  1400. if pi_uses_threadvar in flags then
  1401. allocate_tls_register(aktproccode);
  1402. { Allocate space in temp/registers for parast and localst }
  1403. current_filepos:=entrypos;
  1404. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1405. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1406. { Store temp offset for information about 'real' temps }
  1407. tempstart:=tg.lasttemp;
  1408. { Generate code to load register parameters in temps and insert local
  1409. copies for values parameters. This must be done before the code for the
  1410. body is generated because the localloc is updated.
  1411. Note: The generated code will be inserted after the code generation of
  1412. the body is finished, because only then the position is known }
  1413. {$ifdef oldregvars}
  1414. assign_regvars(code);
  1415. {$endif oldreg}
  1416. current_filepos:=entrypos;
  1417. hlcg.gen_load_para_value(templist);
  1418. { caller paraloc info is also necessary in the stackframe_entry
  1419. code of the ppc (and possibly other processors) }
  1420. procdef.init_paraloc_info(callerside);
  1421. CalcExecutionWeights(code);
  1422. { Print the node to tree.log }
  1423. if paraprintnodetree=1 then
  1424. printproc( 'right before code generation');
  1425. { generate code for the node tree }
  1426. do_secondpass(code);
  1427. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1428. { The position of the loadpara_asmnode is now known }
  1429. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1430. { first generate entry and initialize code with the correct
  1431. position and switches }
  1432. current_filepos:=entrypos;
  1433. current_settings.localswitches:=entryswitches;
  1434. cg.set_regalloc_live_range_direction(rad_backwards);
  1435. hlcg.gen_entry_code(templist);
  1436. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1437. hlcg.gen_initialize_code(templist);
  1438. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1439. { now generate finalize and exit code with the correct position
  1440. and switches }
  1441. current_filepos:=exitpos;
  1442. current_settings.localswitches:=exitswitches;
  1443. cg.set_regalloc_live_range_direction(rad_forward);
  1444. if assigned(finalize_procinfo) then
  1445. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1446. else if not temps_finalized then
  1447. begin
  1448. hlcg.gen_finalize_code(templist);
  1449. { the finalcode must be concated if there was no position available,
  1450. using insertlistafter will result in an insert at the start
  1451. when currentai=nil }
  1452. aktproccode.concatlist(templist);
  1453. end;
  1454. { insert exit label at the correct position }
  1455. hlcg.a_label(templist,CurrExitLabel);
  1456. if assigned(exitlabel_asmnode.currenttai) then
  1457. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1458. else
  1459. aktproccode.concatlist(templist);
  1460. { exit code }
  1461. hlcg.gen_exit_code(templist);
  1462. aktproccode.concatlist(templist);
  1463. {$ifdef OLDREGVARS}
  1464. { note: this must be done only after as much code as possible has }
  1465. { been generated. The result is that when you ungetregister() a }
  1466. { regvar, it will actually free the regvar (and alse free the }
  1467. { the regvars at the same time). Doing this too early will }
  1468. { confuse the register allocator, as the regvars will still be }
  1469. { used. It should be done before loading the result regs (so }
  1470. { they don't conflict with the regvars) and before }
  1471. { gen_entry_code (that one has to be able to allocate the }
  1472. { regvars again) (JM) }
  1473. free_regvars(aktproccode);
  1474. {$endif OLDREGVARS}
  1475. { generate symbol and save end of header position }
  1476. current_filepos:=entrypos;
  1477. hlcg.gen_proc_symbol(templist);
  1478. headertai:=tai(templist.last);
  1479. { insert symbol }
  1480. aktproccode.insertlist(templist);
  1481. { Free space in temp/registers for parast and localst, must be
  1482. done after gen_entry_code }
  1483. current_filepos:=exitpos;
  1484. { make sure the got/pic register doesn't get freed in the }
  1485. { middle of a loop }
  1486. if (cs_create_pic in current_settings.moduleswitches) and
  1487. (pi_needs_got in flags) and
  1488. (got<>NR_NO) then
  1489. cg.a_reg_sync(aktproccode,got);
  1490. if (pi_uses_threadvar in flags) and
  1491. (tlsoffset<>NR_NO) then
  1492. cg.a_reg_sync(aktproccode,tlsoffset);
  1493. gen_free_symtable(aktproccode,procdef.localst);
  1494. gen_free_symtable(aktproccode,procdef.parast);
  1495. { add code that will load the return value, this is not done
  1496. for assembler routines when they didn't reference the result
  1497. variable }
  1498. hlcg.gen_load_return_value(templist);
  1499. aktproccode.concatlist(templist);
  1500. { Already reserve all registers for stack checking code and
  1501. generate the call to the helper function }
  1502. if not(tf_no_generic_stackcheck in target_info.flags) and
  1503. (cs_check_stack in entryswitches) and
  1504. not(po_assembler in procdef.procoptions) and
  1505. (procdef.proctypeoption<>potype_proginit) then
  1506. begin
  1507. current_filepos:=entrypos;
  1508. hlcg.gen_stack_check_call(templist);
  1509. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1510. end;
  1511. { this code (got loading) comes before everything which has }
  1512. { already been generated, so reset the info about already }
  1513. { backwards extended registers (so their live range can be }
  1514. { extended backwards even further if needed) }
  1515. { This code must be }
  1516. { a) generated after do_secondpass has been called }
  1517. { (because pi_needs_got may be set there) }
  1518. { b) generated before register allocation, because the }
  1519. { got/pic register can be a virtual one }
  1520. { c) inserted before the entry code, because the entry }
  1521. { code may need global symbols such as init rtti }
  1522. { d) inserted after the stackframe allocation, because }
  1523. { this register may have to be spilled }
  1524. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1525. current_filepos:=entrypos;
  1526. { load got if necessary }
  1527. cg.g_maybe_got_init(templist);
  1528. aktproccode.insertlistafter(headertai,templist);
  1529. if (pi_uses_threadvar in flags) and (tf_section_threadvars in target_info.flags) then
  1530. cg.g_maybe_tls_init(templist);
  1531. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1532. { re-enable if more code at the end is ever generated here
  1533. cg.set_regalloc_live_range_direction(rad_forward);
  1534. }
  1535. {$ifndef NoOpt}
  1536. {$ifndef i386}
  1537. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1538. { do not optimize pure assembler procedures }
  1539. not(pi_is_assembler in flags) then
  1540. preregallocschedule(aktproccode);
  1541. {$endif i386}
  1542. {$endif NoOpt}
  1543. { The procedure body is finished, we can now
  1544. allocate the registers }
  1545. cg.do_register_allocation(aktproccode,headertai);
  1546. { translate imag. register to their real counter parts
  1547. this is necessary for debuginfo and verbose assembler output
  1548. when SSA will be implented, this will be more complicated because we've to
  1549. maintain location lists }
  1550. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1551. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1552. if (cs_create_pic in current_settings.moduleswitches) and
  1553. (pi_needs_got in flags) and
  1554. not(cs_no_regalloc in current_settings.globalswitches) and
  1555. (got<>NR_NO) then
  1556. cg.translate_register(got);
  1557. { Add save and restore of used registers }
  1558. current_filepos:=entrypos;
  1559. gen_save_used_regs(templist);
  1560. { Remember the last instruction of register saving block
  1561. (may be =nil for e.g. assembler procedures) }
  1562. endprologue_ai:=templist.last;
  1563. aktproccode.insertlistafter(headertai,templist);
  1564. current_filepos:=exitpos;
  1565. gen_restore_used_regs(aktproccode);
  1566. { We know the size of the stack, now we can generate the
  1567. parameter that is passed to the stack checking code }
  1568. if not(tf_no_generic_stackcheck in target_info.flags) and
  1569. (cs_check_stack in entryswitches) and
  1570. not(po_assembler in procdef.procoptions) and
  1571. (procdef.proctypeoption<>potype_proginit) then
  1572. begin
  1573. current_filepos:=entrypos;
  1574. hlcg.gen_stack_check_size_para(templist);
  1575. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1576. end;
  1577. { Add entry code (stack allocation) after header }
  1578. current_filepos:=entrypos;
  1579. gen_proc_entry_code(templist);
  1580. aktproccode.insertlistafter(headertai,templist);
  1581. {$ifdef SUPPORT_SAFECALL}
  1582. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1583. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1584. (tf_safecall_exceptions in target_info.flags) and
  1585. (procdef.proccalloption=pocall_safecall) then
  1586. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1587. {$endif}
  1588. { Add exit code at the end }
  1589. current_filepos:=exitpos;
  1590. gen_proc_exit_code(templist);
  1591. aktproccode.concatlist(templist);
  1592. { check if the implicit finally has been generated. The flag
  1593. should already be set in pass1 }
  1594. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1595. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1596. (pi_needs_implicit_finally in flags) and
  1597. not(pi_has_implicit_finally in flags) and
  1598. not(target_info.system in systems_garbage_collected_managed_types) then
  1599. internalerror(200405231);
  1600. { Position markers are only used to insert additional code after the secondpass
  1601. and before this point. They are of no use in optimizer. Instead of checking and
  1602. ignoring all over the optimizer, just remove them here. }
  1603. delete_marker(entry_asmnode);
  1604. delete_marker(loadpara_asmnode);
  1605. delete_marker(exitlabel_asmnode);
  1606. delete_marker(stackcheck_asmnode);
  1607. delete_marker(init_asmnode);
  1608. {$ifndef NoOpt}
  1609. if not(cs_no_regalloc in current_settings.globalswitches) then
  1610. begin
  1611. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1612. { do not optimize pure assembler procedures }
  1613. not(pi_is_assembler in flags) then
  1614. optimize(aktproccode);
  1615. {$ifndef i386}
  1616. { schedule after assembler optimization, it could have brought up
  1617. new schedule possibilities }
  1618. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1619. { do not optimize pure assembler procedures }
  1620. not(pi_is_assembler in flags) then
  1621. preregallocschedule(aktproccode);
  1622. {$endif i386}
  1623. end;
  1624. {$endif NoOpt}
  1625. { Perform target-specific processing if necessary }
  1626. postprocess_code;
  1627. { Add end symbol and debug info }
  1628. { this must be done after the pcrelativedata is appended else the distance calculation of
  1629. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1630. so it should be inserted before the end symbol (FK)
  1631. }
  1632. current_filepos:=exitpos;
  1633. hlcg.gen_proc_symbol_end(templist);
  1634. aktproccode.concatlist(templist);
  1635. { insert line debuginfo }
  1636. if (cs_debuginfo in current_settings.moduleswitches) or
  1637. (cs_use_lineinfo in current_settings.globalswitches) then
  1638. current_debuginfo.insertlineinfo(aktproccode);
  1639. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1640. { only now we can remove the temps }
  1641. if (procdef.proctypeoption<>potype_exceptfilter) then
  1642. begin
  1643. tg.resettempgen;
  1644. tg.free;
  1645. tg:=nil;
  1646. end;
  1647. { stop tempgen and ra }
  1648. hlcg.done_register_allocators;
  1649. destroy_hlcodegen;
  1650. end;
  1651. dfabuilder.free;
  1652. { restore symtablestack }
  1653. remove_from_symtablestack;
  1654. { restore }
  1655. templist.free;
  1656. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1657. current_filepos:=oldfilepos;
  1658. current_structdef:=old_current_structdef;
  1659. current_procinfo:=old_current_procinfo;
  1660. end;
  1661. procedure tcgprocinfo.add_to_symtablestack;
  1662. begin
  1663. { insert symtables for the class, but only if it is no nested function }
  1664. if assigned(procdef.struct) and
  1665. not(assigned(parent) and
  1666. assigned(parent.procdef) and
  1667. assigned(parent.procdef.struct)) then
  1668. push_nested_hierarchy(procdef.struct);
  1669. { insert parasymtable in symtablestack when parsing
  1670. a function }
  1671. if procdef.parast.symtablelevel>=normal_function_level then
  1672. symtablestack.push(procdef.parast);
  1673. { insert localsymtable, except for the main procedure
  1674. (in that case the localst is the unit's static symtable,
  1675. which is already on the stack) }
  1676. if procdef.localst.symtablelevel>=normal_function_level then
  1677. symtablestack.push(procdef.localst);
  1678. end;
  1679. procedure tcgprocinfo.remove_from_symtablestack;
  1680. begin
  1681. { remove localsymtable }
  1682. if procdef.localst.symtablelevel>=normal_function_level then
  1683. symtablestack.pop(procdef.localst);
  1684. { remove parasymtable }
  1685. if procdef.parast.symtablelevel>=normal_function_level then
  1686. symtablestack.pop(procdef.parast);
  1687. { remove symtables for the class, but only if it is no nested function }
  1688. if assigned(procdef.struct) and
  1689. not(assigned(parent) and
  1690. assigned(parent.procdef) and
  1691. assigned(parent.procdef.struct)) then
  1692. pop_nested_hierarchy(procdef.struct);
  1693. end;
  1694. procedure tcgprocinfo.resetprocdef;
  1695. begin
  1696. { remove code tree, if not inline procedure }
  1697. if assigned(code) then
  1698. begin
  1699. { the inline procedure has already got a copy of the tree
  1700. stored in procdef.inlininginfo }
  1701. code.free;
  1702. code:=nil;
  1703. end;
  1704. end;
  1705. procedure tcgprocinfo.parse_body;
  1706. var
  1707. old_current_procinfo : tprocinfo;
  1708. old_block_type : tblock_type;
  1709. st : TSymtable;
  1710. old_current_structdef: tabstractrecorddef;
  1711. old_current_genericdef,
  1712. old_current_specializedef: tstoreddef;
  1713. parentfpinitblock: tnode;
  1714. old_parse_generic: boolean;
  1715. recordtokens : boolean;
  1716. begin
  1717. old_current_procinfo:=current_procinfo;
  1718. old_block_type:=block_type;
  1719. old_current_structdef:=current_structdef;
  1720. old_current_genericdef:=current_genericdef;
  1721. old_current_specializedef:=current_specializedef;
  1722. old_parse_generic:=parse_generic;
  1723. current_procinfo:=self;
  1724. current_structdef:=procdef.struct;
  1725. { check if the definitions of certain types are available which might not be available in older rtls and
  1726. which are assigned "on the fly" in types_dec }
  1727. {$ifndef jvm}
  1728. if not assigned(rec_exceptaddr) then
  1729. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  1730. if not assigned(rec_tguid) then
  1731. Message1(cg_f_internal_type_not_found,'TGUID');
  1732. if not assigned(rec_jmp_buf) then
  1733. Message1(cg_f_internal_type_not_found,'TJMPBUF');
  1734. {$endif}
  1735. { if the procdef is truly a generic (thus takes parameters itself) then
  1736. /that/ is our genericdef, not the - potentially - generic struct }
  1737. if procdef.is_generic then
  1738. begin
  1739. current_genericdef:=procdef;
  1740. parse_generic:=true;
  1741. end
  1742. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1743. begin
  1744. current_genericdef:=current_structdef;
  1745. parse_generic:=true;
  1746. end;
  1747. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1748. current_specializedef:=current_structdef;
  1749. { calculate the lexical level }
  1750. if procdef.parast.symtablelevel>maxnesting then
  1751. Message(parser_e_too_much_lexlevel);
  1752. block_type:=bt_body;
  1753. {$ifdef state_tracking}
  1754. { aktstate:=Tstate_storage.create;}
  1755. {$endif state_tracking}
  1756. { allocate the symbol for this procedure }
  1757. alloc_proc_symbol(procdef);
  1758. { add parast/localst to symtablestack }
  1759. add_to_symtablestack;
  1760. { save entry info }
  1761. entrypos:=current_filepos;
  1762. entryswitches:=current_settings.localswitches;
  1763. recordtokens:=procdef.is_generic or
  1764. (
  1765. assigned(procdef.struct) and
  1766. (df_generic in procdef.struct.defoptions) and
  1767. assigned(procdef.owner) and
  1768. (procdef.owner.defowner=procdef.struct)
  1769. );
  1770. if recordtokens then
  1771. begin
  1772. { start token recorder for generic template }
  1773. procdef.initgeneric;
  1774. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1775. end;
  1776. { parse the code ... }
  1777. code:=block(current_module.islibrary);
  1778. if recordtokens then
  1779. begin
  1780. { stop token recorder for generic template }
  1781. current_scanner.stoprecordtokens;
  1782. { Give an error for accesses in the static symtable that aren't visible
  1783. outside the current unit }
  1784. st:=procdef.owner;
  1785. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  1786. st:=st.defowner.owner;
  1787. if (pi_uses_static_symtable in flags) and
  1788. (st.symtabletype<>staticsymtable) then
  1789. Message(parser_e_global_generic_references_static);
  1790. end;
  1791. { save exit info }
  1792. exitswitches:=current_settings.localswitches;
  1793. exitpos:=last_endtoken_filepos;
  1794. { the procedure is now defined }
  1795. procdef.forwarddef:=false;
  1796. if assigned(code) then
  1797. begin
  1798. { get a better entry point }
  1799. entrypos:=code.fileinfo;
  1800. { Finish type checking pass }
  1801. do_typecheckpass(code);
  1802. if assigned(procdef.parentfpinitblock) then
  1803. begin
  1804. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  1805. begin
  1806. parentfpinitblock:=procdef.parentfpinitblock;
  1807. do_typecheckpass(parentfpinitblock);
  1808. procdef.parentfpinitblock:=parentfpinitblock;
  1809. end
  1810. end;
  1811. end;
  1812. { Check for unused labels, forwards, symbols for procedures. Static
  1813. symtable is checked in pmodules.
  1814. The check must be done after the typecheckpass }
  1815. if (Errorcount=0) and
  1816. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1817. begin
  1818. { check if forwards are resolved }
  1819. tstoredsymtable(procdef.localst).check_forwards;
  1820. { check if all labels are used }
  1821. tstoredsymtable(procdef.localst).checklabels;
  1822. { check for unused symbols, but only if there is no asm block }
  1823. if not(pi_has_assembler_block in flags) then
  1824. begin
  1825. tstoredsymtable(procdef.localst).allsymbolsused;
  1826. tstoredsymtable(procdef.parast).allsymbolsused;
  1827. end;
  1828. end;
  1829. if (po_inline in procdef.procoptions) and
  1830. { Can we inline this procedure? }
  1831. checknodeinlining(procdef) then
  1832. CreateInlineInfo;
  1833. { Print the node to tree.log }
  1834. if paraprintnodetree=1 then
  1835. printproc( 'after parsing');
  1836. { ... remove symbol tables }
  1837. remove_from_symtablestack;
  1838. {$ifdef state_tracking}
  1839. { aktstate.destroy;}
  1840. {$endif state_tracking}
  1841. current_structdef:=old_current_structdef;
  1842. current_genericdef:=old_current_genericdef;
  1843. current_specializedef:=old_current_specializedef;
  1844. current_procinfo:=old_current_procinfo;
  1845. parse_generic:=old_parse_generic;
  1846. { Restore old state }
  1847. block_type:=old_block_type;
  1848. end;
  1849. {****************************************************************************
  1850. PROCEDURE/FUNCTION PARSING
  1851. ****************************************************************************}
  1852. procedure check_init_paras(p:TObject;arg:pointer);
  1853. begin
  1854. if tsym(p).typ<>paravarsym then
  1855. exit;
  1856. with tparavarsym(p) do
  1857. if (is_managed_type(vardef) and
  1858. (varspez in [vs_value,vs_out])) or
  1859. (is_shortstring(vardef) and
  1860. (varspez=vs_value)) then
  1861. include(current_procinfo.flags,pi_do_call);
  1862. end;
  1863. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1864. {
  1865. Parses the procedure directives, then parses the procedure body, then
  1866. generates the code for it
  1867. }
  1868. var
  1869. oldfailtokenmode : tmodeswitches;
  1870. isnestedproc : boolean;
  1871. begin
  1872. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1873. oldfailtokenmode:=[];
  1874. { create a new procedure }
  1875. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1876. current_module.procinfo:=current_procinfo;
  1877. current_procinfo.procdef:=pd;
  1878. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1879. { Insert mangledname }
  1880. pd.aliasnames.insert(pd.mangledname);
  1881. { Handle Export of this procedure }
  1882. if (po_exports in pd.procoptions) and
  1883. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1884. begin
  1885. pd.aliasnames.insert(pd.procsym.realname);
  1886. if cs_link_deffile in current_settings.globalswitches then
  1887. deffile.AddExport(pd.mangledname);
  1888. end;
  1889. { Insert result variables in the localst }
  1890. insert_funcret_local(pd);
  1891. { check if there are para's which require initing -> set }
  1892. { pi_do_call (if not yet set) }
  1893. if not(pi_do_call in current_procinfo.flags) then
  1894. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1895. { set _FAIL as keyword if constructor }
  1896. if (pd.proctypeoption=potype_constructor) then
  1897. begin
  1898. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1899. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  1900. end;
  1901. tcgprocinfo(current_procinfo).parse_body;
  1902. { reset _FAIL as _SELF normal }
  1903. if (pd.proctypeoption=potype_constructor) then
  1904. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1905. { When it's a nested procedure then defer the code generation,
  1906. when back at normal function level then generate the code
  1907. for all defered nested procedures and the current procedure }
  1908. if not isnestedproc then
  1909. begin
  1910. if not(df_generic in current_procinfo.procdef.defoptions) then
  1911. begin
  1912. { also generate the bodies for all previously done
  1913. specializations so that we might inline them }
  1914. generate_specialization_procs;
  1915. tcgprocinfo(current_procinfo).generate_code_tree;
  1916. end;
  1917. end;
  1918. { release procinfo }
  1919. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1920. internalerror(200304274);
  1921. current_module.procinfo:=current_procinfo.parent;
  1922. { For specialization we didn't record the last semicolon. Moving this parsing
  1923. into the parse_body routine is not done because of having better file position
  1924. information available }
  1925. if not current_procinfo.procdef.is_specialization and
  1926. (
  1927. not assigned(current_procinfo.procdef.struct) or
  1928. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  1929. or not (
  1930. assigned(current_procinfo.procdef.owner) and
  1931. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  1932. )
  1933. ) then
  1934. consume(_SEMICOLON);
  1935. if not isnestedproc then
  1936. { current_procinfo is checked for nil later on }
  1937. freeandnil(current_procinfo);
  1938. end;
  1939. procedure read_proc_body(pd:tprocdef);
  1940. var
  1941. old_module_procinfo : tobject;
  1942. old_current_procinfo : tprocinfo;
  1943. begin
  1944. old_current_procinfo:=current_procinfo;
  1945. old_module_procinfo:=current_module.procinfo;
  1946. current_procinfo:=nil;
  1947. current_module.procinfo:=nil;
  1948. read_proc_body(nil,pd);
  1949. current_procinfo:=old_current_procinfo;
  1950. current_module.procinfo:=old_module_procinfo;
  1951. end;
  1952. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef;isgeneric:boolean);
  1953. {
  1954. Parses the procedure directives, then parses the procedure body, then
  1955. generates the code for it
  1956. }
  1957. var
  1958. old_current_procinfo : tprocinfo;
  1959. old_current_structdef: tabstractrecorddef;
  1960. old_current_genericdef,
  1961. old_current_specializedef: tstoreddef;
  1962. pdflags : tpdflags;
  1963. pd,firstpd : tprocdef;
  1964. {$ifdef genericdef_for_nested}
  1965. def : tprocdef;
  1966. srsym : tsym;
  1967. i : longint;
  1968. {$endif genericdef_for_nested}
  1969. begin
  1970. { save old state }
  1971. old_current_procinfo:=current_procinfo;
  1972. old_current_structdef:=current_structdef;
  1973. old_current_genericdef:=current_genericdef;
  1974. old_current_specializedef:=current_specializedef;
  1975. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1976. to another procdef }
  1977. current_procinfo:=nil;
  1978. current_structdef:=nil;
  1979. current_genericdef:=nil;
  1980. current_specializedef:=nil;
  1981. if not assigned(usefwpd) then
  1982. { parse procedure declaration }
  1983. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  1984. else
  1985. pd:=usefwpd;
  1986. { set the default function options }
  1987. if parse_only then
  1988. begin
  1989. pd.forwarddef:=true;
  1990. { set also the interface flag, for better error message when the
  1991. implementation doesn't match this header }
  1992. pd.interfacedef:=true;
  1993. include(pd.procoptions,po_global);
  1994. pdflags:=[pd_interface];
  1995. end
  1996. else
  1997. begin
  1998. pdflags:=[pd_body];
  1999. if (not current_module.in_interface) then
  2000. include(pdflags,pd_implemen);
  2001. if (not current_module.is_unit) or
  2002. create_smartlink_library then
  2003. include(pd.procoptions,po_global);
  2004. pd.forwarddef:=false;
  2005. end;
  2006. if not assigned(usefwpd) then
  2007. begin
  2008. { parse the directives that may follow }
  2009. parse_proc_directives(pd,pdflags);
  2010. { hint directives, these can be separated by semicolons here,
  2011. that needs to be handled here with a loop (PFV) }
  2012. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2013. Consume(_SEMICOLON);
  2014. { Set calling convention }
  2015. if parse_only then
  2016. handle_calling_convention(pd,hcc_default_actions_intf)
  2017. else
  2018. handle_calling_convention(pd,hcc_default_actions_impl)
  2019. end;
  2020. { search for forward declarations }
  2021. if not proc_add_definition(pd) then
  2022. begin
  2023. { A method must be forward defined (in the object declaration) }
  2024. if assigned(pd.struct) and
  2025. (not assigned(old_current_structdef)) then
  2026. begin
  2027. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2028. tprocsym(pd.procsym).write_parameter_lists(pd);
  2029. end
  2030. else
  2031. begin
  2032. { Give a better error if there is a forward def in the interface and only
  2033. a single implementation }
  2034. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2035. if (not pd.forwarddef) and
  2036. (not pd.interfacedef) and
  2037. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2038. firstpd.forwarddef and
  2039. firstpd.interfacedef and
  2040. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2041. { don't give an error if it may be an overload }
  2042. not(m_fpc in current_settings.modeswitches) and
  2043. (not(po_overload in pd.procoptions) or
  2044. not(po_overload in firstpd.procoptions)) then
  2045. begin
  2046. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2047. tprocsym(pd.procsym).write_parameter_lists(pd);
  2048. end
  2049. else
  2050. begin
  2051. if pd.is_generic and not assigned(pd.struct) then
  2052. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2053. end;
  2054. end;
  2055. end;
  2056. { Set mangled name }
  2057. proc_set_mangledname(pd);
  2058. { inherit generic flags from parent routine }
  2059. if assigned(old_current_procinfo) and
  2060. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2061. begin
  2062. if df_generic in old_current_procinfo.procdef.defoptions then
  2063. include(pd.defoptions,df_generic);
  2064. if df_specialization in old_current_procinfo.procdef.defoptions then
  2065. begin
  2066. include(pd.defoptions,df_specialization);
  2067. { the procdefs encountered here are nested procdefs of which
  2068. their complete definition also resides inside the current token
  2069. stream, thus access to their genericdef is not required }
  2070. {$ifdef genericdef_for_nested}
  2071. { find the corresponding routine in the generic routine }
  2072. if not assigned(old_current_procinfo.procdef.genericdef) then
  2073. internalerror(2016121701);
  2074. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2075. if not assigned(srsym) or (srsym.typ<>procsym) then
  2076. internalerror(2016121702);
  2077. { in practice the generic procdef should be at the same index
  2078. as the index of the current procdef, but as there *might* be
  2079. differences between the amount of defs generated for the
  2080. specialization and the generic search for the def using
  2081. parameter comparison }
  2082. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2083. begin
  2084. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2085. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2086. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2087. begin
  2088. pd.genericdef:=def;
  2089. break;
  2090. end;
  2091. end;
  2092. if not assigned(pd.genericdef) then
  2093. internalerror(2016121703);
  2094. {$endif}
  2095. end;
  2096. end;
  2097. { compile procedure when a body is needed }
  2098. if (pd_body in pdflags) then
  2099. begin
  2100. read_proc_body(old_current_procinfo,pd);
  2101. end
  2102. else
  2103. begin
  2104. { Handle imports }
  2105. if (po_external in pd.procoptions) then
  2106. begin
  2107. import_external_proc(pd);
  2108. {$ifdef cpuhighleveltarget}
  2109. { it's hard to factor this out in a virtual method, because the
  2110. generic version (the one inside this ifdef) doesn't fit in
  2111. hlcgobj but in symcreat or here, while the other version
  2112. doesn't fit in symcreat (since it uses the code generator).
  2113. Maybe we need another class for this kind of code that could
  2114. either be symcreat- or hlcgobj-based
  2115. }
  2116. if (not pd.forwarddef) and
  2117. (pd.hasforward) and
  2118. (proc_get_importname(pd)<>'') then
  2119. call_through_new_name(pd,proc_get_importname(pd))
  2120. else
  2121. {$endif cpuhighleveltarget}
  2122. begin
  2123. create_hlcodegen;
  2124. hlcg.handle_external_proc(
  2125. current_asmdata.asmlists[al_procedures],
  2126. pd,
  2127. proc_get_importname(pd));
  2128. destroy_hlcodegen;
  2129. end
  2130. end;
  2131. end;
  2132. { always register public functions that are only declared in the
  2133. implementation section as they might be called using an external
  2134. declaration from another unit }
  2135. if (po_global in pd.procoptions) and
  2136. not pd.interfacedef and
  2137. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2138. begin
  2139. pd.register_def;
  2140. pd.procsym.register_sym;
  2141. end;
  2142. { make sure that references to forward-declared functions are not }
  2143. { treated as references to external symbols, needed for darwin. }
  2144. { make sure we don't change the binding of real external symbols }
  2145. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2146. begin
  2147. if (po_global in pd.procoptions) or
  2148. (cs_profile in current_settings.moduleswitches) then
  2149. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION,pd)
  2150. else
  2151. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION,pd);
  2152. end;
  2153. current_structdef:=old_current_structdef;
  2154. current_genericdef:=old_current_genericdef;
  2155. current_specializedef:=old_current_specializedef;
  2156. current_procinfo:=old_current_procinfo;
  2157. end;
  2158. procedure import_external_proc(pd:tprocdef);
  2159. var
  2160. name : string;
  2161. begin
  2162. if not (po_external in pd.procoptions) then
  2163. internalerror(2015121101);
  2164. { Import DLL specified? }
  2165. if assigned(pd.import_dll) then
  2166. begin
  2167. if assigned (pd.import_name) then
  2168. current_module.AddExternalImport(pd.import_dll^,
  2169. pd.import_name^,proc_get_importname(pd),
  2170. pd.import_nr,false,false)
  2171. else
  2172. current_module.AddExternalImport(pd.import_dll^,
  2173. proc_get_importname(pd),proc_get_importname(pd),
  2174. pd.import_nr,false,true);
  2175. end
  2176. else
  2177. begin
  2178. name:=proc_get_importname(pd);
  2179. { add import name to external list for DLL scanning }
  2180. if tf_has_dllscanner in target_info.flags then
  2181. current_module.dllscannerinputlist.Add(name,pd);
  2182. { needed for units that use functions in packages this way }
  2183. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2184. end;
  2185. end;
  2186. {****************************************************************************
  2187. DECLARATION PARSING
  2188. ****************************************************************************}
  2189. { search in symtablestack for not complete classes }
  2190. procedure check_forward_class(p:TObject;arg:pointer);
  2191. begin
  2192. if (tsym(p).typ=typesym) and
  2193. (ttypesym(p).typedef.typ=objectdef) and
  2194. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2195. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2196. end;
  2197. procedure read_declarations(islibrary : boolean);
  2198. var
  2199. hadgeneric : boolean;
  2200. procedure handle_unexpected_had_generic;
  2201. begin
  2202. if hadgeneric then
  2203. begin
  2204. Message(parser_e_procedure_or_function_expected);
  2205. hadgeneric:=false;
  2206. end;
  2207. end;
  2208. var
  2209. is_classdef:boolean;
  2210. begin
  2211. is_classdef:=false;
  2212. hadgeneric:=false;
  2213. repeat
  2214. if not assigned(current_procinfo) then
  2215. internalerror(200304251);
  2216. case token of
  2217. _LABEL:
  2218. begin
  2219. handle_unexpected_had_generic;
  2220. label_dec;
  2221. end;
  2222. _CONST:
  2223. begin
  2224. handle_unexpected_had_generic;
  2225. const_dec(hadgeneric);
  2226. end;
  2227. _TYPE:
  2228. begin
  2229. handle_unexpected_had_generic;
  2230. type_dec(hadgeneric);
  2231. end;
  2232. _VAR:
  2233. begin
  2234. handle_unexpected_had_generic;
  2235. var_dec(hadgeneric);
  2236. end;
  2237. _THREADVAR:
  2238. begin
  2239. handle_unexpected_had_generic;
  2240. threadvar_dec(hadgeneric);
  2241. end;
  2242. _CLASS:
  2243. begin
  2244. is_classdef:=false;
  2245. if try_to_consume(_CLASS) then
  2246. begin
  2247. { class modifier is only allowed for procedures, functions, }
  2248. { constructors, destructors }
  2249. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2250. not((token=_ID) and (idtoken=_OPERATOR)) then
  2251. Message(parser_e_procedure_or_function_expected);
  2252. if is_interface(current_structdef) then
  2253. Message(parser_e_no_static_method_in_interfaces)
  2254. else
  2255. { class methods are also allowed for Objective-C protocols }
  2256. is_classdef:=true;
  2257. end;
  2258. end;
  2259. _CONSTRUCTOR,
  2260. _DESTRUCTOR,
  2261. _FUNCTION,
  2262. _PROCEDURE,
  2263. _OPERATOR:
  2264. begin
  2265. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2266. begin
  2267. Message(parser_e_procedure_or_function_expected);
  2268. hadgeneric:=false;
  2269. end;
  2270. read_proc(is_classdef,nil,hadgeneric);
  2271. is_classdef:=false;
  2272. hadgeneric:=false;
  2273. end;
  2274. _EXPORTS:
  2275. begin
  2276. handle_unexpected_had_generic;
  2277. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2278. begin
  2279. Message(parser_e_syntax_error);
  2280. consume_all_until(_SEMICOLON);
  2281. end
  2282. else if islibrary or
  2283. (target_info.system in systems_unit_program_exports) then
  2284. read_exports
  2285. else
  2286. begin
  2287. Message(parser_w_unsupported_feature);
  2288. consume(_BEGIN);
  2289. end;
  2290. end;
  2291. _PROPERTY:
  2292. begin
  2293. handle_unexpected_had_generic;
  2294. if (m_fpc in current_settings.modeswitches) then
  2295. property_dec
  2296. else
  2297. break;
  2298. end;
  2299. else
  2300. begin
  2301. case idtoken of
  2302. _RESOURCESTRING:
  2303. begin
  2304. handle_unexpected_had_generic;
  2305. { m_class is needed, because the resourcestring
  2306. loading is in the ObjPas unit }
  2307. { if (m_class in current_settings.modeswitches) then}
  2308. resourcestring_dec(hadgeneric)
  2309. { else
  2310. break;}
  2311. end;
  2312. _OPERATOR:
  2313. begin
  2314. handle_unexpected_had_generic;
  2315. if is_classdef then
  2316. begin
  2317. read_proc(is_classdef,nil,false);
  2318. is_classdef:=false;
  2319. end
  2320. else
  2321. break;
  2322. end;
  2323. _GENERIC:
  2324. begin
  2325. handle_unexpected_had_generic;
  2326. if not (m_delphi in current_settings.modeswitches) then
  2327. begin
  2328. consume(_ID);
  2329. hadgeneric:=true;
  2330. end
  2331. else
  2332. break;
  2333. end
  2334. else
  2335. break;
  2336. end;
  2337. end;
  2338. end;
  2339. until false;
  2340. { add implementations for synthetic method declarations added by
  2341. the compiler (not for unit/program init functions, their localst
  2342. is the staticst -> would duplicate the work done in pmodules) }
  2343. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2344. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2345. { check for incomplete class definitions, this is only required
  2346. for fpc modes }
  2347. if (m_fpc in current_settings.modeswitches) then
  2348. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2349. end;
  2350. procedure read_interface_declarations;
  2351. var
  2352. hadgeneric : boolean;
  2353. procedure handle_unexpected_had_generic;
  2354. begin
  2355. if hadgeneric then
  2356. begin
  2357. Message(parser_e_procedure_or_function_expected);
  2358. hadgeneric:=false;
  2359. end;
  2360. end;
  2361. begin
  2362. hadgeneric:=false;
  2363. repeat
  2364. case token of
  2365. _CONST :
  2366. begin
  2367. handle_unexpected_had_generic;
  2368. const_dec(hadgeneric);
  2369. end;
  2370. _TYPE :
  2371. begin
  2372. handle_unexpected_had_generic;
  2373. type_dec(hadgeneric);
  2374. end;
  2375. _VAR :
  2376. begin
  2377. handle_unexpected_had_generic;
  2378. var_dec(hadgeneric);
  2379. end;
  2380. _THREADVAR :
  2381. begin
  2382. handle_unexpected_had_generic;
  2383. threadvar_dec(hadgeneric);
  2384. end;
  2385. _FUNCTION,
  2386. _PROCEDURE,
  2387. _OPERATOR :
  2388. begin
  2389. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2390. begin
  2391. message(parser_e_procedure_or_function_expected);
  2392. hadgeneric:=false;
  2393. end;
  2394. read_proc(false,nil,hadgeneric);
  2395. hadgeneric:=false;
  2396. end;
  2397. else
  2398. begin
  2399. case idtoken of
  2400. _RESOURCESTRING :
  2401. begin
  2402. handle_unexpected_had_generic;
  2403. resourcestring_dec(hadgeneric);
  2404. end;
  2405. _PROPERTY:
  2406. begin
  2407. handle_unexpected_had_generic;
  2408. if (m_fpc in current_settings.modeswitches) then
  2409. property_dec
  2410. else
  2411. break;
  2412. end;
  2413. _GENERIC:
  2414. begin
  2415. handle_unexpected_had_generic;
  2416. if not (m_delphi in current_settings.modeswitches) then
  2417. begin
  2418. hadgeneric:=true;
  2419. consume(_ID);
  2420. end
  2421. else
  2422. break;
  2423. end
  2424. else
  2425. break;
  2426. end;
  2427. end;
  2428. end;
  2429. until false;
  2430. { check for incomplete class definitions, this is only required
  2431. for fpc modes }
  2432. if (m_fpc in current_settings.modeswitches) then
  2433. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2434. end;
  2435. end.