optloop.pas 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. {
  2. Loop optimization
  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 optloop;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. node;
  22. function unroll_loop(node : tnode) : tnode;
  23. function OptimizeInductionVariables(node : tnode) : boolean;
  24. implementation
  25. uses
  26. cutils,cclasses,
  27. globtype,globals,constexp,
  28. symdef,symsym,
  29. defutil,
  30. cpuinfo,
  31. nutils,
  32. nadd,nbas,nflw,ncon,ninl,ncal,nld,nmem,ncnv,
  33. ncgmem,
  34. pass_1,
  35. optbase,optutils,
  36. procinfo;
  37. function number_unrolls(node : tnode) : cardinal;
  38. begin
  39. {$ifdef i386}
  40. { multiply by 2 for CPUs with a long pipeline }
  41. if current_settings.optimizecputype in [cpu_Pentium4] then
  42. number_unrolls:=60 div node_count(node)
  43. else
  44. {$endif i386}
  45. number_unrolls:=30 div node_count(node);
  46. if number_unrolls=0 then
  47. number_unrolls:=1;
  48. end;
  49. type
  50. treplaceinfo = record
  51. node : tnode;
  52. value : Tconstexprint;
  53. end;
  54. preplaceinfo = ^treplaceinfo;
  55. function checkbreakcontinue(var n:tnode; arg: pointer): foreachnoderesult;
  56. begin
  57. if n.nodetype in [breakn,continuen] then
  58. result:=fen_norecurse_true
  59. else
  60. result:=fen_false;
  61. end;
  62. function replaceloadnodes(var n: tnode; arg: pointer): foreachnoderesult;
  63. begin
  64. if ((n.nodetype=loadn) and (preplaceinfo(arg)^.node.nodetype=loadn) and
  65. (tloadnode(n).symtableentry=tloadnode(preplaceinfo(arg)^.node).symtableentry)) or
  66. ((n.nodetype=temprefn) and (preplaceinfo(arg)^.node.nodetype=temprefn) and
  67. (ttemprefnode(n).tempinfo=ttemprefnode(preplaceinfo(arg)^.node).tempinfo)) then
  68. begin
  69. if n.flags*[nf_modify,nf_write]<>[] then
  70. internalerror(2012090402);
  71. n.free;
  72. n:=cordconstnode.create(preplaceinfo(arg)^.value,preplaceinfo(arg)^.node.resultdef,false);
  73. end;
  74. result:=fen_false;
  75. end;
  76. function unroll_loop(node : tnode) : tnode;
  77. var
  78. unrolls,i : cardinal;
  79. counts : qword;
  80. unrollstatement,newforstatement : tstatementnode;
  81. unrollblock : tblocknode;
  82. getridoffor : boolean;
  83. replaceinfo : treplaceinfo;
  84. usesbreakcontinue : boolean;
  85. begin
  86. result:=nil;
  87. if (cs_opt_size in current_settings.optimizerswitches) then
  88. exit;
  89. if not(node.nodetype in [forn]) then
  90. exit;
  91. unrolls:=number_unrolls(tfornode(node).t2);
  92. if unrolls>1 then
  93. begin
  94. { number of executions known? }
  95. if (tfornode(node).right.nodetype=ordconstn) and (tfornode(node).t1.nodetype=ordconstn) then
  96. begin
  97. if lnf_backward in tfornode(node).loopflags then
  98. counts:=tordconstnode(tfornode(node).right).value-tordconstnode(tfornode(node).t1).value+1
  99. else
  100. counts:=tordconstnode(tfornode(node).t1).value-tordconstnode(tfornode(node).right).value+1;
  101. usesbreakcontinue:=foreachnodestatic(tfornode(node).t2,@checkbreakcontinue,nil);
  102. { don't unroll more than we need,
  103. multiply unroll by two here because we can get rid
  104. of the counter variable completely and replace it by a constant
  105. if unrolls=counts }
  106. if unrolls*2>counts then
  107. unrolls:=counts;
  108. { create block statement }
  109. unrollblock:=internalstatements(unrollstatement);
  110. { can we get rid completly of the for ? }
  111. getridoffor:=(unrolls=counts) and not(usesbreakcontinue);
  112. if getridoffor then
  113. begin
  114. if not(tfornode(node).left.nodetype in [temprefn,loadn]) then
  115. internalerror(2012090301);
  116. replaceinfo.node:=tfornode(node).left;
  117. replaceinfo.value:=tordconstnode(tfornode(node).right).value;
  118. end;
  119. { let's unroll (and rock of course) }
  120. for i:=1 to unrolls do
  121. begin
  122. { create and insert copy of the statement block }
  123. addstatement(unrollstatement,tfornode(node).t2.getcopy);
  124. { set and insert entry label? }
  125. if (counts mod unrolls<>0) and
  126. ((counts mod unrolls)=unrolls-i) then
  127. begin
  128. tfornode(node).entrylabel:=clabelnode.create(cnothingnode.create,tlabelsym.create('$optunrol'));
  129. addstatement(unrollstatement,tfornode(node).entrylabel);
  130. end;
  131. if getridoffor then
  132. begin
  133. foreachnodestatic(tnode(unrollstatement),@replaceloadnodes,@replaceinfo);
  134. if lnf_backward in tfornode(node).loopflags then
  135. replaceinfo.value:=replaceinfo.value-1
  136. else
  137. replaceinfo.value:=replaceinfo.value+1;
  138. end
  139. else
  140. begin
  141. { for itself increases at the last iteration }
  142. if i<unrolls then
  143. begin
  144. { insert incr/decrementation of counter var }
  145. if lnf_backward in tfornode(node).loopflags then
  146. addstatement(unrollstatement,
  147. geninlinenode(in_dec_x,false,ccallparanode.create(tfornode(node).left.getcopy,nil)))
  148. else
  149. addstatement(unrollstatement,
  150. geninlinenode(in_inc_x,false,ccallparanode.create(tfornode(node).left.getcopy,nil)));
  151. end;
  152. end;
  153. end;
  154. { can we get rid of the for statement? }
  155. if getridoffor then
  156. begin
  157. { create block statement }
  158. result:=internalstatements(newforstatement);
  159. addstatement(newforstatement,unrollblock);
  160. end;
  161. end
  162. else
  163. begin
  164. { unrolling is a little bit more tricky if we don't know the
  165. loop count at compile time, but the solution is to use a jump table
  166. which is indexed by "loop count mod unrolls" at run time and which
  167. jumps then at the appropriate place inside the loop. Because
  168. a module division is expensive, we can use only unroll counts dividable
  169. by 2 }
  170. case unrolls of
  171. 1..2:
  172. ;
  173. 3:
  174. unrolls:=2;
  175. 4..7:
  176. unrolls:=4;
  177. { unrolls>4 already make no sense imo, but who knows (FK) }
  178. 8..15:
  179. unrolls:=8;
  180. 16..31:
  181. unrolls:=16;
  182. 32..63:
  183. unrolls:=32;
  184. 64..$7fff:
  185. unrolls:=64;
  186. else
  187. exit;
  188. end;
  189. { we don't handle this yet }
  190. exit;
  191. end;
  192. if not(assigned(result)) then
  193. begin
  194. tfornode(node).t2.free;
  195. tfornode(node).t2:=unrollblock;
  196. end;
  197. end;
  198. end;
  199. var
  200. initcode,
  201. calccode,
  202. deletecode : tblocknode;
  203. initcodestatements,
  204. calccodestatements,
  205. deletecodestatements: tstatementnode;
  206. templist : tfplist;
  207. inductionexprs : tfplist;
  208. changedforloop,
  209. containsnestedforloop : boolean;
  210. function is_loop_invariant(loop : tnode;expr : tnode) : boolean;
  211. begin
  212. result:=is_constnode(expr);
  213. case expr.nodetype of
  214. loadn:
  215. begin
  216. if (pi_dfaavailable in current_procinfo.flags) and
  217. assigned(loop.optinfo) and
  218. assigned(expr.optinfo) then
  219. { no aliasing? }
  220. result:=not(tabstractvarsym(tloadnode(expr).symtableentry).addr_taken) and
  221. { no definition in the loop? }
  222. not(DFASetIn(loop.optinfo^.defsum,expr.optinfo^.index));
  223. end;
  224. vecn:
  225. begin
  226. result:=((tvecnode(expr).left.nodetype=loadn) or is_loop_invariant(loop,tvecnode(expr).left)) and
  227. is_loop_invariant(loop,tvecnode(expr).right);
  228. end;
  229. typeconvn:
  230. result:=is_loop_invariant(loop,ttypeconvnode(expr).left);
  231. end;
  232. end;
  233. { checks if the strength of n can be recuded, arg is the tforloop being considered }
  234. function dostrengthreductiontest(var n: tnode; arg: pointer): foreachnoderesult;
  235. function findpreviousstrengthreduction : boolean;
  236. var
  237. i : longint;
  238. begin
  239. result:=false;
  240. for i:=0 to inductionexprs.count-1 do
  241. begin
  242. { do we already maintain one expression? }
  243. if tnode(inductionexprs[i]).isequal(n) then
  244. begin
  245. n.free;
  246. case n.nodetype of
  247. muln:
  248. n:=ctemprefnode.create(ttempcreatenode(templist[i]));
  249. vecn:
  250. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(
  251. ttempcreatenode(templist[i]))),n.resultdef);
  252. else
  253. internalerror(200809211);
  254. end;
  255. result:=true;
  256. exit;
  257. end;
  258. end;
  259. end;
  260. procedure CreateNodes;
  261. begin
  262. if not assigned(initcode) then
  263. begin
  264. initcode:=internalstatements(initcodestatements);
  265. calccode:=internalstatements(calccodestatements);
  266. deletecode:=internalstatements(deletecodestatements);
  267. end;
  268. end;
  269. var
  270. tempnode : ttempcreatenode;
  271. dummy : longint;
  272. begin
  273. result:=fen_false;
  274. case n.nodetype of
  275. forn:
  276. { inform for loop search routine, that it needs to search more deeply }
  277. containsnestedforloop:=true;
  278. muln:
  279. begin
  280. if (taddnode(n).right.nodetype=loadn) and
  281. taddnode(n).right.isequal(tfornode(arg).left) and
  282. { plain read of the loop variable? }
  283. not(nf_write in taddnode(n).right.flags) and
  284. not(nf_modify in taddnode(n).right.flags) and
  285. is_loop_invariant(tfornode(arg),taddnode(n).left) and
  286. { for now, we can handle only constant lower borders }
  287. is_constnode(tfornode(arg).right) then
  288. taddnode(n).swapleftright;
  289. if (taddnode(n).left.nodetype=loadn) and
  290. taddnode(n).left.isequal(tfornode(arg).left) and
  291. { plain read of the loop variable? }
  292. not(nf_write in taddnode(n).left.flags) and
  293. not(nf_modify in taddnode(n).left.flags) and
  294. is_loop_invariant(tfornode(arg),taddnode(n).right) and
  295. { for now, we can handle only constant lower borders }
  296. is_constnode(tfornode(arg).right) then
  297. begin
  298. changedforloop:=true;
  299. { did we use the same expression before already? }
  300. if not(findpreviousstrengthreduction) then
  301. begin
  302. tempnode:=ctempcreatenode.create(n.resultdef,n.resultdef.size,tt_persistent,
  303. tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable);
  304. templist.Add(tempnode);
  305. inductionexprs.Add(n);
  306. CreateNodes;
  307. if lnf_backward in tfornode(arg).loopflags then
  308. addstatement(calccodestatements,
  309. geninlinenode(in_dec_x,false,
  310. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))))
  311. else
  312. addstatement(calccodestatements,
  313. geninlinenode(in_inc_x,false,
  314. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))));
  315. addstatement(initcodestatements,tempnode);
  316. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  317. caddnode.create(muln,
  318. caddnode.create(subn,tfornode(arg).right.getcopy,cordconstnode.create(1,tfornode(arg).right.resultdef,false)),
  319. taddnode(n).right.getcopy)
  320. )
  321. );
  322. { finally replace the node by a temp. ref }
  323. n:=ctemprefnode.create(tempnode);
  324. { ... and add a temp. release node }
  325. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  326. end;
  327. { set types }
  328. do_firstpass(n);
  329. result:=fen_norecurse_false;
  330. end;
  331. end;
  332. vecn:
  333. begin
  334. { is the index the counter variable? }
  335. if not(is_special_array(tvecnode(n).left.resultdef)) and
  336. (tvecnode(n).right.isequal(tfornode(arg).left) or
  337. { fpc usually creates a type cast to access an array }
  338. ((tvecnode(n).right.nodetype=typeconvn) and
  339. ttypeconvnode(tvecnode(n).right).left.isequal(tfornode(arg).left)
  340. )
  341. ) and
  342. { plain read of the loop variable? }
  343. not(nf_write in tvecnode(n).right.flags) and
  344. not(nf_modify in tvecnode(n).right.flags) and
  345. { direct array access? }
  346. ((tvecnode(n).left.nodetype=loadn) or
  347. { ... or loop invariant expression? }
  348. is_loop_invariant(tfornode(arg),tvecnode(n).left)) and
  349. { removing the multiplication is only worth the
  350. effort if it's not a simple shift }
  351. not(ispowerof2(tcgvecnode(n).get_mul_size,dummy)) then
  352. begin
  353. changedforloop:=true;
  354. { did we use the same expression before already? }
  355. if not(findpreviousstrengthreduction) then
  356. begin
  357. tempnode:=ctempcreatenode.create(voidpointertype,voidpointertype.size,tt_persistent,true);
  358. templist.Add(tempnode);
  359. inductionexprs.Add(n);
  360. CreateNodes;
  361. if lnf_backward in tfornode(arg).loopflags then
  362. addstatement(calccodestatements,
  363. geninlinenode(in_dec_x,false,
  364. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  365. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))))
  366. else
  367. addstatement(calccodestatements,
  368. geninlinenode(in_inc_x,false,
  369. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  370. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))));
  371. addstatement(initcodestatements,tempnode);
  372. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  373. caddrnode.create(
  374. cvecnode.create(tvecnode(n).left.getcopy,tfornode(arg).right.getcopy)
  375. )
  376. ));
  377. { finally replace the node by a temp. ref }
  378. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(tempnode)),n.resultdef);
  379. { ... and add a temp. release node }
  380. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  381. end;
  382. { set types }
  383. do_firstpass(n);
  384. result:=fen_norecurse_false;
  385. end;
  386. end;
  387. end;
  388. end;
  389. function OptimizeInductionVariablesSingleForLoop(node : tnode) : tnode;
  390. var
  391. loopcode : tblocknode;
  392. loopcodestatements,
  393. newcodestatements : tstatementnode;
  394. fornode : tfornode;
  395. begin
  396. result:=nil;
  397. if node.nodetype<>forn then
  398. exit;
  399. templist:=TFPList.Create;
  400. inductionexprs:=TFPList.Create;
  401. initcode:=nil;
  402. calccode:=nil;
  403. deletecode:=nil;
  404. initcodestatements:=nil;
  405. calccodestatements:=nil;
  406. deletecodestatements:=nil;
  407. { find all expressions being candidates for strength reduction
  408. and replace them }
  409. foreachnodestatic(pm_postprocess,node,@dostrengthreductiontest,node);
  410. { clue everything together }
  411. if assigned(initcode) then
  412. begin
  413. do_firstpass(tnode(initcode));
  414. do_firstpass(tnode(calccode));
  415. do_firstpass(tnode(deletecode));
  416. { create a new for node, the old one will be released by the compiler }
  417. with tfornode(node) do
  418. begin
  419. fornode:=cfornode.create(left,right,t1,t2,lnf_backward in loopflags);
  420. left:=nil;
  421. right:=nil;
  422. t1:=nil;
  423. t2:=nil;
  424. end;
  425. node:=fornode;
  426. loopcode:=internalstatements(loopcodestatements);
  427. addstatement(loopcodestatements,calccode);
  428. addstatement(loopcodestatements,tfornode(node).t2);
  429. tfornode(node).t2:=loopcode;
  430. do_firstpass(node);
  431. result:=internalstatements(newcodestatements);
  432. addstatement(newcodestatements,initcode);
  433. addstatement(newcodestatements,node);
  434. addstatement(newcodestatements,deletecode);
  435. end;
  436. templist.Free;
  437. inductionexprs.Free;
  438. end;
  439. function iterforloops(var n: tnode; arg: pointer): foreachnoderesult;
  440. var
  441. hp : tnode;
  442. begin
  443. Result:=fen_false;
  444. if n.nodetype=forn then
  445. begin
  446. { do we have DFA available? }
  447. if pi_dfaavailable in current_procinfo.flags then
  448. begin
  449. CalcDefSum(n);
  450. end;
  451. containsnestedforloop:=false;
  452. hp:=OptimizeInductionVariablesSingleForLoop(n);
  453. if assigned(hp) then
  454. begin
  455. n.Free;
  456. n:=hp;
  457. end;
  458. { can we avoid further searching? }
  459. if not(containsnestedforloop) then
  460. Result:=fen_norecurse_false;
  461. end;
  462. end;
  463. function OptimizeInductionVariables(node : tnode) : boolean;
  464. begin
  465. changedforloop:=false;
  466. foreachnodestatic(pm_postprocess,node,@iterforloops,nil);
  467. Result:=changedforloop;
  468. end;
  469. end.