optloop.pas 21 KB

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