optcse.pas 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. {
  2. Common subexpression elimination on base blocks
  3. Copyright (c) 2005 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 can be done too late
  28. - cse's in chained expressions are not recognized: the common subexpression
  29. in (a1 and b and c) vs. (a2 and b and c) is not recognized because there is no common
  30. subtree b and c
  31. - the cse knows nothing about register pressure. In case of high register pressure, cse might
  32. have a negative impact
  33. - assignment nodes are currently cse borders: things like a[i,j]:=a[i,j]+1; are not improved
  34. - the list of cseinvariant node types and inline numbers is not complete yet
  35. Further, it could be done probably in a faster way though the complexity can't probably not reduced
  36. }
  37. function do_optcse(var rootnode : tnode) : tnode;
  38. implementation
  39. uses
  40. globtype,globals,
  41. cclasses,
  42. verbose,
  43. nutils,
  44. procinfo,
  45. nbas,nld,ninl,ncal,ncnv,nadd,nmem,
  46. pass_1,
  47. symconst,symtype,symdef,symsym,
  48. defutil,
  49. optbase;
  50. const
  51. cseinvariant : set of tnodetype = [addn,muln,subn,divn,slashn,modn,andn,orn,xorn,notn,vecn,
  52. derefn,equaln,unequaln,ltn,gtn,lten,gten,typeconvn,subscriptn,
  53. inn,symdifn,shrn,shln,ordconstn,realconstn,unaryminusn,pointerconstn,stringconstn,setconstn,
  54. isn,asn,starstarn,nothingn,temprefn,loadparentfpn {,callparan},assignn];
  55. function searchsubdomain(var n:tnode; arg: pointer) : foreachnoderesult;
  56. begin
  57. if (n.nodetype in cseinvariant) or
  58. ((n.nodetype=inlinen) and
  59. (tinlinenode(n).inlinenumber in [in_assigned_x])
  60. ) or
  61. ((n.nodetype=loadn) and
  62. not((tloadnode(n).symtableentry.typ in [staticvarsym,localvarsym,paravarsym]) and
  63. (vo_volatile in tabstractvarsym(tloadnode(n).symtableentry).varoptions))
  64. ) then
  65. result:=fen_true
  66. else
  67. begin
  68. pboolean(arg)^:=false;
  69. result:=fen_norecurse_true;
  70. end;
  71. end;
  72. type
  73. tlists = record
  74. nodelist : tfplist;
  75. locationlist : tfplist;
  76. equalto : tfplist;
  77. refs : tfplist;
  78. avail : TDFASet;
  79. end;
  80. plists = ^tlists;
  81. { collectnodes needs the address of itself to call foreachnodestatic,
  82. so we need a wrapper because @<func> inside <func doesn't work }
  83. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;forward;
  84. function collectnodes2(var n:tnode; arg: pointer) : foreachnoderesult;
  85. begin
  86. result:=collectnodes(n,arg);
  87. end;
  88. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;
  89. var
  90. i,j : longint;
  91. begin
  92. result:=fen_false;
  93. { don't add the tree below an untyped const parameter: there is
  94. no information available that this kind of tree actually needs
  95. to be addresable, this could be improved }
  96. if ((n.nodetype=callparan) and
  97. (tcallparanode(n).left.resultdef.typ=formaldef) and
  98. (tcallparanode(n).parasym.varspez=vs_const)) then
  99. begin
  100. result:=fen_norecurse_false;
  101. exit;
  102. end;
  103. { so far, we can handle only nodes being read }
  104. if
  105. { node possible to add? }
  106. assigned(n.resultdef) and
  107. (
  108. { regable expressions }
  109. (n.actualtargetnode.flags*[nf_write,nf_modify]=[]) and
  110. ((tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable) and
  111. { is_int/fpuregable allows arrays and records to be in registers, cse cannot handle this }
  112. (not(n.resultdef.typ in [arraydef,recorddef])) and
  113. { same for voiddef }
  114. not(is_void(n.resultdef)) and
  115. { adding tempref nodes is worthless but their complexity is probably <= 1 anyways }
  116. not(n.nodetype in [temprefn]) and
  117. { node worth to add?
  118. We consider almost every node because even loading a variables from
  119. a register instead of memory is more beneficial. This behaviour should
  120. not increase register pressure because if a variable is already
  121. in a register, the reg. allocator can merge the nodes. If a variable
  122. is loaded from memory, loading this variable and spilling another register
  123. should not add a speed penalty.
  124. }
  125. {
  126. load nodes are not considered if they load para or local symbols from the
  127. current stack frame, those are in registers anyways if possible
  128. }
  129. (not(n.nodetype=loadn) or
  130. not(tloadnode(n).symtableentry.typ in [paravarsym,localvarsym]) or
  131. (tloadnode(n).symtable.symtablelevel<>current_procinfo.procdef.parast.symtablelevel)
  132. ) and
  133. {
  134. Const nodes however are only considered if their complexity is >1
  135. This might be the case for the risc architectures if they need
  136. more than one instruction to load this particular value
  137. }
  138. (not(is_constnode(n)) or (node_complexity(n)>1)))
  139. {$ifndef x86}
  140. or
  141. { store reference of expression? }
  142. { loading the address of a global symbol takes typically more than
  143. one instruction on every platform except x86
  144. so consider in this case loading the address of the data
  145. }
  146. (((n.resultdef.typ in [arraydef,recorddef]) or is_object(n.resultdef)) and
  147. (n.nodetype=loadn) and
  148. (tloadnode(n).symtableentry.typ=staticvarsym)
  149. )
  150. {$endif x86}
  151. ) then
  152. begin
  153. plists(arg)^.nodelist.Add(n);
  154. plists(arg)^.locationlist.Add(@n);
  155. plists(arg)^.refs.Add(nil);
  156. plists(arg)^.equalto.Add(pointer(-1));
  157. DFASetInclude(plists(arg)^.avail,plists(arg)^.nodelist.count-1);
  158. for i:=0 to plists(arg)^.nodelist.count-2 do
  159. begin
  160. if tnode(plists(arg)^.nodelist[i]).isequal(n) and DFASetIn(plists(arg)^.avail,i) then
  161. begin
  162. { use always the first occurence }
  163. if plists(arg)^.equalto[i]<>pointer(-1) then
  164. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=plists(arg)^.equalto[i]
  165. else
  166. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=pointer(ptrint(i));
  167. plists(arg)^.refs[i]:=pointer(plists(arg)^.refs[i])+1;
  168. break;
  169. end;
  170. end;
  171. { boolean and/or require a special handling: after evaluating the and/or node,
  172. the expressions of the right side might not be available due to short boolean
  173. evaluation, so after handling the right side, mark those expressions
  174. as unavailable }
  175. if (n.nodetype in [orn,andn]) and is_boolean(taddnode(n).left.resultdef) then
  176. begin
  177. foreachnodestatic(pm_postprocess,taddnode(n).left,@collectnodes2,arg);
  178. j:=plists(arg)^.nodelist.count;
  179. foreachnodestatic(pm_postprocess,taddnode(n).right,@collectnodes2,arg);
  180. for i:=j to plists(arg)^.nodelist.count-1 do
  181. DFASetExclude(plists(arg)^.avail,i);
  182. result:=fen_norecurse_false;
  183. end;
  184. end;
  185. end;
  186. function searchcsedomain(var n: tnode; arg: pointer) : foreachnoderesult;
  187. var
  188. csedomain : boolean;
  189. lists : tlists;
  190. templist : tfplist;
  191. i : longint;
  192. def : tstoreddef;
  193. nodes : tblocknode;
  194. creates,
  195. statements : tstatementnode;
  196. hp : ttempcreatenode;
  197. addrstored : boolean;
  198. hp2 : tnode;
  199. begin
  200. result:=fen_false;
  201. if n.nodetype in cseinvariant then
  202. begin
  203. csedomain:=true;
  204. foreachnodestatic(pm_postprocess,n,@searchsubdomain,@csedomain);
  205. if not(csedomain) then
  206. begin
  207. { try to transform the tree to get better cse domains, consider:
  208. +
  209. / \
  210. + C
  211. / \
  212. A B
  213. if A is not cse'able but B and C are, then the compiler cannot do cse so the tree is transformed into
  214. +
  215. / \
  216. A +
  217. / \
  218. B C
  219. Because A could be another tree of this kind, the whole process is done in a while loop
  220. }
  221. if (n.nodetype in [andn,orn,addn,muln]) and
  222. (n.nodetype=tbinarynode(n).left.nodetype) and
  223. { do is optimizations only for integers, reals (no currency!), vectors and sets }
  224. (is_integer(n.resultdef) or is_real(n.resultdef) or is_vector(n.resultdef) or is_set(n.resultdef)) and
  225. { either if fastmath is on }
  226. ((cs_opt_fastmath in current_settings.optimizerswitches) or
  227. { or for the logical operators, they cannot overflow }
  228. (n.nodetype in [andn,orn]) or
  229. { or for integers if range checking is off }
  230. ((is_integer(n.resultdef) and
  231. (n.localswitches*[cs_check_range,cs_check_overflow]=[]) and
  232. (tbinarynode(n).left.localswitches*[cs_check_range,cs_check_overflow]=[]))) or
  233. { for sets, we can do this always }
  234. (is_set(n.resultdef))
  235. ) then
  236. while n.nodetype=tbinarynode(n).left.nodetype do
  237. begin
  238. csedomain:=true;
  239. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@searchsubdomain,@csedomain);
  240. if csedomain then
  241. begin
  242. csedomain:=true;
  243. foreachnodestatic(pm_postprocess,tbinarynode(tbinarynode(n).left).right,@searchsubdomain,@csedomain);
  244. if csedomain then
  245. begin
  246. hp2:=tbinarynode(tbinarynode(n).left).left;
  247. tbinarynode(tbinarynode(n).left).left:=tbinarynode(tbinarynode(n).left).right;
  248. tbinarynode(tbinarynode(n).left).right:=tbinarynode(n).right;
  249. tbinarynode(n).right:=tbinarynode(n).left;
  250. tbinarynode(n).left:=hp2;
  251. { the transformed tree could result in new possibilities to fold constants
  252. so force a firstpass on the root node }
  253. exclude(tbinarynode(n).right.flags,nf_pass1_done);
  254. do_firstpass(tbinarynode(n).right);
  255. end
  256. else
  257. break;
  258. end
  259. else
  260. break;
  261. end;
  262. end
  263. else
  264. begin
  265. statements:=nil;
  266. result:=fen_norecurse_true;
  267. {$ifdef csedebug}
  268. writeln('============ cse domain ==================');
  269. printnode(output,n);
  270. writeln('Complexity: ',node_complexity(n));
  271. {$endif csedebug}
  272. lists.nodelist:=tfplist.create;
  273. lists.locationlist:=tfplist.create;
  274. lists.equalto:=tfplist.create;
  275. lists.refs:=tfplist.create;
  276. foreachnodestatic(pm_postprocess,n,@collectnodes,@lists);
  277. templist:=tfplist.create;
  278. templist.count:=lists.nodelist.count;
  279. { check all nodes if one is used more than once }
  280. for i:=0 to lists.nodelist.count-1 do
  281. begin
  282. { current node used more than once? }
  283. if assigned(lists.refs[i]) then
  284. begin
  285. if not(assigned(statements)) then
  286. begin
  287. nodes:=internalstatements(statements);
  288. addstatement(statements,internalstatements(creates));
  289. end;
  290. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  291. { we cannot handle register stored records or array in CSE yet
  292. but we can store their reference }
  293. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  294. if addrstored then
  295. templist[i]:=ctempcreatenode.create_value(getpointerdef(def),voidpointertype.size,tt_persistent,
  296. true,caddrnode.create(tnode(lists.nodelist[i])))
  297. else
  298. templist[i]:=ctempcreatenode.create_value(def,def.size,tt_persistent,
  299. def.is_intregable or def.is_fpuregable,tnode(lists.nodelist[i]));
  300. { make debugging easier and set temp. location to the original location }
  301. tnode(templist[i]).fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  302. addstatement(creates,tnode(templist[i]));
  303. { make debugging easier and set temp. location to the original location }
  304. creates.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  305. hp:=ttempcreatenode(templist[i]);
  306. do_firstpass(tnode(hp));
  307. templist[i]:=hp;
  308. if addrstored then
  309. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[i])))
  310. else
  311. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[i]));
  312. { make debugging easier and set temp. location to the original location }
  313. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  314. do_firstpass(pnode(lists.locationlist[i])^);
  315. {$ifdef csedebug}
  316. printnode(output,statements);
  317. {$endif csedebug}
  318. end
  319. { current node reference to another node? }
  320. else if lists.equalto[i]<>pointer(-1) then
  321. begin
  322. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  323. { we cannot handle register stored records or array in CSE yet
  324. but we can store their reference }
  325. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  326. {$if defined(csedebug) or defined(csestats)}
  327. printnode(output,tnode(lists.nodelist[i]));
  328. writeln(i,' equals ',ptrint(lists.equalto[i]));
  329. printnode(output,tnode(lists.nodelist[ptrint(lists.equalto[i])]));
  330. {$endif defined(csedebug) or defined(csestats)}
  331. templist[i]:=templist[ptrint(lists.equalto[i])];
  332. if addrstored then
  333. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])])))
  334. else
  335. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])]));
  336. { make debugging easier and set temp. location to the original location }
  337. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  338. do_firstpass(pnode(lists.locationlist[i])^);
  339. end;
  340. end;
  341. { clean up unused trees }
  342. for i:=0 to lists.nodelist.count-1 do
  343. if lists.equalto[i]<>pointer(-1) then
  344. tnode(lists.nodelist[i]).free;
  345. {$ifdef csedebug}
  346. writeln('nodes: ',lists.nodelist.count);
  347. writeln('==========================================');
  348. {$endif csedebug}
  349. lists.nodelist.free;
  350. lists.locationlist.free;
  351. lists.equalto.free;
  352. lists.refs.free;
  353. templist.free;
  354. if assigned(statements) then
  355. begin
  356. { call para nodes need a special handling because
  357. they can be only children nodes of call nodes
  358. so the initialization code is inserted below the
  359. call para node
  360. }
  361. if n.nodetype=callparan then
  362. begin
  363. addstatement(statements,tcallparanode(n).left);
  364. tcallparanode(n).left:=nodes;
  365. do_firstpass(tcallparanode(n).left);
  366. end
  367. else
  368. begin
  369. addstatement(statements,n);
  370. n:=nodes;
  371. do_firstpass(n);
  372. end;
  373. {$ifdef csedebug}
  374. printnode(output,nodes);
  375. {$endif csedebug}
  376. end;
  377. end
  378. end;
  379. end;
  380. function do_optcse(var rootnode : tnode) : tnode;
  381. begin
  382. foreachnodestatic(pm_postprocess,rootnode,@searchcsedomain,nil);
  383. result:=nil;
  384. end;
  385. end.