optcse.pas 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. {
  2. Common subexpression elimination on base blocks
  3. Copyright (c) 2005-2012 by Florian Klaempfl
  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 optcse;
  18. {$i fpcdefs.inc}
  19. { $define csedebug}
  20. { $define csestats}
  21. interface
  22. uses
  23. node;
  24. {
  25. the function creates non optimal code so far:
  26. - call para nodes are cse barriers because they can be reordered and thus the
  27. temp. creation could be done too late
  28. - the cse knows nothing about register pressure. In case of high register pressure, cse might
  29. have a negative impact
  30. - the list of cseinvariant node types and inline numbers is not complete yet
  31. Further, it could be done probably in a faster way though the complexity can't probably not reduced
  32. }
  33. function do_optcse(var rootnode : tnode) : tnode;
  34. function do_consttovar(var rootnode : tnode) : tnode;
  35. implementation
  36. uses
  37. globtype,globals,
  38. cutils,cclasses,
  39. nutils,compinnr,
  40. nbas,nld,ninl,ncal,nadd,nmem,ncnv,
  41. pass_1,
  42. procinfo,
  43. paramgr,
  44. cpubase,
  45. symconst,symdef,symsym,symtable,symtype,
  46. defutil,
  47. optbase;
  48. const
  49. cseinvariant : set of tnodetype = [addn,muln,subn,divn,slashn,modn,andn,orn,xorn,notn,vecn,
  50. derefn,equaln,unequaln,ltn,gtn,lten,gten,typeconvn,subscriptn,
  51. inn,symdifn,shrn,shln,ordconstn,realconstn,unaryminusn,pointerconstn,stringconstn,setconstn,niln,
  52. setelementn,{arrayconstructorn,arrayconstructorrangen,}
  53. isn,asn,starstarn,nothingn,temprefn,loadparentfpn {,callparan},assignn,addrn];
  54. function searchsubdomain(var n:tnode; arg: pointer) : foreachnoderesult;
  55. begin
  56. if (n.nodetype in cseinvariant) or
  57. ((n.nodetype=inlinen) and
  58. (tinlinenode(n).inlinenumber in [in_length_x,in_assigned_x,in_sqr_real,in_sqrt_real,in_sin_real,in_cos_real,in_abs_long,
  59. in_abs_real,in_exp_real,in_ln_real,in_pi_real,in_popcnt_x,in_arctan_real,in_round_real,in_trunc_real,
  60. { cse on fma will still not work because it would require proper handling of call nodes
  61. with more than one parameter }
  62. in_fma_single,in_fma_double,in_fma_extended,in_fma_float128,
  63. in_min_single,in_min_double,in_max_single,in_max_double,
  64. in_max_longint,in_max_dword,in_min_longint,in_min_dword
  65. ])
  66. ) or
  67. ((n.nodetype=callparan) and not(assigned(tcallparanode(n).right))) or
  68. ((n.nodetype=loadn) and
  69. not((tloadnode(n).symtableentry.typ in [staticvarsym,localvarsym,paravarsym]) and
  70. (vo_volatile in tabstractvarsym(tloadnode(n).symtableentry).varoptions))
  71. ) then
  72. result:=fen_true
  73. else
  74. begin
  75. pboolean(arg)^:=false;
  76. result:=fen_norecurse_true;
  77. end;
  78. end;
  79. type
  80. tlists = record
  81. nodelist : tfplist;
  82. locationlist : tfplist;
  83. equalto : tfplist;
  84. refs : tfplist;
  85. avail : TDFASet;
  86. end;
  87. plists = ^tlists;
  88. { collectnodes needs the address of itself to call foreachnodestatic,
  89. so we need a wrapper because @<func> inside <func doesn't work }
  90. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;forward;
  91. function collectnodes2(var n:tnode; arg: pointer) : foreachnoderesult;
  92. begin
  93. result:=collectnodes(n,arg);
  94. end;
  95. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;
  96. { when compiling a tree like
  97. and
  98. / \
  99. and C
  100. / \
  101. A B
  102. all expressions of B are available during evaluation of C. However considerung the whole expression,
  103. values of B and C might not be available due to short boolean evaluation.
  104. So recurseintobooleanchain detectes such chained and/or expressions and makes sub-expressions of B
  105. available during the evaluation of C
  106. firstleftend is later used to remove all sub expressions of B and C by storing the expression count
  107. in the cse table after handling A
  108. }
  109. var
  110. firstleftend : longint;
  111. procedure recurseintobooleanchain(t : tnodetype;n : tnode);
  112. begin
  113. if (tbinarynode(n).left.nodetype=t) and is_boolean(tbinarynode(n).left.resultdef) then
  114. recurseintobooleanchain(t,tbinarynode(n).left)
  115. else
  116. foreachnodestatic(pm_postprocess,tbinarynode(n).left,@collectnodes2,arg);
  117. firstleftend:=min(plists(arg)^.nodelist.count,firstleftend);
  118. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@collectnodes2,arg);
  119. end;
  120. var
  121. i : longint;
  122. tempdef : tdef;
  123. begin
  124. result:=fen_false;
  125. { don't add the tree below an untyped const parameter: there is
  126. no information available that this kind of tree actually needs
  127. to be addresable, this could be improved }
  128. { the nodes below a type conversion node created for an absolute
  129. reference cannot be handled separately, because the absolute reference
  130. may have special requirements (no regability, must be in memory, ...)
  131. }
  132. if (((n.nodetype=callparan) and
  133. (tcallparanode(n).left.resultdef.typ=formaldef) and
  134. (tcallparanode(n).parasym.varspez=vs_const)) or
  135. ((n.nodetype=typeconvn) and
  136. (nf_absolute in n.flags))
  137. ) then
  138. begin
  139. result:=fen_norecurse_false;
  140. exit;
  141. end;
  142. if
  143. { node possible to add? }
  144. assigned(n.resultdef) and
  145. ((
  146. { regable expressions }
  147. (actualtargetnode(@n)^.flags*[nf_write,nf_modify,nf_address_taken]=[]) and
  148. (
  149. tstoreddef(n.resultdef).is_intregable or
  150. tstoreddef(n.resultdef).is_fpuregable or
  151. tstoreddef(n.resultdef).is_const_intregable
  152. ) and
  153. { is_int/fpuregable allows arrays and records to be in registers, cse cannot handle this }
  154. (
  155. not(n.resultdef.typ in [arraydef,recorddef]) or
  156. (
  157. (
  158. (n.resultdef.typ = recorddef) and
  159. tabstractrecordsymtable(tabstractrecorddef(n.resultdef).symtable).has_single_field(tempdef)
  160. ) or
  161. is_dynamic_array(n.resultdef) or
  162. (
  163. not(is_special_array(tstoreddef(n.resultdef))) and
  164. not(tstoreddef(n.resultdef).is_intregable) and
  165. not(tstoreddef(n.resultdef).is_fpuregable)
  166. )
  167. )
  168. ) and
  169. { same for voiddef }
  170. not(is_void(n.resultdef)) and
  171. { adding tempref and callpara nodes itself is worthless but
  172. their complexity is probably <= 1 anyways
  173. neither add setelementn nodes because the compiler sometimes depends on the fact
  174. that a certain node stays a setelementn, this does not hurt either because
  175. setelementn nodes itself generate no real code (except moving data into register) }
  176. not(n.nodetype in [temprefn,callparan,setelementn]) and
  177. { node worth to add?
  178. We consider almost every node because even loading a variables from
  179. a register instead of memory is more beneficial. This behaviour should
  180. not increase register pressure because if a variable is already
  181. in a register, the reg. allocator can merge the nodes. If a variable
  182. is loaded from memory, loading this variable and spilling another register
  183. should not add a speed penalty.
  184. }
  185. {
  186. load nodes are not considered if they load para or local symbols from the
  187. current stack frame, those are in registers anyways if possible
  188. }
  189. (not(actualtargetnode(@n)^.nodetype=loadn) or
  190. not(tloadnode(actualtargetnode(@n)^).symtableentry.typ in [paravarsym,localvarsym,staticvarsym]) or
  191. { apply cse on non-regable variables }
  192. ((tloadnode(actualtargetnode(@n)^).symtableentry.typ in [paravarsym,localvarsym,staticvarsym]) and
  193. not(tabstractvarsym(tloadnode(actualtargetnode(@n)^).symtableentry).is_regvar(true)) and
  194. not(vo_volatile in tabstractvarsym(tloadnode(actualtargetnode(@n)^).symtableentry).varoptions)) or
  195. (node_complexity(n)>1)
  196. ) and
  197. {
  198. Const nodes however are only considered if their complexity is >1
  199. This might be the case for the risc architectures if they need
  200. more than one instruction to load this particular value
  201. }
  202. (not(is_constnode(n)) or (node_complexity(n)>1)))
  203. {$if not(defined(i386)) and not(defined(i8086))}
  204. or
  205. { store reference of expression? }
  206. { loading the address of a global symbol takes typically more than
  207. one instruction on every platform except i8086/i386
  208. so consider in this case loading the address of the data
  209. }
  210. (((n.resultdef.typ in [arraydef,recorddef]) or is_object(n.resultdef)) and not(is_dynamic_array(n.resultdef)) and
  211. (n.nodetype=loadn) and
  212. (tloadnode(n).symtableentry.typ=staticvarsym)
  213. )
  214. {$endif not(defined(i386)) and not(defined(i8086))}
  215. ) then
  216. begin
  217. plists(arg)^.nodelist.Add(n);
  218. plists(arg)^.locationlist.Add(@n);
  219. plists(arg)^.refs.Add(nil);
  220. plists(arg)^.equalto.Add(pointer(-1));
  221. DFASetInclude(plists(arg)^.avail,plists(arg)^.nodelist.count-1);
  222. for i:=0 to plists(arg)^.nodelist.count-2 do
  223. begin
  224. if tnode(plists(arg)^.nodelist[i]).isequal(n) and DFASetIn(plists(arg)^.avail,i) then
  225. begin
  226. { use always the first occurence }
  227. if plists(arg)^.equalto[i]<>pointer(-1) then
  228. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=plists(arg)^.equalto[i]
  229. else
  230. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=pointer(ptrint(i));
  231. plists(arg)^.refs[i]:=pointer(plists(arg)^.refs[i])+1;
  232. { tree has been found, no need to search further,
  233. sub-trees have been added by the first occurence of
  234. the tree already }
  235. result:=fen_norecurse_false;
  236. break;
  237. end;
  238. end;
  239. end;
  240. { boolean and/or require a special handling: after evaluating the and/or node,
  241. the expressions of the right side might not be available due to short boolean
  242. evaluation, so after handling the right side, mark those expressions
  243. as unavailable }
  244. if (n.nodetype in [orn,andn]) and is_boolean(taddnode(n).left.resultdef) then
  245. begin
  246. firstleftend:=high(longint);
  247. recurseintobooleanchain(n.nodetype,n);
  248. for i:=firstleftend to plists(arg)^.nodelist.count-1 do
  249. DFASetExclude(plists(arg)^.avail,i);
  250. result:=fen_norecurse_false;
  251. end;
  252. {$ifdef cpuhighleveltarget}
  253. { The high level targets use the functionality from ncgnstld for
  254. nested accesses, and that one stores the complete location of the
  255. nested variable in tloadnode.left rather than only the location of
  256. the parent context containing it. This causes problems with the
  257. CSE in case the nested variable is used as an lvalue, so disable
  258. CSE in that case
  259. }
  260. if (n.nodetype=loadn) and assigned(tloadnode(n).left) then
  261. result:=fen_norecurse_false;
  262. {$endif}
  263. end;
  264. function searchcsedomain(var n: tnode; arg: pointer) : foreachnoderesult;
  265. var
  266. csedomain : boolean;
  267. lists : tlists;
  268. templist : tfplist;
  269. i : longint;
  270. def : tstoreddef;
  271. nodes : tblocknode;
  272. creates,
  273. statements : tstatementnode;
  274. deletetemp : ttempdeletenode;
  275. hp : ttempcreatenode;
  276. addrstored : boolean;
  277. hp2 : tnode;
  278. begin
  279. result:=fen_false;
  280. nodes:=nil;
  281. if (n.nodetype in cseinvariant) and
  282. { a setelement node is cseinvariant, but it might not be replaced by a block so
  283. it cannot be the root of the cse search }
  284. (n.nodetype<>setelementn) then
  285. begin
  286. csedomain:=true;
  287. foreachnodestatic(pm_postprocess,n,@searchsubdomain,@csedomain);
  288. if not(csedomain) then
  289. begin
  290. { try to transform the tree to get better cse domains, consider:
  291. + (1)
  292. / \
  293. (2) + C
  294. / \
  295. A B
  296. if A is not cse'able but B and C are, then the compiler cannot do cse so the tree is transformed into
  297. +
  298. / \
  299. A +
  300. / \
  301. B C
  302. Because A could be another tree of this kind, the whole process is done in a while loop
  303. }
  304. if (n.nodetype in [andn,orn,addn,muln]) and
  305. (n.nodetype=tbinarynode(n).left.nodetype) and
  306. { do is optimizations only for integers, reals (no currency!), vectors, sets or booleans }
  307. (is_integer(n.resultdef) or is_real(n.resultdef) or is_vector(n.resultdef) or is_set(n.resultdef) or
  308. is_boolean(n.resultdef)) and
  309. { either if fastmath is on }
  310. ((cs_opt_fastmath in current_settings.optimizerswitches) or
  311. { or for the logical operators, they cannot overflow }
  312. (n.nodetype in [andn,orn]) or
  313. { or for integers if range checking is off }
  314. ((is_integer(n.resultdef) and
  315. (n.localswitches*[cs_check_range,cs_check_overflow]=[]) and
  316. (tbinarynode(n).left.localswitches*[cs_check_range,cs_check_overflow]=[]))) or
  317. { for sets, we can do this always }
  318. (is_set(n.resultdef))
  319. ) then
  320. while (n.nodetype=tbinarynode(n).left.nodetype) and
  321. { if node (1) is fully boolean evaluated and node (2) not, we cannot do the swap as this might result in B being evaluated always,
  322. the other way round is no problem, C is still evaluated only if needed }
  323. (not(is_boolean(n.resultdef)) or not(n.nodetype in [andn,orn]) or doshortbooleval(n) or not(doshortbooleval(tbinarynode(n).left))) and
  324. { the resulttypes of the operands we'll swap must be equal,
  325. required in case of a 32x32->64 multiplication, then we
  326. cannot swap out one of the 32 bit operands for a 64 bit one
  327. }
  328. (tbinarynode(tbinarynode(n).left).left.resultdef=tbinarynode(n).left.resultdef) and
  329. (tbinarynode(n).left.resultdef=tbinarynode(n).right.resultdef) do
  330. begin
  331. csedomain:=true;
  332. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@searchsubdomain,@csedomain);
  333. if csedomain then
  334. begin
  335. csedomain:=true;
  336. foreachnodestatic(pm_postprocess,tbinarynode(tbinarynode(n).left).right,@searchsubdomain,@csedomain);
  337. if csedomain then
  338. begin
  339. { move the full boolean evaluation of (2) to (1), if it was there (so it again applies to A and
  340. what follows) }
  341. if not(doshortbooleval(tbinarynode(n).left)) and
  342. doshortbooleval(n) then
  343. begin
  344. n.localswitches:=n.localswitches+(tbinarynode(n).left.localswitches*[cs_full_boolean_eval]);
  345. exclude(tbinarynode(n).left.localswitches,cs_full_boolean_eval);
  346. tbinarynode(n).left.flags:=tbinarynode(n).left.flags+(n.flags*[nf_short_bool]);
  347. exclude(n.Flags,nf_short_bool);
  348. end;
  349. hp2:=tbinarynode(tbinarynode(n).left).left;
  350. tbinarynode(tbinarynode(n).left).left:=tbinarynode(tbinarynode(n).left).right;
  351. tbinarynode(tbinarynode(n).left).right:=tbinarynode(n).right;
  352. tbinarynode(n).right:=tbinarynode(n).left;
  353. tbinarynode(n).left:=hp2;
  354. { the transformed tree could result in new possibilities to fold constants
  355. so force a firstpass on the root node }
  356. exclude(tbinarynode(n).right.flags,nf_pass1_done);
  357. do_firstpass(tbinarynode(n).right);
  358. end
  359. else
  360. break;
  361. end
  362. else
  363. break;
  364. end;
  365. end
  366. else
  367. begin
  368. statements:=nil;
  369. result:=fen_norecurse_true;
  370. {$ifdef csedebug}
  371. writeln('============ cse domain ==================');
  372. printnode(output,n);
  373. writeln('Complexity: ',node_complexity(n));
  374. {$endif csedebug}
  375. lists.nodelist:=tfplist.create;
  376. lists.locationlist:=tfplist.create;
  377. lists.equalto:=tfplist.create;
  378. lists.refs:=tfplist.create;
  379. foreachnodestatic(pm_postprocess,n,@collectnodes,@lists);
  380. templist:=tfplist.create;
  381. templist.count:=lists.nodelist.count;
  382. { check all nodes if one is used more than once }
  383. for i:=0 to lists.nodelist.count-1 do
  384. begin
  385. { current node used more than once? }
  386. if assigned(lists.refs[i]) then
  387. begin
  388. if not(assigned(statements)) then
  389. begin
  390. nodes:=internalstatements(statements);
  391. addstatement(statements,internalstatements(creates));
  392. end;
  393. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  394. { we cannot handle register stored records or array in CSE yet
  395. but we can store their reference }
  396. addrstored:=((def.typ in [arraydef,recorddef]) or is_object(def)) and not(is_dynamic_array(def));
  397. if addrstored then
  398. templist[i]:=ctempcreatenode.create_value(cpointerdef.getreusable(def),voidpointertype.size,tt_persistent,
  399. true,caddrnode.create_internal(tnode(lists.nodelist[i])))
  400. else
  401. templist[i]:=ctempcreatenode.create_value(def,def.size,tt_persistent,
  402. def.is_intregable or def.is_fpuregable or def.is_const_intregable,tnode(lists.nodelist[i]));
  403. { the value described by the temp. is immutable and the temp. can be always in register
  404. ttempcreatenode.create normally takes care of the register location but it does not
  405. know about immutability so it cannot take care of managed types }
  406. ttempcreatenode(templist[i]).includetempflag(ti_const);
  407. ttempcreatenode(templist[i]).includetempflag(ti_may_be_in_reg);
  408. { make debugging easier and set temp. location to the original location }
  409. tnode(templist[i]).fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  410. addstatement(creates,tnode(templist[i]));
  411. { the delete node has no semantic use yet, it is just used to clean up memory }
  412. deletetemp:=ctempdeletenode.create(ttempcreatenode(templist[i]));
  413. deletetemp.includetempflag(ti_cleanup_only);
  414. addstatement(tstatementnode(arg^),deletetemp);
  415. { make debugging easier and set temp. location to the original location }
  416. creates.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  417. hp:=ttempcreatenode(templist[i]);
  418. do_firstpass(tnode(hp));
  419. templist[i]:=hp;
  420. if addrstored then
  421. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[i])))
  422. else
  423. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[i]));
  424. { make debugging easier and set temp. location to the original location }
  425. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  426. do_firstpass(pnode(lists.locationlist[i])^);
  427. {$ifdef csedebug}
  428. printnode(output,statements);
  429. {$endif csedebug}
  430. end
  431. { current node reference to another node? }
  432. else if lists.equalto[i]<>pointer(-1) then
  433. begin
  434. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  435. { we cannot handle register stored records or array in CSE yet
  436. but we can store their reference }
  437. addrstored:=((def.typ in [arraydef,recorddef]) or is_object(def)) and not(is_dynamic_array(def));
  438. {$if defined(csedebug) or defined(csestats)}
  439. writeln;
  440. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  441. writeln('Complexity: ',node_complexity(tnode(lists.nodelist[i])),' Node ',i,' equals Node ',ptrint(lists.equalto[i]));
  442. printnode(output,tnode(lists.nodelist[i]));
  443. printnode(output,tnode(lists.nodelist[ptrint(lists.equalto[i])]));
  444. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  445. writeln;
  446. {$endif defined(csedebug) or defined(csestats)}
  447. templist[i]:=templist[ptrint(lists.equalto[i])];
  448. if addrstored then
  449. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])])))
  450. else
  451. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])]));
  452. { make debugging easier and set temp. location to the original location }
  453. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  454. do_firstpass(pnode(lists.locationlist[i])^);
  455. end;
  456. end;
  457. { clean up unused trees }
  458. for i:=0 to lists.nodelist.count-1 do
  459. if lists.equalto[i]<>pointer(-1) then
  460. tnode(lists.nodelist[i]).free;
  461. {$ifdef csedebug}
  462. writeln('nodes: ',lists.nodelist.count);
  463. writeln('==========================================');
  464. {$endif csedebug}
  465. lists.nodelist.free;
  466. lists.locationlist.free;
  467. lists.equalto.free;
  468. lists.refs.free;
  469. templist.free;
  470. if assigned(statements) then
  471. begin
  472. { call para nodes need a special handling because
  473. they can be only children nodes of call nodes
  474. so the initialization code is inserted below the
  475. call para node
  476. }
  477. if n.nodetype=callparan then
  478. begin
  479. addstatement(statements,tcallparanode(n).left);
  480. tcallparanode(n).left:=nodes;
  481. do_firstpass(tcallparanode(n).left);
  482. end
  483. else
  484. begin
  485. addstatement(statements,n);
  486. n:=nodes;
  487. do_firstpass(n);
  488. end;
  489. {$ifdef csedebug}
  490. printnode(output,nodes);
  491. {$endif csedebug}
  492. end;
  493. end
  494. end;
  495. end;
  496. function do_optcse(var rootnode : tnode) : tnode;
  497. var
  498. deletes,
  499. statements : tstatementnode;
  500. deleteblock,
  501. rootblock : tblocknode;
  502. begin
  503. {$ifdef csedebug}
  504. writeln('====================================================================================');
  505. writeln('CSE optimization pass started');
  506. writeln('====================================================================================');
  507. printnode(rootnode);
  508. writeln('====================================================================================');
  509. writeln;
  510. {$endif csedebug}
  511. deleteblock:=internalstatements(deletes);
  512. foreachnodestatic(pm_postprocess,rootnode,@searchcsedomain,@deletes);
  513. rootblock:=internalstatements(statements);
  514. addstatement(statements,rootnode);
  515. addstatement(statements,deleteblock);
  516. rootnode:=rootblock;
  517. do_firstpass(rootnode);
  518. {$ifdef csedebug}
  519. writeln('====================================================================================');
  520. writeln('CSE optimization result');
  521. writeln('====================================================================================');
  522. printnode(rootnode);
  523. writeln('====================================================================================');
  524. writeln;
  525. {$endif csedebug}
  526. result:=nil;
  527. end;
  528. type
  529. tconstentry = record
  530. valuenode : tnode;
  531. weight : TCGInt;
  532. temp : ttempcreatenode;
  533. end;
  534. pconstentry = ^tconstentry;
  535. tconstentries = array of tconstentry;
  536. pconstentries = ^tconstentries;
  537. function CSEOnReference(n : tnode) : Boolean;
  538. begin
  539. Result:=(n.nodetype=loadn) and (tloadnode(n).symtableentry.typ=staticvarsym)
  540. and ((vo_is_thread_var in tstaticvarsym(tloadnode(n).symtableentry).varoptions)
  541. {$if defined(aarch64)}
  542. or (not(tabstractvarsym(tloadnode(n).symtableentry).is_regvar(false)))
  543. {$endif defined(aarch64)}
  544. );
  545. end;
  546. function collectconsts(var n:tnode; arg: pointer) : foreachnoderesult;
  547. var
  548. consts: pconstentries;
  549. found: Boolean;
  550. i: Integer;
  551. begin
  552. result:=fen_true;
  553. consts:=pconstentries(arg);
  554. if ((n.nodetype=realconstn)
  555. {$ifdef x86}
  556. { x87 consts would end up in memory, so loading them in temps. makes no sense }
  557. and use_vectorfpu(n.resultdef)
  558. {$endif x86}
  559. ) or
  560. CSEOnReference(n) then
  561. begin
  562. found:=false;
  563. i:=0;
  564. for i:=0 to High(consts^) do
  565. begin
  566. if tnode(consts^[i].valuenode).isequal(n) then
  567. begin
  568. found:=true;
  569. break;
  570. end;
  571. end;
  572. if found then
  573. inc(consts^[i].weight)
  574. else
  575. begin
  576. SetLength(consts^,length(consts^)+1);
  577. with consts^[high(consts^)] do
  578. begin
  579. valuenode:=n.getcopy;
  580. valuenode.fileinfo:=current_procinfo.entrypos;
  581. weight:=1;
  582. end;
  583. end;
  584. end;
  585. end;
  586. function replaceconsts(var n:tnode; arg: pointer) : foreachnoderesult;
  587. var
  588. hp: tnode;
  589. begin
  590. result:=fen_true;
  591. if tnode(pconstentry(arg)^.valuenode).isequal(n) then
  592. begin
  593. { shall we take the address? }
  594. if CSEOnReference(pconstentry(arg)^.valuenode) then
  595. begin
  596. hp:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(pconstentry(arg)^.temp)),pconstentry(arg)^.valuenode.resultdef);
  597. ttypeconvnode(hp).left.fileinfo:=n.fileinfo;
  598. end
  599. else
  600. hp:=ctemprefnode.create(pconstentry(arg)^.temp);
  601. hp.fileinfo:=n.fileinfo;
  602. n.Free;
  603. n:=hp;
  604. do_firstpass(n);
  605. end;
  606. end;
  607. function do_consttovar(var rootnode : tnode) : tnode;
  608. var
  609. constentries : tconstentries;
  610. Procedure QuickSort(L, R : Longint);
  611. var
  612. I, J, P: Longint;
  613. Item, Q : tconstentry;
  614. begin
  615. repeat
  616. I := L;
  617. J := R;
  618. P := (L + R) div 2;
  619. repeat
  620. Item := constentries[P];
  621. while Item.weight>constentries[I].weight do
  622. I := I + 1;
  623. while Item.weight<constentries[J].weight do
  624. J := J - 1;
  625. If I <= J then
  626. begin
  627. Q := constentries[I];
  628. constentries[I] := constentries[J];
  629. constentries[J] := Q;
  630. if P = I then
  631. P := J
  632. else if P = J then
  633. P := I;
  634. I := I + 1;
  635. J := J - 1;
  636. end;
  637. until I > J;
  638. if L < J then
  639. QuickSort(L, J);
  640. L := I;
  641. until I >= R;
  642. end;
  643. var
  644. creates,
  645. deletes,
  646. statements : tstatementnode;
  647. createblock,
  648. deleteblock,
  649. rootblock : tblocknode;
  650. i, max_fpu_regs_assigned, fpu_regs_assigned,
  651. max_int_regs_assigned, int_regs_assigned: Integer;
  652. old_current_filepos: tfileposinfo;
  653. begin
  654. {$ifdef csedebug}
  655. writeln('====================================================================================');
  656. writeln('Const optimization pass started');
  657. writeln('====================================================================================');
  658. printnode(rootnode);
  659. writeln('====================================================================================');
  660. writeln;
  661. {$endif csedebug}
  662. foreachnodestatic(pm_postprocess,rootnode,@collectconsts,@constentries);
  663. createblock:=nil;
  664. deleteblock:=nil;
  665. rootblock:=nil;
  666. { estimate how many int registers can be used }
  667. if pi_do_call in current_procinfo.flags then
  668. max_int_regs_assigned:=length(paramanager.get_saved_registers_int(current_procinfo.procdef.proccalloption))
  669. { we store only addresses, so take care of the relation between address sizes and register sizes }
  670. div (sizeof(PtrUInt) div sizeof(ALUUInt))
  671. { heuristics, just use a quarter of all registers at maximum }
  672. div 4
  673. else
  674. max_int_regs_assigned:=max(first_int_imreg div 4,1);
  675. {$if defined(x86) or defined(aarch64) or defined(arm)}
  676. { x86, aarch64 and arm (neglecting fpa) use mm registers for floats }
  677. if pi_do_call in current_procinfo.flags then
  678. { heuristics, just use a fifth of all registers at maximum }
  679. max_fpu_regs_assigned:=length(paramanager.get_saved_registers_mm(current_procinfo.procdef.proccalloption)) div 5
  680. else
  681. max_fpu_regs_assigned:=max(first_mm_imreg div 5,1);
  682. {$else defined(x86) or defined(aarch64) or defined(arm)}
  683. if pi_do_call in current_procinfo.flags then
  684. { heuristics, just use a fifth of all registers at maximum }
  685. max_fpu_regs_assigned:=length(paramanager.get_saved_registers_fpu(current_procinfo.procdef.proccalloption)) div 5
  686. else
  687. max_fpu_regs_assigned:=max(first_fpu_imreg div 5,1);
  688. {$endif defined(x86) or defined(aarch64) or defined(arm)}
  689. fpu_regs_assigned:=0;
  690. int_regs_assigned:=0;
  691. if Length(constentries)>0 then
  692. begin
  693. { sort entries by weight }
  694. QuickSort(0,High(constentries));
  695. { assign only the constants with the highest weight to a register }
  696. for i:=High(constentries) downto 0 do
  697. begin
  698. if (constentries[i].valuenode.nodetype=realconstn) and
  699. { if there is a call, we need most likely to save/restore a register }
  700. ((constentries[i].weight>3) or
  701. ((constentries[i].weight>1) and not(pi_do_call in current_procinfo.flags)))
  702. then
  703. begin
  704. if fpu_regs_assigned>=max_fpu_regs_assigned then
  705. break;
  706. old_current_filepos:=current_filepos;
  707. current_filepos:=current_procinfo.entrypos;
  708. if not(assigned(createblock)) then
  709. begin
  710. rootblock:=internalstatements(statements);
  711. createblock:=internalstatements(creates);
  712. deleteblock:=internalstatements(deletes);
  713. end;
  714. constentries[i].temp:=ctempcreatenode.create(constentries[i].valuenode.resultdef,
  715. constentries[i].valuenode.resultdef.size,tt_persistent,true);
  716. addstatement(creates,constentries[i].temp);
  717. addstatement(creates,cassignmentnode.create_internal(ctemprefnode.create(constentries[i].temp),constentries[i].valuenode));
  718. current_filepos:=old_current_filepos;
  719. foreachnodestatic(pm_postprocess,rootnode,@replaceconsts,@constentries[i]);
  720. inc(fpu_regs_assigned);
  721. end
  722. else if CSEOnReference(constentries[i].valuenode) and
  723. { if there is a call, we need most likely to save/restore a register }
  724. ((constentries[i].weight>2) or
  725. ((constentries[i].weight>1) and not(pi_do_call in current_procinfo.flags)))
  726. then
  727. begin
  728. if int_regs_assigned>=max_int_regs_assigned then
  729. break;
  730. old_current_filepos:=current_filepos;
  731. current_filepos:=current_procinfo.entrypos;
  732. if not(assigned(createblock)) then
  733. begin
  734. rootblock:=internalstatements(statements);
  735. createblock:=internalstatements(creates);
  736. deleteblock:=internalstatements(deletes);
  737. end;
  738. constentries[i].temp:=ctempcreatenode.create(voidpointertype,
  739. voidpointertype.size,tt_persistent,true);
  740. addstatement(creates,constentries[i].temp);
  741. addstatement(creates,cassignmentnode.create_internal(ctemprefnode.create(constentries[i].temp),
  742. caddrnode.create_internal(constentries[i].valuenode)));
  743. current_filepos:=old_current_filepos;
  744. foreachnodestatic(pm_postprocess,rootnode,@replaceconsts,@constentries[i]);
  745. inc(int_regs_assigned);
  746. end;
  747. end;
  748. end;
  749. if assigned(createblock) then
  750. begin
  751. addstatement(statements,createblock);
  752. addstatement(statements,rootnode);
  753. addstatement(statements,deleteblock);
  754. rootnode:=rootblock;
  755. do_firstpass(rootnode);
  756. end;
  757. {$ifdef csedebug}
  758. writeln('====================================================================================');
  759. writeln('Const optimization result');
  760. writeln('====================================================================================');
  761. printnode(rootnode);
  762. writeln('====================================================================================');
  763. writeln;
  764. {$endif csedebug}
  765. result:=nil;
  766. end;
  767. end.