psub.pas 108 KB

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