optvirt.pas 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. {
  2. Copyright (c) 2008 by Jonas Maebe
  3. Virtual methods optimizations (devirtualization)
  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 optvirt;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. globtype,
  22. cclasses,
  23. symtype,symdef,
  24. wpobase;
  25. type
  26. { node in an inheritance tree, contains a link to the parent type (if any) and to all
  27. child types
  28. }
  29. tinheritancetreenode = class
  30. private
  31. fdef: tobjectdef;
  32. fparent: tinheritancetreenode;
  33. fchilds: tfpobjectlist;
  34. finstantiated: boolean;
  35. function getchild(index: longint): tinheritancetreenode;
  36. public
  37. constructor create(_parent: tinheritancetreenode; _def: tobjectdef; _instantiated: boolean);
  38. { destroys both this node and all of its siblings }
  39. destructor destroy; override;
  40. function childcount: longint;
  41. function haschilds: boolean;
  42. property childs[index: longint]: tinheritancetreenode read getchild;
  43. property parent: tinheritancetreenode read fparent;
  44. property def: tobjectdef read fdef;
  45. property instantiated: boolean read finstantiated write finstantiated;
  46. { if def is not yet a child of this node, add it. In all cases, return node containing
  47. this def (either new or existing one
  48. }
  49. function maybeaddchild(_def: tobjectdef; _instantiated: boolean): tinheritancetreenode;
  50. end;
  51. tinheritancetreecallback = procedure(node: tinheritancetreenode; arg: pointer) of object;
  52. tinheritancetree = class
  53. private
  54. { just a regular node with parent = nil }
  55. froots: tinheritancetreenode;
  56. classrefdefs: tfpobjectlist;
  57. procedure foreachnodefromroot(root: tinheritancetreenode; proctocall: tinheritancetreecallback; arg: pointer);
  58. function registerinstantiatedobjectdefrecursive(def: tobjectdef; instantiated: boolean): tinheritancetreenode;
  59. procedure markvmethods(node: tinheritancetreenode; p: pointer);
  60. procedure printobjectvmtinfo(node: tinheritancetreenode; arg: pointer);
  61. public
  62. constructor create;
  63. destructor destroy; override;
  64. { adds an objectdef (the def itself, and all of its parents that do not yet exist) to
  65. the tree, and returns the leaf node
  66. }
  67. procedure registerinstantiatedobjdef(def: tdef);
  68. procedure registerinstantiatedclassrefdef(def: tdef);
  69. procedure checkforclassrefinheritance(def: tdef);
  70. procedure foreachnode(proctocall: tinheritancetreecallback; arg: pointer);
  71. procedure foreachleafnode(proctocall: tinheritancetreecallback; arg: pointer);
  72. procedure optimizevirtualmethods;
  73. procedure printvmtinfo;
  74. end;
  75. { devirtualisation information for a class }
  76. tclassdevirtinfo = class(tfphashobject)
  77. private
  78. { array (indexed by vmt entry nr) of replacement statically callable method names }
  79. fstaticmethodnames: tfplist;
  80. function isstaticvmtentry(vmtindex: longint; out replacementname: pshortstring): boolean;
  81. public
  82. constructor create(hashobjectlist:tfphashobjectlist;const n: shortstring);reintroduce;
  83. destructor destroy; override;
  84. procedure addstaticmethod(vmtindex: longint; const replacementname: shortstring);
  85. end;
  86. { devirtualisation information for all classes in a unit }
  87. tunitdevirtinfo = class(tfphashobject)
  88. private
  89. { hashtable of classes }
  90. fclasses: tfphashobjectlist;
  91. public
  92. constructor create(hashobjectlist:tfphashobjectlist;const n: shortstring);reintroduce;
  93. destructor destroy; override;
  94. function addclass(const n: shortstring): tclassdevirtinfo;
  95. function findclass(const n: shortstring): tclassdevirtinfo;
  96. end;
  97. { devirtualisation information for all units in a program }
  98. { tprogdevirtinfo }
  99. tprogdevirtinfo = class(twpodevirtualisationhandler)
  100. private
  101. { hashtable of tunitdevirtinfo (which contain tclassdevirtinfo) }
  102. funits: tfphashobjectlist;
  103. procedure converttreenode(node: tinheritancetreenode; arg: pointer);
  104. function addunitifnew(const n: shortstring): tunitdevirtinfo;
  105. function findunit(const n: shortstring): tunitdevirtinfo;
  106. public
  107. constructor create; override;
  108. destructor destroy; override;
  109. class function getwpotype: twpotype; override;
  110. class function generatesinfoforwposwitches: twpoptimizerswitches; override;
  111. class function performswpoforswitches: twpoptimizerswitches; override;
  112. class function sectionname: shortstring; override;
  113. { information collection }
  114. procedure constructfromcompilerstate; override;
  115. procedure storewpofilesection(writer: twposectionwriterintf); override;
  116. { information providing }
  117. procedure loadfromwpofilesection(reader: twposectionreaderintf); override;
  118. function staticnameforvirtualmethod(objdef, procdef: tdef; out staticname: string): boolean; override;
  119. end;
  120. implementation
  121. uses
  122. cutils,
  123. fmodule,
  124. symconst,
  125. symbase,
  126. symtable,
  127. nobj,
  128. verbose;
  129. const
  130. DEVIRT_SECTION_NAME = 'contextinsensitive_devirtualization';
  131. { *************************** tinheritancetreenode ************************* }
  132. constructor tinheritancetreenode.create(_parent: tinheritancetreenode; _def: tobjectdef; _instantiated: boolean);
  133. begin
  134. fparent:=_parent;
  135. fdef:=_def;
  136. finstantiated:=_instantiated;
  137. end;
  138. destructor tinheritancetreenode.destroy;
  139. begin
  140. { fchilds owns its members, so it will free them too }
  141. fchilds.free;
  142. inherited destroy;
  143. end;
  144. function tinheritancetreenode.childcount: longint;
  145. begin
  146. if assigned(fchilds) then
  147. result:=fchilds.count
  148. else
  149. result:=0;
  150. end;
  151. function tinheritancetreenode.haschilds: boolean;
  152. begin
  153. result:=assigned(fchilds)
  154. end;
  155. function tinheritancetreenode.getchild(index: longint): tinheritancetreenode;
  156. begin
  157. result:=tinheritancetreenode(fchilds[index]);
  158. end;
  159. function tinheritancetreenode.maybeaddchild(_def: tobjectdef; _instantiated: boolean): tinheritancetreenode;
  160. var
  161. i: longint;
  162. begin
  163. { sanity check }
  164. if assigned(_def.childof) then
  165. begin
  166. if (_def.childof<>def) then
  167. internalerror(2008092201);
  168. end
  169. else if assigned(fparent) then
  170. internalerror(2008092202);
  171. if not assigned(fchilds) then
  172. fchilds:=tfpobjectlist.create(true);
  173. { def already a child -> return }
  174. for i := 0 to fchilds.count-1 do
  175. if (tinheritancetreenode(fchilds[i]).def=_def) then
  176. begin
  177. result:=tinheritancetreenode(fchilds[i]);
  178. result.finstantiated:=result.finstantiated or _instantiated;
  179. exit;
  180. end;
  181. { not found, add new child }
  182. result:=tinheritancetreenode.create(self,_def,_instantiated);
  183. fchilds.add(result);
  184. end;
  185. { *************************** tinheritancetree ************************* }
  186. constructor tinheritancetree.create;
  187. begin
  188. froots:=tinheritancetreenode.create(nil,nil,false);
  189. classrefdefs:=tfpobjectlist.create(false);
  190. end;
  191. destructor tinheritancetree.destroy;
  192. begin
  193. froots.free;
  194. classrefdefs.free;
  195. inherited destroy;
  196. end;
  197. function tinheritancetree.registerinstantiatedobjectdefrecursive(def: tobjectdef; instantiated: boolean): tinheritancetreenode;
  198. begin
  199. if assigned(def.childof) then
  200. begin
  201. { recursively add parent, of which we have no info about whether or not it is
  202. instantiated at this point -> default to false (will be overridden by "true"
  203. if this class is instantioted, since then registerinstantiatedobjdef() will
  204. be called for this class as well)
  205. }
  206. result:=registerinstantiatedobjectdefrecursive(def.childof,false);
  207. { and add ourselves to the parent }
  208. result:=result.maybeaddchild(def,instantiated);
  209. end
  210. else
  211. { add ourselves to the roots }
  212. result:=froots.maybeaddchild(def,instantiated);
  213. end;
  214. procedure tinheritancetree.registerinstantiatedobjdef(def: tdef);
  215. begin
  216. { add the def }
  217. if (def.typ=objectdef) then
  218. registerinstantiatedobjectdefrecursive(tobjectdef(def),true)
  219. else
  220. internalerror(2008092401);
  221. end;
  222. procedure tinheritancetree.registerinstantiatedclassrefdef(def: tdef);
  223. begin
  224. { queue for later checking (these are the objectdefs
  225. to which the classrefdefs point) }
  226. if (def.typ=objectdef) then
  227. classrefdefs.add(def)
  228. else
  229. internalerror(2008101401);
  230. end;
  231. procedure tinheritancetree.checkforclassrefinheritance(def: tdef);
  232. var
  233. i: longint;
  234. begin
  235. if (def.typ=objectdef) then
  236. begin
  237. {$ifdef debug_devirt}
  238. write(' Checking for classrefdef inheritance of ',def.typename);
  239. {$endif debug_devirt}
  240. for i:=0 to classrefdefs.count-1 do
  241. if tobjectdef(def).is_related(tobjectdef(classrefdefs[i])) then
  242. begin
  243. {$ifdef debug_devirt}
  244. writeln('... Found: inherits from Class Of ',tobjectdef(classrefdefs[i]).typename);
  245. {$endif debug_devirt}
  246. registerinstantiatedobjdef(def);
  247. exit;
  248. end;
  249. {$ifdef debug_devirt}
  250. writeln('... Not found!');
  251. {$endif debug_devirt}
  252. end;
  253. end;
  254. procedure tinheritancetree.foreachnodefromroot(root: tinheritancetreenode; proctocall: tinheritancetreecallback; arg: pointer);
  255. procedure process(const node: tinheritancetreenode);
  256. var
  257. i: longint;
  258. begin
  259. for i:=0 to node.childcount-1 do
  260. if node.childs[i].haschilds then
  261. begin
  262. proctocall(node.childs[i],arg);
  263. process(node.childs[i])
  264. end
  265. else
  266. proctocall(node.childs[i],arg);
  267. end;
  268. begin
  269. process(root);
  270. end;
  271. procedure tinheritancetree.foreachnode(proctocall: tinheritancetreecallback; arg: pointer);
  272. begin
  273. foreachnodefromroot(froots,proctocall,arg);
  274. end;
  275. procedure tinheritancetree.foreachleafnode(proctocall: tinheritancetreecallback; arg: pointer);
  276. procedure process(const node: tinheritancetreenode);
  277. var
  278. i: longint;
  279. begin
  280. for i:=0 to node.childcount-1 do
  281. if node.childs[i].haschilds then
  282. process(node.childs[i])
  283. else
  284. proctocall(node.childs[i],arg);
  285. end;
  286. begin
  287. process(froots);
  288. end;
  289. procedure tinheritancetree.markvmethods(node: tinheritancetreenode; p: pointer);
  290. var
  291. currnode: tinheritancetreenode;
  292. vmtbuilder: tvmtbuilder;
  293. pd: tobject;
  294. i: longint;
  295. makeallvirtual: boolean;
  296. begin
  297. {$IFDEF DEBUG_DEVIRT}
  298. writeln('processing leaf node ',node.def.typename);
  299. {$ENDIF}
  300. { todo: also process interfaces (ImplementedInterfaces) }
  301. if not assigned(node.def.vmtentries) then
  302. exit;
  303. { process all vmt entries for this class/object }
  304. for i:=0 to node.def.vmtentries.count-1 do
  305. begin
  306. currnode:=node;
  307. pd:=currnode.def.vmtentries[i];
  308. { abstract methods cannot be called directly }
  309. if (po_abstractmethod in tprocdef(pd).procoptions) then
  310. continue;
  311. {$IFDEF DEBUG_DEVIRT}
  312. writeln(' method ',tprocdef(pd).typename);
  313. {$ENDIF}
  314. { Now mark all virtual methods static that are the same in parent
  315. classes as in this instantiated child class (only instantiated
  316. classes can be leaf nodes, since only instantiated classes were
  317. added to the tree).
  318. If a first child does not override a parent method while a
  319. a second one does, the first will mark it as statically
  320. callable, but the second will set it to not statically callable.
  321. In the opposite situation, the first will mark it as not
  322. statically callable and the second will leave it alone.
  323. }
  324. makeallvirtual:=false;
  325. repeat
  326. { this parent may not have any virtual methods }
  327. if not assigned(currnode.def.vmtentries) or
  328. { stop when this method does not exist in a parent }
  329. (currnode.def.vmtentries.count<=i) then
  330. break;
  331. if not assigned(currnode.def.vmcallstaticinfo) then
  332. currnode.def.vmcallstaticinfo:=allocmem(currnode.def.vmtentries.count*sizeof(tvmcallstatic));
  333. { same procdef as in all instantiated childs? (yes or don't know) }
  334. if (currnode.def.vmcallstaticinfo^[i] in [vmcs_default,vmcs_yes]) then
  335. begin
  336. { methods in uninstantiated classes can be made static if
  337. they are the same in all instantiated derived classes
  338. }
  339. if ((currnode.def.vmtentries[i]=pd) or
  340. (not currnode.instantiated and
  341. (currnode.def.vmcallstaticinfo^[i]=vmcs_default))) and
  342. not makeallvirtual then
  343. begin
  344. {$IFDEF DEBUG_DEVIRT}
  345. writeln(' marking as static for ',currnode.def.typename);
  346. {$ENDIF}
  347. currnode.def.vmcallstaticinfo^[i]:=vmcs_yes;
  348. { this is in case of a non-instantiated parent of an instantiated child:
  349. the method declared in the child will always be called here
  350. }
  351. currnode.def.vmtentries[i]:=pd;
  352. end
  353. else
  354. begin
  355. {$IFDEF DEBUG_DEVIRT}
  356. writeln(' marking as non-static for ',currnode.def.typename);
  357. {$ENDIF}
  358. { this vmt entry must also remain virtual for all parents }
  359. makeallvirtual:=true;
  360. currnode.def.vmcallstaticinfo^[i]:=vmcs_no;
  361. end;
  362. currnode:=currnode.parent;
  363. end
  364. else
  365. begin
  366. {$IFDEF DEBUG_DEVIRT}
  367. writeln(' not processing parents, already non-static for ',currnode.def.typename);
  368. {$ENDIF}
  369. { parents are already set to vmcs_no, so no need to continue }
  370. currnode:=nil;
  371. end;
  372. until not assigned(currnode) or
  373. not assigned(currnode.def);
  374. end;
  375. end;
  376. procedure tinheritancetree.optimizevirtualmethods;
  377. begin
  378. foreachleafnode(@markvmethods,nil);
  379. end;
  380. procedure tinheritancetree.printobjectvmtinfo(node: tinheritancetreenode; arg: pointer);
  381. var
  382. i,
  383. totaldevirtualised,
  384. totalvirtual: ptrint;
  385. begin
  386. totaldevirtualised:=0;
  387. totalvirtual:=0;
  388. writeln(node.def.typename);
  389. if not assigned(node.def.vmtentries) then
  390. begin
  391. writeln(' No virtual methods!');
  392. exit;
  393. end;
  394. for i:=0 to node.def.vmtentries.count-1 do
  395. if (po_virtualmethod in tabstractprocdef(node.def.vmtentries[i]).procoptions) then
  396. begin
  397. inc(totalvirtual);
  398. if (node.def.vmcallstaticinfo^[i]=vmcs_yes) then
  399. begin
  400. inc(totaldevirtualised);
  401. writeln(' Devirtualised: ',tabstractprocdef(node.def.vmtentries[i]).typename);
  402. end;
  403. end;
  404. writeln('Total devirtualised: ',totaldevirtualised,'/',totalvirtual);
  405. writeln;
  406. end;
  407. procedure tinheritancetree.printvmtinfo;
  408. begin
  409. foreachnode(@printobjectvmtinfo,nil);
  410. end;
  411. { helper routine: decompose an object & procdef combo into a unitname, class name and vmtentry number
  412. (unit name where the objectdef is declared, class name of the objectdef, vmtentry number of the
  413. procdef -- procdef does not necessarily belong to objectdef, it may also belong to a descendant
  414. or parent) }
  415. procedure defsdecompose(objdef: tobjectdef; procdef: tprocdef; out unitname, classname: pshortstring; out vmtentry: longint);
  416. const
  417. mainprogname: string[2] = 'P$';
  418. var
  419. mainsymtab,
  420. objparentsymtab: tsymtable;
  421. begin
  422. objparentsymtab:=objdef.symtable;
  423. mainsymtab:=objparentsymtab.defowner.owner;
  424. { main symtable must be static or global }
  425. if not(mainsymtab.symtabletype in [staticsymtable,globalsymtable]) then
  426. internalerror(200204175);
  427. if (TSymtable(main_module.localsymtable)=mainsymtab) and
  428. (not main_module.is_unit) then
  429. { same convention as for mangled names }
  430. unitname:=@mainprogname
  431. else
  432. unitname:=mainsymtab.name;
  433. classname:=tobjectdef(objparentsymtab.defowner).objname;
  434. vmtentry:=procdef.extnumber;
  435. { if it's $ffff, this is not a valid virtual method }
  436. if (vmtentry=$ffff) then
  437. internalerror(2008100509);
  438. end;
  439. { tclassdevirtinfo }
  440. constructor tclassdevirtinfo.create(hashobjectlist:tfphashobjectlist;const n: shortstring);
  441. begin
  442. inherited create(hashobjectlist,n);
  443. fstaticmethodnames:=tfplist.create;
  444. end;
  445. destructor tclassdevirtinfo.destroy;
  446. var
  447. i: longint;
  448. begin
  449. for i:=0 to fstaticmethodnames.count-1 do
  450. if assigned(fstaticmethodnames[i]) then
  451. freemem(fstaticmethodnames[i]);
  452. fstaticmethodnames.free;
  453. inherited destroy;
  454. end;
  455. procedure tclassdevirtinfo.addstaticmethod(vmtindex: longint;
  456. const replacementname: shortstring);
  457. begin
  458. if (vmtindex>=fstaticmethodnames.count) then
  459. fstaticmethodnames.Count:=vmtindex+10;
  460. fstaticmethodnames[vmtindex]:=stringdup(replacementname);
  461. end;
  462. function tclassdevirtinfo.isstaticvmtentry(vmtindex: longint; out
  463. replacementname: pshortstring): boolean;
  464. begin
  465. result:=false;
  466. if (vmtindex>=fstaticmethodnames.count) then
  467. exit;
  468. replacementname:=fstaticmethodnames[vmtindex];
  469. result:=assigned(replacementname);
  470. end;
  471. { tunitdevirtinfo }
  472. constructor tunitdevirtinfo.create(hashobjectlist:tfphashobjectlist;const n: shortstring);
  473. begin
  474. inherited create(hashobjectlist,n);
  475. fclasses:=tfphashobjectlist.create(true);
  476. end;
  477. destructor tunitdevirtinfo.destroy;
  478. begin
  479. fclasses.free;
  480. inherited destroy;
  481. end;
  482. function tunitdevirtinfo.addclass(const n: shortstring): tclassdevirtinfo;
  483. begin
  484. result:=findclass(n);
  485. { can't have two classes with the same name in a single unit }
  486. if assigned(result) then
  487. internalerror(2008100501);
  488. result:=tclassdevirtinfo.create(fclasses,n);
  489. end;
  490. function tunitdevirtinfo.findclass(const n: shortstring): tclassdevirtinfo;
  491. begin
  492. result:=tclassdevirtinfo(fclasses.find(n));
  493. end;
  494. { tprogdevirtinfo }
  495. procedure tprogdevirtinfo.converttreenode(node: tinheritancetreenode; arg: pointer);
  496. var
  497. i,
  498. vmtentry: longint;
  499. unitid, classid: pshortstring;
  500. unitdevirtinfo: tunitdevirtinfo;
  501. classdevirtinfo: tclassdevirtinfo;
  502. first : boolean;
  503. begin
  504. if not assigned(node.def.vmtentries) then
  505. exit;
  506. first:=true;
  507. for i:=0 to node.def.vmtentries.count-1 do
  508. if (po_virtualmethod in tabstractprocdef(node.def.vmtentries[i]).procoptions) and
  509. (node.def.vmcallstaticinfo^[i]=vmcs_yes) then
  510. begin
  511. if first then
  512. begin
  513. { add necessary entries for the unit and the class }
  514. defsdecompose(node.def,tprocdef(node.def.vmtentries[i]),unitid,classid,vmtentry);
  515. unitdevirtinfo:=addunitifnew(unitid^);
  516. classdevirtinfo:=unitdevirtinfo.addclass(classid^);
  517. first:=false;
  518. end;
  519. { add info about devirtualised vmt entry }
  520. classdevirtinfo.addstaticmethod(i,tprocdef(node.def.vmtentries[i]).mangledname);
  521. end;
  522. end;
  523. constructor tprogdevirtinfo.create;
  524. begin
  525. inherited create;
  526. end;
  527. destructor tprogdevirtinfo.destroy;
  528. begin
  529. funits.free;
  530. inherited destroy;
  531. end;
  532. class function tprogdevirtinfo.getwpotype: twpotype;
  533. begin
  534. result:=wpo_devirtualization_context_insensitive;
  535. end;
  536. class function tprogdevirtinfo.generatesinfoforwposwitches: twpoptimizerswitches;
  537. begin
  538. result:=[cs_wpo_devirtualize_calls,cs_wpo_optimize_vmts];
  539. end;
  540. class function tprogdevirtinfo.performswpoforswitches: twpoptimizerswitches;
  541. begin
  542. result:=[cs_wpo_devirtualize_calls,cs_wpo_optimize_vmts];
  543. end;
  544. class function tprogdevirtinfo.sectionname: shortstring;
  545. begin
  546. result:=DEVIRT_SECTION_NAME;
  547. end;
  548. procedure reset_all_impl_defs;
  549. procedure reset_used_unit_impl_defs(hp:tmodule);
  550. var
  551. pu : tused_unit;
  552. begin
  553. pu:=tused_unit(hp.used_units.first);
  554. while assigned(pu) do
  555. begin
  556. if not pu.u.is_reset then
  557. begin
  558. { prevent infinte loop for circular dependencies }
  559. pu.u.is_reset:=true;
  560. if assigned(pu.u.localsymtable) then
  561. begin
  562. tstaticsymtable(pu.u.localsymtable).reset_all_defs;
  563. reset_used_unit_impl_defs(pu.u);
  564. end;
  565. end;
  566. pu:=tused_unit(pu.next);
  567. end;
  568. end;
  569. var
  570. hp2 : tmodule;
  571. begin
  572. hp2:=tmodule(loaded_units.first);
  573. while assigned(hp2) do
  574. begin
  575. hp2.is_reset:=false;
  576. hp2:=tmodule(hp2.next);
  577. end;
  578. reset_used_unit_impl_defs(current_module);
  579. end;
  580. procedure tprogdevirtinfo.constructfromcompilerstate;
  581. var
  582. hp: tmodule;
  583. i: longint;
  584. inheritancetree: tinheritancetree;
  585. begin
  586. { the compiler already resets all interface defs after every unit
  587. compilation, but not the implementation defs (because this is only
  588. done for the purpose of writing debug info, and you can never see
  589. a type defined in the implementation of one unit in another unit).
  590. Here, we want to record all classes constructed anywhere in the
  591. program, also if those class(ref) types are defined in the
  592. implementation of a unit. So reset the state of all defs in
  593. implementation sections before starting the collection process. }
  594. reset_all_impl_defs;
  595. { register all instantiated class/object types }
  596. hp:=tmodule(loaded_units.first);
  597. while assigned(hp) do
  598. begin
  599. if assigned(hp.wpoinfo.createdobjtypes) then
  600. for i:=0 to hp.wpoinfo.createdobjtypes.count-1 do
  601. tdef(hp.wpoinfo.createdobjtypes[i]).register_created_object_type;
  602. if assigned(hp.wpoinfo.createdclassrefobjtypes) then
  603. for i:=0 to hp.wpoinfo.createdclassrefobjtypes.count-1 do
  604. tobjectdef(hp.wpoinfo.createdclassrefobjtypes[i]).register_created_classref_type;
  605. hp:=tmodule(hp.next);
  606. end;
  607. inheritancetree:=tinheritancetree.create;
  608. {$IFDEF DEBUG_DEVIRT}
  609. writeln('constructed object/class/classreftypes in ',current_module.realmodulename^);
  610. {$ENDIF}
  611. for i := 0 to current_module.wpoinfo.createdobjtypes.count-1 do
  612. begin
  613. inheritancetree.registerinstantiatedobjdef(tdef(current_module.wpoinfo.createdobjtypes[i]));
  614. {$IFDEF DEBUG_DEVIRT}
  615. write(' ',tdef(current_module.wpoinfo.createdobjtypes[i]).GetTypeName);
  616. {$ENDIF}
  617. case tdef(current_module.wpoinfo.createdobjtypes[i]).typ of
  618. objectdef:
  619. case tobjectdef(current_module.wpoinfo.createdobjtypes[i]).objecttype of
  620. odt_object:
  621. {$IFDEF DEBUG_DEVIRT}
  622. writeln(' (object)')
  623. {$ENDIF}
  624. ;
  625. odt_class:
  626. {$IFDEF DEBUG_DEVIRT}
  627. writeln(' (class)')
  628. {$ENDIF}
  629. ;
  630. else
  631. internalerror(2008092101);
  632. end;
  633. else
  634. internalerror(2008092102);
  635. end;
  636. end;
  637. for i := 0 to current_module.wpoinfo.createdclassrefobjtypes.count-1 do
  638. begin
  639. inheritancetree.registerinstantiatedclassrefdef(tdef(current_module.wpoinfo.createdclassrefobjtypes[i]));
  640. {$IFDEF DEBUG_DEVIRT}
  641. write(' Class Of ',tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).GetTypeName);
  642. {$ENDIF}
  643. case tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).typ of
  644. objectdef:
  645. {$IFDEF DEBUG_DEVIRT}
  646. writeln(' (classrefdef)')
  647. {$ENDIF}
  648. ;
  649. else
  650. internalerror(2008101101);
  651. end;
  652. end;
  653. { now add all objectdefs derived from the instantiated
  654. classrefdefs to the tree (as they can, in theory, all
  655. be instantiated as well)
  656. }
  657. hp:=tmodule(loaded_units.first);
  658. while assigned(hp) do
  659. begin
  660. { we cannot just walk over the module's deflists, because a bunch of
  661. the defs in there don't exist anymore (when destroyed, they're
  662. removed from their symtable but not from the module's deflist)
  663. procedure-local (or class-local) class definitions do not (yet)
  664. exit, so it's enough to just walk the global and local symtables
  665. }
  666. { globalsymtable (interface), is nil for main program itself }
  667. if assigned(hp.globalsymtable) then
  668. for i:=0 to hp.globalsymtable.deflist.count-1 do
  669. inheritancetree.checkforclassrefinheritance(tdef(hp.globalsymtable.deflist[i]));
  670. { staticsymtable (implementation), is nil for units with nothing
  671. in the implementation }
  672. if assigned(hp.localsymtable) then
  673. for i:=0 to hp.localsymtable.deflist.count-1 do
  674. inheritancetree.checkforclassrefinheritance(tdef(hp.localsymtable.deflist[i]));
  675. hp:=tmodule(hp.next);
  676. end;
  677. inheritancetree.optimizevirtualmethods;
  678. {$ifdef DEBUG_DEVIRT}
  679. inheritancetree.printvmtinfo;
  680. {$endif DEBUG_DEVIRT}
  681. inheritancetree.foreachnode(@converttreenode,nil);
  682. inheritancetree.free;
  683. end;
  684. function tprogdevirtinfo.addunitifnew(const n: shortstring): tunitdevirtinfo;
  685. begin
  686. if assigned(funits) then
  687. result:=findunit(n)
  688. else
  689. begin
  690. funits:=tfphashobjectlist.create;
  691. result:=nil;
  692. end;
  693. if not assigned(result) then
  694. begin
  695. result:=tunitdevirtinfo.create(funits,n);
  696. end;
  697. end;
  698. function tprogdevirtinfo.findunit(const n: shortstring): tunitdevirtinfo;
  699. begin
  700. result:=tunitdevirtinfo(funits.find(n));
  701. end;
  702. procedure tprogdevirtinfo.loadfromwpofilesection(reader: twposectionreaderintf);
  703. var
  704. unitid,
  705. classid,
  706. vmtentryname: string;
  707. vmttype: string[15];
  708. vmtentrynrstr: string[7];
  709. vmtentry, error: longint;
  710. unitdevirtinfo: tunitdevirtinfo;
  711. classdevirtinfo: tclassdevirtinfo;
  712. begin
  713. { format:
  714. unit1^
  715. class1&
  716. basevmt
  717. 0
  718. staticvmtentryforslot0
  719. 5
  720. staticvmtentryforslot5
  721. intfvmt1
  722. 0
  723. staticvmtentryforslot0
  724. class2&
  725. basevmt
  726. 1
  727. staticvmtentryforslot1
  728. unit2^
  729. class3&
  730. ...
  731. currently, only basevmt is supported (no interfaces yet)
  732. }
  733. { could be empty if no classes or so }
  734. if not reader.sectiongetnextline(unitid) then
  735. exit;
  736. repeat
  737. if (unitid='') or
  738. (unitid[length(unitid)]<>'^') then
  739. internalerror(2008100502);
  740. { cut off the trailing ^ }
  741. setlength(unitid,length(unitid)-1);
  742. unitdevirtinfo:=addunitifnew(unitid);
  743. { now read classes }
  744. if not reader.sectiongetnextline(classid) then
  745. internalerror(2008100505);
  746. repeat
  747. if (classid='') or
  748. (classid[length(classid)]<>'&') then
  749. internalerror(2008100503);
  750. { cut off the trailing & }
  751. setlength(classid,length(classid)-1);
  752. classdevirtinfo:=unitdevirtinfo.addclass(classid);
  753. if not reader.sectiongetnextline(vmttype) then
  754. internalerror(2008100506);
  755. { interface info is not yet supported }
  756. if (vmttype<>'basevmt') then
  757. internalerror(2008100507);
  758. { read all vmt entries for this class }
  759. while reader.sectiongetnextline(vmtentrynrstr) and
  760. (vmtentrynrstr<>'') do
  761. begin
  762. val(vmtentrynrstr,vmtentry,error);
  763. if (error<>0) then
  764. internalerror(2008100504);
  765. if not reader.sectiongetnextline(vmtentryname) or
  766. (vmtentryname='') then
  767. internalerror(2008100508);
  768. classdevirtinfo.addstaticmethod(vmtentry,vmtentryname);
  769. end;
  770. { end of section -> exit }
  771. if not(reader.sectiongetnextline(classid)) then
  772. exit;
  773. until (classid='') or
  774. (classid[length(classid)]='^');
  775. { next unit, or error }
  776. unitid:=classid;
  777. until false;
  778. end;
  779. procedure tprogdevirtinfo.storewpofilesection(writer: twposectionwriterintf);
  780. var
  781. unitcount,
  782. classcount,
  783. vmtentrycount: longint;
  784. unitdevirtinfo: tunitdevirtinfo;
  785. classdevirtinfo: tclassdevirtinfo;
  786. begin
  787. { if there are no optimised virtual methods, we have stored no info }
  788. if not assigned(funits) then
  789. exit;
  790. writer.startsection(DEVIRT_SECTION_NAME);
  791. for unitcount:=0 to funits.count-1 do
  792. begin
  793. unitdevirtinfo:=tunitdevirtinfo(funits[unitcount]);
  794. writer.sectionputline(unitdevirtinfo.name+'^');
  795. for classcount:=0 to unitdevirtinfo.fclasses.count-1 do
  796. begin
  797. classdevirtinfo:=tclassdevirtinfo(tunitdevirtinfo(funits[unitcount]).fclasses[classcount]);
  798. writer.sectionputline(classdevirtinfo.name+'&');
  799. writer.sectionputline('basevmt');
  800. for vmtentrycount:=0 to classdevirtinfo.fstaticmethodnames.count-1 do
  801. if assigned(classdevirtinfo.fstaticmethodnames[vmtentrycount]) then
  802. begin
  803. writer.sectionputline(tostr(vmtentrycount));
  804. writer.sectionputline(pshortstring(classdevirtinfo.fstaticmethodnames[vmtentrycount])^);
  805. end;
  806. writer.sectionputline('');
  807. end;
  808. end;
  809. end;
  810. function tprogdevirtinfo.staticnameforvirtualmethod(objdef, procdef: tdef; out staticname: string): boolean;
  811. var
  812. unitid,
  813. classid,
  814. newname: pshortstring;
  815. unitdevirtinfo: tunitdevirtinfo;
  816. classdevirtinfo: tclassdevirtinfo;
  817. vmtentry: longint;
  818. realobjdef: tobjectdef;
  819. begin
  820. { class methods are in the regular vmt, so we can handle classrefs
  821. the same way as plain objectdefs
  822. }
  823. if (objdef.typ=classrefdef) then
  824. realobjdef:=tobjectdef(tclassrefdef(objdef).pointeddef)
  825. else if (objdef.typ=objectdef) and
  826. (tobjectdef(objdef).objecttype in [odt_class,odt_object]) then
  827. realobjdef:=tobjectdef(objdef)
  828. else
  829. begin
  830. { we don't support interfaces yet }
  831. result:=false;
  832. exit;
  833. end;
  834. { get the component names for the class/procdef combo }
  835. defsdecompose(realobjdef,tprocdef(procdef),unitid,classid,vmtentry);
  836. { do we have any info for this unit? }
  837. unitdevirtinfo:=findunit(unitid^);
  838. result:=false;
  839. if not assigned(unitdevirtinfo) then
  840. exit;
  841. { and for this class? }
  842. classdevirtinfo:=unitdevirtinfo.findclass(classid^);
  843. if not assigned(classdevirtinfo) then
  844. exit;
  845. { now check whether it can be devirtualised, and if so to what }
  846. result:=classdevirtinfo.isstaticvmtentry(vmtentry,newname);
  847. if result then
  848. staticname:=newname^;
  849. end;
  850. end.