psub.pas 108 KB

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