optloop.pas 21 KB

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