tree-tailcall.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. /* Tail call optimization on trees.
  2. Copyright (C) 2003-2015 Free Software Foundation, Inc.
  3. This file is part of GCC.
  4. GCC 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 3, or (at your option)
  7. any later version.
  8. GCC 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 GCC; see the file COPYING3. If not see
  14. <http://www.gnu.org/licenses/>. */
  15. #include "config.h"
  16. #include "system.h"
  17. #include "coretypes.h"
  18. #include "tm.h"
  19. #include "hash-set.h"
  20. #include "machmode.h"
  21. #include "vec.h"
  22. #include "double-int.h"
  23. #include "input.h"
  24. #include "alias.h"
  25. #include "symtab.h"
  26. #include "wide-int.h"
  27. #include "inchash.h"
  28. #include "tree.h"
  29. #include "fold-const.h"
  30. #include "stor-layout.h"
  31. #include "tm_p.h"
  32. #include "predict.h"
  33. #include "hard-reg-set.h"
  34. #include "function.h"
  35. #include "dominance.h"
  36. #include "cfg.h"
  37. #include "basic-block.h"
  38. #include "tree-ssa-alias.h"
  39. #include "internal-fn.h"
  40. #include "gimple-expr.h"
  41. #include "is-a.h"
  42. #include "gimple.h"
  43. #include "gimple-iterator.h"
  44. #include "gimplify-me.h"
  45. #include "gimple-ssa.h"
  46. #include "tree-cfg.h"
  47. #include "tree-phinodes.h"
  48. #include "stringpool.h"
  49. #include "tree-ssanames.h"
  50. #include "tree-into-ssa.h"
  51. #include "hashtab.h"
  52. #include "rtl.h"
  53. #include "flags.h"
  54. #include "statistics.h"
  55. #include "real.h"
  56. #include "fixed-value.h"
  57. #include "insn-config.h"
  58. #include "expmed.h"
  59. #include "dojump.h"
  60. #include "explow.h"
  61. #include "calls.h"
  62. #include "emit-rtl.h"
  63. #include "varasm.h"
  64. #include "stmt.h"
  65. #include "expr.h"
  66. #include "tree-dfa.h"
  67. #include "gimple-pretty-print.h"
  68. #include "except.h"
  69. #include "tree-pass.h"
  70. #include "langhooks.h"
  71. #include "dbgcnt.h"
  72. #include "target.h"
  73. #include "cfgloop.h"
  74. #include "common/common-target.h"
  75. #include "hash-map.h"
  76. #include "plugin-api.h"
  77. #include "ipa-ref.h"
  78. #include "cgraph.h"
  79. #include "ipa-utils.h"
  80. /* The file implements the tail recursion elimination. It is also used to
  81. analyze the tail calls in general, passing the results to the rtl level
  82. where they are used for sibcall optimization.
  83. In addition to the standard tail recursion elimination, we handle the most
  84. trivial cases of making the call tail recursive by creating accumulators.
  85. For example the following function
  86. int sum (int n)
  87. {
  88. if (n > 0)
  89. return n + sum (n - 1);
  90. else
  91. return 0;
  92. }
  93. is transformed into
  94. int sum (int n)
  95. {
  96. int acc = 0;
  97. while (n > 0)
  98. acc += n--;
  99. return acc;
  100. }
  101. To do this, we maintain two accumulators (a_acc and m_acc) that indicate
  102. when we reach the return x statement, we should return a_acc + x * m_acc
  103. instead. They are initially initialized to 0 and 1, respectively,
  104. so the semantics of the function is obviously preserved. If we are
  105. guaranteed that the value of the accumulator never change, we
  106. omit the accumulator.
  107. There are three cases how the function may exit. The first one is
  108. handled in adjust_return_value, the other two in adjust_accumulator_values
  109. (the second case is actually a special case of the third one and we
  110. present it separately just for clarity):
  111. 1) Just return x, where x is not in any of the remaining special shapes.
  112. We rewrite this to a gimple equivalent of return m_acc * x + a_acc.
  113. 2) return f (...), where f is the current function, is rewritten in a
  114. classical tail-recursion elimination way, into assignment of arguments
  115. and jump to the start of the function. Values of the accumulators
  116. are unchanged.
  117. 3) return a + m * f(...), where a and m do not depend on call to f.
  118. To preserve the semantics described before we want this to be rewritten
  119. in such a way that we finally return
  120. a_acc + (a + m * f(...)) * m_acc = (a_acc + a * m_acc) + (m * m_acc) * f(...).
  121. I.e. we increase a_acc by a * m_acc, multiply m_acc by m and
  122. eliminate the tail call to f. Special cases when the value is just
  123. added or just multiplied are obtained by setting a = 0 or m = 1.
  124. TODO -- it is possible to do similar tricks for other operations. */
  125. /* A structure that describes the tailcall. */
  126. struct tailcall
  127. {
  128. /* The iterator pointing to the call statement. */
  129. gimple_stmt_iterator call_gsi;
  130. /* True if it is a call to the current function. */
  131. bool tail_recursion;
  132. /* The return value of the caller is mult * f + add, where f is the return
  133. value of the call. */
  134. tree mult, add;
  135. /* Next tailcall in the chain. */
  136. struct tailcall *next;
  137. };
  138. /* The variables holding the value of multiplicative and additive
  139. accumulator. */
  140. static tree m_acc, a_acc;
  141. static bool suitable_for_tail_opt_p (void);
  142. static bool optimize_tail_call (struct tailcall *, bool);
  143. static void eliminate_tail_call (struct tailcall *);
  144. static void find_tail_calls (basic_block, struct tailcall **);
  145. /* Returns false when the function is not suitable for tail call optimization
  146. from some reason (e.g. if it takes variable number of arguments). */
  147. static bool
  148. suitable_for_tail_opt_p (void)
  149. {
  150. if (cfun->stdarg)
  151. return false;
  152. return true;
  153. }
  154. /* Returns false when the function is not suitable for tail call optimization
  155. from some reason (e.g. if it takes variable number of arguments).
  156. This test must pass in addition to suitable_for_tail_opt_p in order to make
  157. tail call discovery happen. */
  158. static bool
  159. suitable_for_tail_call_opt_p (void)
  160. {
  161. tree param;
  162. /* alloca (until we have stack slot life analysis) inhibits
  163. sibling call optimizations, but not tail recursion. */
  164. if (cfun->calls_alloca)
  165. return false;
  166. /* If we are using sjlj exceptions, we may need to add a call to
  167. _Unwind_SjLj_Unregister at exit of the function. Which means
  168. that we cannot do any sibcall transformations. */
  169. if (targetm_common.except_unwind_info (&global_options) == UI_SJLJ
  170. && current_function_has_exception_handlers ())
  171. return false;
  172. /* Any function that calls setjmp might have longjmp called from
  173. any called function. ??? We really should represent this
  174. properly in the CFG so that this needn't be special cased. */
  175. if (cfun->calls_setjmp)
  176. return false;
  177. /* ??? It is OK if the argument of a function is taken in some cases,
  178. but not in all cases. See PR15387 and PR19616. Revisit for 4.1. */
  179. for (param = DECL_ARGUMENTS (current_function_decl);
  180. param;
  181. param = DECL_CHAIN (param))
  182. if (TREE_ADDRESSABLE (param))
  183. return false;
  184. return true;
  185. }
  186. /* Checks whether the expression EXPR in stmt AT is independent of the
  187. statement pointed to by GSI (in a sense that we already know EXPR's value
  188. at GSI). We use the fact that we are only called from the chain of
  189. basic blocks that have only single successor. Returns the expression
  190. containing the value of EXPR at GSI. */
  191. static tree
  192. independent_of_stmt_p (tree expr, gimple at, gimple_stmt_iterator gsi)
  193. {
  194. basic_block bb, call_bb, at_bb;
  195. edge e;
  196. edge_iterator ei;
  197. if (is_gimple_min_invariant (expr))
  198. return expr;
  199. if (TREE_CODE (expr) != SSA_NAME)
  200. return NULL_TREE;
  201. /* Mark the blocks in the chain leading to the end. */
  202. at_bb = gimple_bb (at);
  203. call_bb = gimple_bb (gsi_stmt (gsi));
  204. for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
  205. bb->aux = &bb->aux;
  206. bb->aux = &bb->aux;
  207. while (1)
  208. {
  209. at = SSA_NAME_DEF_STMT (expr);
  210. bb = gimple_bb (at);
  211. /* The default definition or defined before the chain. */
  212. if (!bb || !bb->aux)
  213. break;
  214. if (bb == call_bb)
  215. {
  216. for (; !gsi_end_p (gsi); gsi_next (&gsi))
  217. if (gsi_stmt (gsi) == at)
  218. break;
  219. if (!gsi_end_p (gsi))
  220. expr = NULL_TREE;
  221. break;
  222. }
  223. if (gimple_code (at) != GIMPLE_PHI)
  224. {
  225. expr = NULL_TREE;
  226. break;
  227. }
  228. FOR_EACH_EDGE (e, ei, bb->preds)
  229. if (e->src->aux)
  230. break;
  231. gcc_assert (e);
  232. expr = PHI_ARG_DEF_FROM_EDGE (at, e);
  233. if (TREE_CODE (expr) != SSA_NAME)
  234. {
  235. /* The value is a constant. */
  236. break;
  237. }
  238. }
  239. /* Unmark the blocks. */
  240. for (bb = call_bb; bb != at_bb; bb = single_succ (bb))
  241. bb->aux = NULL;
  242. bb->aux = NULL;
  243. return expr;
  244. }
  245. /* Simulates the effect of an assignment STMT on the return value of the tail
  246. recursive CALL passed in ASS_VAR. M and A are the multiplicative and the
  247. additive factor for the real return value. */
  248. static bool
  249. process_assignment (gassign *stmt, gimple_stmt_iterator call, tree *m,
  250. tree *a, tree *ass_var)
  251. {
  252. tree op0, op1 = NULL_TREE, non_ass_var = NULL_TREE;
  253. tree dest = gimple_assign_lhs (stmt);
  254. enum tree_code code = gimple_assign_rhs_code (stmt);
  255. enum gimple_rhs_class rhs_class = get_gimple_rhs_class (code);
  256. tree src_var = gimple_assign_rhs1 (stmt);
  257. /* See if this is a simple copy operation of an SSA name to the function
  258. result. In that case we may have a simple tail call. Ignore type
  259. conversions that can never produce extra code between the function
  260. call and the function return. */
  261. if ((rhs_class == GIMPLE_SINGLE_RHS || gimple_assign_cast_p (stmt))
  262. && (TREE_CODE (src_var) == SSA_NAME))
  263. {
  264. /* Reject a tailcall if the type conversion might need
  265. additional code. */
  266. if (gimple_assign_cast_p (stmt))
  267. {
  268. if (TYPE_MODE (TREE_TYPE (dest)) != TYPE_MODE (TREE_TYPE (src_var)))
  269. return false;
  270. /* Even if the type modes are the same, if the precision of the
  271. type is smaller than mode's precision,
  272. reduce_to_bit_field_precision would generate additional code. */
  273. if (INTEGRAL_TYPE_P (TREE_TYPE (dest))
  274. && (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (dest)))
  275. > TYPE_PRECISION (TREE_TYPE (dest))))
  276. return false;
  277. }
  278. if (src_var != *ass_var)
  279. return false;
  280. *ass_var = dest;
  281. return true;
  282. }
  283. switch (rhs_class)
  284. {
  285. case GIMPLE_BINARY_RHS:
  286. op1 = gimple_assign_rhs2 (stmt);
  287. /* Fall through. */
  288. case GIMPLE_UNARY_RHS:
  289. op0 = gimple_assign_rhs1 (stmt);
  290. break;
  291. default:
  292. return false;
  293. }
  294. /* Accumulator optimizations will reverse the order of operations.
  295. We can only do that for floating-point types if we're assuming
  296. that addition and multiplication are associative. */
  297. if (!flag_associative_math)
  298. if (FLOAT_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
  299. return false;
  300. if (rhs_class == GIMPLE_UNARY_RHS)
  301. ;
  302. else if (op0 == *ass_var
  303. && (non_ass_var = independent_of_stmt_p (op1, stmt, call)))
  304. ;
  305. else if (op1 == *ass_var
  306. && (non_ass_var = independent_of_stmt_p (op0, stmt, call)))
  307. ;
  308. else
  309. return false;
  310. switch (code)
  311. {
  312. case PLUS_EXPR:
  313. *a = non_ass_var;
  314. *ass_var = dest;
  315. return true;
  316. case POINTER_PLUS_EXPR:
  317. if (op0 != *ass_var)
  318. return false;
  319. *a = non_ass_var;
  320. *ass_var = dest;
  321. return true;
  322. case MULT_EXPR:
  323. *m = non_ass_var;
  324. *ass_var = dest;
  325. return true;
  326. case NEGATE_EXPR:
  327. *m = build_minus_one_cst (TREE_TYPE (op0));
  328. *ass_var = dest;
  329. return true;
  330. case MINUS_EXPR:
  331. if (*ass_var == op0)
  332. *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
  333. else
  334. {
  335. *m = build_minus_one_cst (TREE_TYPE (non_ass_var));
  336. *a = fold_build1 (NEGATE_EXPR, TREE_TYPE (non_ass_var), non_ass_var);
  337. }
  338. *ass_var = dest;
  339. return true;
  340. /* TODO -- Handle POINTER_PLUS_EXPR. */
  341. default:
  342. return false;
  343. }
  344. }
  345. /* Propagate VAR through phis on edge E. */
  346. static tree
  347. propagate_through_phis (tree var, edge e)
  348. {
  349. basic_block dest = e->dest;
  350. gphi_iterator gsi;
  351. for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
  352. {
  353. gphi *phi = gsi.phi ();
  354. if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var)
  355. return PHI_RESULT (phi);
  356. }
  357. return var;
  358. }
  359. /* Finds tailcalls falling into basic block BB. The list of found tailcalls is
  360. added to the start of RET. */
  361. static void
  362. find_tail_calls (basic_block bb, struct tailcall **ret)
  363. {
  364. tree ass_var = NULL_TREE, ret_var, func, param;
  365. gimple stmt;
  366. gcall *call = NULL;
  367. gimple_stmt_iterator gsi, agsi;
  368. bool tail_recursion;
  369. struct tailcall *nw;
  370. edge e;
  371. tree m, a;
  372. basic_block abb;
  373. size_t idx;
  374. tree var;
  375. if (!single_succ_p (bb))
  376. return;
  377. for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
  378. {
  379. stmt = gsi_stmt (gsi);
  380. /* Ignore labels, returns, clobbers and debug stmts. */
  381. if (gimple_code (stmt) == GIMPLE_LABEL
  382. || gimple_code (stmt) == GIMPLE_RETURN
  383. || gimple_clobber_p (stmt)
  384. || is_gimple_debug (stmt))
  385. continue;
  386. /* Check for a call. */
  387. if (is_gimple_call (stmt))
  388. {
  389. call = as_a <gcall *> (stmt);
  390. ass_var = gimple_call_lhs (call);
  391. break;
  392. }
  393. /* If the statement references memory or volatile operands, fail. */
  394. if (gimple_references_memory_p (stmt)
  395. || gimple_has_volatile_ops (stmt))
  396. return;
  397. }
  398. if (gsi_end_p (gsi))
  399. {
  400. edge_iterator ei;
  401. /* Recurse to the predecessors. */
  402. FOR_EACH_EDGE (e, ei, bb->preds)
  403. find_tail_calls (e->src, ret);
  404. return;
  405. }
  406. /* If the LHS of our call is not just a simple register, we can't
  407. transform this into a tail or sibling call. This situation happens,
  408. in (e.g.) "*p = foo()" where foo returns a struct. In this case
  409. we won't have a temporary here, but we need to carry out the side
  410. effect anyway, so tailcall is impossible.
  411. ??? In some situations (when the struct is returned in memory via
  412. invisible argument) we could deal with this, e.g. by passing 'p'
  413. itself as that argument to foo, but it's too early to do this here,
  414. and expand_call() will not handle it anyway. If it ever can, then
  415. we need to revisit this here, to allow that situation. */
  416. if (ass_var && !is_gimple_reg (ass_var))
  417. return;
  418. /* We found the call, check whether it is suitable. */
  419. tail_recursion = false;
  420. func = gimple_call_fndecl (call);
  421. if (func
  422. && !DECL_BUILT_IN (func)
  423. && recursive_call_p (current_function_decl, func))
  424. {
  425. tree arg;
  426. for (param = DECL_ARGUMENTS (func), idx = 0;
  427. param && idx < gimple_call_num_args (call);
  428. param = DECL_CHAIN (param), idx ++)
  429. {
  430. arg = gimple_call_arg (call, idx);
  431. if (param != arg)
  432. {
  433. /* Make sure there are no problems with copying. The parameter
  434. have a copyable type and the two arguments must have reasonably
  435. equivalent types. The latter requirement could be relaxed if
  436. we emitted a suitable type conversion statement. */
  437. if (!is_gimple_reg_type (TREE_TYPE (param))
  438. || !useless_type_conversion_p (TREE_TYPE (param),
  439. TREE_TYPE (arg)))
  440. break;
  441. /* The parameter should be a real operand, so that phi node
  442. created for it at the start of the function has the meaning
  443. of copying the value. This test implies is_gimple_reg_type
  444. from the previous condition, however this one could be
  445. relaxed by being more careful with copying the new value
  446. of the parameter (emitting appropriate GIMPLE_ASSIGN and
  447. updating the virtual operands). */
  448. if (!is_gimple_reg (param))
  449. break;
  450. }
  451. }
  452. if (idx == gimple_call_num_args (call) && !param)
  453. tail_recursion = true;
  454. }
  455. /* Make sure the tail invocation of this function does not refer
  456. to local variables. */
  457. FOR_EACH_LOCAL_DECL (cfun, idx, var)
  458. {
  459. if (TREE_CODE (var) != PARM_DECL
  460. && auto_var_in_fn_p (var, cfun->decl)
  461. && (ref_maybe_used_by_stmt_p (call, var)
  462. || call_may_clobber_ref_p (call, var)))
  463. return;
  464. }
  465. /* Now check the statements after the call. None of them has virtual
  466. operands, so they may only depend on the call through its return
  467. value. The return value should also be dependent on each of them,
  468. since we are running after dce. */
  469. m = NULL_TREE;
  470. a = NULL_TREE;
  471. abb = bb;
  472. agsi = gsi;
  473. while (1)
  474. {
  475. tree tmp_a = NULL_TREE;
  476. tree tmp_m = NULL_TREE;
  477. gsi_next (&agsi);
  478. while (gsi_end_p (agsi))
  479. {
  480. ass_var = propagate_through_phis (ass_var, single_succ_edge (abb));
  481. abb = single_succ (abb);
  482. agsi = gsi_start_bb (abb);
  483. }
  484. stmt = gsi_stmt (agsi);
  485. if (gimple_code (stmt) == GIMPLE_LABEL)
  486. continue;
  487. if (gimple_code (stmt) == GIMPLE_RETURN)
  488. break;
  489. if (gimple_clobber_p (stmt))
  490. continue;
  491. if (is_gimple_debug (stmt))
  492. continue;
  493. if (gimple_code (stmt) != GIMPLE_ASSIGN)
  494. return;
  495. /* This is a gimple assign. */
  496. if (! process_assignment (as_a <gassign *> (stmt), gsi, &tmp_m,
  497. &tmp_a, &ass_var))
  498. return;
  499. if (tmp_a)
  500. {
  501. tree type = TREE_TYPE (tmp_a);
  502. if (a)
  503. a = fold_build2 (PLUS_EXPR, type, fold_convert (type, a), tmp_a);
  504. else
  505. a = tmp_a;
  506. }
  507. if (tmp_m)
  508. {
  509. tree type = TREE_TYPE (tmp_m);
  510. if (m)
  511. m = fold_build2 (MULT_EXPR, type, fold_convert (type, m), tmp_m);
  512. else
  513. m = tmp_m;
  514. if (a)
  515. a = fold_build2 (MULT_EXPR, type, fold_convert (type, a), tmp_m);
  516. }
  517. }
  518. /* See if this is a tail call we can handle. */
  519. ret_var = gimple_return_retval (as_a <greturn *> (stmt));
  520. /* We may proceed if there either is no return value, or the return value
  521. is identical to the call's return. */
  522. if (ret_var
  523. && (ret_var != ass_var))
  524. return;
  525. /* If this is not a tail recursive call, we cannot handle addends or
  526. multiplicands. */
  527. if (!tail_recursion && (m || a))
  528. return;
  529. /* For pointers only allow additions. */
  530. if (m && POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (current_function_decl))))
  531. return;
  532. nw = XNEW (struct tailcall);
  533. nw->call_gsi = gsi;
  534. nw->tail_recursion = tail_recursion;
  535. nw->mult = m;
  536. nw->add = a;
  537. nw->next = *ret;
  538. *ret = nw;
  539. }
  540. /* Helper to insert PHI_ARGH to the phi of VAR in the destination of edge E. */
  541. static void
  542. add_successor_phi_arg (edge e, tree var, tree phi_arg)
  543. {
  544. gphi_iterator gsi;
  545. for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
  546. if (PHI_RESULT (gsi.phi ()) == var)
  547. break;
  548. gcc_assert (!gsi_end_p (gsi));
  549. add_phi_arg (gsi.phi (), phi_arg, e, UNKNOWN_LOCATION);
  550. }
  551. /* Creates a GIMPLE statement which computes the operation specified by
  552. CODE, ACC and OP1 to a new variable with name LABEL and inserts the
  553. statement in the position specified by GSI. Returns the
  554. tree node of the statement's result. */
  555. static tree
  556. adjust_return_value_with_ops (enum tree_code code, const char *label,
  557. tree acc, tree op1, gimple_stmt_iterator gsi)
  558. {
  559. tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
  560. tree result = make_temp_ssa_name (ret_type, NULL, label);
  561. gassign *stmt;
  562. if (POINTER_TYPE_P (ret_type))
  563. {
  564. gcc_assert (code == PLUS_EXPR && TREE_TYPE (acc) == sizetype);
  565. code = POINTER_PLUS_EXPR;
  566. }
  567. if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1))
  568. && code != POINTER_PLUS_EXPR)
  569. stmt = gimple_build_assign (result, code, acc, op1);
  570. else
  571. {
  572. tree tem;
  573. if (code == POINTER_PLUS_EXPR)
  574. tem = fold_build2 (code, TREE_TYPE (op1), op1, acc);
  575. else
  576. tem = fold_build2 (code, TREE_TYPE (op1),
  577. fold_convert (TREE_TYPE (op1), acc), op1);
  578. tree rhs = fold_convert (ret_type, tem);
  579. rhs = force_gimple_operand_gsi (&gsi, rhs,
  580. false, NULL, true, GSI_SAME_STMT);
  581. stmt = gimple_build_assign (result, rhs);
  582. }
  583. gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
  584. return result;
  585. }
  586. /* Creates a new GIMPLE statement that adjusts the value of accumulator ACC by
  587. the computation specified by CODE and OP1 and insert the statement
  588. at the position specified by GSI as a new statement. Returns new SSA name
  589. of updated accumulator. */
  590. static tree
  591. update_accumulator_with_ops (enum tree_code code, tree acc, tree op1,
  592. gimple_stmt_iterator gsi)
  593. {
  594. gassign *stmt;
  595. tree var = copy_ssa_name (acc);
  596. if (types_compatible_p (TREE_TYPE (acc), TREE_TYPE (op1)))
  597. stmt = gimple_build_assign (var, code, acc, op1);
  598. else
  599. {
  600. tree rhs = fold_convert (TREE_TYPE (acc),
  601. fold_build2 (code,
  602. TREE_TYPE (op1),
  603. fold_convert (TREE_TYPE (op1), acc),
  604. op1));
  605. rhs = force_gimple_operand_gsi (&gsi, rhs,
  606. false, NULL, false, GSI_CONTINUE_LINKING);
  607. stmt = gimple_build_assign (var, rhs);
  608. }
  609. gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
  610. return var;
  611. }
  612. /* Adjust the accumulator values according to A and M after GSI, and update
  613. the phi nodes on edge BACK. */
  614. static void
  615. adjust_accumulator_values (gimple_stmt_iterator gsi, tree m, tree a, edge back)
  616. {
  617. tree var, a_acc_arg, m_acc_arg;
  618. if (m)
  619. m = force_gimple_operand_gsi (&gsi, m, true, NULL, true, GSI_SAME_STMT);
  620. if (a)
  621. a = force_gimple_operand_gsi (&gsi, a, true, NULL, true, GSI_SAME_STMT);
  622. a_acc_arg = a_acc;
  623. m_acc_arg = m_acc;
  624. if (a)
  625. {
  626. if (m_acc)
  627. {
  628. if (integer_onep (a))
  629. var = m_acc;
  630. else
  631. var = adjust_return_value_with_ops (MULT_EXPR, "acc_tmp", m_acc,
  632. a, gsi);
  633. }
  634. else
  635. var = a;
  636. a_acc_arg = update_accumulator_with_ops (PLUS_EXPR, a_acc, var, gsi);
  637. }
  638. if (m)
  639. m_acc_arg = update_accumulator_with_ops (MULT_EXPR, m_acc, m, gsi);
  640. if (a_acc)
  641. add_successor_phi_arg (back, a_acc, a_acc_arg);
  642. if (m_acc)
  643. add_successor_phi_arg (back, m_acc, m_acc_arg);
  644. }
  645. /* Adjust value of the return at the end of BB according to M and A
  646. accumulators. */
  647. static void
  648. adjust_return_value (basic_block bb, tree m, tree a)
  649. {
  650. tree retval;
  651. greturn *ret_stmt = as_a <greturn *> (gimple_seq_last_stmt (bb_seq (bb)));
  652. gimple_stmt_iterator gsi = gsi_last_bb (bb);
  653. gcc_assert (gimple_code (ret_stmt) == GIMPLE_RETURN);
  654. retval = gimple_return_retval (ret_stmt);
  655. if (!retval || retval == error_mark_node)
  656. return;
  657. if (m)
  658. retval = adjust_return_value_with_ops (MULT_EXPR, "mul_tmp", m_acc, retval,
  659. gsi);
  660. if (a)
  661. retval = adjust_return_value_with_ops (PLUS_EXPR, "acc_tmp", a_acc, retval,
  662. gsi);
  663. gimple_return_set_retval (ret_stmt, retval);
  664. update_stmt (ret_stmt);
  665. }
  666. /* Subtract COUNT and FREQUENCY from the basic block and it's
  667. outgoing edge. */
  668. static void
  669. decrease_profile (basic_block bb, gcov_type count, int frequency)
  670. {
  671. edge e;
  672. bb->count -= count;
  673. if (bb->count < 0)
  674. bb->count = 0;
  675. bb->frequency -= frequency;
  676. if (bb->frequency < 0)
  677. bb->frequency = 0;
  678. if (!single_succ_p (bb))
  679. {
  680. gcc_assert (!EDGE_COUNT (bb->succs));
  681. return;
  682. }
  683. e = single_succ_edge (bb);
  684. e->count -= count;
  685. if (e->count < 0)
  686. e->count = 0;
  687. }
  688. /* Returns true if argument PARAM of the tail recursive call needs to be copied
  689. when the call is eliminated. */
  690. static bool
  691. arg_needs_copy_p (tree param)
  692. {
  693. tree def;
  694. if (!is_gimple_reg (param))
  695. return false;
  696. /* Parameters that are only defined but never used need not be copied. */
  697. def = ssa_default_def (cfun, param);
  698. if (!def)
  699. return false;
  700. return true;
  701. }
  702. /* Eliminates tail call described by T. TMP_VARS is a list of
  703. temporary variables used to copy the function arguments. */
  704. static void
  705. eliminate_tail_call (struct tailcall *t)
  706. {
  707. tree param, rslt;
  708. gimple stmt, call;
  709. tree arg;
  710. size_t idx;
  711. basic_block bb, first;
  712. edge e;
  713. gphi *phi;
  714. gphi_iterator gpi;
  715. gimple_stmt_iterator gsi;
  716. gimple orig_stmt;
  717. stmt = orig_stmt = gsi_stmt (t->call_gsi);
  718. bb = gsi_bb (t->call_gsi);
  719. if (dump_file && (dump_flags & TDF_DETAILS))
  720. {
  721. fprintf (dump_file, "Eliminated tail recursion in bb %d : ",
  722. bb->index);
  723. print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
  724. fprintf (dump_file, "\n");
  725. }
  726. gcc_assert (is_gimple_call (stmt));
  727. first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
  728. /* Remove the code after call_gsi that will become unreachable. The
  729. possibly unreachable code in other blocks is removed later in
  730. cfg cleanup. */
  731. gsi = t->call_gsi;
  732. gsi_next (&gsi);
  733. while (!gsi_end_p (gsi))
  734. {
  735. gimple t = gsi_stmt (gsi);
  736. /* Do not remove the return statement, so that redirect_edge_and_branch
  737. sees how the block ends. */
  738. if (gimple_code (t) == GIMPLE_RETURN)
  739. break;
  740. gsi_remove (&gsi, true);
  741. release_defs (t);
  742. }
  743. /* Number of executions of function has reduced by the tailcall. */
  744. e = single_succ_edge (gsi_bb (t->call_gsi));
  745. decrease_profile (EXIT_BLOCK_PTR_FOR_FN (cfun), e->count, EDGE_FREQUENCY (e));
  746. decrease_profile (ENTRY_BLOCK_PTR_FOR_FN (cfun), e->count,
  747. EDGE_FREQUENCY (e));
  748. if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
  749. decrease_profile (e->dest, e->count, EDGE_FREQUENCY (e));
  750. /* Replace the call by a jump to the start of function. */
  751. e = redirect_edge_and_branch (single_succ_edge (gsi_bb (t->call_gsi)),
  752. first);
  753. gcc_assert (e);
  754. PENDING_STMT (e) = NULL;
  755. /* Add phi node entries for arguments. The ordering of the phi nodes should
  756. be the same as the ordering of the arguments. */
  757. for (param = DECL_ARGUMENTS (current_function_decl),
  758. idx = 0, gpi = gsi_start_phis (first);
  759. param;
  760. param = DECL_CHAIN (param), idx++)
  761. {
  762. if (!arg_needs_copy_p (param))
  763. continue;
  764. arg = gimple_call_arg (stmt, idx);
  765. phi = gpi.phi ();
  766. gcc_assert (param == SSA_NAME_VAR (PHI_RESULT (phi)));
  767. add_phi_arg (phi, arg, e, gimple_location (stmt));
  768. gsi_next (&gpi);
  769. }
  770. /* Update the values of accumulators. */
  771. adjust_accumulator_values (t->call_gsi, t->mult, t->add, e);
  772. call = gsi_stmt (t->call_gsi);
  773. rslt = gimple_call_lhs (call);
  774. if (rslt != NULL_TREE)
  775. {
  776. /* Result of the call will no longer be defined. So adjust the
  777. SSA_NAME_DEF_STMT accordingly. */
  778. SSA_NAME_DEF_STMT (rslt) = gimple_build_nop ();
  779. }
  780. gsi_remove (&t->call_gsi, true);
  781. release_defs (call);
  782. }
  783. /* Optimizes the tailcall described by T. If OPT_TAILCALLS is true, also
  784. mark the tailcalls for the sibcall optimization. */
  785. static bool
  786. optimize_tail_call (struct tailcall *t, bool opt_tailcalls)
  787. {
  788. if (t->tail_recursion)
  789. {
  790. eliminate_tail_call (t);
  791. return true;
  792. }
  793. if (opt_tailcalls)
  794. {
  795. gcall *stmt = as_a <gcall *> (gsi_stmt (t->call_gsi));
  796. gimple_call_set_tail (stmt, true);
  797. cfun->tail_call_marked = true;
  798. if (dump_file && (dump_flags & TDF_DETAILS))
  799. {
  800. fprintf (dump_file, "Found tail call ");
  801. print_gimple_stmt (dump_file, stmt, 0, dump_flags);
  802. fprintf (dump_file, " in bb %i\n", (gsi_bb (t->call_gsi))->index);
  803. }
  804. }
  805. return false;
  806. }
  807. /* Creates a tail-call accumulator of the same type as the return type of the
  808. current function. LABEL is the name used to creating the temporary
  809. variable for the accumulator. The accumulator will be inserted in the
  810. phis of a basic block BB with single predecessor with an initial value
  811. INIT converted to the current function return type. */
  812. static tree
  813. create_tailcall_accumulator (const char *label, basic_block bb, tree init)
  814. {
  815. tree ret_type = TREE_TYPE (DECL_RESULT (current_function_decl));
  816. if (POINTER_TYPE_P (ret_type))
  817. ret_type = sizetype;
  818. tree tmp = make_temp_ssa_name (ret_type, NULL, label);
  819. gphi *phi;
  820. phi = create_phi_node (tmp, bb);
  821. /* RET_TYPE can be a float when -ffast-maths is enabled. */
  822. add_phi_arg (phi, fold_convert (ret_type, init), single_pred_edge (bb),
  823. UNKNOWN_LOCATION);
  824. return PHI_RESULT (phi);
  825. }
  826. /* Optimizes tail calls in the function, turning the tail recursion
  827. into iteration. */
  828. static unsigned int
  829. tree_optimize_tail_calls_1 (bool opt_tailcalls)
  830. {
  831. edge e;
  832. bool phis_constructed = false;
  833. struct tailcall *tailcalls = NULL, *act, *next;
  834. bool changed = false;
  835. basic_block first = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
  836. tree param;
  837. gimple stmt;
  838. edge_iterator ei;
  839. if (!suitable_for_tail_opt_p ())
  840. return 0;
  841. if (opt_tailcalls)
  842. opt_tailcalls = suitable_for_tail_call_opt_p ();
  843. FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
  844. {
  845. /* Only traverse the normal exits, i.e. those that end with return
  846. statement. */
  847. stmt = last_stmt (e->src);
  848. if (stmt
  849. && gimple_code (stmt) == GIMPLE_RETURN)
  850. find_tail_calls (e->src, &tailcalls);
  851. }
  852. /* Construct the phi nodes and accumulators if necessary. */
  853. a_acc = m_acc = NULL_TREE;
  854. for (act = tailcalls; act; act = act->next)
  855. {
  856. if (!act->tail_recursion)
  857. continue;
  858. if (!phis_constructed)
  859. {
  860. /* Ensure that there is only one predecessor of the block
  861. or if there are existing degenerate PHI nodes. */
  862. if (!single_pred_p (first)
  863. || !gimple_seq_empty_p (phi_nodes (first)))
  864. first =
  865. split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
  866. /* Copy the args if needed. */
  867. for (param = DECL_ARGUMENTS (current_function_decl);
  868. param;
  869. param = DECL_CHAIN (param))
  870. if (arg_needs_copy_p (param))
  871. {
  872. tree name = ssa_default_def (cfun, param);
  873. tree new_name = make_ssa_name (param, SSA_NAME_DEF_STMT (name));
  874. gphi *phi;
  875. set_ssa_default_def (cfun, param, new_name);
  876. phi = create_phi_node (name, first);
  877. add_phi_arg (phi, new_name, single_pred_edge (first),
  878. EXPR_LOCATION (param));
  879. }
  880. phis_constructed = true;
  881. }
  882. if (act->add && !a_acc)
  883. a_acc = create_tailcall_accumulator ("add_acc", first,
  884. integer_zero_node);
  885. if (act->mult && !m_acc)
  886. m_acc = create_tailcall_accumulator ("mult_acc", first,
  887. integer_one_node);
  888. }
  889. if (a_acc || m_acc)
  890. {
  891. /* When the tail call elimination using accumulators is performed,
  892. statements adding the accumulated value are inserted at all exits.
  893. This turns all other tail calls to non-tail ones. */
  894. opt_tailcalls = false;
  895. }
  896. for (; tailcalls; tailcalls = next)
  897. {
  898. next = tailcalls->next;
  899. changed |= optimize_tail_call (tailcalls, opt_tailcalls);
  900. free (tailcalls);
  901. }
  902. if (a_acc || m_acc)
  903. {
  904. /* Modify the remaining return statements. */
  905. FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
  906. {
  907. stmt = last_stmt (e->src);
  908. if (stmt
  909. && gimple_code (stmt) == GIMPLE_RETURN)
  910. adjust_return_value (e->src, m_acc, a_acc);
  911. }
  912. }
  913. if (changed)
  914. {
  915. /* We may have created new loops. Make them magically appear. */
  916. loops_state_set (LOOPS_NEED_FIXUP);
  917. free_dominance_info (CDI_DOMINATORS);
  918. }
  919. /* Add phi nodes for the virtual operands defined in the function to the
  920. header of the loop created by tail recursion elimination. Do so
  921. by triggering the SSA renamer. */
  922. if (phis_constructed)
  923. mark_virtual_operands_for_renaming (cfun);
  924. if (changed)
  925. return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
  926. return 0;
  927. }
  928. static bool
  929. gate_tail_calls (void)
  930. {
  931. return flag_optimize_sibling_calls != 0 && dbg_cnt (tail_call);
  932. }
  933. static unsigned int
  934. execute_tail_calls (void)
  935. {
  936. return tree_optimize_tail_calls_1 (true);
  937. }
  938. namespace {
  939. const pass_data pass_data_tail_recursion =
  940. {
  941. GIMPLE_PASS, /* type */
  942. "tailr", /* name */
  943. OPTGROUP_NONE, /* optinfo_flags */
  944. TV_NONE, /* tv_id */
  945. ( PROP_cfg | PROP_ssa ), /* properties_required */
  946. 0, /* properties_provided */
  947. 0, /* properties_destroyed */
  948. 0, /* todo_flags_start */
  949. 0, /* todo_flags_finish */
  950. };
  951. class pass_tail_recursion : public gimple_opt_pass
  952. {
  953. public:
  954. pass_tail_recursion (gcc::context *ctxt)
  955. : gimple_opt_pass (pass_data_tail_recursion, ctxt)
  956. {}
  957. /* opt_pass methods: */
  958. opt_pass * clone () { return new pass_tail_recursion (m_ctxt); }
  959. virtual bool gate (function *) { return gate_tail_calls (); }
  960. virtual unsigned int execute (function *)
  961. {
  962. return tree_optimize_tail_calls_1 (false);
  963. }
  964. }; // class pass_tail_recursion
  965. } // anon namespace
  966. gimple_opt_pass *
  967. make_pass_tail_recursion (gcc::context *ctxt)
  968. {
  969. return new pass_tail_recursion (ctxt);
  970. }
  971. namespace {
  972. const pass_data pass_data_tail_calls =
  973. {
  974. GIMPLE_PASS, /* type */
  975. "tailc", /* name */
  976. OPTGROUP_NONE, /* optinfo_flags */
  977. TV_NONE, /* tv_id */
  978. ( PROP_cfg | PROP_ssa ), /* properties_required */
  979. 0, /* properties_provided */
  980. 0, /* properties_destroyed */
  981. 0, /* todo_flags_start */
  982. 0, /* todo_flags_finish */
  983. };
  984. class pass_tail_calls : public gimple_opt_pass
  985. {
  986. public:
  987. pass_tail_calls (gcc::context *ctxt)
  988. : gimple_opt_pass (pass_data_tail_calls, ctxt)
  989. {}
  990. /* opt_pass methods: */
  991. virtual bool gate (function *) { return gate_tail_calls (); }
  992. virtual unsigned int execute (function *) { return execute_tail_calls (); }
  993. }; // class pass_tail_calls
  994. } // anon namespace
  995. gimple_opt_pass *
  996. make_pass_tail_calls (gcc::context *ctxt)
  997. {
  998. return new pass_tail_calls (ctxt);
  999. }