optcse.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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,
  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}];
  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 (n.flags*[nf_write,nf_modify]=[]) and
  105. { node possible to add? }
  106. assigned(n.resultdef) and
  107. (
  108. ((tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable) and
  109. { is_int/fpuregable allows arrays and records to be in registers, cse cannot handle this }
  110. (not(n.resultdef.typ in [arraydef,recorddef])) and
  111. { same for voiddef }
  112. not(is_void(n.resultdef)) and
  113. { adding tempref nodes is worthless but their complexity is probably <= 1 anyways }
  114. not(n.nodetype in [temprefn]) and
  115. { node worth to add?
  116. We consider almost every node because even loading a variables from
  117. a register instead of memory is more beneficial. This behaviour should
  118. not increase register pressure because if a variable is already
  119. in a register, the reg. allocator can merge the nodes. If a variable
  120. is loaded from memory, loading this variable and spilling another register
  121. should not add a speed penalty.
  122. }
  123. {
  124. load nodes are not considered if they load para or local symbols from the
  125. current stack frame, those are in registers anyways if possible
  126. }
  127. (not(n.nodetype=loadn) or
  128. not(tloadnode(n).symtableentry.typ in [paravarsym,localvarsym]) or
  129. (tloadnode(n).symtable.symtablelevel<>current_procinfo.procdef.parast.symtablelevel)
  130. ) and
  131. {
  132. Const nodes however are only considered if their complexity is >1
  133. This might be the case for the risc architectures if they need
  134. more than one instruction to load this particular value
  135. }
  136. (not(is_constnode(n)) or (node_complexity(n)>1)))
  137. {$ifndef x86}
  138. or
  139. { loading the address of a global symbol takes typically more than
  140. one instruction on every platform except x86
  141. so consider in this case loading the address of the data
  142. }
  143. (((n.resultdef.typ in [arraydef,recorddef]) or is_object(n.resultdef)) and
  144. (n.nodetype=loadn) and
  145. (tloadnode(n).symtableentry.typ=staticvarsym)
  146. )
  147. {$endif x86}
  148. ) then
  149. begin
  150. plists(arg)^.nodelist.Add(n);
  151. plists(arg)^.locationlist.Add(@n);
  152. plists(arg)^.refs.Add(nil);
  153. plists(arg)^.equalto.Add(pointer(-1));
  154. DFASetInclude(plists(arg)^.avail,plists(arg)^.nodelist.count-1);
  155. for i:=0 to plists(arg)^.nodelist.count-2 do
  156. begin
  157. if tnode(plists(arg)^.nodelist[i]).isequal(n) and DFASetIn(plists(arg)^.avail,i) then
  158. begin
  159. { use always the first occurence }
  160. if plists(arg)^.equalto[i]<>pointer(-1) then
  161. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=plists(arg)^.equalto[i]
  162. else
  163. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=pointer(ptrint(i));
  164. plists(arg)^.refs[i]:=pointer(plists(arg)^.refs[i])+1;
  165. break;
  166. end;
  167. end;
  168. { boolean and/or require a special handling: after evaluating the and/or node,
  169. the expressions of the right side might not be available due to short boolean
  170. evaluation, so after handling the right side, mark those expressions
  171. as unavailable }
  172. if (n.nodetype in [orn,andn]) and is_boolean(taddnode(n).left.resultdef) then
  173. begin
  174. foreachnodestatic(pm_postprocess,taddnode(n).left,@collectnodes2,arg);
  175. j:=plists(arg)^.nodelist.count;
  176. foreachnodestatic(pm_postprocess,taddnode(n).right,@collectnodes2,arg);
  177. for i:=j to plists(arg)^.nodelist.count-1 do
  178. DFASetExclude(plists(arg)^.avail,i);
  179. result:=fen_norecurse_false;
  180. end;
  181. end;
  182. end;
  183. function searchcsedomain(var n: tnode; arg: pointer) : foreachnoderesult;
  184. var
  185. csedomain : boolean;
  186. lists : tlists;
  187. templist : tfplist;
  188. i : longint;
  189. def : tstoreddef;
  190. nodes : tblocknode;
  191. creates,
  192. statements : tstatementnode;
  193. hp : ttempcreatenode;
  194. addrstored : boolean;
  195. begin
  196. result:=fen_false;
  197. if n.nodetype in cseinvariant then
  198. begin
  199. csedomain:=true;
  200. foreachnodestatic(pm_postprocess,n,@searchsubdomain,@csedomain);
  201. { found a cse domain }
  202. if csedomain then
  203. begin
  204. statements:=nil;
  205. result:=fen_norecurse_true;
  206. {$ifdef csedebug}
  207. writeln('============ cse domain ==================');
  208. printnode(output,n);
  209. writeln('Complexity: ',node_complexity(n));
  210. {$endif csedebug}
  211. lists.nodelist:=tfplist.create;
  212. lists.locationlist:=tfplist.create;
  213. lists.equalto:=tfplist.create;
  214. lists.refs:=tfplist.create;
  215. foreachnodestatic(pm_postprocess,n,@collectnodes,@lists);
  216. templist:=tfplist.create;
  217. templist.count:=lists.nodelist.count;
  218. { check all nodes if one is used more than once }
  219. for i:=0 to lists.nodelist.count-1 do
  220. begin
  221. { current node used more than once? }
  222. if assigned(lists.refs[i]) then
  223. begin
  224. if not(assigned(statements)) then
  225. begin
  226. nodes:=internalstatements(statements);
  227. addstatement(statements,internalstatements(creates));
  228. end;
  229. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  230. { we cannot handle register stored records or array in CSE yet
  231. but we can store their reference }
  232. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  233. if addrstored then
  234. templist[i]:=ctempcreatenode.create_value(getpointerdef(def),voidpointertype.size,tt_persistent,
  235. true,caddrnode.create(tnode(lists.nodelist[i])))
  236. else
  237. templist[i]:=ctempcreatenode.create_value(def,def.size,tt_persistent,
  238. def.is_intregable or def.is_fpuregable,tnode(lists.nodelist[i]));
  239. { make debugging easier and set temp. location to the original location }
  240. tnode(templist[i]).fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  241. addstatement(creates,tnode(templist[i]));
  242. { make debugging easier and set temp. location to the original location }
  243. creates.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  244. hp:=ttempcreatenode(templist[i]);
  245. do_firstpass(tnode(hp));
  246. templist[i]:=hp;
  247. if addrstored then
  248. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[i])))
  249. else
  250. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[i]));
  251. { make debugging easier and set temp. location to the original location }
  252. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  253. do_firstpass(pnode(lists.locationlist[i])^);
  254. {$ifdef csedebug}
  255. printnode(output,statements);
  256. {$endif csedebug}
  257. end
  258. { current node reference to another node? }
  259. else if lists.equalto[i]<>pointer(-1) then
  260. begin
  261. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  262. { we cannot handle register stored records or array in CSE yet
  263. but we can store their reference }
  264. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  265. {$if defined(csedebug) or defined(csestats)}
  266. printnode(output,tnode(lists.nodelist[i]));
  267. writeln(i,' equals ',ptrint(lists.equalto[i]));
  268. printnode(output,tnode(lists.nodelist[ptrint(lists.equalto[i])]));
  269. {$endif defined(csedebug) or defined(csestats)}
  270. templist[i]:=templist[ptrint(lists.equalto[i])];
  271. if addrstored then
  272. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])])))
  273. else
  274. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])]));
  275. { make debugging easier and set temp. location to the original location }
  276. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  277. do_firstpass(pnode(lists.locationlist[i])^);
  278. end;
  279. end;
  280. { clean up unused trees }
  281. for i:=0 to lists.nodelist.count-1 do
  282. if lists.equalto[i]<>pointer(-1) then
  283. tnode(lists.nodelist[i]).free;
  284. {$ifdef csedebug}
  285. writeln('nodes: ',lists.nodelist.count);
  286. writeln('==========================================');
  287. {$endif csedebug}
  288. lists.nodelist.free;
  289. lists.locationlist.free;
  290. lists.equalto.free;
  291. lists.refs.free;
  292. templist.free;
  293. if assigned(statements) then
  294. begin
  295. { call para nodes need a special handling because
  296. they can be only children nodes of call nodes
  297. so the initialization code is inserted below the
  298. call para node
  299. }
  300. if n.nodetype=callparan then
  301. begin
  302. addstatement(statements,tcallparanode(n).left);
  303. tcallparanode(n).left:=nodes;
  304. do_firstpass(tcallparanode(n).left);
  305. end
  306. else
  307. begin
  308. addstatement(statements,n);
  309. n:=nodes;
  310. do_firstpass(n);
  311. end;
  312. {$ifdef csedebug}
  313. printnode(output,nodes);
  314. {$endif csedebug}
  315. end;
  316. end
  317. end;
  318. end;
  319. function do_optcse(var rootnode : tnode) : tnode;
  320. begin
  321. foreachnodestatic(pm_postprocess,rootnode,@searchcsedomain,nil);
  322. result:=nil;
  323. end;
  324. end.