optloop.pas 21 KB

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