2
0

psub.pas 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  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. cclasses,globals,
  22. node,nbas,
  23. symdef,procinfo,optdfa;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  28. procedure add_entry_exit_code;
  29. procedure setup_tempgen;
  30. public
  31. { code for the subroutine as tree }
  32. code : tnode;
  33. { positions in the tree for init/final }
  34. entry_asmnode,
  35. loadpara_asmnode,
  36. exitlabel_asmnode,
  37. stackcheck_asmnode,
  38. init_asmnode,
  39. final_asmnode : tasmnode;
  40. dfabuilder : TDFABuilder;
  41. destructor destroy;override;
  42. procedure printproc(pass:string);
  43. procedure generate_code;
  44. procedure generate_code_tree;
  45. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  46. procedure resetprocdef;
  47. procedure add_to_symtablestack;
  48. procedure remove_from_symtablestack;
  49. procedure parse_body;
  50. function has_assembler_child : boolean;
  51. end;
  52. procedure printnode_reset;
  53. { reads the declaration blocks }
  54. procedure read_declarations(islibrary : boolean);
  55. { reads declarations in the interface part of a unit }
  56. procedure read_interface_declarations;
  57. procedure generate_specialization_procs;
  58. implementation
  59. uses
  60. sysutils,
  61. { common }
  62. cutils,
  63. { global }
  64. globtype,tokens,verbose,comphook,constexp,
  65. systems,
  66. { aasm }
  67. cpuinfo,cpubase,aasmbase,aasmtai,aasmdata,
  68. { symtable }
  69. symconst,symbase,symsym,symtype,symtable,defutil,
  70. paramgr,
  71. ppu,fmodule,
  72. { pass 1 }
  73. nutils,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  74. pass_1,
  75. {$ifdef state_tracking}
  76. nstate,
  77. {$endif state_tracking}
  78. { pass 2 }
  79. {$ifndef NOPASS2}
  80. pass_2,
  81. {$endif}
  82. { parser }
  83. scanner,import,gendef,
  84. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,
  85. { codegen }
  86. tgobj,cgbase,cgobj,cgcpu,dbgbase,
  87. ncgutil,regvars,
  88. optbase,
  89. opttail,
  90. optcse,optloop,
  91. optutils
  92. {$if defined(arm) or defined(powerpc) or defined(powerpc64) or defined(avr)}
  93. ,aasmcpu
  94. {$endif arm}
  95. {$ifndef NOOPT}
  96. {$ifdef i386}
  97. ,aopt386
  98. {$else i386}
  99. ,aopt
  100. {$endif i386}
  101. {$endif}
  102. ;
  103. {****************************************************************************
  104. PROCEDURE/FUNCTION BODY PARSING
  105. ****************************************************************************}
  106. procedure initializedefaultvars(p:TObject;arg:pointer);
  107. var
  108. b : tblocknode;
  109. begin
  110. if tsym(p).typ<>localvarsym then
  111. exit;
  112. with tabstractnormalvarsym(p) do
  113. begin
  114. if vo_is_default_var in varoptions then
  115. begin
  116. b:=tblocknode(arg);
  117. b.left:=cstatementnode.create(
  118. ccallnode.createintern('fpc_zeromem',
  119. ccallparanode.create(
  120. cordconstnode.create(vardef.size,ptruinttype,false),
  121. ccallparanode.create(
  122. caddrnode.create_internal(
  123. cloadnode.create(tsym(p),tsym(p).owner)),
  124. nil
  125. )
  126. )
  127. ),
  128. b.left);
  129. end;
  130. end;
  131. end;
  132. procedure initializevars(p:TObject;arg:pointer);
  133. var
  134. b : tblocknode;
  135. begin
  136. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  137. exit;
  138. with tabstractnormalvarsym(p) do
  139. begin
  140. if assigned(defaultconstsym) then
  141. begin
  142. b:=tblocknode(arg);
  143. b.left:=cstatementnode.create(
  144. cassignmentnode.create(
  145. cloadnode.create(tsym(p),tsym(p).owner),
  146. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  147. b.left);
  148. end
  149. else
  150. initializedefaultvars(p,arg);
  151. end;
  152. end;
  153. procedure check_finalize_paras(p:TObject;arg:pointer);
  154. begin
  155. if (tsym(p).typ=paravarsym) and
  156. tparavarsym(p).needs_finalization then
  157. include(current_procinfo.flags,pi_needs_implicit_finally);
  158. end;
  159. procedure check_finalize_locals(p:TObject;arg:pointer);
  160. begin
  161. { include the result: it needs to be finalized in case an exception }
  162. { occurs }
  163. if (tsym(p).typ=localvarsym) and
  164. (tlocalvarsym(p).refs>0) and
  165. is_managed_type(tlocalvarsym(p).vardef) then
  166. include(current_procinfo.flags,pi_needs_implicit_finally);
  167. end;
  168. function block(islibrary : boolean) : tnode;
  169. var
  170. oldfilepos: tfileposinfo;
  171. begin
  172. { parse const,types and vars }
  173. read_declarations(islibrary);
  174. { do we have an assembler block without the po_assembler?
  175. we should allow this for Delphi compatibility (PFV) }
  176. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  177. include(current_procinfo.procdef.procoptions,po_assembler);
  178. { Handle assembler block different }
  179. if (po_assembler in current_procinfo.procdef.procoptions) then
  180. begin
  181. block:=assembler_block;
  182. exit;
  183. end;
  184. {Unit initialization?.}
  185. if (
  186. assigned(current_procinfo.procdef.localst) and
  187. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  188. (current_module.is_unit or islibrary)
  189. ) then
  190. begin
  191. if (token=_END) then
  192. begin
  193. consume(_END);
  194. { We need at least a node, else the entry/exit code is not
  195. generated and thus no PASCALMAIN symbol which we need (PFV) }
  196. if islibrary then
  197. block:=cnothingnode.create
  198. else
  199. block:=nil;
  200. end
  201. else
  202. begin
  203. if token=_INITIALIZATION then
  204. begin
  205. { The library init code is already called and does not
  206. need to be in the initfinal table (PFV) }
  207. block:=statement_block(_INITIALIZATION);
  208. end
  209. else if token=_FINALIZATION then
  210. begin
  211. { when a unit has only a finalization section, we can come to this
  212. point when we try to read the nonh existing initalization section
  213. so we've to check if we are really try to parse the finalization }
  214. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  215. block:=statement_block(_FINALIZATION)
  216. else
  217. block:=nil;
  218. end
  219. else
  220. block:=statement_block(_BEGIN);
  221. end;
  222. end
  223. else
  224. begin
  225. block:=statement_block(_BEGIN);
  226. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  227. begin
  228. { initialization of local variables with their initial
  229. values: part of function entry }
  230. oldfilepos:=current_filepos;
  231. current_filepos:=current_procinfo.entrypos;
  232. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  233. current_filepos:=oldfilepos;
  234. end
  235. else
  236. if current_procinfo.procdef.localst.symtabletype=staticsymtable then
  237. begin
  238. { for program and unit initialization code we also need to
  239. initialize the local variables used of Default() }
  240. oldfilepos:=current_filepos;
  241. current_filepos:=current_procinfo.entrypos;
  242. current_procinfo.procdef.localst.SymList.ForEachCall(@initializedefaultvars,block);
  243. current_filepos:=oldfilepos;
  244. end;
  245. end;
  246. end;
  247. {****************************************************************************
  248. PROCEDURE/FUNCTION COMPILING
  249. ****************************************************************************}
  250. procedure printnode_reset;
  251. begin
  252. assign(printnodefile,treelogfilename);
  253. {$push}{$I-}
  254. rewrite(printnodefile);
  255. {$pop}
  256. if ioresult<>0 then
  257. begin
  258. Comment(V_Error,'Error creating '+treelogfilename);
  259. exit;
  260. end;
  261. close(printnodefile);
  262. end;
  263. procedure add_label_init(p:TObject;arg:pointer);
  264. begin
  265. if tstoredsym(p).typ=labelsym then
  266. begin
  267. addstatement(tstatementnode(arg^),
  268. cifnode.create(caddnode.create(equaln,
  269. ccallnode.createintern('fpc_setjmp',
  270. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  271. cordconstnode.create(1,sinttype,true))
  272. ,cgotonode.create(tlabelsym(p)),nil)
  273. );
  274. end;
  275. end;
  276. function generate_bodyentry_block:tnode;
  277. var
  278. srsym : tsym;
  279. para : tcallparanode;
  280. newstatement : tstatementnode;
  281. begin
  282. result:=internalstatements(newstatement);
  283. if assigned(current_structdef) then
  284. begin
  285. { a constructor needs a help procedure }
  286. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  287. begin
  288. if is_class(current_structdef) then
  289. begin
  290. srsym:=search_struct_member(current_structdef,'NEWINSTANCE');
  291. if assigned(srsym) and
  292. (srsym.typ=procsym) then
  293. begin
  294. { if vmt>1 then newinstance }
  295. addstatement(newstatement,cifnode.create(
  296. caddnode.create(gtn,
  297. ctypeconvnode.create_internal(
  298. load_vmt_pointer_node,
  299. voidpointertype),
  300. cpointerconstnode.create(1,voidpointertype)),
  301. cassignmentnode.create(
  302. ctypeconvnode.create_internal(
  303. load_self_pointer_node,
  304. voidpointertype),
  305. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  306. nil));
  307. end
  308. else
  309. internalerror(200305108);
  310. end
  311. else
  312. if is_object(current_structdef) then
  313. begin
  314. { parameter 3 : vmt_offset }
  315. { parameter 2 : address of pointer to vmt,
  316. this is required to allow setting the vmt to -1 to indicate
  317. that memory was allocated }
  318. { parameter 1 : self pointer }
  319. para:=ccallparanode.create(
  320. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  321. ccallparanode.create(
  322. ctypeconvnode.create_internal(
  323. load_vmt_pointer_node,
  324. voidpointertype),
  325. ccallparanode.create(
  326. ctypeconvnode.create_internal(
  327. load_self_pointer_node,
  328. voidpointertype),
  329. nil)));
  330. addstatement(newstatement,cassignmentnode.create(
  331. ctypeconvnode.create_internal(
  332. load_self_pointer_node,
  333. voidpointertype),
  334. ccallnode.createintern('fpc_help_constructor',para)));
  335. end
  336. else
  337. if not is_record(current_structdef) then
  338. internalerror(200305103);
  339. { if self=nil then exit
  340. calling fail instead of exit is useless because
  341. there is nothing to dispose (PFV) }
  342. if is_class_or_object(current_structdef) then
  343. addstatement(newstatement,cifnode.create(
  344. caddnode.create(equaln,
  345. load_self_pointer_node,
  346. cnilnode.create),
  347. cexitnode.create(nil),
  348. nil));
  349. end;
  350. { maybe call BeforeDestruction for classes }
  351. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  352. is_class(current_structdef) then
  353. begin
  354. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  355. if assigned(srsym) and
  356. (srsym.typ=procsym) then
  357. begin
  358. { if vmt>0 then beforedestruction }
  359. addstatement(newstatement,cifnode.create(
  360. caddnode.create(gtn,
  361. ctypeconvnode.create_internal(
  362. load_vmt_pointer_node,ptrsinttype),
  363. ctypeconvnode.create_internal(
  364. cnilnode.create,ptrsinttype)),
  365. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  366. nil));
  367. end
  368. else
  369. internalerror(200305104);
  370. end;
  371. end;
  372. if m_non_local_goto in current_settings.modeswitches then
  373. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  374. end;
  375. function generate_bodyexit_block:tnode;
  376. var
  377. srsym : tsym;
  378. para : tcallparanode;
  379. newstatement : tstatementnode;
  380. oldlocalswitches: tlocalswitches;
  381. begin
  382. result:=internalstatements(newstatement);
  383. if assigned(current_structdef) then
  384. begin
  385. { Don't test self and the vmt here. The reason is that }
  386. { a constructor already checks whether these are valid }
  387. { before. Further, in case of TThread the thread may }
  388. { free the class instance right after AfterConstruction }
  389. { has been called, so it may no longer be valid (JM) }
  390. oldlocalswitches:=current_settings.localswitches;
  391. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  392. { a destructor needs a help procedure }
  393. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  394. begin
  395. if is_class(current_structdef) then
  396. begin
  397. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  398. if assigned(srsym) and
  399. (srsym.typ=procsym) then
  400. begin
  401. { if self<>0 and vmt<>0 then freeinstance }
  402. addstatement(newstatement,cifnode.create(
  403. caddnode.create(andn,
  404. caddnode.create(unequaln,
  405. load_self_pointer_node,
  406. cnilnode.create),
  407. caddnode.create(unequaln,
  408. ctypeconvnode.create(
  409. load_vmt_pointer_node,
  410. voidpointertype),
  411. cpointerconstnode.create(0,voidpointertype))),
  412. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  413. nil));
  414. end
  415. else
  416. internalerror(200305108);
  417. end
  418. else
  419. if is_object(current_structdef) then
  420. begin
  421. { finalize object data, but only if not in inherited call }
  422. if is_managed_type(current_structdef) then
  423. begin
  424. addstatement(newstatement,cifnode.create(
  425. caddnode.create(unequaln,
  426. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  427. cnilnode.create),
  428. finalize_data_node(load_self_node),
  429. nil));
  430. end;
  431. { parameter 3 : vmt_offset }
  432. { parameter 2 : pointer to vmt }
  433. { parameter 1 : self pointer }
  434. para:=ccallparanode.create(
  435. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  436. ccallparanode.create(
  437. ctypeconvnode.create_internal(
  438. load_vmt_pointer_node,
  439. voidpointertype),
  440. ccallparanode.create(
  441. ctypeconvnode.create_internal(
  442. load_self_pointer_node,
  443. voidpointertype),
  444. nil)));
  445. addstatement(newstatement,
  446. ccallnode.createintern('fpc_help_destructor',para));
  447. end
  448. else
  449. internalerror(200305105);
  450. end;
  451. current_settings.localswitches:=oldlocalswitches;
  452. end;
  453. end;
  454. function generate_except_block:tnode;
  455. var
  456. newstatement : tstatementnode;
  457. begin
  458. generate_except_block:=internalstatements(newstatement);
  459. { a constructor needs call destructor (if available) when it
  460. is not inherited }
  461. if not assigned(current_structdef) or
  462. (current_procinfo.procdef.proctypeoption<>potype_constructor) then
  463. begin
  464. { no constructor }
  465. { must be the return value finalized before reraising the exception? }
  466. if (not is_void(current_procinfo.procdef.returndef)) and
  467. is_managed_type(current_procinfo.procdef.returndef) and
  468. (not paramanager.ret_in_param(current_procinfo.procdef.returndef, current_procinfo.procdef.proccalloption)) and
  469. (not is_class(current_procinfo.procdef.returndef)) then
  470. addstatement(newstatement,finalize_data_node(load_result_node));
  471. end;
  472. end;
  473. {****************************************************************************
  474. TCGProcInfo
  475. ****************************************************************************}
  476. destructor tcgprocinfo.destroy;
  477. begin
  478. if assigned(code) then
  479. code.free;
  480. inherited destroy;
  481. end;
  482. procedure tcgprocinfo.printproc(pass:string);
  483. begin
  484. assign(printnodefile,treelogfilename);
  485. {$push}{$I-}
  486. append(printnodefile);
  487. if ioresult<>0 then
  488. rewrite(printnodefile);
  489. {$pop}
  490. if ioresult<>0 then
  491. begin
  492. Comment(V_Error,'Error creating '+treelogfilename);
  493. exit;
  494. end;
  495. writeln(printnodefile);
  496. writeln(printnodefile,'*******************************************************************************');
  497. writeln(printnodefile, pass);
  498. writeln(printnodefile,procdef.fullprocname(false));
  499. writeln(printnodefile,'*******************************************************************************');
  500. printnode(printnodefile,code);
  501. close(printnodefile);
  502. end;
  503. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  504. var
  505. oldlocalswitches: tlocalswitches;
  506. srsym: tsym;
  507. afterconstructionblock,
  508. exceptblock,
  509. newblock: tblocknode;
  510. newstatement: tstatementnode;
  511. pd: tprocdef;
  512. begin
  513. if assigned(procdef.struct) and
  514. (procdef.proctypeoption=potype_constructor) then
  515. begin
  516. { Don't test self and the vmt here. See generate_bodyexit_block }
  517. { why (JM) }
  518. oldlocalswitches:=current_settings.localswitches;
  519. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  520. { call AfterConstruction for classes }
  521. if is_class(procdef.struct) then
  522. begin
  523. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  524. if assigned(srsym) and
  525. (srsym.typ=procsym) then
  526. begin
  527. current_filepos:=exitpos;
  528. afterconstructionblock:=internalstatements(newstatement);
  529. { first execute all constructor code. If no exception
  530. occurred then we will execute afterconstruction,
  531. otherwise we won't (the exception will jump over us) }
  532. addstatement(newstatement,tocode);
  533. { if implicit finally node wasn't created, then exit label and
  534. finalization code must be handled here and placed before
  535. afterconstruction }
  536. if not ((pi_needs_implicit_finally in flags) and
  537. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  538. begin
  539. include(tocode.flags,nf_block_with_exit);
  540. addstatement(newstatement,final_asmnode);
  541. end;
  542. { Self can be nil when fail is called }
  543. { if self<>nil and vmt<>nil then afterconstruction }
  544. addstatement(newstatement,cifnode.create(
  545. caddnode.create(andn,
  546. caddnode.create(unequaln,
  547. load_self_node,
  548. cnilnode.create),
  549. caddnode.create(unequaln,
  550. load_vmt_pointer_node,
  551. cnilnode.create)),
  552. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  553. nil));
  554. tocode:=afterconstructionblock;
  555. end
  556. else
  557. internalerror(200305106);
  558. end;
  559. if withexceptblock and (procdef.struct.typ=objectdef) then
  560. begin
  561. { Generate the implicit "fail" code for a constructor (destroy
  562. in case an exception happened) }
  563. pd:=tobjectdef(procdef.struct).find_destructor;
  564. { this will always be the case for classes, since tobject has
  565. a destructor }
  566. if assigned(pd) then
  567. begin
  568. current_filepos:=exitpos;
  569. exceptblock:=internalstatements(newstatement);
  570. { first free the instance if non-nil }
  571. { if vmt<>0 then call destructor }
  572. addstatement(newstatement,cifnode.create(
  573. caddnode.create(unequaln,
  574. load_vmt_pointer_node,
  575. cnilnode.create),
  576. { cnf_create_failed -> don't call BeforeDestruction }
  577. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed]),
  578. nil));
  579. { then re-raise the exception }
  580. addstatement(newstatement,craisenode.create(nil,nil,nil));
  581. current_filepos:=entrypos;
  582. newblock:=internalstatements(newstatement);
  583. { try
  584. tocode
  585. except
  586. exceptblock
  587. end
  588. }
  589. addstatement(newstatement,ctryexceptnode.create(
  590. tocode,
  591. nil,
  592. exceptblock));
  593. tocode:=newblock;
  594. end;
  595. end;
  596. current_settings.localswitches:=oldlocalswitches;
  597. end;
  598. end;
  599. procedure tcgprocinfo.add_entry_exit_code;
  600. var
  601. finalcode,
  602. bodyentrycode,
  603. bodyexitcode,
  604. exceptcode,
  605. wrappedbody: tnode;
  606. newblock : tblocknode;
  607. codestatement,
  608. newstatement : tstatementnode;
  609. oldfilepos : tfileposinfo;
  610. is_constructor: boolean;
  611. begin
  612. is_constructor:=assigned(procdef.struct) and
  613. (procdef.proctypeoption=potype_constructor);
  614. oldfilepos:=current_filepos;
  615. { Generate code/locations used at start of proc }
  616. current_filepos:=entrypos;
  617. entry_asmnode:=casmnode.create_get_position;
  618. loadpara_asmnode:=casmnode.create_get_position;
  619. stackcheck_asmnode:=casmnode.create_get_position;
  620. init_asmnode:=casmnode.create_get_position;
  621. bodyentrycode:=generate_bodyentry_block;
  622. { Generate code/locations used at end of proc }
  623. current_filepos:=exitpos;
  624. exitlabel_asmnode:=casmnode.create_get_position;
  625. final_asmnode:=casmnode.create_get_position;
  626. bodyexitcode:=generate_bodyexit_block;
  627. { Generate procedure by combining init+body+final,
  628. depending on the implicit finally we need to add
  629. an try...finally...end wrapper }
  630. newblock:=internalstatements(newstatement);
  631. { initialization is common for all cases }
  632. addstatement(newstatement,loadpara_asmnode);
  633. addstatement(newstatement,stackcheck_asmnode);
  634. addstatement(newstatement,entry_asmnode);
  635. addstatement(newstatement,init_asmnode);
  636. addstatement(newstatement,bodyentrycode);
  637. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  638. (pi_needs_implicit_finally in flags) and
  639. { but it's useless in init/final code of units }
  640. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  641. not(po_assembler in procdef.procoptions) then
  642. begin
  643. { Generate special exception block only needed when
  644. implicit finaly is used }
  645. current_filepos:=exitpos;
  646. exceptcode:=generate_except_block;
  647. { Generate code that will be in the try...finally }
  648. finalcode:=internalstatements(codestatement);
  649. addstatement(codestatement,final_asmnode);
  650. current_filepos:=entrypos;
  651. wrappedbody:=ctryfinallynode.create_implicit(
  652. code,
  653. finalcode,
  654. exceptcode);
  655. { afterconstruction must be called after final_asmnode, because it
  656. has to execute after the temps have been finalised in case of a
  657. refcounted class (afterconstruction decreases the refcount
  658. without freeing the instance if the count becomes nil, while
  659. the finalising of the temps can free the instance) }
  660. maybe_add_constructor_wrapper(wrappedbody,true);
  661. addstatement(newstatement,wrappedbody);
  662. addstatement(newstatement,exitlabel_asmnode);
  663. addstatement(newstatement,bodyexitcode);
  664. { set flag the implicit finally has been generated }
  665. include(flags,pi_has_implicit_finally);
  666. end
  667. else
  668. begin
  669. { constructors need destroy-on-exception code even if they don't
  670. have managed variables/temps }
  671. maybe_add_constructor_wrapper(code,
  672. cs_implicit_exceptions in current_settings.moduleswitches);
  673. addstatement(newstatement,code);
  674. addstatement(newstatement,exitlabel_asmnode);
  675. addstatement(newstatement,bodyexitcode);
  676. if not is_constructor then
  677. addstatement(newstatement,final_asmnode);
  678. end;
  679. do_firstpass(tnode(newblock));
  680. code:=newblock;
  681. current_filepos:=oldfilepos;
  682. end;
  683. procedure clearrefs(p:TObject;arg:pointer);
  684. begin
  685. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  686. if tabstractvarsym(p).refs>1 then
  687. tabstractvarsym(p).refs:=1;
  688. end;
  689. procedure translate_registers(p:TObject;list:pointer);
  690. begin
  691. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  692. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  693. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  694. begin
  695. if not(cs_no_regalloc in current_settings.globalswitches) then
  696. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  697. if cs_asm_source in current_settings.globalswitches then
  698. TAsmList(list).concat(Tai_comment.Create(strpnew('Var '+tabstractnormalvarsym(p).realname+' located in register '+
  699. std_regname(tabstractnormalvarsym(p).localloc.register))))
  700. end;
  701. end;
  702. procedure tcgprocinfo.setup_tempgen;
  703. begin
  704. tg:=ttgobj.create;
  705. {$if defined(x86) or defined(arm)}
  706. { try to strip the stack frame }
  707. { set the framepointer to esp if:
  708. - no assembler directive, those are handled in assembler_block
  709. in pstatment.pas (for cases not caught by the Delphi
  710. exception below)
  711. - no exceptions are used
  712. - no pushes are used/esp modifications, could be:
  713. * outgoing parameters on the stack
  714. * incoming parameters on the stack
  715. * open arrays
  716. - no inline assembler
  717. or
  718. - Delphi mode
  719. - assembler directive
  720. - no pushes are used/esp modifications, could be:
  721. * outgoing parameters on the stack
  722. * incoming parameters on the stack
  723. * open arrays
  724. - no local variables
  725. }
  726. if ((po_assembler in procdef.procoptions) and
  727. (m_delphi in current_settings.modeswitches) and
  728. { localst at main_program_level is a staticsymtable }
  729. (procdef.localst.symtablelevel<>main_program_level) and
  730. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  731. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  732. not(cs_generate_stackframes in current_settings.localswitches) and
  733. not(po_assembler in procdef.procoptions) and
  734. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  735. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  736. pi_needs_stackframe])=[])
  737. )
  738. then
  739. begin
  740. { we need the parameter info here to determine if the procedure gets
  741. parameters on the stack
  742. calling generate_parameter_info doesn't hurt but it costs time
  743. (necessary to init para_stack_size)
  744. }
  745. generate_parameter_info;
  746. if not(procdef.stack_tainting_parameter(calleeside)) and
  747. not(has_assembler_child) and (para_stack_size=0) then
  748. begin
  749. { Only need to set the framepointer }
  750. framepointer:=NR_STACK_POINTER_REG;
  751. tg.direction:=1;
  752. end;
  753. end;
  754. {$endif}
  755. { set the start offset to the start of the temp area in the stack }
  756. set_first_temp_offset;
  757. end;
  758. function tcgprocinfo.has_assembler_child : boolean;
  759. var
  760. hp : tprocinfo;
  761. begin
  762. result:=false;
  763. hp:=get_first_nestedproc;
  764. while assigned(hp) do
  765. begin
  766. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  767. begin
  768. result:=true;
  769. exit;
  770. end;
  771. hp:=tprocinfo(hp.next);
  772. end;
  773. end;
  774. procedure tcgprocinfo.generate_code_tree;
  775. var
  776. hpi : tcgprocinfo;
  777. begin
  778. { generate code for this procedure }
  779. generate_code;
  780. { process nested procedures }
  781. hpi:=tcgprocinfo(get_first_nestedproc);
  782. while assigned(hpi) do
  783. begin
  784. hpi.generate_code_tree;
  785. hpi:=tcgprocinfo(hpi.next);
  786. end;
  787. resetprocdef;
  788. end;
  789. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  790. var
  791. saved_cg: tcg;
  792. begin
  793. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  794. InternalError(201201141);
  795. { flush code generated this far }
  796. aktproccode.concatlist(current_asmdata.CurrAsmList);
  797. { save the codegen }
  798. saved_cg:=cg;
  799. cg:=nil;
  800. nestedpi.generate_code;
  801. { prevents generating code the second time when processing nested procedures }
  802. nestedpi.resetprocdef;
  803. cg:=saved_cg;
  804. add_reg_instruction_hook:[email protected]_reg_instruction;
  805. end;
  806. procedure tcgprocinfo.generate_code;
  807. var
  808. old_current_procinfo : tprocinfo;
  809. oldmaxfpuregisters : longint;
  810. oldfilepos : tfileposinfo;
  811. old_current_structdef : tabstractrecorddef;
  812. templist : TAsmList;
  813. headertai : tai;
  814. i : integer;
  815. varsym : tabstractnormalvarsym;
  816. {RedoDFA : boolean;}
  817. begin
  818. { the initialization procedure can be empty, then we
  819. don't need to generate anything. When it was an empty
  820. procedure there would be at least a blocknode }
  821. if not assigned(code) then
  822. exit;
  823. { We need valid code }
  824. if Errorcount<>0 then
  825. exit;
  826. { No code can be generated for generic template }
  827. if (df_generic in procdef.defoptions) then
  828. internalerror(200511152);
  829. { For regular procedures the RA and Tempgen shall not be available yet,
  830. but exception filters reuse Tempgen of parent }
  831. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  832. internalerror(200309201);
  833. old_current_procinfo:=current_procinfo;
  834. oldfilepos:=current_filepos;
  835. old_current_structdef:=current_structdef;
  836. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  837. current_procinfo:=self;
  838. current_filepos:=entrypos;
  839. current_structdef:=procdef.struct;
  840. templist:=TAsmList.create;
  841. { add parast/localst to symtablestack }
  842. add_to_symtablestack;
  843. { clear register count }
  844. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  845. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  846. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  847. if (procdef.localst.symtablelevel=main_program_level) and
  848. (not current_module.is_unit) then
  849. include(flags,pi_do_call);
  850. { set implicit_finally flag when there are locals/paras to be finalized }
  851. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  852. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  853. {$if defined(x86) or defined(arm)}
  854. { set implicit_finally flag for if procedure is safecall }
  855. if (tf_safecall_exceptions in target_info.flags) and
  856. (procdef.proccalloption=pocall_safecall) then
  857. include(flags, pi_needs_implicit_finally);
  858. {$endif}
  859. { firstpass everything }
  860. flowcontrol:=[];
  861. do_firstpass(code);
  862. {$ifdef i386}
  863. procdef.fpu_used:=node_resources_fpu(code);
  864. if procdef.fpu_used>0 then
  865. include(flags,pi_uses_fpu);
  866. {$endif i386}
  867. { Print the node to tree.log }
  868. if paraprintnodetree=1 then
  869. printproc( 'after the firstpass');
  870. { do this before adding the entry code else the tail recursion recognition won't work,
  871. if this causes troubles, it must be if'ed
  872. }
  873. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  874. (pi_is_recursive in flags) then
  875. do_opttail(code,procdef);
  876. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  877. { creating dfa is not always possible }
  878. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  879. pi_needs_implicit_finally,pi_has_implicit_finally])=[]) then
  880. begin
  881. dfabuilder:=TDFABuilder.Create;
  882. dfabuilder.createdfainfo(code);
  883. { when life info is available, we can give more sophisticated warning about unintialized
  884. variables }
  885. { iterate through life info of the first node }
  886. for i:=0 to dfabuilder.nodemap.count-1 do
  887. begin
  888. if DFASetIn(code.optinfo^.life,i) then
  889. case tnode(dfabuilder.nodemap[i]).nodetype of
  890. loadn:
  891. begin
  892. varsym:=tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry);
  893. { Give warning/note for living locals }
  894. if assigned(varsym.owner) and
  895. not(vo_is_external in varsym.varoptions) then
  896. begin
  897. if (vo_is_funcret in varsym.varoptions) then
  898. CGMessage(sym_w_function_result_uninitialized)
  899. else
  900. begin
  901. if (varsym.owner=procdef.localst) and not (vo_is_typed_const in varsym.varoptions) then
  902. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  903. end;
  904. end;
  905. end;
  906. end;
  907. end;
  908. include(flags,pi_dfaavailable);
  909. end;
  910. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  911. { our induction variable strength reduction doesn't like
  912. for loops with more than one entry }
  913. and not(pi_has_label in flags) then
  914. begin
  915. {RedoDFA:=}OptimizeInductionVariables(code);
  916. end;
  917. if cs_opt_nodecse in current_settings.optimizerswitches then
  918. do_optcse(code);
  919. { add implicit entry and exit code }
  920. add_entry_exit_code;
  921. { only do secondpass if there are no errors }
  922. if (ErrorCount=0) then
  923. begin
  924. create_codegen;
  925. if (procdef.proctypeoption<>potype_exceptfilter) then
  926. setup_tempgen;
  927. { Create register allocator, must come after framepointer is known }
  928. cg.init_register_allocators;
  929. generate_parameter_info;
  930. { allocate got register if needed }
  931. allocate_got_register(aktproccode);
  932. { Allocate space in temp/registers for parast and localst }
  933. current_filepos:=entrypos;
  934. gen_alloc_symtable(aktproccode,procdef.parast);
  935. gen_alloc_symtable(aktproccode,procdef.localst);
  936. { Store temp offset for information about 'real' temps }
  937. tempstart:=tg.lasttemp;
  938. { Generate code to load register parameters in temps and insert local
  939. copies for values parameters. This must be done before the code for the
  940. body is generated because the localloc is updated.
  941. Note: The generated code will be inserted after the code generation of
  942. the body is finished, because only then the position is known }
  943. {$ifdef oldregvars}
  944. assign_regvars(code);
  945. {$endif oldreg}
  946. current_filepos:=entrypos;
  947. gen_load_para_value(templist);
  948. { caller paraloc info is also necessary in the stackframe_entry
  949. code of the ppc (and possibly other processors) }
  950. procdef.init_paraloc_info(callerside);
  951. { generate code for the node tree }
  952. do_secondpass(code);
  953. aktproccode.concatlist(current_asmdata.CurrAsmList);
  954. { The position of the loadpara_asmnode is now known }
  955. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  956. { first generate entry and initialize code with the correct
  957. position and switches }
  958. current_filepos:=entrypos;
  959. current_settings.localswitches:=entryswitches;
  960. cg.set_regalloc_live_range_direction(rad_backwards);
  961. gen_entry_code(templist);
  962. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  963. gen_initialize_code(templist);
  964. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  965. { now generate finalize and exit code with the correct position
  966. and switches }
  967. current_filepos:=exitpos;
  968. current_settings.localswitches:=exitswitches;
  969. cg.set_regalloc_live_range_direction(rad_forward);
  970. if assigned(finalize_procinfo) then
  971. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  972. else
  973. begin
  974. gen_finalize_code(templist);
  975. { the finalcode must be concated if there was no position available,
  976. using insertlistafter will result in an insert at the start
  977. when currentai=nil }
  978. if assigned(final_asmnode) and assigned(final_asmnode.currenttai) then
  979. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  980. else
  981. aktproccode.concatlist(templist);
  982. end;
  983. { insert exit label at the correct position }
  984. cg.a_label(templist,CurrExitLabel);
  985. if assigned(exitlabel_asmnode.currenttai) then
  986. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  987. else
  988. aktproccode.concatlist(templist);
  989. { exit code }
  990. gen_exit_code(templist);
  991. aktproccode.concatlist(templist);
  992. {$ifdef OLDREGVARS}
  993. { note: this must be done only after as much code as possible has }
  994. { been generated. The result is that when you ungetregister() a }
  995. { regvar, it will actually free the regvar (and alse free the }
  996. { the regvars at the same time). Doing this too early will }
  997. { confuse the register allocator, as the regvars will still be }
  998. { used. It should be done before loading the result regs (so }
  999. { they don't conflict with the regvars) and before }
  1000. { gen_entry_code (that one has to be able to allocate the }
  1001. { regvars again) (JM) }
  1002. free_regvars(aktproccode);
  1003. {$endif OLDREGVARS}
  1004. { generate symbol and save end of header position }
  1005. current_filepos:=entrypos;
  1006. gen_proc_symbol(templist);
  1007. headertai:=tai(templist.last);
  1008. { insert symbol }
  1009. aktproccode.insertlist(templist);
  1010. { Free space in temp/registers for parast and localst, must be
  1011. done after gen_entry_code }
  1012. current_filepos:=exitpos;
  1013. { make sure the got/pic register doesn't get freed in the }
  1014. { middle of a loop }
  1015. if (cs_create_pic in current_settings.moduleswitches) and
  1016. (pi_needs_got in flags) and
  1017. (got<>NR_NO) then
  1018. cg.a_reg_sync(aktproccode,got);
  1019. gen_free_symtable(aktproccode,procdef.localst);
  1020. gen_free_symtable(aktproccode,procdef.parast);
  1021. { add code that will load the return value, this is not done
  1022. for assembler routines when they didn't reference the result
  1023. variable }
  1024. gen_load_return_value(templist);
  1025. aktproccode.concatlist(templist);
  1026. { Already reserve all registers for stack checking code and
  1027. generate the call to the helper function }
  1028. if not(tf_no_generic_stackcheck in target_info.flags) and
  1029. (cs_check_stack in entryswitches) and
  1030. not(po_assembler in procdef.procoptions) and
  1031. (procdef.proctypeoption<>potype_proginit) then
  1032. begin
  1033. current_filepos:=entrypos;
  1034. gen_stack_check_call(templist);
  1035. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1036. end;
  1037. { this code (got loading) comes before everything which has }
  1038. { already been generated, so reset the info about already }
  1039. { backwards extended registers (so their live range can be }
  1040. { extended backwards even further if needed) }
  1041. { This code must be }
  1042. { a) generated after do_secondpass has been called }
  1043. { (because pi_needs_got may be set there) }
  1044. { b) generated before register allocation, because the }
  1045. { got/pic register can be a virtual one }
  1046. { c) inserted before the entry code, because the entry }
  1047. { code may need global symbols such as init rtti }
  1048. { d) inserted after the stackframe allocation, because }
  1049. { this register may have to be spilled }
  1050. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1051. current_filepos:=entrypos;
  1052. { load got if necessary }
  1053. cg.g_maybe_got_init(templist);
  1054. aktproccode.insertlistafter(headertai,templist);
  1055. { re-enable if more code at the end is ever generated here
  1056. cg.set_regalloc_live_range_direction(rad_forward);
  1057. }
  1058. {$ifndef NoOpt}
  1059. {$ifndef i386}
  1060. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1061. { do not optimize pure assembler procedures }
  1062. not(pi_is_assembler in flags) then
  1063. preregallocschedule(aktproccode);
  1064. {$endif i386}
  1065. {$endif NoOpt}
  1066. { The procedure body is finished, we can now
  1067. allocate the registers }
  1068. cg.do_register_allocation(aktproccode,headertai);
  1069. { translate imag. register to their real counter parts
  1070. this is necessary for debuginfo and verbose assembler output
  1071. when SSA will be implented, this will be more complicated because we've to
  1072. maintain location lists }
  1073. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1074. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1075. if (cs_create_pic in current_settings.moduleswitches) and
  1076. (pi_needs_got in flags) and
  1077. not(cs_no_regalloc in current_settings.globalswitches) and
  1078. (got<>NR_NO) then
  1079. cg.translate_register(got);
  1080. { Add save and restore of used registers }
  1081. current_filepos:=entrypos;
  1082. gen_save_used_regs(templist);
  1083. { Remember the last instruction of register saving block
  1084. (may be =nil for e.g. assembler procedures) }
  1085. endprologue_ai:=templist.last;
  1086. aktproccode.insertlistafter(headertai,templist);
  1087. current_filepos:=exitpos;
  1088. gen_restore_used_regs(aktproccode);
  1089. { We know the size of the stack, now we can generate the
  1090. parameter that is passed to the stack checking code }
  1091. if not(tf_no_generic_stackcheck in target_info.flags) and
  1092. (cs_check_stack in entryswitches) and
  1093. not(po_assembler in procdef.procoptions) and
  1094. (procdef.proctypeoption<>potype_proginit) then
  1095. begin
  1096. current_filepos:=entrypos;
  1097. gen_stack_check_size_para(templist);
  1098. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1099. end;
  1100. { Add entry code (stack allocation) after header }
  1101. current_filepos:=entrypos;
  1102. gen_proc_entry_code(templist);
  1103. aktproccode.insertlistafter(headertai,templist);
  1104. {$if defined(x86) or defined(arm)}
  1105. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1106. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1107. (tf_safecall_exceptions in target_info.flags) and
  1108. (procdef.proccalloption=pocall_safecall) then
  1109. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1110. {$endif}
  1111. { Add exit code at the end }
  1112. current_filepos:=exitpos;
  1113. gen_proc_exit_code(templist);
  1114. aktproccode.concatlist(templist);
  1115. { check if the implicit finally has been generated. The flag
  1116. should already be set in pass1 }
  1117. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1118. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1119. (pi_needs_implicit_finally in flags) and
  1120. not(po_assembler in procdef.procoptions) and
  1121. not(pi_has_implicit_finally in flags) then
  1122. internalerror(200405231);
  1123. {$ifndef NoOpt}
  1124. if not(cs_no_regalloc in current_settings.globalswitches) then
  1125. begin
  1126. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1127. { do not optimize pure assembler procedures }
  1128. not(pi_is_assembler in flags) then
  1129. optimize(aktproccode);
  1130. {$ifndef i386}
  1131. { schedule after assembler optimization, it could have brought up
  1132. new schedule possibilities }
  1133. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1134. { do not optimize pure assembler procedures }
  1135. not(pi_is_assembler in flags) then
  1136. preregallocschedule(aktproccode);
  1137. {$endif i386}
  1138. end;
  1139. {$endif NoOpt}
  1140. {$ifdef ARM}
  1141. { because of the limited constant size of the arm, all data access is done pc relative }
  1142. finalizearmcode(aktproccode,aktlocaldata);
  1143. {$endif ARM}
  1144. {$ifdef AVR}
  1145. { because of the limited branch distance of cond. branches, they must be replaced
  1146. somtimes by normal jmps and an inverse branch }
  1147. finalizeavrcode(aktproccode);
  1148. {$endif AVR}
  1149. { Add end symbol and debug info }
  1150. { this must be done after the pcrelativedata is appended else the distance calculation of
  1151. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1152. so it should be inserted before the end symbol (FK)
  1153. }
  1154. current_filepos:=exitpos;
  1155. gen_proc_symbol_end(templist);
  1156. aktproccode.concatlist(templist);
  1157. {$if defined(POWERPC) or defined(POWERPC64)}
  1158. fixup_jmps(aktproccode);
  1159. {$endif}
  1160. { insert line debuginfo }
  1161. if (cs_debuginfo in current_settings.moduleswitches) or
  1162. (cs_use_lineinfo in current_settings.globalswitches) then
  1163. current_debuginfo.insertlineinfo(aktproccode);
  1164. { add the procedure to the al_procedures }
  1165. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  1166. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  1167. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  1168. { save local data (casetable) also in the same file }
  1169. if assigned(aktlocaldata) and
  1170. (not aktlocaldata.empty) then
  1171. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  1172. { only now we can remove the temps }
  1173. if (procdef.proctypeoption<>potype_exceptfilter) then
  1174. begin
  1175. tg.resettempgen;
  1176. tg.free;
  1177. tg:=nil;
  1178. end;
  1179. { stop tempgen and ra }
  1180. cg.done_register_allocators;
  1181. destroy_codegen;
  1182. end;
  1183. dfabuilder.free;
  1184. { restore symtablestack }
  1185. remove_from_symtablestack;
  1186. { restore }
  1187. templist.free;
  1188. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1189. current_filepos:=oldfilepos;
  1190. current_structdef:=old_current_structdef;
  1191. current_procinfo:=old_current_procinfo;
  1192. end;
  1193. procedure tcgprocinfo.add_to_symtablestack;
  1194. begin
  1195. { insert symtables for the class, but only if it is no nested function }
  1196. if assigned(procdef.struct) and
  1197. not(assigned(parent) and
  1198. assigned(parent.procdef) and
  1199. assigned(parent.procdef.struct)) then
  1200. push_nested_hierarchy(procdef.struct);
  1201. { insert parasymtable in symtablestack when parsing
  1202. a function }
  1203. if procdef.parast.symtablelevel>=normal_function_level then
  1204. symtablestack.push(procdef.parast);
  1205. { insert localsymtable, except for the main procedure
  1206. (in that case the localst is the unit's static symtable,
  1207. which is already on the stack) }
  1208. if procdef.localst.symtablelevel>=normal_function_level then
  1209. symtablestack.push(procdef.localst);
  1210. end;
  1211. procedure tcgprocinfo.remove_from_symtablestack;
  1212. begin
  1213. { remove localsymtable }
  1214. if procdef.localst.symtablelevel>=normal_function_level then
  1215. symtablestack.pop(procdef.localst);
  1216. { remove parasymtable }
  1217. if procdef.parast.symtablelevel>=normal_function_level then
  1218. symtablestack.pop(procdef.parast);
  1219. { remove symtables for the class, but only if it is no nested function }
  1220. if assigned(procdef.struct) and
  1221. not(assigned(parent) and
  1222. assigned(parent.procdef) and
  1223. assigned(parent.procdef.struct)) then
  1224. pop_nested_hierarchy(procdef.struct);
  1225. end;
  1226. procedure tcgprocinfo.resetprocdef;
  1227. begin
  1228. { remove code tree, if not inline procedure }
  1229. if assigned(code) then
  1230. begin
  1231. { the inline procedure has already got a copy of the tree
  1232. stored in procdef.inlininginfo }
  1233. code.free;
  1234. code:=nil;
  1235. end;
  1236. end;
  1237. function checknodeinlining(procdef: tprocdef): boolean;
  1238. var
  1239. i : integer;
  1240. currpara : tparavarsym;
  1241. begin
  1242. result := false;
  1243. if (pi_has_assembler_block in current_procinfo.flags) then
  1244. begin
  1245. Message1(parser_h_not_supported_for_inline,'assembler');
  1246. Message(parser_h_inlining_disabled);
  1247. exit;
  1248. end;
  1249. for i:=0 to procdef.paras.count-1 do
  1250. begin
  1251. currpara:=tparavarsym(procdef.paras[i]);
  1252. case currpara.vardef.typ of
  1253. formaldef :
  1254. begin
  1255. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  1256. begin
  1257. Message1(parser_h_not_supported_for_inline,'formal parameter');
  1258. Message(parser_h_inlining_disabled);
  1259. exit;
  1260. end;
  1261. end;
  1262. arraydef :
  1263. begin
  1264. if is_array_of_const(currpara.vardef) or
  1265. is_variant_array(currpara.vardef) then
  1266. begin
  1267. Message1(parser_h_not_supported_for_inline,'array of const');
  1268. Message(parser_h_inlining_disabled);
  1269. exit;
  1270. end;
  1271. { open arrays might need re-basing of the index, i.e. if you pass
  1272. an array[1..10] as open array, you have to add 1 to all index operations
  1273. if you directly inline it }
  1274. if is_open_array(currpara.vardef) then
  1275. begin
  1276. Message1(parser_h_not_supported_for_inline,'open array');
  1277. Message(parser_h_inlining_disabled);
  1278. exit;
  1279. end;
  1280. end;
  1281. end;
  1282. end;
  1283. result:=true;
  1284. end;
  1285. procedure tcgprocinfo.parse_body;
  1286. var
  1287. old_current_procinfo : tprocinfo;
  1288. old_block_type : tblock_type;
  1289. st : TSymtable;
  1290. old_current_structdef: tabstractrecorddef;
  1291. old_current_genericdef,
  1292. old_current_specializedef: tstoreddef;
  1293. old_parse_generic: boolean;
  1294. begin
  1295. old_current_procinfo:=current_procinfo;
  1296. old_block_type:=block_type;
  1297. old_current_structdef:=current_structdef;
  1298. old_current_genericdef:=current_genericdef;
  1299. old_current_specializedef:=current_specializedef;
  1300. old_parse_generic:=parse_generic;
  1301. current_procinfo:=self;
  1302. current_structdef:=procdef.struct;
  1303. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1304. begin
  1305. current_genericdef:=current_structdef;
  1306. parse_generic:=true;
  1307. end;
  1308. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1309. current_specializedef:=current_structdef;
  1310. { calculate the lexical level }
  1311. if procdef.parast.symtablelevel>maxnesting then
  1312. Message(parser_e_too_much_lexlevel);
  1313. block_type:=bt_body;
  1314. {$ifdef state_tracking}
  1315. { aktstate:=Tstate_storage.create;}
  1316. {$endif state_tracking}
  1317. { allocate the symbol for this procedure }
  1318. alloc_proc_symbol(procdef);
  1319. { add parast/localst to symtablestack }
  1320. add_to_symtablestack;
  1321. { save entry info }
  1322. entrypos:=current_filepos;
  1323. entryswitches:=current_settings.localswitches;
  1324. if (df_generic in procdef.defoptions) then
  1325. begin
  1326. { start token recorder for generic template }
  1327. procdef.initgeneric;
  1328. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1329. end;
  1330. { parse the code ... }
  1331. code:=block(current_module.islibrary);
  1332. if (df_generic in procdef.defoptions) then
  1333. begin
  1334. { stop token recorder for generic template }
  1335. current_scanner.stoprecordtokens;
  1336. { Give an error for accesses in the static symtable that aren't visible
  1337. outside the current unit }
  1338. st:=procdef.owner;
  1339. while (st.symtabletype=ObjectSymtable) do
  1340. st:=st.defowner.owner;
  1341. if (pi_uses_static_symtable in flags) and
  1342. (st.symtabletype<>staticsymtable) then
  1343. Comment(V_Error,'Global Generic template references static symtable');
  1344. end;
  1345. { save exit info }
  1346. exitswitches:=current_settings.localswitches;
  1347. exitpos:=last_endtoken_filepos;
  1348. { the procedure is now defined }
  1349. procdef.forwarddef:=false;
  1350. if assigned(code) then
  1351. begin
  1352. { get a better entry point }
  1353. entrypos:=code.fileinfo;
  1354. { Finish type checking pass }
  1355. do_typecheckpass(code);
  1356. end;
  1357. { Check for unused labels, forwards, symbols for procedures. Static
  1358. symtable is checked in pmodules.
  1359. The check must be done after the typecheckpass }
  1360. if (Errorcount=0) and
  1361. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1362. begin
  1363. { check if forwards are resolved }
  1364. tstoredsymtable(procdef.localst).check_forwards;
  1365. { check if all labels are used }
  1366. tstoredsymtable(procdef.localst).checklabels;
  1367. { check for unused symbols, but only if there is no asm block }
  1368. if not(pi_has_assembler_block in flags) then
  1369. begin
  1370. tstoredsymtable(procdef.localst).allsymbolsused;
  1371. tstoredsymtable(procdef.parast).allsymbolsused;
  1372. end;
  1373. end;
  1374. if (po_inline in procdef.procoptions) then
  1375. begin
  1376. { Can we inline this procedure? }
  1377. if checknodeinlining(procdef) then
  1378. begin
  1379. new(procdef.inlininginfo);
  1380. include(procdef.procoptions,po_has_inlininginfo);
  1381. procdef.inlininginfo^.code:=code.getcopy;
  1382. procdef.inlininginfo^.flags:=flags;
  1383. { The blocknode needs to set an exit label }
  1384. if procdef.inlininginfo^.code.nodetype=blockn then
  1385. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1386. end;
  1387. end;
  1388. { Print the node to tree.log }
  1389. if paraprintnodetree=1 then
  1390. printproc( 'after parsing');
  1391. { ... remove symbol tables }
  1392. remove_from_symtablestack;
  1393. {$ifdef state_tracking}
  1394. { aktstate.destroy;}
  1395. {$endif state_tracking}
  1396. current_structdef:=old_current_structdef;
  1397. current_genericdef:=old_current_genericdef;
  1398. current_specializedef:=old_current_specializedef;
  1399. current_procinfo:=old_current_procinfo;
  1400. parse_generic:=old_parse_generic;
  1401. { Restore old state }
  1402. block_type:=old_block_type;
  1403. end;
  1404. {****************************************************************************
  1405. PROCEDURE/FUNCTION PARSING
  1406. ****************************************************************************}
  1407. procedure check_init_paras(p:TObject;arg:pointer);
  1408. begin
  1409. if tsym(p).typ<>paravarsym then
  1410. exit;
  1411. with tparavarsym(p) do
  1412. if is_managed_type(vardef) and
  1413. (varspez in [vs_value,vs_out]) then
  1414. include(current_procinfo.flags,pi_do_call);
  1415. end;
  1416. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1417. {
  1418. Parses the procedure directives, then parses the procedure body, then
  1419. generates the code for it
  1420. }
  1421. var
  1422. oldfailtokenmode : tmodeswitch;
  1423. isnestedproc : boolean;
  1424. begin
  1425. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1426. { create a new procedure }
  1427. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1428. current_module.procinfo:=current_procinfo;
  1429. current_procinfo.procdef:=pd;
  1430. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1431. { Insert mangledname }
  1432. pd.aliasnames.insert(pd.mangledname);
  1433. { Handle Export of this procedure }
  1434. if (po_exports in pd.procoptions) and
  1435. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1436. begin
  1437. pd.aliasnames.insert(pd.procsym.realname);
  1438. if cs_link_deffile in current_settings.globalswitches then
  1439. deffile.AddExport(pd.mangledname);
  1440. end;
  1441. { Insert result variables in the localst }
  1442. insert_funcret_local(pd);
  1443. { check if there are para's which require initing -> set }
  1444. { pi_do_call (if not yet set) }
  1445. if not(pi_do_call in current_procinfo.flags) then
  1446. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1447. { set _FAIL as keyword if constructor }
  1448. if (pd.proctypeoption=potype_constructor) then
  1449. begin
  1450. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1451. tokeninfo^[_FAIL].keyword:=m_all;
  1452. end;
  1453. tcgprocinfo(current_procinfo).parse_body;
  1454. { We can't support inlining for procedures that have nested
  1455. procedures because the nested procedures use a fixed offset
  1456. for accessing locals in the parent procedure (PFV) }
  1457. if current_procinfo.has_nestedprocs then
  1458. begin
  1459. if (df_generic in current_procinfo.procdef.defoptions) then
  1460. Comment(V_Error,'Generic methods cannot have nested procedures')
  1461. else
  1462. if (po_inline in current_procinfo.procdef.procoptions) then
  1463. begin
  1464. Message1(parser_h_not_supported_for_inline,'nested procedures');
  1465. Message(parser_h_inlining_disabled);
  1466. exclude(current_procinfo.procdef.procoptions,po_inline);
  1467. end;
  1468. end;
  1469. { When it's a nested procedure then defer the code generation,
  1470. when back at normal function level then generate the code
  1471. for all defered nested procedures and the current procedure }
  1472. if not isnestedproc then
  1473. begin
  1474. if not(df_generic in current_procinfo.procdef.defoptions) then
  1475. tcgprocinfo(current_procinfo).generate_code_tree;
  1476. end;
  1477. { reset _FAIL as _SELF normal }
  1478. if (pd.proctypeoption=potype_constructor) then
  1479. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1480. { release procinfo }
  1481. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1482. internalerror(200304274);
  1483. current_module.procinfo:=current_procinfo.parent;
  1484. { For specialization we didn't record the last semicolon. Moving this parsing
  1485. into the parse_body routine is not done because of having better file position
  1486. information available }
  1487. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1488. consume(_SEMICOLON);
  1489. if not isnestedproc then
  1490. { current_procinfo is checked for nil later on }
  1491. freeandnil(current_procinfo);
  1492. end;
  1493. procedure read_proc(isclassmethod:boolean);
  1494. {
  1495. Parses the procedure directives, then parses the procedure body, then
  1496. generates the code for it
  1497. }
  1498. var
  1499. old_current_procinfo : tprocinfo;
  1500. old_current_structdef: tabstractrecorddef;
  1501. old_current_genericdef,
  1502. old_current_specializedef: tstoreddef;
  1503. pdflags : tpdflags;
  1504. pd,firstpd : tprocdef;
  1505. s : string;
  1506. begin
  1507. { save old state }
  1508. old_current_procinfo:=current_procinfo;
  1509. old_current_structdef:=current_structdef;
  1510. old_current_genericdef:=current_genericdef;
  1511. old_current_specializedef:=current_specializedef;
  1512. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1513. to another procdef }
  1514. current_procinfo:=nil;
  1515. current_structdef:=nil;
  1516. current_genericdef:=nil;
  1517. current_specializedef:=nil;
  1518. { parse procedure declaration }
  1519. pd:=parse_proc_dec(isclassmethod,old_current_structdef);
  1520. { set the default function options }
  1521. if parse_only then
  1522. begin
  1523. pd.forwarddef:=true;
  1524. { set also the interface flag, for better error message when the
  1525. implementation doesn't much this header }
  1526. pd.interfacedef:=true;
  1527. include(pd.procoptions,po_global);
  1528. pdflags:=[pd_interface];
  1529. end
  1530. else
  1531. begin
  1532. pdflags:=[pd_body];
  1533. if (not current_module.in_interface) then
  1534. include(pdflags,pd_implemen);
  1535. if (not current_module.is_unit) or
  1536. create_smartlink or
  1537. {
  1538. taking addresses of static procedures goes wrong
  1539. if they aren't global when pic is used (FK)
  1540. }
  1541. (cs_create_pic in current_settings.moduleswitches) then
  1542. include(pd.procoptions,po_global);
  1543. pd.forwarddef:=false;
  1544. end;
  1545. { parse the directives that may follow }
  1546. parse_proc_directives(pd,pdflags);
  1547. { hint directives, these can be separated by semicolons here,
  1548. that needs to be handled here with a loop (PFV) }
  1549. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1550. Consume(_SEMICOLON);
  1551. { Set calling convention }
  1552. handle_calling_convention(pd);
  1553. { search for forward declarations }
  1554. if not proc_add_definition(pd) then
  1555. begin
  1556. { A method must be forward defined (in the object declaration) }
  1557. if assigned(pd.struct) and
  1558. (not assigned(old_current_structdef)) then
  1559. begin
  1560. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1561. tprocsym(pd.procsym).write_parameter_lists(pd);
  1562. end
  1563. else
  1564. begin
  1565. { Give a better error if there is a forward def in the interface and only
  1566. a single implementation }
  1567. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1568. if (not pd.forwarddef) and
  1569. (not pd.interfacedef) and
  1570. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1571. firstpd.forwarddef and
  1572. firstpd.interfacedef and
  1573. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1574. { don't give an error if it may be an overload }
  1575. not(m_fpc in current_settings.modeswitches) and
  1576. (not(po_overload in pd.procoptions) or
  1577. not(po_overload in firstpd.procoptions)) then
  1578. begin
  1579. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1580. tprocsym(pd.procsym).write_parameter_lists(pd);
  1581. end;
  1582. end;
  1583. end;
  1584. { Set mangled name }
  1585. proc_set_mangledname(pd);
  1586. { compile procedure when a body is needed }
  1587. if (pd_body in pdflags) then
  1588. begin
  1589. read_proc_body(old_current_procinfo,pd);
  1590. end
  1591. else
  1592. begin
  1593. { Handle imports }
  1594. if (po_external in pd.procoptions) then
  1595. begin
  1596. { External declared in implementation, and there was already a
  1597. forward (or interface) declaration then we need to generate
  1598. a stub that calls the external routine }
  1599. if (not pd.forwarddef) and
  1600. (pd.hasforward)
  1601. { it is unclear to me what's the use of the following condition,
  1602. so commented out, see also issue #18371 (FK)
  1603. and
  1604. not(
  1605. assigned(pd.import_dll) and
  1606. (target_info.system in [system_i386_wdosx,
  1607. system_arm_wince,system_i386_wince])
  1608. ) } then
  1609. begin
  1610. s:=proc_get_importname(pd);
  1611. if s<>'' then
  1612. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1613. end;
  1614. { Import DLL specified? }
  1615. if assigned(pd.import_dll) then
  1616. begin
  1617. if assigned (pd.import_name) then
  1618. current_module.AddExternalImport(pd.import_dll^,
  1619. pd.import_name^,proc_get_importname(pd),
  1620. pd.import_nr,false,false)
  1621. else
  1622. current_module.AddExternalImport(pd.import_dll^,
  1623. proc_get_importname(pd),proc_get_importname(pd),
  1624. pd.import_nr,false,true);
  1625. end
  1626. else
  1627. begin
  1628. { add import name to external list for DLL scanning }
  1629. if tf_has_dllscanner in target_info.flags then
  1630. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1631. end;
  1632. end;
  1633. end;
  1634. { make sure that references to forward-declared functions are not }
  1635. { treated as references to external symbols, needed for darwin. }
  1636. { make sure we don't change the binding of real external symbols }
  1637. if not(po_external in pd.procoptions) then
  1638. begin
  1639. if (po_global in pd.procoptions) or
  1640. (cs_profile in current_settings.moduleswitches) then
  1641. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1642. else
  1643. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1644. end;
  1645. current_structdef:=old_current_structdef;
  1646. current_genericdef:=old_current_genericdef;
  1647. current_specializedef:=old_current_specializedef;
  1648. current_procinfo:=old_current_procinfo;
  1649. end;
  1650. {****************************************************************************
  1651. DECLARATION PARSING
  1652. ****************************************************************************}
  1653. { search in symtablestack for not complete classes }
  1654. procedure check_forward_class(p:TObject;arg:pointer);
  1655. begin
  1656. if (tsym(p).typ=typesym) and
  1657. (ttypesym(p).typedef.typ=objectdef) and
  1658. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1659. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1660. end;
  1661. procedure read_declarations(islibrary : boolean);
  1662. var
  1663. is_classdef:boolean;
  1664. begin
  1665. is_classdef:=false;
  1666. repeat
  1667. if not assigned(current_procinfo) then
  1668. internalerror(200304251);
  1669. case token of
  1670. _LABEL:
  1671. label_dec;
  1672. _CONST:
  1673. const_dec;
  1674. _TYPE:
  1675. type_dec;
  1676. _VAR:
  1677. var_dec;
  1678. _THREADVAR:
  1679. threadvar_dec;
  1680. _CLASS:
  1681. begin
  1682. is_classdef:=false;
  1683. if try_to_consume(_CLASS) then
  1684. begin
  1685. { class modifier is only allowed for procedures, functions, }
  1686. { constructors, destructors }
  1687. if not(token in [_FUNCTION,_PROCEDURE,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1688. not((token=_ID) and (idtoken=_OPERATOR)) then
  1689. Message(parser_e_procedure_or_function_expected);
  1690. if is_interface(current_structdef) then
  1691. Message(parser_e_no_static_method_in_interfaces)
  1692. else
  1693. { class methods are also allowed for Objective-C protocols }
  1694. is_classdef:=true;
  1695. end;
  1696. end;
  1697. _CONSTRUCTOR,
  1698. _DESTRUCTOR,
  1699. _FUNCTION,
  1700. _PROCEDURE,
  1701. _OPERATOR:
  1702. begin
  1703. read_proc(is_classdef);
  1704. is_classdef:=false;
  1705. end;
  1706. _EXPORTS:
  1707. begin
  1708. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1709. begin
  1710. Message(parser_e_syntax_error);
  1711. consume_all_until(_SEMICOLON);
  1712. end
  1713. else if islibrary or
  1714. (target_info.system in systems_unit_program_exports) then
  1715. read_exports
  1716. else
  1717. begin
  1718. Message(parser_w_unsupported_feature);
  1719. consume(_BEGIN);
  1720. end;
  1721. end
  1722. else
  1723. begin
  1724. case idtoken of
  1725. _RESOURCESTRING:
  1726. begin
  1727. { m_class is needed, because the resourcestring
  1728. loading is in the ObjPas unit }
  1729. { if (m_class in current_settings.modeswitches) then}
  1730. resourcestring_dec
  1731. { else
  1732. break;}
  1733. end;
  1734. _OPERATOR:
  1735. begin
  1736. if is_classdef then
  1737. begin
  1738. read_proc(is_classdef);
  1739. is_classdef:=false;
  1740. end
  1741. else
  1742. break;
  1743. end;
  1744. _PROPERTY:
  1745. begin
  1746. if (m_fpc in current_settings.modeswitches) then
  1747. property_dec
  1748. else
  1749. break;
  1750. end;
  1751. else
  1752. break;
  1753. end;
  1754. end;
  1755. end;
  1756. until false;
  1757. { check for incomplete class definitions, this is only required
  1758. for fpc modes }
  1759. if (m_fpc in current_settings.modeswitches) then
  1760. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1761. end;
  1762. procedure read_interface_declarations;
  1763. begin
  1764. repeat
  1765. case token of
  1766. _CONST :
  1767. const_dec;
  1768. _TYPE :
  1769. type_dec;
  1770. _VAR :
  1771. var_dec;
  1772. _THREADVAR :
  1773. threadvar_dec;
  1774. _FUNCTION,
  1775. _PROCEDURE,
  1776. _OPERATOR :
  1777. read_proc(false);
  1778. else
  1779. begin
  1780. case idtoken of
  1781. _RESOURCESTRING :
  1782. resourcestring_dec;
  1783. _PROPERTY:
  1784. begin
  1785. if (m_fpc in current_settings.modeswitches) then
  1786. property_dec
  1787. else
  1788. break;
  1789. end;
  1790. else
  1791. break;
  1792. end;
  1793. end;
  1794. end;
  1795. until false;
  1796. { check for incomplete class definitions, this is only required
  1797. for fpc modes }
  1798. if (m_fpc in current_settings.modeswitches) then
  1799. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1800. end;
  1801. {****************************************************************************
  1802. SPECIALIZATION BODY GENERATION
  1803. ****************************************************************************}
  1804. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1805. var
  1806. oldcurrent_filepos : tfileposinfo;
  1807. specobj : tabstractrecorddef;
  1808. state : tspecializationstate;
  1809. procedure process_abstractrecorddef(def:tabstractrecorddef);
  1810. var
  1811. i : longint;
  1812. hp : tdef;
  1813. hmodule : tmodule;
  1814. begin
  1815. hmodule:=find_module_from_symtable(def.genericdef.owner);
  1816. if hmodule=nil then
  1817. internalerror(201202041);
  1818. for i:=0 to def.symtable.DefList.Count-1 do
  1819. begin
  1820. hp:=tdef(def.symtable.DefList[i]);
  1821. if hp.typ=procdef then
  1822. begin
  1823. { only generate the code if we need a body }
  1824. if assigned(tprocdef(hp).struct) and not tprocdef(hp).forwarddef then
  1825. continue;
  1826. if assigned(tprocdef(hp).genericdef) and
  1827. (tprocdef(hp).genericdef.typ=procdef) and
  1828. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1829. begin
  1830. oldcurrent_filepos:=current_filepos;
  1831. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1832. { use the index the module got from the current compilation process }
  1833. current_filepos.moduleindex:=hmodule.unit_index;
  1834. current_tokenpos:=current_filepos;
  1835. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf,
  1836. tprocdef(tprocdef(hp).genericdef).change_endian);
  1837. read_proc_body(nil,tprocdef(hp));
  1838. current_filepos:=oldcurrent_filepos;
  1839. end
  1840. else
  1841. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  1842. end
  1843. else
  1844. if hp.typ in [objectdef,recorddef] then
  1845. { generate code for subtypes as well }
  1846. process_abstractrecorddef(tabstractrecorddef(hp));
  1847. end;
  1848. end;
  1849. begin
  1850. if not((tsym(p).typ=typesym) and
  1851. (ttypesym(p).typedef.typesym=tsym(p)) and
  1852. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  1853. (df_specialization in ttypesym(p).typedef.defoptions)
  1854. ) then
  1855. exit;
  1856. { Setup symtablestack a definition time }
  1857. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  1858. if not (is_class_or_object(specobj) or is_record(specobj)) then
  1859. exit;
  1860. specialization_init(specobj.genericdef,state);
  1861. { procedure definitions for classes or objects }
  1862. process_abstractrecorddef(specobj);
  1863. specialization_done(state);
  1864. end;
  1865. procedure generate_specialization_procs;
  1866. begin
  1867. if assigned(current_module.globalsymtable) then
  1868. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1869. if assigned(current_module.localsymtable) then
  1870. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1871. end;
  1872. end.