optloop.pas 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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,
  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. {$ifdef i386}
  42. { multiply by 2 for CPUs with a long pipeline }
  43. if current_settings.optimizecputype in [cpu_Pentium4] then
  44. number_unrolls:=60 div node_count(node)
  45. else
  46. {$endif i386}
  47. number_unrolls:=30 div node_count(node);
  48. if number_unrolls=0 then
  49. number_unrolls:=1;
  50. end;
  51. type
  52. treplaceinfo = record
  53. node : tnode;
  54. value : Tconstexprint;
  55. end;
  56. preplaceinfo = ^treplaceinfo;
  57. function checkbreakcontinue(var n:tnode; arg: pointer): foreachnoderesult;
  58. begin
  59. if n.nodetype in [breakn,continuen] then
  60. result:=fen_norecurse_true
  61. else
  62. result:=fen_false;
  63. end;
  64. function replaceloadnodes(var n: tnode; arg: pointer): foreachnoderesult;
  65. begin
  66. if n.isequal(preplaceinfo(arg)^.node) then
  67. begin
  68. if n.flags*[nf_modify,nf_write,nf_address_taken]<>[] then
  69. internalerror(2012090402);
  70. n.free;
  71. n:=cordconstnode.create(preplaceinfo(arg)^.value,preplaceinfo(arg)^.node.resultdef,false);
  72. do_firstpass(n);
  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) and
  112. { TP/Macpas allows assignments to the for-variables, so we cannot get rid of the for }
  113. ([m_tp7,m_mac]*current_settings.modeswitches=[]);
  114. if getridoffor then
  115. begin
  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,clabelsym.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. doinlinesimplify(result);
  161. end;
  162. end
  163. else
  164. begin
  165. { unrolling is a little bit more tricky if we don't know the
  166. loop count at compile time, but the solution is to use a jump table
  167. which is indexed by "loop count mod unrolls" at run time and which
  168. jumps then at the appropriate place inside the loop. Because
  169. a module division is expensive, we can use only unroll counts dividable
  170. by 2 }
  171. case unrolls of
  172. 1..2:
  173. ;
  174. 3:
  175. unrolls:=2;
  176. 4..7:
  177. unrolls:=4;
  178. { unrolls>4 already make no sense imo, but who knows (FK) }
  179. 8..15:
  180. unrolls:=8;
  181. 16..31:
  182. unrolls:=16;
  183. 32..63:
  184. unrolls:=32;
  185. 64..$7fff:
  186. unrolls:=64;
  187. else
  188. exit;
  189. end;
  190. { we don't handle this yet }
  191. exit;
  192. end;
  193. if not(assigned(result)) then
  194. begin
  195. tfornode(node).t2.free;
  196. tfornode(node).t2:=unrollblock;
  197. end;
  198. end;
  199. end;
  200. var
  201. initcode,
  202. calccode,
  203. deletecode : tblocknode;
  204. initcodestatements,
  205. calccodestatements,
  206. deletecodestatements: tstatementnode;
  207. templist : tfplist;
  208. inductionexprs : tfplist;
  209. changedforloop,
  210. containsnestedforloop : boolean;
  211. function is_loop_invariant(loop : tnode;expr : tnode) : boolean;
  212. begin
  213. result:=is_constnode(expr);
  214. case expr.nodetype of
  215. loadn:
  216. begin
  217. if (pi_dfaavailable in current_procinfo.flags) and
  218. assigned(loop.optinfo) and
  219. assigned(expr.optinfo) then
  220. { no aliasing? }
  221. result:=not(tabstractvarsym(tloadnode(expr).symtableentry).addr_taken) and
  222. { no definition in the loop? }
  223. not(DFASetIn(loop.optinfo^.defsum,expr.optinfo^.index));
  224. end;
  225. vecn:
  226. begin
  227. result:=((tvecnode(expr).left.nodetype=loadn) or is_loop_invariant(loop,tvecnode(expr).left)) and
  228. is_loop_invariant(loop,tvecnode(expr).right);
  229. end;
  230. typeconvn:
  231. result:=is_loop_invariant(loop,ttypeconvnode(expr).left);
  232. end;
  233. end;
  234. { checks if the strength of n can be recuded, arg is the tforloop being considered }
  235. function dostrengthreductiontest(var n: tnode; arg: pointer): foreachnoderesult;
  236. function findpreviousstrengthreduction : boolean;
  237. var
  238. i : longint;
  239. begin
  240. result:=false;
  241. for i:=0 to inductionexprs.count-1 do
  242. begin
  243. { do we already maintain one expression? }
  244. if tnode(inductionexprs[i]).isequal(n) then
  245. begin
  246. n.free;
  247. case n.nodetype of
  248. muln:
  249. n:=ctemprefnode.create(ttempcreatenode(templist[i]));
  250. vecn:
  251. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(
  252. ttempcreatenode(templist[i]))),n.resultdef);
  253. else
  254. internalerror(200809211);
  255. end;
  256. result:=true;
  257. exit;
  258. end;
  259. end;
  260. end;
  261. procedure CreateNodes;
  262. begin
  263. if not assigned(initcode) then
  264. begin
  265. initcode:=internalstatements(initcodestatements);
  266. calccode:=internalstatements(calccodestatements);
  267. deletecode:=internalstatements(deletecodestatements);
  268. end;
  269. end;
  270. var
  271. tempnode : ttempcreatenode;
  272. dummy : longint;
  273. begin
  274. result:=fen_false;
  275. case n.nodetype of
  276. forn:
  277. { inform for loop search routine, that it needs to search more deeply }
  278. containsnestedforloop:=true;
  279. muln:
  280. begin
  281. if (taddnode(n).right.nodetype=loadn) and
  282. taddnode(n).right.isequal(tfornode(arg).left) and
  283. { plain read of the loop variable? }
  284. not(nf_write in taddnode(n).right.flags) and
  285. not(nf_modify in taddnode(n).right.flags) and
  286. is_loop_invariant(tfornode(arg),taddnode(n).left) and
  287. { for now, we can handle only constant lower borders }
  288. is_constnode(tfornode(arg).right) then
  289. taddnode(n).swapleftright;
  290. if (taddnode(n).left.nodetype=loadn) and
  291. taddnode(n).left.isequal(tfornode(arg).left) and
  292. { plain read of the loop variable? }
  293. not(nf_write in taddnode(n).left.flags) and
  294. not(nf_modify in taddnode(n).left.flags) and
  295. is_loop_invariant(tfornode(arg),taddnode(n).right) and
  296. { for now, we can handle only constant lower borders }
  297. is_constnode(tfornode(arg).right) then
  298. begin
  299. changedforloop:=true;
  300. { did we use the same expression before already? }
  301. if not(findpreviousstrengthreduction) then
  302. begin
  303. tempnode:=ctempcreatenode.create(n.resultdef,n.resultdef.size,tt_persistent,
  304. tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable);
  305. templist.Add(tempnode);
  306. inductionexprs.Add(n);
  307. CreateNodes;
  308. if lnf_backward in tfornode(arg).loopflags then
  309. addstatement(calccodestatements,
  310. geninlinenode(in_dec_x,false,
  311. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))))
  312. else
  313. addstatement(calccodestatements,
  314. geninlinenode(in_inc_x,false,
  315. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))));
  316. addstatement(initcodestatements,tempnode);
  317. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  318. caddnode.create(muln,
  319. caddnode.create(subn,tfornode(arg).right.getcopy,cordconstnode.create(1,tfornode(arg).right.resultdef,false)),
  320. taddnode(n).right.getcopy)
  321. )
  322. );
  323. { finally replace the node by a temp. ref }
  324. n:=ctemprefnode.create(tempnode);
  325. { ... and add a temp. release node }
  326. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  327. end;
  328. { set types }
  329. do_firstpass(n);
  330. result:=fen_norecurse_false;
  331. end;
  332. end;
  333. vecn:
  334. begin
  335. { is the index the counter variable? }
  336. if not(is_special_array(tvecnode(n).left.resultdef)) and
  337. (tvecnode(n).right.isequal(tfornode(arg).left) or
  338. { fpc usually creates a type cast to access an array }
  339. ((tvecnode(n).right.nodetype=typeconvn) and
  340. ttypeconvnode(tvecnode(n).right).left.isequal(tfornode(arg).left)
  341. )
  342. ) and
  343. { plain read of the loop variable? }
  344. not(nf_write in tvecnode(n).right.flags) and
  345. not(nf_modify in tvecnode(n).right.flags) and
  346. { direct array access? }
  347. ((tvecnode(n).left.nodetype=loadn) or
  348. { ... or loop invariant expression? }
  349. is_loop_invariant(tfornode(arg),tvecnode(n).right)) and
  350. { removing the multiplication is only worth the
  351. effort if it's not a simple shift }
  352. not(ispowerof2(tcgvecnode(n).get_mul_size,dummy)) then
  353. begin
  354. changedforloop:=true;
  355. { did we use the same expression before already? }
  356. if not(findpreviousstrengthreduction) then
  357. begin
  358. {$ifdef DEBUG_OPTSTRENGTH}
  359. writeln('**********************************************************************************');
  360. writeln('Found expression for strength reduction: ');
  361. printnode(n);
  362. writeln('**********************************************************************************');
  363. {$endif DEBUG_OPTSTRENGTH}
  364. tempnode:=ctempcreatenode.create(voidpointertype,voidpointertype.size,tt_persistent,true);
  365. templist.Add(tempnode);
  366. inductionexprs.Add(n);
  367. CreateNodes;
  368. if lnf_backward in tfornode(arg).loopflags then
  369. addstatement(calccodestatements,
  370. geninlinenode(in_dec_x,false,
  371. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  372. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))))
  373. else
  374. addstatement(calccodestatements,
  375. geninlinenode(in_inc_x,false,
  376. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  377. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))));
  378. addstatement(initcodestatements,tempnode);
  379. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  380. caddrnode.create(
  381. cvecnode.create(tvecnode(n).left.getcopy,tfornode(arg).right.getcopy)
  382. )
  383. ));
  384. { finally replace the node by a temp. ref }
  385. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(tempnode)),n.resultdef);
  386. { ... and add a temp. release node }
  387. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  388. end;
  389. { set types }
  390. do_firstpass(n);
  391. result:=fen_norecurse_false;
  392. end;
  393. end;
  394. end;
  395. end;
  396. function OptimizeInductionVariablesSingleForLoop(node : tnode) : tnode;
  397. var
  398. loopcode : tblocknode;
  399. loopcodestatements,
  400. newcodestatements : tstatementnode;
  401. fornode : tfornode;
  402. begin
  403. result:=nil;
  404. if node.nodetype<>forn then
  405. exit;
  406. templist:=TFPList.Create;
  407. inductionexprs:=TFPList.Create;
  408. initcode:=nil;
  409. calccode:=nil;
  410. deletecode:=nil;
  411. initcodestatements:=nil;
  412. calccodestatements:=nil;
  413. deletecodestatements:=nil;
  414. { find all expressions being candidates for strength reduction
  415. and replace them }
  416. foreachnodestatic(pm_postprocess,node,@dostrengthreductiontest,node);
  417. { clue everything together }
  418. if assigned(initcode) then
  419. begin
  420. do_firstpass(tnode(initcode));
  421. do_firstpass(tnode(calccode));
  422. do_firstpass(tnode(deletecode));
  423. { create a new for node, the old one will be released by the compiler }
  424. with tfornode(node) do
  425. begin
  426. fornode:=cfornode.create(left,right,t1,t2,lnf_backward in loopflags);
  427. left:=nil;
  428. right:=nil;
  429. t1:=nil;
  430. t2:=nil;
  431. end;
  432. node:=fornode;
  433. loopcode:=internalstatements(loopcodestatements);
  434. addstatement(loopcodestatements,tfornode(node).t2);
  435. tfornode(node).t2:=loopcode;
  436. do_firstpass(node);
  437. addstatement(loopcodestatements,calccode);
  438. result:=internalstatements(newcodestatements);
  439. addstatement(newcodestatements,initcode);
  440. initcode:=nil;
  441. addstatement(newcodestatements,node);
  442. addstatement(newcodestatements,deletecode);
  443. end;
  444. templist.Free;
  445. inductionexprs.Free;
  446. end;
  447. function iterforloops(var n: tnode; arg: pointer): foreachnoderesult;
  448. var
  449. hp : tnode;
  450. begin
  451. Result:=fen_false;
  452. if n.nodetype=forn then
  453. begin
  454. { do we have DFA available? }
  455. if pi_dfaavailable in current_procinfo.flags then
  456. begin
  457. CalcDefSum(tfornode(n).t2);
  458. end;
  459. containsnestedforloop:=false;
  460. hp:=OptimizeInductionVariablesSingleForLoop(n);
  461. if assigned(hp) then
  462. begin
  463. n.Free;
  464. n:=hp;
  465. end;
  466. { can we avoid further searching? }
  467. if not(containsnestedforloop) then
  468. Result:=fen_norecurse_false;
  469. end;
  470. end;
  471. function OptimizeInductionVariables(node : tnode) : boolean;
  472. begin
  473. changedforloop:=false;
  474. foreachnodestatic(pm_postprocess,node,@iterforloops,nil);
  475. Result:=changedforloop;
  476. end;
  477. end.