]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-ssa-math-opts.c
2012-08-14 Richard Guenther <rguenther@suse.de>
[thirdparty/gcc.git] / gcc / tree-ssa-math-opts.c
CommitLineData
abacb398 1/* Global, SSA-based optimizations using mathematical identities.
e78306af 2 Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011
7cf0dbf3 3 Free Software Foundation, Inc.
48e1416a 4
abacb398 5This file is part of GCC.
48e1416a 6
abacb398 7GCC is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
8c4c00c1 9Free Software Foundation; either version 3, or (at your option) any
abacb398 10later version.
48e1416a 11
abacb398 12GCC is distributed in the hope that it will be useful, but WITHOUT
13ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
48e1416a 16
abacb398 17You should have received a copy of the GNU General Public License
8c4c00c1 18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
abacb398 20
21/* Currently, the only mini-pass in this file tries to CSE reciprocal
22 operations. These are common in sequences such as this one:
23
24 modulus = sqrt(x*x + y*y + z*z);
25 x = x / modulus;
26 y = y / modulus;
27 z = z / modulus;
28
29 that can be optimized to
30
31 modulus = sqrt(x*x + y*y + z*z);
32 rmodulus = 1.0 / modulus;
33 x = x * rmodulus;
34 y = y * rmodulus;
35 z = z * rmodulus;
36
37 We do this for loop invariant divisors, and with this pass whenever
ac70caad 38 we notice that a division has the same divisor multiple times.
39
40 Of course, like in PRE, we don't insert a division if a dominator
41 already has one. However, this cannot be done as an extension of
42 PRE for several reasons.
43
44 First of all, with some experiments it was found out that the
45 transformation is not always useful if there are only two divisions
46 hy the same divisor. This is probably because modern processors
47 can pipeline the divisions; on older, in-order processors it should
48 still be effective to optimize two divisions by the same number.
49 We make this a param, and it shall be called N in the remainder of
50 this comment.
51
52 Second, if trapping math is active, we have less freedom on where
53 to insert divisions: we can only do so in basic blocks that already
54 contain one. (If divisions don't trap, instead, we can insert
55 divisions elsewhere, which will be in blocks that are common dominators
56 of those that have the division).
57
58 We really don't want to compute the reciprocal unless a division will
59 be found. To do this, we won't insert the division in a basic block
60 that has less than N divisions *post-dominating* it.
61
62 The algorithm constructs a subset of the dominator tree, holding the
63 blocks containing the divisions and the common dominators to them,
64 and walk it twice. The first walk is in post-order, and it annotates
65 each block with the number of divisions that post-dominate it: this
66 gives information on where divisions can be inserted profitably.
67 The second walk is in pre-order, and it inserts divisions as explained
68 above, and replaces divisions by multiplications.
69
70 In the best case, the cost of the pass is O(n_statements). In the
71 worst-case, the cost is due to creating the dominator tree subset,
72 with a cost of O(n_basic_blocks ^ 2); however this can only happen
73 for n_statements / n_basic_blocks statements. So, the amortized cost
74 of creating the dominator tree subset is O(n_basic_blocks) and the
75 worst-case cost of the pass is O(n_statements * n_basic_blocks).
76
77 More practically, the cost will be small because there are few
78 divisions, and they tend to be in the same basic block, so insert_bb
79 is called very few times.
80
81 If we did this using domwalk.c, an efficient implementation would have
82 to work on all the variables in a single pass, because we could not
83 work on just a subset of the dominator tree, as we do now, and the
84 cost would also be something like O(n_statements * n_basic_blocks).
85 The data structures would be more complex in order to work on all the
86 variables in a single pass. */
abacb398 87
88#include "config.h"
89#include "system.h"
90#include "coretypes.h"
91#include "tm.h"
92#include "flags.h"
93#include "tree.h"
94#include "tree-flow.h"
abacb398 95#include "tree-pass.h"
ac70caad 96#include "alloc-pool.h"
97#include "basic-block.h"
98#include "target.h"
ce084dfc 99#include "gimple-pretty-print.h"
a7a46268 100
101/* FIXME: RTL headers have to be included here for optabs. */
102#include "rtl.h" /* Because optabs.h wants enum rtx_code. */
103#include "expr.h" /* Because optabs.h wants sepops. */
84cc784c 104#include "optabs.h"
ac70caad 105
106/* This structure represents one basic block that either computes a
107 division, or is a common dominator for basic block that compute a
108 division. */
109struct occurrence {
110 /* The basic block represented by this structure. */
111 basic_block bb;
112
113 /* If non-NULL, the SSA_NAME holding the definition for a reciprocal
114 inserted in BB. */
115 tree recip_def;
116
75a70cf9 117 /* If non-NULL, the GIMPLE_ASSIGN for a reciprocal computation that
ac70caad 118 was inserted in BB. */
75a70cf9 119 gimple recip_def_stmt;
ac70caad 120
121 /* Pointer to a list of "struct occurrence"s for blocks dominated
122 by BB. */
123 struct occurrence *children;
124
125 /* Pointer to the next "struct occurrence"s in the list of blocks
126 sharing a common dominator. */
127 struct occurrence *next;
128
129 /* The number of divisions that are in BB before compute_merit. The
130 number of divisions that are in BB or post-dominate it after
131 compute_merit. */
132 int num_divisions;
133
134 /* True if the basic block has a division, false if it is a common
135 dominator for basic blocks that do. If it is false and trapping
136 math is active, BB is not a candidate for inserting a reciprocal. */
137 bool bb_has_division;
138};
139
30c4e60d 140static struct
141{
142 /* Number of 1.0/X ops inserted. */
143 int rdivs_inserted;
144
145 /* Number of 1.0/FUNC ops inserted. */
146 int rfuncs_inserted;
147} reciprocal_stats;
148
149static struct
150{
151 /* Number of cexpi calls inserted. */
152 int inserted;
153} sincos_stats;
154
155static struct
156{
157 /* Number of hand-written 32-bit bswaps found. */
158 int found_32bit;
159
160 /* Number of hand-written 64-bit bswaps found. */
161 int found_64bit;
162} bswap_stats;
163
164static struct
165{
166 /* Number of widening multiplication ops inserted. */
167 int widen_mults_inserted;
168
169 /* Number of integer multiply-and-accumulate ops inserted. */
170 int maccs_inserted;
171
172 /* Number of fp fused multiply-add ops inserted. */
173 int fmas_inserted;
174} widen_mul_stats;
ac70caad 175
176/* The instance of "struct occurrence" representing the highest
177 interesting block in the dominator tree. */
178static struct occurrence *occ_head;
179
180/* Allocation pool for getting instances of "struct occurrence". */
181static alloc_pool occ_pool;
182
183
184
185/* Allocate and return a new struct occurrence for basic block BB, and
186 whose children list is headed by CHILDREN. */
187static struct occurrence *
188occ_new (basic_block bb, struct occurrence *children)
abacb398 189{
ac70caad 190 struct occurrence *occ;
191
f0d6e81c 192 bb->aux = occ = (struct occurrence *) pool_alloc (occ_pool);
ac70caad 193 memset (occ, 0, sizeof (struct occurrence));
194
195 occ->bb = bb;
196 occ->children = children;
197 return occ;
abacb398 198}
199
ac70caad 200
201/* Insert NEW_OCC into our subset of the dominator tree. P_HEAD points to a
202 list of "struct occurrence"s, one per basic block, having IDOM as
203 their common dominator.
204
205 We try to insert NEW_OCC as deep as possible in the tree, and we also
206 insert any other block that is a common dominator for BB and one
207 block already in the tree. */
208
209static void
210insert_bb (struct occurrence *new_occ, basic_block idom,
211 struct occurrence **p_head)
9e583fac 212{
ac70caad 213 struct occurrence *occ, **p_occ;
9e583fac 214
ac70caad 215 for (p_occ = p_head; (occ = *p_occ) != NULL; )
216 {
217 basic_block bb = new_occ->bb, occ_bb = occ->bb;
218 basic_block dom = nearest_common_dominator (CDI_DOMINATORS, occ_bb, bb);
219 if (dom == bb)
220 {
221 /* BB dominates OCC_BB. OCC becomes NEW_OCC's child: remove OCC
222 from its list. */
223 *p_occ = occ->next;
224 occ->next = new_occ->children;
225 new_occ->children = occ;
226
227 /* Try the next block (it may as well be dominated by BB). */
228 }
229
230 else if (dom == occ_bb)
231 {
232 /* OCC_BB dominates BB. Tail recurse to look deeper. */
233 insert_bb (new_occ, dom, &occ->children);
234 return;
235 }
236
237 else if (dom != idom)
238 {
239 gcc_assert (!dom->aux);
240
241 /* There is a dominator between IDOM and BB, add it and make
242 two children out of NEW_OCC and OCC. First, remove OCC from
243 its list. */
244 *p_occ = occ->next;
245 new_occ->next = occ;
246 occ->next = NULL;
247
248 /* None of the previous blocks has DOM as a dominator: if we tail
249 recursed, we would reexamine them uselessly. Just switch BB with
250 DOM, and go on looking for blocks dominated by DOM. */
251 new_occ = occ_new (dom, new_occ);
252 }
253
254 else
255 {
256 /* Nothing special, go on with the next element. */
257 p_occ = &occ->next;
258 }
259 }
260
261 /* No place was found as a child of IDOM. Make BB a sibling of IDOM. */
262 new_occ->next = *p_head;
263 *p_head = new_occ;
264}
265
266/* Register that we found a division in BB. */
267
268static inline void
269register_division_in (basic_block bb)
270{
271 struct occurrence *occ;
272
273 occ = (struct occurrence *) bb->aux;
274 if (!occ)
275 {
276 occ = occ_new (bb, NULL);
277 insert_bb (occ, ENTRY_BLOCK_PTR, &occ_head);
278 }
279
280 occ->bb_has_division = true;
281 occ->num_divisions++;
282}
283
284
285/* Compute the number of divisions that postdominate each block in OCC and
286 its children. */
abacb398 287
abacb398 288static void
ac70caad 289compute_merit (struct occurrence *occ)
abacb398 290{
ac70caad 291 struct occurrence *occ_child;
292 basic_block dom = occ->bb;
abacb398 293
ac70caad 294 for (occ_child = occ->children; occ_child; occ_child = occ_child->next)
abacb398 295 {
ac70caad 296 basic_block bb;
297 if (occ_child->children)
298 compute_merit (occ_child);
299
300 if (flag_exceptions)
301 bb = single_noncomplex_succ (dom);
302 else
303 bb = dom;
304
305 if (dominated_by_p (CDI_POST_DOMINATORS, bb, occ_child->bb))
306 occ->num_divisions += occ_child->num_divisions;
307 }
308}
309
310
311/* Return whether USE_STMT is a floating-point division by DEF. */
312static inline bool
75a70cf9 313is_division_by (gimple use_stmt, tree def)
ac70caad 314{
75a70cf9 315 return is_gimple_assign (use_stmt)
316 && gimple_assign_rhs_code (use_stmt) == RDIV_EXPR
317 && gimple_assign_rhs2 (use_stmt) == def
119368d7 318 /* Do not recognize x / x as valid division, as we are getting
319 confused later by replacing all immediate uses x in such
320 a stmt. */
75a70cf9 321 && gimple_assign_rhs1 (use_stmt) != def;
ac70caad 322}
323
324/* Walk the subset of the dominator tree rooted at OCC, setting the
325 RECIP_DEF field to a definition of 1.0 / DEF that can be used in
326 the given basic block. The field may be left NULL, of course,
327 if it is not possible or profitable to do the optimization.
328
329 DEF_BSI is an iterator pointing at the statement defining DEF.
330 If RECIP_DEF is set, a dominator already has a computation that can
331 be used. */
332
333static void
75a70cf9 334insert_reciprocals (gimple_stmt_iterator *def_gsi, struct occurrence *occ,
ac70caad 335 tree def, tree recip_def, int threshold)
336{
75a70cf9 337 tree type;
338 gimple new_stmt;
339 gimple_stmt_iterator gsi;
ac70caad 340 struct occurrence *occ_child;
341
342 if (!recip_def
343 && (occ->bb_has_division || !flag_trapping_math)
344 && occ->num_divisions >= threshold)
345 {
346 /* Make a variable with the replacement and substitute it. */
347 type = TREE_TYPE (def);
072f7ab1 348 recip_def = create_tmp_reg (type, "reciptmp");
75a70cf9 349 new_stmt = gimple_build_assign_with_ops (RDIV_EXPR, recip_def,
350 build_one_cst (type), def);
48e1416a 351
ac70caad 352 if (occ->bb_has_division)
353 {
354 /* Case 1: insert before an existing division. */
75a70cf9 355 gsi = gsi_after_labels (occ->bb);
356 while (!gsi_end_p (gsi) && !is_division_by (gsi_stmt (gsi), def))
357 gsi_next (&gsi);
ac70caad 358
75a70cf9 359 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
ac70caad 360 }
75a70cf9 361 else if (def_gsi && occ->bb == def_gsi->bb)
685b24f5 362 {
ac70caad 363 /* Case 2: insert right after the definition. Note that this will
364 never happen if the definition statement can throw, because in
365 that case the sole successor of the statement's basic block will
366 dominate all the uses as well. */
75a70cf9 367 gsi_insert_after (def_gsi, new_stmt, GSI_NEW_STMT);
685b24f5 368 }
ac70caad 369 else
370 {
371 /* Case 3: insert in a basic block not containing defs/uses. */
75a70cf9 372 gsi = gsi_after_labels (occ->bb);
373 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
ac70caad 374 }
375
30c4e60d 376 reciprocal_stats.rdivs_inserted++;
377
ac70caad 378 occ->recip_def_stmt = new_stmt;
abacb398 379 }
380
ac70caad 381 occ->recip_def = recip_def;
382 for (occ_child = occ->children; occ_child; occ_child = occ_child->next)
75a70cf9 383 insert_reciprocals (def_gsi, occ_child, def, recip_def, threshold);
ac70caad 384}
385
386
387/* Replace the division at USE_P with a multiplication by the reciprocal, if
388 possible. */
389
390static inline void
391replace_reciprocal (use_operand_p use_p)
392{
75a70cf9 393 gimple use_stmt = USE_STMT (use_p);
394 basic_block bb = gimple_bb (use_stmt);
ac70caad 395 struct occurrence *occ = (struct occurrence *) bb->aux;
396
0bfd8d5c 397 if (optimize_bb_for_speed_p (bb)
398 && occ->recip_def && use_stmt != occ->recip_def_stmt)
ac70caad 399 {
50aacf4c 400 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
75a70cf9 401 gimple_assign_set_rhs_code (use_stmt, MULT_EXPR);
ac70caad 402 SET_USE (use_p, occ->recip_def);
50aacf4c 403 fold_stmt_inplace (&gsi);
ac70caad 404 update_stmt (use_stmt);
405 }
406}
407
408
409/* Free OCC and return one more "struct occurrence" to be freed. */
410
411static struct occurrence *
412free_bb (struct occurrence *occ)
413{
414 struct occurrence *child, *next;
415
416 /* First get the two pointers hanging off OCC. */
417 next = occ->next;
418 child = occ->children;
419 occ->bb->aux = NULL;
420 pool_free (occ_pool, occ);
421
422 /* Now ensure that we don't recurse unless it is necessary. */
423 if (!child)
424 return next;
9e583fac 425 else
ac70caad 426 {
427 while (next)
428 next = free_bb (next);
429
430 return child;
431 }
432}
433
434
435/* Look for floating-point divisions among DEF's uses, and try to
436 replace them by multiplications with the reciprocal. Add
437 as many statements computing the reciprocal as needed.
438
439 DEF must be a GIMPLE register of a floating-point type. */
440
441static void
75a70cf9 442execute_cse_reciprocals_1 (gimple_stmt_iterator *def_gsi, tree def)
ac70caad 443{
444 use_operand_p use_p;
445 imm_use_iterator use_iter;
446 struct occurrence *occ;
447 int count = 0, threshold;
abacb398 448
ac70caad 449 gcc_assert (FLOAT_TYPE_P (TREE_TYPE (def)) && is_gimple_reg (def));
450
451 FOR_EACH_IMM_USE_FAST (use_p, use_iter, def)
abacb398 452 {
75a70cf9 453 gimple use_stmt = USE_STMT (use_p);
ac70caad 454 if (is_division_by (use_stmt, def))
abacb398 455 {
75a70cf9 456 register_division_in (gimple_bb (use_stmt));
ac70caad 457 count++;
abacb398 458 }
459 }
48e1416a 460
ac70caad 461 /* Do the expensive part only if we can hope to optimize something. */
462 threshold = targetm.min_divisions_for_recip_mul (TYPE_MODE (TREE_TYPE (def)));
463 if (count >= threshold)
464 {
75a70cf9 465 gimple use_stmt;
ac70caad 466 for (occ = occ_head; occ; occ = occ->next)
467 {
468 compute_merit (occ);
75a70cf9 469 insert_reciprocals (def_gsi, occ, def, NULL, threshold);
ac70caad 470 }
471
09aca5bc 472 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, def)
ac70caad 473 {
ac70caad 474 if (is_division_by (use_stmt, def))
09aca5bc 475 {
476 FOR_EACH_IMM_USE_ON_STMT (use_p, use_iter)
477 replace_reciprocal (use_p);
478 }
ac70caad 479 }
480 }
481
482 for (occ = occ_head; occ; )
483 occ = free_bb (occ);
484
485 occ_head = NULL;
abacb398 486}
487
ac70caad 488static bool
489gate_cse_reciprocals (void)
490{
0bfd8d5c 491 return optimize && flag_reciprocal_math;
ac70caad 492}
493
ac70caad 494/* Go through all the floating-point SSA_NAMEs, and call
495 execute_cse_reciprocals_1 on each of them. */
2a1990e9 496static unsigned int
abacb398 497execute_cse_reciprocals (void)
498{
499 basic_block bb;
51b60a11 500 tree arg;
685b24f5 501
ac70caad 502 occ_pool = create_alloc_pool ("dominators for recip",
503 sizeof (struct occurrence),
504 n_basic_blocks / 3 + 1);
685b24f5 505
30c4e60d 506 memset (&reciprocal_stats, 0, sizeof (reciprocal_stats));
c136ae61 507 calculate_dominance_info (CDI_DOMINATORS);
508 calculate_dominance_info (CDI_POST_DOMINATORS);
ac70caad 509
510#ifdef ENABLE_CHECKING
511 FOR_EACH_BB (bb)
512 gcc_assert (!bb->aux);
513#endif
514
1767a056 515 for (arg = DECL_ARGUMENTS (cfun->decl); arg; arg = DECL_CHAIN (arg))
c6dfe037 516 if (FLOAT_TYPE_P (TREE_TYPE (arg))
ac70caad 517 && is_gimple_reg (arg))
c6dfe037 518 {
519 tree name = ssa_default_def (cfun, arg);
520 if (name)
521 execute_cse_reciprocals_1 (NULL, name);
522 }
51b60a11 523
abacb398 524 FOR_EACH_BB (bb)
525 {
75a70cf9 526 gimple_stmt_iterator gsi;
527 gimple phi;
528 tree def;
abacb398 529
75a70cf9 530 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
abacb398 531 {
75a70cf9 532 phi = gsi_stmt (gsi);
abacb398 533 def = PHI_RESULT (phi);
534 if (FLOAT_TYPE_P (TREE_TYPE (def))
535 && is_gimple_reg (def))
ac70caad 536 execute_cse_reciprocals_1 (NULL, def);
abacb398 537 }
538
75a70cf9 539 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
abacb398 540 {
75a70cf9 541 gimple stmt = gsi_stmt (gsi);
a0315874 542
75a70cf9 543 if (gimple_has_lhs (stmt)
abacb398 544 && (def = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_DEF)) != NULL
545 && FLOAT_TYPE_P (TREE_TYPE (def))
51b60a11 546 && TREE_CODE (def) == SSA_NAME)
75a70cf9 547 execute_cse_reciprocals_1 (&gsi, def);
abacb398 548 }
e174638f 549
0bfd8d5c 550 if (optimize_bb_for_size_p (bb))
551 continue;
552
e174638f 553 /* Scan for a/func(b) and convert it to reciprocal a*rfunc(b). */
75a70cf9 554 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
e174638f 555 {
75a70cf9 556 gimple stmt = gsi_stmt (gsi);
e174638f 557 tree fndecl;
558
75a70cf9 559 if (is_gimple_assign (stmt)
560 && gimple_assign_rhs_code (stmt) == RDIV_EXPR)
e174638f 561 {
75a70cf9 562 tree arg1 = gimple_assign_rhs2 (stmt);
563 gimple stmt1;
2cd360b6 564
565 if (TREE_CODE (arg1) != SSA_NAME)
566 continue;
567
568 stmt1 = SSA_NAME_DEF_STMT (arg1);
e174638f 569
75a70cf9 570 if (is_gimple_call (stmt1)
571 && gimple_call_lhs (stmt1)
572 && (fndecl = gimple_call_fndecl (stmt1))
e174638f 573 && (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
574 || DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD))
575 {
576 enum built_in_function code;
774b1cdd 577 bool md_code, fail;
578 imm_use_iterator ui;
579 use_operand_p use_p;
e174638f 580
581 code = DECL_FUNCTION_CODE (fndecl);
2cd360b6 582 md_code = DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD;
583
584 fndecl = targetm.builtin_reciprocal (code, md_code, false);
e174638f 585 if (!fndecl)
586 continue;
587
774b1cdd 588 /* Check that all uses of the SSA name are divisions,
589 otherwise replacing the defining statement will do
590 the wrong thing. */
591 fail = false;
592 FOR_EACH_IMM_USE_FAST (use_p, ui, arg1)
593 {
594 gimple stmt2 = USE_STMT (use_p);
595 if (is_gimple_debug (stmt2))
596 continue;
597 if (!is_gimple_assign (stmt2)
598 || gimple_assign_rhs_code (stmt2) != RDIV_EXPR
599 || gimple_assign_rhs1 (stmt2) == arg1
600 || gimple_assign_rhs2 (stmt2) != arg1)
601 {
602 fail = true;
603 break;
604 }
605 }
606 if (fail)
607 continue;
608
5fb3d93f 609 gimple_replace_lhs (stmt1, arg1);
0acacf9e 610 gimple_call_set_fndecl (stmt1, fndecl);
e174638f 611 update_stmt (stmt1);
30c4e60d 612 reciprocal_stats.rfuncs_inserted++;
e174638f 613
774b1cdd 614 FOR_EACH_IMM_USE_STMT (stmt, ui, arg1)
615 {
50aacf4c 616 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
774b1cdd 617 gimple_assign_set_rhs_code (stmt, MULT_EXPR);
50aacf4c 618 fold_stmt_inplace (&gsi);
774b1cdd 619 update_stmt (stmt);
620 }
e174638f 621 }
622 }
623 }
abacb398 624 }
685b24f5 625
30c4e60d 626 statistics_counter_event (cfun, "reciprocal divs inserted",
627 reciprocal_stats.rdivs_inserted);
628 statistics_counter_event (cfun, "reciprocal functions inserted",
629 reciprocal_stats.rfuncs_inserted);
630
c136ae61 631 free_dominance_info (CDI_DOMINATORS);
632 free_dominance_info (CDI_POST_DOMINATORS);
ac70caad 633 free_alloc_pool (occ_pool);
2a1990e9 634 return 0;
abacb398 635}
636
20099e35 637struct gimple_opt_pass pass_cse_reciprocals =
abacb398 638{
20099e35 639 {
640 GIMPLE_PASS,
abacb398 641 "recip", /* name */
642 gate_cse_reciprocals, /* gate */
643 execute_cse_reciprocals, /* execute */
644 NULL, /* sub */
645 NULL, /* next */
646 0, /* static_pass_number */
0b1615c1 647 TV_NONE, /* tv_id */
abacb398 648 PROP_ssa, /* properties_required */
649 0, /* properties_provided */
650 0, /* properties_destroyed */
651 0, /* todo_flags_start */
771e2890 652 TODO_update_ssa | TODO_verify_ssa
20099e35 653 | TODO_verify_stmts /* todo_flags_finish */
654 }
abacb398 655};
a0315874 656
0d424440 657/* Records an occurrence at statement USE_STMT in the vector of trees
a0315874 658 STMTS if it is dominated by *TOP_BB or dominates it or this basic block
0d424440 659 is not yet initialized. Returns true if the occurrence was pushed on
a0315874 660 the vector. Adjusts *TOP_BB to be the basic block dominating all
661 statements in the vector. */
662
663static bool
75a70cf9 664maybe_record_sincos (VEC(gimple, heap) **stmts,
665 basic_block *top_bb, gimple use_stmt)
a0315874 666{
75a70cf9 667 basic_block use_bb = gimple_bb (use_stmt);
a0315874 668 if (*top_bb
669 && (*top_bb == use_bb
670 || dominated_by_p (CDI_DOMINATORS, use_bb, *top_bb)))
75a70cf9 671 VEC_safe_push (gimple, heap, *stmts, use_stmt);
a0315874 672 else if (!*top_bb
673 || dominated_by_p (CDI_DOMINATORS, *top_bb, use_bb))
674 {
75a70cf9 675 VEC_safe_push (gimple, heap, *stmts, use_stmt);
a0315874 676 *top_bb = use_bb;
677 }
678 else
679 return false;
680
681 return true;
682}
683
684/* Look for sin, cos and cexpi calls with the same argument NAME and
685 create a single call to cexpi CSEing the result in this case.
686 We first walk over all immediate uses of the argument collecting
687 statements that we can CSE in a vector and in a second pass replace
688 the statement rhs with a REALPART or IMAGPART expression on the
689 result of the cexpi call we insert before the use statement that
690 dominates all other candidates. */
691
4c80086d 692static bool
a0315874 693execute_cse_sincos_1 (tree name)
694{
75a70cf9 695 gimple_stmt_iterator gsi;
a0315874 696 imm_use_iterator use_iter;
75a70cf9 697 tree fndecl, res, type;
698 gimple def_stmt, use_stmt, stmt;
a0315874 699 int seen_cos = 0, seen_sin = 0, seen_cexpi = 0;
75a70cf9 700 VEC(gimple, heap) *stmts = NULL;
a0315874 701 basic_block top_bb = NULL;
702 int i;
4c80086d 703 bool cfg_changed = false;
a0315874 704
705 type = TREE_TYPE (name);
706 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, name)
707 {
75a70cf9 708 if (gimple_code (use_stmt) != GIMPLE_CALL
709 || !gimple_call_lhs (use_stmt)
710 || !(fndecl = gimple_call_fndecl (use_stmt))
a0315874 711 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
712 continue;
713
714 switch (DECL_FUNCTION_CODE (fndecl))
715 {
716 CASE_FLT_FN (BUILT_IN_COS):
717 seen_cos |= maybe_record_sincos (&stmts, &top_bb, use_stmt) ? 1 : 0;
718 break;
719
720 CASE_FLT_FN (BUILT_IN_SIN):
721 seen_sin |= maybe_record_sincos (&stmts, &top_bb, use_stmt) ? 1 : 0;
722 break;
723
724 CASE_FLT_FN (BUILT_IN_CEXPI):
725 seen_cexpi |= maybe_record_sincos (&stmts, &top_bb, use_stmt) ? 1 : 0;
726 break;
727
728 default:;
729 }
730 }
731
732 if (seen_cos + seen_sin + seen_cexpi <= 1)
733 {
75a70cf9 734 VEC_free(gimple, heap, stmts);
4c80086d 735 return false;
a0315874 736 }
737
738 /* Simply insert cexpi at the beginning of top_bb but not earlier than
739 the name def statement. */
740 fndecl = mathfn_built_in (type, BUILT_IN_CEXPI);
741 if (!fndecl)
4c80086d 742 return false;
75a70cf9 743 stmt = gimple_build_call (fndecl, 1, name);
03d37e4e 744 res = make_temp_ssa_name (TREE_TYPE (TREE_TYPE (fndecl)), stmt, "sincostmp");
75a70cf9 745 gimple_call_set_lhs (stmt, res);
746
a0315874 747 def_stmt = SSA_NAME_DEF_STMT (name);
8090c12d 748 if (!SSA_NAME_IS_DEFAULT_DEF (name)
75a70cf9 749 && gimple_code (def_stmt) != GIMPLE_PHI
750 && gimple_bb (def_stmt) == top_bb)
a0315874 751 {
75a70cf9 752 gsi = gsi_for_stmt (def_stmt);
753 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
a0315874 754 }
755 else
756 {
75a70cf9 757 gsi = gsi_after_labels (top_bb);
758 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
a0315874 759 }
30c4e60d 760 sincos_stats.inserted++;
a0315874 761
762 /* And adjust the recorded old call sites. */
75a70cf9 763 for (i = 0; VEC_iterate(gimple, stmts, i, use_stmt); ++i)
a0315874 764 {
75a70cf9 765 tree rhs = NULL;
766 fndecl = gimple_call_fndecl (use_stmt);
767
a0315874 768 switch (DECL_FUNCTION_CODE (fndecl))
769 {
770 CASE_FLT_FN (BUILT_IN_COS):
75a70cf9 771 rhs = fold_build1 (REALPART_EXPR, type, res);
a0315874 772 break;
773
774 CASE_FLT_FN (BUILT_IN_SIN):
75a70cf9 775 rhs = fold_build1 (IMAGPART_EXPR, type, res);
a0315874 776 break;
777
778 CASE_FLT_FN (BUILT_IN_CEXPI):
75a70cf9 779 rhs = res;
a0315874 780 break;
781
782 default:;
783 gcc_unreachable ();
784 }
785
75a70cf9 786 /* Replace call with a copy. */
787 stmt = gimple_build_assign (gimple_call_lhs (use_stmt), rhs);
788
789 gsi = gsi_for_stmt (use_stmt);
4c80086d 790 gsi_replace (&gsi, stmt, true);
791 if (gimple_purge_dead_eh_edges (gimple_bb (stmt)))
792 cfg_changed = true;
a0315874 793 }
794
75a70cf9 795 VEC_free(gimple, heap, stmts);
4c80086d 796
797 return cfg_changed;
a0315874 798}
799
e9a6c4bc 800/* To evaluate powi(x,n), the floating point value x raised to the
801 constant integer exponent n, we use a hybrid algorithm that
802 combines the "window method" with look-up tables. For an
803 introduction to exponentiation algorithms and "addition chains",
804 see section 4.6.3, "Evaluation of Powers" of Donald E. Knuth,
805 "Seminumerical Algorithms", Vol. 2, "The Art of Computer Programming",
806 3rd Edition, 1998, and Daniel M. Gordon, "A Survey of Fast Exponentiation
807 Methods", Journal of Algorithms, Vol. 27, pp. 129-146, 1998. */
808
809/* Provide a default value for POWI_MAX_MULTS, the maximum number of
810 multiplications to inline before calling the system library's pow
811 function. powi(x,n) requires at worst 2*bits(n)-2 multiplications,
812 so this default never requires calling pow, powf or powl. */
813
814#ifndef POWI_MAX_MULTS
815#define POWI_MAX_MULTS (2*HOST_BITS_PER_WIDE_INT-2)
816#endif
817
818/* The size of the "optimal power tree" lookup table. All
819 exponents less than this value are simply looked up in the
820 powi_table below. This threshold is also used to size the
821 cache of pseudo registers that hold intermediate results. */
822#define POWI_TABLE_SIZE 256
823
824/* The size, in bits of the window, used in the "window method"
825 exponentiation algorithm. This is equivalent to a radix of
826 (1<<POWI_WINDOW_SIZE) in the corresponding "m-ary method". */
827#define POWI_WINDOW_SIZE 3
828
829/* The following table is an efficient representation of an
830 "optimal power tree". For each value, i, the corresponding
831 value, j, in the table states than an optimal evaluation
832 sequence for calculating pow(x,i) can be found by evaluating
833 pow(x,j)*pow(x,i-j). An optimal power tree for the first
834 100 integers is given in Knuth's "Seminumerical algorithms". */
835
836static const unsigned char powi_table[POWI_TABLE_SIZE] =
837 {
838 0, 1, 1, 2, 2, 3, 3, 4, /* 0 - 7 */
839 4, 6, 5, 6, 6, 10, 7, 9, /* 8 - 15 */
840 8, 16, 9, 16, 10, 12, 11, 13, /* 16 - 23 */
841 12, 17, 13, 18, 14, 24, 15, 26, /* 24 - 31 */
842 16, 17, 17, 19, 18, 33, 19, 26, /* 32 - 39 */
843 20, 25, 21, 40, 22, 27, 23, 44, /* 40 - 47 */
844 24, 32, 25, 34, 26, 29, 27, 44, /* 48 - 55 */
845 28, 31, 29, 34, 30, 60, 31, 36, /* 56 - 63 */
846 32, 64, 33, 34, 34, 46, 35, 37, /* 64 - 71 */
847 36, 65, 37, 50, 38, 48, 39, 69, /* 72 - 79 */
848 40, 49, 41, 43, 42, 51, 43, 58, /* 80 - 87 */
849 44, 64, 45, 47, 46, 59, 47, 76, /* 88 - 95 */
850 48, 65, 49, 66, 50, 67, 51, 66, /* 96 - 103 */
851 52, 70, 53, 74, 54, 104, 55, 74, /* 104 - 111 */
852 56, 64, 57, 69, 58, 78, 59, 68, /* 112 - 119 */
853 60, 61, 61, 80, 62, 75, 63, 68, /* 120 - 127 */
854 64, 65, 65, 128, 66, 129, 67, 90, /* 128 - 135 */
855 68, 73, 69, 131, 70, 94, 71, 88, /* 136 - 143 */
856 72, 128, 73, 98, 74, 132, 75, 121, /* 144 - 151 */
857 76, 102, 77, 124, 78, 132, 79, 106, /* 152 - 159 */
858 80, 97, 81, 160, 82, 99, 83, 134, /* 160 - 167 */
859 84, 86, 85, 95, 86, 160, 87, 100, /* 168 - 175 */
860 88, 113, 89, 98, 90, 107, 91, 122, /* 176 - 183 */
861 92, 111, 93, 102, 94, 126, 95, 150, /* 184 - 191 */
862 96, 128, 97, 130, 98, 133, 99, 195, /* 192 - 199 */
863 100, 128, 101, 123, 102, 164, 103, 138, /* 200 - 207 */
864 104, 145, 105, 146, 106, 109, 107, 149, /* 208 - 215 */
865 108, 200, 109, 146, 110, 170, 111, 157, /* 216 - 223 */
866 112, 128, 113, 130, 114, 182, 115, 132, /* 224 - 231 */
867 116, 200, 117, 132, 118, 158, 119, 206, /* 232 - 239 */
868 120, 240, 121, 162, 122, 147, 123, 152, /* 240 - 247 */
869 124, 166, 125, 214, 126, 138, 127, 153, /* 248 - 255 */
870 };
871
872
873/* Return the number of multiplications required to calculate
874 powi(x,n) where n is less than POWI_TABLE_SIZE. This is a
875 subroutine of powi_cost. CACHE is an array indicating
876 which exponents have already been calculated. */
877
878static int
879powi_lookup_cost (unsigned HOST_WIDE_INT n, bool *cache)
880{
881 /* If we've already calculated this exponent, then this evaluation
882 doesn't require any additional multiplications. */
883 if (cache[n])
884 return 0;
885
886 cache[n] = true;
887 return powi_lookup_cost (n - powi_table[n], cache)
888 + powi_lookup_cost (powi_table[n], cache) + 1;
889}
890
891/* Return the number of multiplications required to calculate
892 powi(x,n) for an arbitrary x, given the exponent N. This
893 function needs to be kept in sync with powi_as_mults below. */
894
895static int
896powi_cost (HOST_WIDE_INT n)
897{
898 bool cache[POWI_TABLE_SIZE];
899 unsigned HOST_WIDE_INT digit;
900 unsigned HOST_WIDE_INT val;
901 int result;
902
903 if (n == 0)
904 return 0;
905
906 /* Ignore the reciprocal when calculating the cost. */
907 val = (n < 0) ? -n : n;
908
909 /* Initialize the exponent cache. */
910 memset (cache, 0, POWI_TABLE_SIZE * sizeof (bool));
911 cache[1] = true;
912
913 result = 0;
914
915 while (val >= POWI_TABLE_SIZE)
916 {
917 if (val & 1)
918 {
919 digit = val & ((1 << POWI_WINDOW_SIZE) - 1);
920 result += powi_lookup_cost (digit, cache)
921 + POWI_WINDOW_SIZE + 1;
922 val >>= POWI_WINDOW_SIZE;
923 }
924 else
925 {
926 val >>= 1;
927 result++;
928 }
929 }
930
931 return result + powi_lookup_cost (val, cache);
932}
933
934/* Recursive subroutine of powi_as_mults. This function takes the
935 array, CACHE, of already calculated exponents and an exponent N and
936 returns a tree that corresponds to CACHE[1]**N, with type TYPE. */
937
938static tree
939powi_as_mults_1 (gimple_stmt_iterator *gsi, location_t loc, tree type,
03d37e4e 940 HOST_WIDE_INT n, tree *cache)
e9a6c4bc 941{
942 tree op0, op1, ssa_target;
943 unsigned HOST_WIDE_INT digit;
944 gimple mult_stmt;
945
946 if (n < POWI_TABLE_SIZE && cache[n])
947 return cache[n];
948
03d37e4e 949 ssa_target = make_temp_ssa_name (type, NULL, "powmult");
e9a6c4bc 950
951 if (n < POWI_TABLE_SIZE)
952 {
953 cache[n] = ssa_target;
03d37e4e 954 op0 = powi_as_mults_1 (gsi, loc, type, n - powi_table[n], cache);
955 op1 = powi_as_mults_1 (gsi, loc, type, powi_table[n], cache);
e9a6c4bc 956 }
957 else if (n & 1)
958 {
959 digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
03d37e4e 960 op0 = powi_as_mults_1 (gsi, loc, type, n - digit, cache);
961 op1 = powi_as_mults_1 (gsi, loc, type, digit, cache);
e9a6c4bc 962 }
963 else
964 {
03d37e4e 965 op0 = powi_as_mults_1 (gsi, loc, type, n >> 1, cache);
e9a6c4bc 966 op1 = op0;
967 }
968
969 mult_stmt = gimple_build_assign_with_ops (MULT_EXPR, ssa_target, op0, op1);
ae43b05e 970 gimple_set_location (mult_stmt, loc);
e9a6c4bc 971 gsi_insert_before (gsi, mult_stmt, GSI_SAME_STMT);
972
973 return ssa_target;
974}
975
976/* Convert ARG0**N to a tree of multiplications of ARG0 with itself.
977 This function needs to be kept in sync with powi_cost above. */
978
979static tree
980powi_as_mults (gimple_stmt_iterator *gsi, location_t loc,
981 tree arg0, HOST_WIDE_INT n)
982{
03d37e4e 983 tree cache[POWI_TABLE_SIZE], result, type = TREE_TYPE (arg0);
e9a6c4bc 984 gimple div_stmt;
03d37e4e 985 tree target;
e9a6c4bc 986
987 if (n == 0)
988 return build_real (type, dconst1);
989
990 memset (cache, 0, sizeof (cache));
991 cache[1] = arg0;
992
03d37e4e 993 result = powi_as_mults_1 (gsi, loc, type, (n < 0) ? -n : n, cache);
e9a6c4bc 994 if (n >= 0)
995 return result;
996
997 /* If the original exponent was negative, reciprocate the result. */
03d37e4e 998 target = make_temp_ssa_name (type, NULL, "powmult");
e9a6c4bc 999 div_stmt = gimple_build_assign_with_ops (RDIV_EXPR, target,
1000 build_real (type, dconst1),
1001 result);
ae43b05e 1002 gimple_set_location (div_stmt, loc);
e9a6c4bc 1003 gsi_insert_before (gsi, div_stmt, GSI_SAME_STMT);
1004
1005 return target;
1006}
1007
1008/* ARG0 and N are the two arguments to a powi builtin in GSI with
1009 location info LOC. If the arguments are appropriate, create an
1010 equivalent sequence of statements prior to GSI using an optimal
1011 number of multiplications, and return an expession holding the
1012 result. */
1013
1014static tree
1015gimple_expand_builtin_powi (gimple_stmt_iterator *gsi, location_t loc,
1016 tree arg0, HOST_WIDE_INT n)
1017{
1018 /* Avoid largest negative number. */
1019 if (n != -n
1020 && ((n >= -1 && n <= 2)
1021 || (optimize_function_for_speed_p (cfun)
1022 && powi_cost (n) <= POWI_MAX_MULTS)))
1023 return powi_as_mults (gsi, loc, arg0, n);
1024
1025 return NULL_TREE;
1026}
1027
ae43b05e 1028/* Build a gimple call statement that calls FN with argument ARG.
03d37e4e 1029 Set the lhs of the call statement to a fresh SSA name. Insert the
ae43b05e 1030 statement prior to GSI's current position, and return the fresh
1031 SSA name. */
1032
1033static tree
ca12eb68 1034build_and_insert_call (gimple_stmt_iterator *gsi, location_t loc,
03d37e4e 1035 tree fn, tree arg)
ae43b05e 1036{
1037 gimple call_stmt;
1038 tree ssa_target;
1039
ae43b05e 1040 call_stmt = gimple_build_call (fn, 1, arg);
03d37e4e 1041 ssa_target = make_temp_ssa_name (TREE_TYPE (arg), NULL, "powroot");
ae43b05e 1042 gimple_set_lhs (call_stmt, ssa_target);
1043 gimple_set_location (call_stmt, loc);
1044 gsi_insert_before (gsi, call_stmt, GSI_SAME_STMT);
1045
1046 return ssa_target;
1047}
1048
ca12eb68 1049/* Build a gimple binary operation with the given CODE and arguments
1050 ARG0, ARG1, assigning the result to a new SSA name for variable
1051 TARGET. Insert the statement prior to GSI's current position, and
1052 return the fresh SSA name.*/
1053
1054static tree
1055build_and_insert_binop (gimple_stmt_iterator *gsi, location_t loc,
03d37e4e 1056 const char *name, enum tree_code code,
1057 tree arg0, tree arg1)
ca12eb68 1058{
03d37e4e 1059 tree result = make_temp_ssa_name (TREE_TYPE (arg0), NULL, name);
ca12eb68 1060 gimple stmt = gimple_build_assign_with_ops (code, result, arg0, arg1);
1061 gimple_set_location (stmt, loc);
1062 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1063 return result;
1064}
1065
a5c384c1 1066/* Build a gimple reference operation with the given CODE and argument
03d37e4e 1067 ARG, assigning the result to a new SSA name of TYPE with NAME.
a5c384c1 1068 Insert the statement prior to GSI's current position, and return
1069 the fresh SSA name. */
1070
1071static inline tree
1072build_and_insert_ref (gimple_stmt_iterator *gsi, location_t loc, tree type,
03d37e4e 1073 const char *name, enum tree_code code, tree arg0)
a5c384c1 1074{
03d37e4e 1075 tree result = make_temp_ssa_name (type, NULL, name);
a5c384c1 1076 gimple stmt = gimple_build_assign (result, build1 (code, type, arg0));
1077 gimple_set_location (stmt, loc);
1078 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1079 return result;
1080}
1081
03d37e4e 1082/* Build a gimple assignment to cast VAL to TYPE. Insert the statement
aff5fb4d 1083 prior to GSI's current position, and return the fresh SSA name. */
1084
1085static tree
1086build_and_insert_cast (gimple_stmt_iterator *gsi, location_t loc,
03d37e4e 1087 tree type, tree val)
aff5fb4d 1088{
03d37e4e 1089 tree result = make_ssa_name (type, NULL);
1090 gimple stmt = gimple_build_assign_with_ops (NOP_EXPR, result, val, NULL_TREE);
1091 gimple_set_location (stmt, loc);
1092 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1093 return result;
aff5fb4d 1094}
1095
e78306af 1096/* ARG0 and ARG1 are the two arguments to a pow builtin call in GSI
1097 with location info LOC. If possible, create an equivalent and
1098 less expensive sequence of statements prior to GSI, and return an
1099 expession holding the result. */
1100
1101static tree
1102gimple_expand_builtin_pow (gimple_stmt_iterator *gsi, location_t loc,
1103 tree arg0, tree arg1)
1104{
ae43b05e 1105 REAL_VALUE_TYPE c, cint, dconst1_4, dconst3_4, dconst1_3, dconst1_6;
ca12eb68 1106 REAL_VALUE_TYPE c2, dconst3;
e78306af 1107 HOST_WIDE_INT n;
ca12eb68 1108 tree type, sqrtfn, cbrtfn, sqrt_arg0, sqrt_sqrt, result, cbrt_x, powi_cbrt_x;
ae43b05e 1109 enum machine_mode mode;
1110 bool hw_sqrt_exists;
e78306af 1111
1112 /* If the exponent isn't a constant, there's nothing of interest
1113 to be done. */
1114 if (TREE_CODE (arg1) != REAL_CST)
1115 return NULL_TREE;
1116
ae43b05e 1117 /* If the exponent is equivalent to an integer, expand to an optimal
1118 multiplication sequence when profitable. */
e78306af 1119 c = TREE_REAL_CST (arg1);
1120 n = real_to_integer (&c);
1121 real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
1122
1123 if (real_identical (&c, &cint)
1124 && ((n >= -1 && n <= 2)
1125 || (flag_unsafe_math_optimizations
1126 && optimize_insn_for_speed_p ()
1127 && powi_cost (n) <= POWI_MAX_MULTS)))
1128 return gimple_expand_builtin_powi (gsi, loc, arg0, n);
1129
ae43b05e 1130 /* Attempt various optimizations using sqrt and cbrt. */
1131 type = TREE_TYPE (arg0);
1132 mode = TYPE_MODE (type);
1133 sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
1134
1135 /* Optimize pow(x,0.5) = sqrt(x). This replacement is always safe
1136 unless signed zeros must be maintained. pow(-0,0.5) = +0, while
1137 sqrt(-0) = -0. */
1138 if (sqrtfn
1139 && REAL_VALUES_EQUAL (c, dconsthalf)
1140 && !HONOR_SIGNED_ZEROS (mode))
03d37e4e 1141 return build_and_insert_call (gsi, loc, sqrtfn, arg0);
ae43b05e 1142
1143 /* Optimize pow(x,0.25) = sqrt(sqrt(x)). Assume on most machines that
1144 a builtin sqrt instruction is smaller than a call to pow with 0.25,
1145 so do this optimization even if -Os. Don't do this optimization
1146 if we don't have a hardware sqrt insn. */
1147 dconst1_4 = dconst1;
1148 SET_REAL_EXP (&dconst1_4, REAL_EXP (&dconst1_4) - 2);
a5c384c1 1149 hw_sqrt_exists = optab_handler (sqrt_optab, mode) != CODE_FOR_nothing;
ae43b05e 1150
1151 if (flag_unsafe_math_optimizations
1152 && sqrtfn
1153 && REAL_VALUES_EQUAL (c, dconst1_4)
1154 && hw_sqrt_exists)
1155 {
1156 /* sqrt(x) */
03d37e4e 1157 sqrt_arg0 = build_and_insert_call (gsi, loc, sqrtfn, arg0);
ae43b05e 1158
1159 /* sqrt(sqrt(x)) */
03d37e4e 1160 return build_and_insert_call (gsi, loc, sqrtfn, sqrt_arg0);
ae43b05e 1161 }
1162
1163 /* Optimize pow(x,0.75) = sqrt(x) * sqrt(sqrt(x)) unless we are
1164 optimizing for space. Don't do this optimization if we don't have
1165 a hardware sqrt insn. */
1166 real_from_integer (&dconst3_4, VOIDmode, 3, 0, 0);
1167 SET_REAL_EXP (&dconst3_4, REAL_EXP (&dconst3_4) - 2);
1168
1169 if (flag_unsafe_math_optimizations
1170 && sqrtfn
1171 && optimize_function_for_speed_p (cfun)
1172 && REAL_VALUES_EQUAL (c, dconst3_4)
1173 && hw_sqrt_exists)
1174 {
1175 /* sqrt(x) */
03d37e4e 1176 sqrt_arg0 = build_and_insert_call (gsi, loc, sqrtfn, arg0);
ae43b05e 1177
1178 /* sqrt(sqrt(x)) */
03d37e4e 1179 sqrt_sqrt = build_and_insert_call (gsi, loc, sqrtfn, sqrt_arg0);
ae43b05e 1180
1181 /* sqrt(x) * sqrt(sqrt(x)) */
03d37e4e 1182 return build_and_insert_binop (gsi, loc, "powroot", MULT_EXPR,
ca12eb68 1183 sqrt_arg0, sqrt_sqrt);
ae43b05e 1184 }
1185
1186 /* Optimize pow(x,1./3.) = cbrt(x). This requires unsafe math
1187 optimizations since 1./3. is not exactly representable. If x
1188 is negative and finite, the correct value of pow(x,1./3.) is
1189 a NaN with the "invalid" exception raised, because the value
1190 of 1./3. actually has an even denominator. The correct value
1191 of cbrt(x) is a negative real value. */
1192 cbrtfn = mathfn_built_in (type, BUILT_IN_CBRT);
1193 dconst1_3 = real_value_truncate (mode, dconst_third ());
1194
1195 if (flag_unsafe_math_optimizations
1196 && cbrtfn
0b7ad900 1197 && (gimple_val_nonnegative_real_p (arg0) || !HONOR_NANS (mode))
ae43b05e 1198 && REAL_VALUES_EQUAL (c, dconst1_3))
03d37e4e 1199 return build_and_insert_call (gsi, loc, cbrtfn, arg0);
ae43b05e 1200
1201 /* Optimize pow(x,1./6.) = cbrt(sqrt(x)). Don't do this optimization
1202 if we don't have a hardware sqrt insn. */
1203 dconst1_6 = dconst1_3;
1204 SET_REAL_EXP (&dconst1_6, REAL_EXP (&dconst1_6) - 1);
1205
1206 if (flag_unsafe_math_optimizations
1207 && sqrtfn
1208 && cbrtfn
0b7ad900 1209 && (gimple_val_nonnegative_real_p (arg0) || !HONOR_NANS (mode))
ae43b05e 1210 && optimize_function_for_speed_p (cfun)
1211 && hw_sqrt_exists
1212 && REAL_VALUES_EQUAL (c, dconst1_6))
1213 {
1214 /* sqrt(x) */
03d37e4e 1215 sqrt_arg0 = build_and_insert_call (gsi, loc, sqrtfn, arg0);
ae43b05e 1216
1217 /* cbrt(sqrt(x)) */
03d37e4e 1218 return build_and_insert_call (gsi, loc, cbrtfn, sqrt_arg0);
ca12eb68 1219 }
1220
1221 /* Optimize pow(x,c), where n = 2c for some nonzero integer n, into
1222
1223 sqrt(x) * powi(x, n/2), n > 0;
1224 1.0 / (sqrt(x) * powi(x, abs(n/2))), n < 0.
1225
1226 Do not calculate the powi factor when n/2 = 0. */
1227 real_arithmetic (&c2, MULT_EXPR, &c, &dconst2);
1228 n = real_to_integer (&c2);
1229 real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
1230
1231 if (flag_unsafe_math_optimizations
1232 && sqrtfn
1233 && real_identical (&c2, &cint))
1234 {
1235 tree powi_x_ndiv2 = NULL_TREE;
1236
1237 /* Attempt to fold powi(arg0, abs(n/2)) into multiplies. If not
1238 possible or profitable, give up. Skip the degenerate case when
1239 n is 1 or -1, where the result is always 1. */
b1757d46 1240 if (absu_hwi (n) != 1)
ca12eb68 1241 {
5ebd604f 1242 powi_x_ndiv2 = gimple_expand_builtin_powi (gsi, loc, arg0,
1243 abs_hwi (n / 2));
ca12eb68 1244 if (!powi_x_ndiv2)
1245 return NULL_TREE;
1246 }
1247
1248 /* Calculate sqrt(x). When n is not 1 or -1, multiply it by the
1249 result of the optimal multiply sequence just calculated. */
03d37e4e 1250 sqrt_arg0 = build_and_insert_call (gsi, loc, sqrtfn, arg0);
ca12eb68 1251
b1757d46 1252 if (absu_hwi (n) == 1)
ca12eb68 1253 result = sqrt_arg0;
1254 else
03d37e4e 1255 result = build_and_insert_binop (gsi, loc, "powroot", MULT_EXPR,
ca12eb68 1256 sqrt_arg0, powi_x_ndiv2);
1257
1258 /* If n is negative, reciprocate the result. */
1259 if (n < 0)
03d37e4e 1260 result = build_and_insert_binop (gsi, loc, "powroot", RDIV_EXPR,
ca12eb68 1261 build_real (type, dconst1), result);
1262 return result;
1263 }
1264
1265 /* Optimize pow(x,c), where 3c = n for some nonzero integer n, into
1266
1267 powi(x, n/3) * powi(cbrt(x), n%3), n > 0;
1268 1.0 / (powi(x, abs(n)/3) * powi(cbrt(x), abs(n)%3)), n < 0.
1269
1270 Do not calculate the first factor when n/3 = 0. As cbrt(x) is
1271 different from pow(x, 1./3.) due to rounding and behavior with
1272 negative x, we need to constrain this transformation to unsafe
1273 math and positive x or finite math. */
1274 real_from_integer (&dconst3, VOIDmode, 3, 0, 0);
1275 real_arithmetic (&c2, MULT_EXPR, &c, &dconst3);
1276 real_round (&c2, mode, &c2);
1277 n = real_to_integer (&c2);
1278 real_from_integer (&cint, VOIDmode, n, n < 0 ? -1 : 0, 0);
1279 real_arithmetic (&c2, RDIV_EXPR, &cint, &dconst3);
1280 real_convert (&c2, mode, &c2);
1281
1282 if (flag_unsafe_math_optimizations
1283 && cbrtfn
0b7ad900 1284 && (gimple_val_nonnegative_real_p (arg0) || !HONOR_NANS (mode))
ca12eb68 1285 && real_identical (&c2, &c)
1286 && optimize_function_for_speed_p (cfun)
1287 && powi_cost (n / 3) <= POWI_MAX_MULTS)
1288 {
1289 tree powi_x_ndiv3 = NULL_TREE;
1290
1291 /* Attempt to fold powi(arg0, abs(n/3)) into multiplies. If not
1292 possible or profitable, give up. Skip the degenerate case when
1293 abs(n) < 3, where the result is always 1. */
b1757d46 1294 if (absu_hwi (n) >= 3)
ca12eb68 1295 {
1296 powi_x_ndiv3 = gimple_expand_builtin_powi (gsi, loc, arg0,
5ebd604f 1297 abs_hwi (n / 3));
ca12eb68 1298 if (!powi_x_ndiv3)
1299 return NULL_TREE;
1300 }
1301
1302 /* Calculate powi(cbrt(x), n%3). Don't use gimple_expand_builtin_powi
1303 as that creates an unnecessary variable. Instead, just produce
1304 either cbrt(x) or cbrt(x) * cbrt(x). */
03d37e4e 1305 cbrt_x = build_and_insert_call (gsi, loc, cbrtfn, arg0);
ca12eb68 1306
b1757d46 1307 if (absu_hwi (n) % 3 == 1)
ca12eb68 1308 powi_cbrt_x = cbrt_x;
1309 else
03d37e4e 1310 powi_cbrt_x = build_and_insert_binop (gsi, loc, "powroot", MULT_EXPR,
ca12eb68 1311 cbrt_x, cbrt_x);
1312
1313 /* Multiply the two subexpressions, unless powi(x,abs(n)/3) = 1. */
b1757d46 1314 if (absu_hwi (n) < 3)
ca12eb68 1315 result = powi_cbrt_x;
1316 else
03d37e4e 1317 result = build_and_insert_binop (gsi, loc, "powroot", MULT_EXPR,
ca12eb68 1318 powi_x_ndiv3, powi_cbrt_x);
1319
1320 /* If n is negative, reciprocate the result. */
1321 if (n < 0)
03d37e4e 1322 result = build_and_insert_binop (gsi, loc, "powroot", RDIV_EXPR,
ca12eb68 1323 build_real (type, dconst1), result);
1324
1325 return result;
ae43b05e 1326 }
1327
ca12eb68 1328 /* No optimizations succeeded. */
e78306af 1329 return NULL_TREE;
1330}
1331
a5c384c1 1332/* ARG is the argument to a cabs builtin call in GSI with location info
1333 LOC. Create a sequence of statements prior to GSI that calculates
1334 sqrt(R*R + I*I), where R and I are the real and imaginary components
1335 of ARG, respectively. Return an expression holding the result. */
1336
1337static tree
1338gimple_expand_builtin_cabs (gimple_stmt_iterator *gsi, location_t loc, tree arg)
1339{
03d37e4e 1340 tree real_part, imag_part, addend1, addend2, sum, result;
a5c384c1 1341 tree type = TREE_TYPE (TREE_TYPE (arg));
1342 tree sqrtfn = mathfn_built_in (type, BUILT_IN_SQRT);
1343 enum machine_mode mode = TYPE_MODE (type);
1344
1345 if (!flag_unsafe_math_optimizations
1346 || !optimize_bb_for_speed_p (gimple_bb (gsi_stmt (*gsi)))
1347 || !sqrtfn
1348 || optab_handler (sqrt_optab, mode) == CODE_FOR_nothing)
1349 return NULL_TREE;
1350
03d37e4e 1351 real_part = build_and_insert_ref (gsi, loc, type, "cabs",
a5c384c1 1352 REALPART_EXPR, arg);
03d37e4e 1353 addend1 = build_and_insert_binop (gsi, loc, "cabs", MULT_EXPR,
a5c384c1 1354 real_part, real_part);
03d37e4e 1355 imag_part = build_and_insert_ref (gsi, loc, type, "cabs",
a5c384c1 1356 IMAGPART_EXPR, arg);
03d37e4e 1357 addend2 = build_and_insert_binop (gsi, loc, "cabs", MULT_EXPR,
a5c384c1 1358 imag_part, imag_part);
03d37e4e 1359 sum = build_and_insert_binop (gsi, loc, "cabs", PLUS_EXPR, addend1, addend2);
1360 result = build_and_insert_call (gsi, loc, sqrtfn, sum);
a5c384c1 1361
1362 return result;
1363}
1364
a0315874 1365/* Go through all calls to sin, cos and cexpi and call execute_cse_sincos_1
e9a6c4bc 1366 on the SSA_NAME argument of each of them. Also expand powi(x,n) into
1367 an optimal number of multiplies, when n is a constant. */
a0315874 1368
1369static unsigned int
1370execute_cse_sincos (void)
1371{
1372 basic_block bb;
4c80086d 1373 bool cfg_changed = false;
a0315874 1374
1375 calculate_dominance_info (CDI_DOMINATORS);
30c4e60d 1376 memset (&sincos_stats, 0, sizeof (sincos_stats));
a0315874 1377
1378 FOR_EACH_BB (bb)
1379 {
75a70cf9 1380 gimple_stmt_iterator gsi;
a0315874 1381
75a70cf9 1382 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
a0315874 1383 {
75a70cf9 1384 gimple stmt = gsi_stmt (gsi);
a0315874 1385 tree fndecl;
1386
75a70cf9 1387 if (is_gimple_call (stmt)
1388 && gimple_call_lhs (stmt)
1389 && (fndecl = gimple_call_fndecl (stmt))
a0315874 1390 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1391 {
e9a6c4bc 1392 tree arg, arg0, arg1, result;
1393 HOST_WIDE_INT n;
1394 location_t loc;
a0315874 1395
1396 switch (DECL_FUNCTION_CODE (fndecl))
1397 {
1398 CASE_FLT_FN (BUILT_IN_COS):
1399 CASE_FLT_FN (BUILT_IN_SIN):
1400 CASE_FLT_FN (BUILT_IN_CEXPI):
d312d7df 1401 /* Make sure we have either sincos or cexp. */
1402 if (!TARGET_HAS_SINCOS && !TARGET_C99_FUNCTIONS)
1403 break;
1404
75a70cf9 1405 arg = gimple_call_arg (stmt, 0);
a0315874 1406 if (TREE_CODE (arg) == SSA_NAME)
4c80086d 1407 cfg_changed |= execute_cse_sincos_1 (arg);
a0315874 1408 break;
1409
e78306af 1410 CASE_FLT_FN (BUILT_IN_POW):
1411 arg0 = gimple_call_arg (stmt, 0);
1412 arg1 = gimple_call_arg (stmt, 1);
1413
1414 loc = gimple_location (stmt);
1415 result = gimple_expand_builtin_pow (&gsi, loc, arg0, arg1);
1416
1417 if (result)
1418 {
1419 tree lhs = gimple_get_lhs (stmt);
1420 gimple new_stmt = gimple_build_assign (lhs, result);
1421 gimple_set_location (new_stmt, loc);
1422 unlink_stmt_vdef (stmt);
1423 gsi_replace (&gsi, new_stmt, true);
bc8a8451 1424 if (gimple_vdef (stmt))
1425 release_ssa_name (gimple_vdef (stmt));
e78306af 1426 }
1427 break;
1428
e9a6c4bc 1429 CASE_FLT_FN (BUILT_IN_POWI):
1430 arg0 = gimple_call_arg (stmt, 0);
1431 arg1 = gimple_call_arg (stmt, 1);
1432 if (!host_integerp (arg1, 0))
1433 break;
1434
1435 n = TREE_INT_CST_LOW (arg1);
1436 loc = gimple_location (stmt);
1437 result = gimple_expand_builtin_powi (&gsi, loc, arg0, n);
1438
1439 if (result)
1440 {
1441 tree lhs = gimple_get_lhs (stmt);
1442 gimple new_stmt = gimple_build_assign (lhs, result);
1443 gimple_set_location (new_stmt, loc);
a5c384c1 1444 unlink_stmt_vdef (stmt);
1445 gsi_replace (&gsi, new_stmt, true);
bc8a8451 1446 if (gimple_vdef (stmt))
1447 release_ssa_name (gimple_vdef (stmt));
a5c384c1 1448 }
1449 break;
1450
1451 CASE_FLT_FN (BUILT_IN_CABS):
1452 arg0 = gimple_call_arg (stmt, 0);
1453 loc = gimple_location (stmt);
1454 result = gimple_expand_builtin_cabs (&gsi, loc, arg0);
1455
1456 if (result)
1457 {
1458 tree lhs = gimple_get_lhs (stmt);
1459 gimple new_stmt = gimple_build_assign (lhs, result);
1460 gimple_set_location (new_stmt, loc);
e9a6c4bc 1461 unlink_stmt_vdef (stmt);
1462 gsi_replace (&gsi, new_stmt, true);
bc8a8451 1463 if (gimple_vdef (stmt))
1464 release_ssa_name (gimple_vdef (stmt));
e9a6c4bc 1465 }
1466 break;
1467
a0315874 1468 default:;
1469 }
1470 }
1471 }
1472 }
1473
30c4e60d 1474 statistics_counter_event (cfun, "sincos statements inserted",
1475 sincos_stats.inserted);
1476
a0315874 1477 free_dominance_info (CDI_DOMINATORS);
4c80086d 1478 return cfg_changed ? TODO_cleanup_cfg : 0;
a0315874 1479}
1480
1481static bool
1482gate_cse_sincos (void)
1483{
e9a6c4bc 1484 /* We no longer require either sincos or cexp, since powi expansion
1485 piggybacks on this pass. */
1486 return optimize;
a0315874 1487}
1488
20099e35 1489struct gimple_opt_pass pass_cse_sincos =
a0315874 1490{
20099e35 1491 {
1492 GIMPLE_PASS,
a0315874 1493 "sincos", /* name */
1494 gate_cse_sincos, /* gate */
1495 execute_cse_sincos, /* execute */
1496 NULL, /* sub */
1497 NULL, /* next */
1498 0, /* static_pass_number */
0b1615c1 1499 TV_NONE, /* tv_id */
a0315874 1500 PROP_ssa, /* properties_required */
1501 0, /* properties_provided */
1502 0, /* properties_destroyed */
1503 0, /* todo_flags_start */
771e2890 1504 TODO_update_ssa | TODO_verify_ssa
20099e35 1505 | TODO_verify_stmts /* todo_flags_finish */
1506 }
a0315874 1507};
e174638f 1508
84cc784c 1509/* A symbolic number is used to detect byte permutation and selection
1510 patterns. Therefore the field N contains an artificial number
1511 consisting of byte size markers:
1512
1513 0 - byte has the value 0
1514 1..size - byte contains the content of the byte
1515 number indexed with that value minus one */
1516
1517struct symbolic_number {
1518 unsigned HOST_WIDEST_INT n;
1519 int size;
1520};
1521
1522/* Perform a SHIFT or ROTATE operation by COUNT bits on symbolic
1523 number N. Return false if the requested operation is not permitted
1524 on a symbolic number. */
1525
1526static inline bool
1527do_shift_rotate (enum tree_code code,
1528 struct symbolic_number *n,
1529 int count)
1530{
1531 if (count % 8 != 0)
1532 return false;
1533
1534 /* Zero out the extra bits of N in order to avoid them being shifted
1535 into the significant bits. */
1536 if (n->size < (int)sizeof (HOST_WIDEST_INT))
1537 n->n &= ((unsigned HOST_WIDEST_INT)1 << (n->size * BITS_PER_UNIT)) - 1;
1538
1539 switch (code)
1540 {
1541 case LSHIFT_EXPR:
1542 n->n <<= count;
1543 break;
1544 case RSHIFT_EXPR:
1545 n->n >>= count;
1546 break;
1547 case LROTATE_EXPR:
1548 n->n = (n->n << count) | (n->n >> ((n->size * BITS_PER_UNIT) - count));
1549 break;
1550 case RROTATE_EXPR:
1551 n->n = (n->n >> count) | (n->n << ((n->size * BITS_PER_UNIT) - count));
1552 break;
1553 default:
1554 return false;
1555 }
0f09ed00 1556 /* Zero unused bits for size. */
1557 if (n->size < (int)sizeof (HOST_WIDEST_INT))
1558 n->n &= ((unsigned HOST_WIDEST_INT)1 << (n->size * BITS_PER_UNIT)) - 1;
84cc784c 1559 return true;
1560}
1561
1562/* Perform sanity checking for the symbolic number N and the gimple
1563 statement STMT. */
1564
1565static inline bool
1566verify_symbolic_number_p (struct symbolic_number *n, gimple stmt)
1567{
1568 tree lhs_type;
1569
1570 lhs_type = gimple_expr_type (stmt);
1571
1572 if (TREE_CODE (lhs_type) != INTEGER_TYPE)
1573 return false;
1574
1575 if (TYPE_PRECISION (lhs_type) != n->size * BITS_PER_UNIT)
1576 return false;
1577
1578 return true;
1579}
1580
1581/* find_bswap_1 invokes itself recursively with N and tries to perform
1582 the operation given by the rhs of STMT on the result. If the
1583 operation could successfully be executed the function returns the
1584 tree expression of the source operand and NULL otherwise. */
1585
1586static tree
1587find_bswap_1 (gimple stmt, struct symbolic_number *n, int limit)
1588{
1589 enum tree_code code;
1590 tree rhs1, rhs2 = NULL;
1591 gimple rhs1_stmt, rhs2_stmt;
1592 tree source_expr1;
1593 enum gimple_rhs_class rhs_class;
1594
1595 if (!limit || !is_gimple_assign (stmt))
1596 return NULL_TREE;
1597
1598 rhs1 = gimple_assign_rhs1 (stmt);
1599
1600 if (TREE_CODE (rhs1) != SSA_NAME)
1601 return NULL_TREE;
1602
1603 code = gimple_assign_rhs_code (stmt);
1604 rhs_class = gimple_assign_rhs_class (stmt);
1605 rhs1_stmt = SSA_NAME_DEF_STMT (rhs1);
1606
1607 if (rhs_class == GIMPLE_BINARY_RHS)
1608 rhs2 = gimple_assign_rhs2 (stmt);
1609
1610 /* Handle unary rhs and binary rhs with integer constants as second
1611 operand. */
1612
1613 if (rhs_class == GIMPLE_UNARY_RHS
1614 || (rhs_class == GIMPLE_BINARY_RHS
1615 && TREE_CODE (rhs2) == INTEGER_CST))
1616 {
1617 if (code != BIT_AND_EXPR
1618 && code != LSHIFT_EXPR
1619 && code != RSHIFT_EXPR
1620 && code != LROTATE_EXPR
1621 && code != RROTATE_EXPR
1622 && code != NOP_EXPR
1623 && code != CONVERT_EXPR)
1624 return NULL_TREE;
1625
1626 source_expr1 = find_bswap_1 (rhs1_stmt, n, limit - 1);
1627
1628 /* If find_bswap_1 returned NULL STMT is a leaf node and we have
1629 to initialize the symbolic number. */
1630 if (!source_expr1)
1631 {
1632 /* Set up the symbolic number N by setting each byte to a
1633 value between 1 and the byte size of rhs1. The highest
f9a210c9 1634 order byte is set to n->size and the lowest order
1635 byte to 1. */
84cc784c 1636 n->size = TYPE_PRECISION (TREE_TYPE (rhs1));
1637 if (n->size % BITS_PER_UNIT != 0)
1638 return NULL_TREE;
1639 n->size /= BITS_PER_UNIT;
1640 n->n = (sizeof (HOST_WIDEST_INT) < 8 ? 0 :
f9a210c9 1641 (unsigned HOST_WIDEST_INT)0x08070605 << 32 | 0x04030201);
1642
1643 if (n->size < (int)sizeof (HOST_WIDEST_INT))
1644 n->n &= ((unsigned HOST_WIDEST_INT)1 <<
1645 (n->size * BITS_PER_UNIT)) - 1;
84cc784c 1646
1647 source_expr1 = rhs1;
1648 }
1649
1650 switch (code)
1651 {
1652 case BIT_AND_EXPR:
1653 {
1654 int i;
1655 unsigned HOST_WIDEST_INT val = widest_int_cst_value (rhs2);
1656 unsigned HOST_WIDEST_INT tmp = val;
1657
1658 /* Only constants masking full bytes are allowed. */
1659 for (i = 0; i < n->size; i++, tmp >>= BITS_PER_UNIT)
1660 if ((tmp & 0xff) != 0 && (tmp & 0xff) != 0xff)
1661 return NULL_TREE;
1662
1663 n->n &= val;
1664 }
1665 break;
1666 case LSHIFT_EXPR:
1667 case RSHIFT_EXPR:
1668 case LROTATE_EXPR:
1669 case RROTATE_EXPR:
1670 if (!do_shift_rotate (code, n, (int)TREE_INT_CST_LOW (rhs2)))
1671 return NULL_TREE;
1672 break;
1673 CASE_CONVERT:
1674 {
1675 int type_size;
1676
1677 type_size = TYPE_PRECISION (gimple_expr_type (stmt));
1678 if (type_size % BITS_PER_UNIT != 0)
1679 return NULL_TREE;
1680
84cc784c 1681 if (type_size / BITS_PER_UNIT < (int)(sizeof (HOST_WIDEST_INT)))
1682 {
1683 /* If STMT casts to a smaller type mask out the bits not
1684 belonging to the target type. */
84cc784c 1685 n->n &= ((unsigned HOST_WIDEST_INT)1 << type_size) - 1;
1686 }
f9a210c9 1687 n->size = type_size / BITS_PER_UNIT;
84cc784c 1688 }
1689 break;
1690 default:
1691 return NULL_TREE;
1692 };
1693 return verify_symbolic_number_p (n, stmt) ? source_expr1 : NULL;
1694 }
1695
1696 /* Handle binary rhs. */
1697
1698 if (rhs_class == GIMPLE_BINARY_RHS)
1699 {
1700 struct symbolic_number n1, n2;
1701 tree source_expr2;
1702
1703 if (code != BIT_IOR_EXPR)
1704 return NULL_TREE;
1705
1706 if (TREE_CODE (rhs2) != SSA_NAME)
1707 return NULL_TREE;
1708
1709 rhs2_stmt = SSA_NAME_DEF_STMT (rhs2);
1710
1711 switch (code)
1712 {
1713 case BIT_IOR_EXPR:
1714 source_expr1 = find_bswap_1 (rhs1_stmt, &n1, limit - 1);
1715
1716 if (!source_expr1)
1717 return NULL_TREE;
1718
1719 source_expr2 = find_bswap_1 (rhs2_stmt, &n2, limit - 1);
1720
1721 if (source_expr1 != source_expr2
1722 || n1.size != n2.size)
1723 return NULL_TREE;
1724
1725 n->size = n1.size;
1726 n->n = n1.n | n2.n;
1727
1728 if (!verify_symbolic_number_p (n, stmt))
1729 return NULL_TREE;
1730
1731 break;
1732 default:
1733 return NULL_TREE;
1734 }
1735 return source_expr1;
1736 }
1737 return NULL_TREE;
1738}
1739
1740/* Check if STMT completes a bswap implementation consisting of ORs,
1741 SHIFTs and ANDs. Return the source tree expression on which the
1742 byte swap is performed and NULL if no bswap was found. */
1743
1744static tree
1745find_bswap (gimple stmt)
1746{
1747/* The number which the find_bswap result should match in order to
f9a210c9 1748 have a full byte swap. The number is shifted to the left according
1749 to the size of the symbolic number before using it. */
84cc784c 1750 unsigned HOST_WIDEST_INT cmp =
1751 sizeof (HOST_WIDEST_INT) < 8 ? 0 :
f9a210c9 1752 (unsigned HOST_WIDEST_INT)0x01020304 << 32 | 0x05060708;
84cc784c 1753
1754 struct symbolic_number n;
1755 tree source_expr;
0f09ed00 1756 int limit;
84cc784c 1757
9bc1852a 1758 /* The last parameter determines the depth search limit. It usually
1759 correlates directly to the number of bytes to be touched. We
0f09ed00 1760 increase that number by three here in order to also
1761 cover signed -> unsigned converions of the src operand as can be seen
1762 in libgcc, and for initial shift/and operation of the src operand. */
1763 limit = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (gimple_expr_type (stmt)));
1764 limit += 1 + (int) ceil_log2 ((unsigned HOST_WIDE_INT) limit);
1765 source_expr = find_bswap_1 (stmt, &n, limit);
84cc784c 1766
1767 if (!source_expr)
1768 return NULL_TREE;
1769
1770 /* Zero out the extra bits of N and CMP. */
1771 if (n.size < (int)sizeof (HOST_WIDEST_INT))
1772 {
1773 unsigned HOST_WIDEST_INT mask =
1774 ((unsigned HOST_WIDEST_INT)1 << (n.size * BITS_PER_UNIT)) - 1;
1775
1776 n.n &= mask;
f9a210c9 1777 cmp >>= (sizeof (HOST_WIDEST_INT) - n.size) * BITS_PER_UNIT;
84cc784c 1778 }
1779
1780 /* A complete byte swap should make the symbolic number to start
1781 with the largest digit in the highest order byte. */
1782 if (cmp != n.n)
1783 return NULL_TREE;
1784
1785 return source_expr;
1786}
1787
1788/* Find manual byte swap implementations and turn them into a bswap
1789 builtin invokation. */
1790
1791static unsigned int
1792execute_optimize_bswap (void)
1793{
1794 basic_block bb;
1795 bool bswap32_p, bswap64_p;
1796 bool changed = false;
0af25806 1797 tree bswap32_type = NULL_TREE, bswap64_type = NULL_TREE;
84cc784c 1798
1799 if (BITS_PER_UNIT != 8)
1800 return 0;
1801
1802 if (sizeof (HOST_WIDEST_INT) < 8)
1803 return 0;
1804
b9a16870 1805 bswap32_p = (builtin_decl_explicit_p (BUILT_IN_BSWAP32)
d6bf3b14 1806 && optab_handler (bswap_optab, SImode) != CODE_FOR_nothing);
b9a16870 1807 bswap64_p = (builtin_decl_explicit_p (BUILT_IN_BSWAP64)
d6bf3b14 1808 && (optab_handler (bswap_optab, DImode) != CODE_FOR_nothing
3328b1fb 1809 || (bswap32_p && word_mode == SImode)));
84cc784c 1810
1811 if (!bswap32_p && !bswap64_p)
1812 return 0;
1813
0af25806 1814 /* Determine the argument type of the builtins. The code later on
1815 assumes that the return and argument type are the same. */
1816 if (bswap32_p)
1817 {
b9a16870 1818 tree fndecl = builtin_decl_explicit (BUILT_IN_BSWAP32);
0af25806 1819 bswap32_type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
1820 }
1821
1822 if (bswap64_p)
1823 {
b9a16870 1824 tree fndecl = builtin_decl_explicit (BUILT_IN_BSWAP64);
0af25806 1825 bswap64_type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
1826 }
1827
30c4e60d 1828 memset (&bswap_stats, 0, sizeof (bswap_stats));
1829
84cc784c 1830 FOR_EACH_BB (bb)
1831 {
1832 gimple_stmt_iterator gsi;
1833
0ec31268 1834 /* We do a reverse scan for bswap patterns to make sure we get the
1835 widest match. As bswap pattern matching doesn't handle
1836 previously inserted smaller bswap replacements as sub-
1837 patterns, the wider variant wouldn't be detected. */
1838 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
84cc784c 1839 {
1840 gimple stmt = gsi_stmt (gsi);
0af25806 1841 tree bswap_src, bswap_type;
1842 tree bswap_tmp;
84cc784c 1843 tree fndecl = NULL_TREE;
1844 int type_size;
1845 gimple call;
1846
1847 if (!is_gimple_assign (stmt)
1848 || gimple_assign_rhs_code (stmt) != BIT_IOR_EXPR)
1849 continue;
1850
1851 type_size = TYPE_PRECISION (gimple_expr_type (stmt));
1852
1853 switch (type_size)
1854 {
1855 case 32:
1856 if (bswap32_p)
0af25806 1857 {
b9a16870 1858 fndecl = builtin_decl_explicit (BUILT_IN_BSWAP32);
0af25806 1859 bswap_type = bswap32_type;
1860 }
84cc784c 1861 break;
1862 case 64:
1863 if (bswap64_p)
0af25806 1864 {
b9a16870 1865 fndecl = builtin_decl_explicit (BUILT_IN_BSWAP64);
0af25806 1866 bswap_type = bswap64_type;
1867 }
84cc784c 1868 break;
1869 default:
1870 continue;
1871 }
1872
1873 if (!fndecl)
1874 continue;
1875
1876 bswap_src = find_bswap (stmt);
1877
1878 if (!bswap_src)
1879 continue;
1880
1881 changed = true;
30c4e60d 1882 if (type_size == 32)
1883 bswap_stats.found_32bit++;
1884 else
1885 bswap_stats.found_64bit++;
0af25806 1886
1887 bswap_tmp = bswap_src;
1888
1889 /* Convert the src expression if necessary. */
1890 if (!useless_type_conversion_p (TREE_TYPE (bswap_tmp), bswap_type))
1891 {
1892 gimple convert_stmt;
03d37e4e 1893 bswap_tmp = make_temp_ssa_name (bswap_type, NULL, "bswapsrc");
1894 convert_stmt = gimple_build_assign_with_ops
1895 (NOP_EXPR, bswap_tmp, bswap_src, NULL);
0af25806 1896 gsi_insert_before (&gsi, convert_stmt, GSI_SAME_STMT);
1897 }
1898
1899 call = gimple_build_call (fndecl, 1, bswap_tmp);
1900
1901 bswap_tmp = gimple_assign_lhs (stmt);
1902
1903 /* Convert the result if necessary. */
1904 if (!useless_type_conversion_p (TREE_TYPE (bswap_tmp), bswap_type))
1905 {
1906 gimple convert_stmt;
03d37e4e 1907 bswap_tmp = make_temp_ssa_name (bswap_type, NULL, "bswapdst");
1908 convert_stmt = gimple_build_assign_with_ops
1909 (NOP_EXPR, gimple_assign_lhs (stmt), bswap_tmp, NULL);
0af25806 1910 gsi_insert_after (&gsi, convert_stmt, GSI_SAME_STMT);
1911 }
1912
1913 gimple_call_set_lhs (call, bswap_tmp);
84cc784c 1914
1915 if (dump_file)
1916 {
1917 fprintf (dump_file, "%d bit bswap implementation found at: ",
1918 (int)type_size);
1919 print_gimple_stmt (dump_file, stmt, 0, 0);
1920 }
1921
1922 gsi_insert_after (&gsi, call, GSI_SAME_STMT);
1923 gsi_remove (&gsi, true);
1924 }
1925 }
1926
30c4e60d 1927 statistics_counter_event (cfun, "32-bit bswap implementations found",
1928 bswap_stats.found_32bit);
1929 statistics_counter_event (cfun, "64-bit bswap implementations found",
1930 bswap_stats.found_64bit);
1931
771e2890 1932 return (changed ? TODO_update_ssa | TODO_verify_ssa
84cc784c 1933 | TODO_verify_stmts : 0);
1934}
1935
1936static bool
1937gate_optimize_bswap (void)
1938{
1939 return flag_expensive_optimizations && optimize;
1940}
1941
1942struct gimple_opt_pass pass_optimize_bswap =
1943{
1944 {
1945 GIMPLE_PASS,
1946 "bswap", /* name */
1947 gate_optimize_bswap, /* gate */
1948 execute_optimize_bswap, /* execute */
1949 NULL, /* sub */
1950 NULL, /* next */
1951 0, /* static_pass_number */
1952 TV_NONE, /* tv_id */
1953 PROP_ssa, /* properties_required */
1954 0, /* properties_provided */
1955 0, /* properties_destroyed */
1956 0, /* todo_flags_start */
1957 0 /* todo_flags_finish */
1958 }
1959};
62be004c 1960
0989f516 1961/* Return true if RHS is a suitable operand for a widening multiplication,
1962 assuming a target type of TYPE.
7e4c867e 1963 There are two cases:
1964
aff5fb4d 1965 - RHS makes some value at least twice as wide. Store that value
1966 in *NEW_RHS_OUT if so, and store its type in *TYPE_OUT.
7e4c867e 1967
1968 - RHS is an integer constant. Store that value in *NEW_RHS_OUT if so,
1969 but leave *TYPE_OUT untouched. */
00f4f705 1970
1971static bool
0989f516 1972is_widening_mult_rhs_p (tree type, tree rhs, tree *type_out,
1973 tree *new_rhs_out)
7e4c867e 1974{
1975 gimple stmt;
0989f516 1976 tree type1, rhs1;
7e4c867e 1977 enum tree_code rhs_code;
1978
1979 if (TREE_CODE (rhs) == SSA_NAME)
1980 {
7e4c867e 1981 stmt = SSA_NAME_DEF_STMT (rhs);
0989f516 1982 if (is_gimple_assign (stmt))
1983 {
1984 rhs_code = gimple_assign_rhs_code (stmt);
1985 if (TREE_CODE (type) == INTEGER_TYPE
1986 ? !CONVERT_EXPR_CODE_P (rhs_code)
1987 : rhs_code != FIXED_CONVERT_EXPR)
1988 rhs1 = rhs;
1989 else
ffebd9c5 1990 {
1991 rhs1 = gimple_assign_rhs1 (stmt);
1992
1993 if (TREE_CODE (rhs1) == INTEGER_CST)
1994 {
1995 *new_rhs_out = rhs1;
1996 *type_out = NULL;
1997 return true;
1998 }
1999 }
0989f516 2000 }
2001 else
2002 rhs1 = rhs;
7e4c867e 2003
7e4c867e 2004 type1 = TREE_TYPE (rhs1);
0989f516 2005
7e4c867e 2006 if (TREE_CODE (type1) != TREE_CODE (type)
aff5fb4d 2007 || TYPE_PRECISION (type1) * 2 > TYPE_PRECISION (type))
7e4c867e 2008 return false;
2009
2010 *new_rhs_out = rhs1;
2011 *type_out = type1;
2012 return true;
2013 }
2014
2015 if (TREE_CODE (rhs) == INTEGER_CST)
2016 {
2017 *new_rhs_out = rhs;
2018 *type_out = NULL;
2019 return true;
2020 }
2021
2022 return false;
2023}
2024
0989f516 2025/* Return true if STMT performs a widening multiplication, assuming the
2026 output type is TYPE. If so, store the unwidened types of the operands
2027 in *TYPE1_OUT and *TYPE2_OUT respectively. Also fill *RHS1_OUT and
2028 *RHS2_OUT such that converting those operands to types *TYPE1_OUT
2029 and *TYPE2_OUT would give the operands of the multiplication. */
7e4c867e 2030
2031static bool
4333b41f 2032is_widening_mult_p (gimple stmt,
7e4c867e 2033 tree *type1_out, tree *rhs1_out,
2034 tree *type2_out, tree *rhs2_out)
00f4f705 2035{
4333b41f 2036 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
2037
7e4c867e 2038 if (TREE_CODE (type) != INTEGER_TYPE
2039 && TREE_CODE (type) != FIXED_POINT_TYPE)
2040 return false;
00f4f705 2041
0989f516 2042 if (!is_widening_mult_rhs_p (type, gimple_assign_rhs1 (stmt), type1_out,
2043 rhs1_out))
00f4f705 2044 return false;
2045
0989f516 2046 if (!is_widening_mult_rhs_p (type, gimple_assign_rhs2 (stmt), type2_out,
2047 rhs2_out))
7e4c867e 2048 return false;
00f4f705 2049
7e4c867e 2050 if (*type1_out == NULL)
00f4f705 2051 {
7e4c867e 2052 if (*type2_out == NULL || !int_fits_type_p (*rhs1_out, *type2_out))
00f4f705 2053 return false;
7e4c867e 2054 *type1_out = *type2_out;
00f4f705 2055 }
00f4f705 2056
7e4c867e 2057 if (*type2_out == NULL)
00f4f705 2058 {
7e4c867e 2059 if (!int_fits_type_p (*rhs2_out, *type1_out))
00f4f705 2060 return false;
7e4c867e 2061 *type2_out = *type1_out;
00f4f705 2062 }
00f4f705 2063
287c271c 2064 /* Ensure that the larger of the two operands comes first. */
2065 if (TYPE_PRECISION (*type1_out) < TYPE_PRECISION (*type2_out))
2066 {
2067 tree tmp;
2068 tmp = *type1_out;
2069 *type1_out = *type2_out;
2070 *type2_out = tmp;
2071 tmp = *rhs1_out;
2072 *rhs1_out = *rhs2_out;
2073 *rhs2_out = tmp;
2074 }
aff5fb4d 2075
7e4c867e 2076 return true;
2077}
00f4f705 2078
7e4c867e 2079/* Process a single gimple statement STMT, which has a MULT_EXPR as
2080 its rhs, and try to convert it into a WIDEN_MULT_EXPR. The return
2081 value is true iff we converted the statement. */
2082
2083static bool
aff5fb4d 2084convert_mult_to_widen (gimple stmt, gimple_stmt_iterator *gsi)
7e4c867e 2085{
03d37e4e 2086 tree lhs, rhs1, rhs2, type, type1, type2;
7e4c867e 2087 enum insn_code handler;
aff5fb4d 2088 enum machine_mode to_mode, from_mode, actual_mode;
5a574e8b 2089 optab op;
aff5fb4d 2090 int actual_precision;
2091 location_t loc = gimple_location (stmt);
3f2ab719 2092 bool from_unsigned1, from_unsigned2;
7e4c867e 2093
2094 lhs = gimple_assign_lhs (stmt);
2095 type = TREE_TYPE (lhs);
2096 if (TREE_CODE (type) != INTEGER_TYPE)
00f4f705 2097 return false;
2098
4333b41f 2099 if (!is_widening_mult_p (stmt, &type1, &rhs1, &type2, &rhs2))
00f4f705 2100 return false;
2101
5a574e8b 2102 to_mode = TYPE_MODE (type);
2103 from_mode = TYPE_MODE (type1);
3f2ab719 2104 from_unsigned1 = TYPE_UNSIGNED (type1);
2105 from_unsigned2 = TYPE_UNSIGNED (type2);
5a574e8b 2106
3f2ab719 2107 if (from_unsigned1 && from_unsigned2)
5a574e8b 2108 op = umul_widen_optab;
3f2ab719 2109 else if (!from_unsigned1 && !from_unsigned2)
5a574e8b 2110 op = smul_widen_optab;
00f4f705 2111 else
5a574e8b 2112 op = usmul_widen_optab;
2113
aff5fb4d 2114 handler = find_widening_optab_handler_and_mode (op, to_mode, from_mode,
2115 0, &actual_mode);
7e4c867e 2116
2117 if (handler == CODE_FOR_nothing)
3f2ab719 2118 {
2119 if (op != smul_widen_optab)
2120 {
22ffd684 2121 /* We can use a signed multiply with unsigned types as long as
2122 there is a wider mode to use, or it is the smaller of the two
2123 types that is unsigned. Note that type1 >= type2, always. */
2124 if ((TYPE_UNSIGNED (type1)
2125 && TYPE_PRECISION (type1) == GET_MODE_PRECISION (from_mode))
2126 || (TYPE_UNSIGNED (type2)
2127 && TYPE_PRECISION (type2) == GET_MODE_PRECISION (from_mode)))
2128 {
2129 from_mode = GET_MODE_WIDER_MODE (from_mode);
2130 if (GET_MODE_SIZE (to_mode) <= GET_MODE_SIZE (from_mode))
2131 return false;
2132 }
3f2ab719 2133
2134 op = smul_widen_optab;
2135 handler = find_widening_optab_handler_and_mode (op, to_mode,
2136 from_mode, 0,
2137 &actual_mode);
2138
2139 if (handler == CODE_FOR_nothing)
2140 return false;
2141
2142 from_unsigned1 = from_unsigned2 = false;
2143 }
2144 else
2145 return false;
2146 }
7e4c867e 2147
aff5fb4d 2148 /* Ensure that the inputs to the handler are in the correct precison
2149 for the opcode. This will be the full mode size. */
2150 actual_precision = GET_MODE_PRECISION (actual_mode);
b36be69d 2151 if (2 * actual_precision > TYPE_PRECISION (type))
2152 return false;
3f2ab719 2153 if (actual_precision != TYPE_PRECISION (type1)
2154 || from_unsigned1 != TYPE_UNSIGNED (type1))
03d37e4e 2155 rhs1 = build_and_insert_cast (gsi, loc,
2156 build_nonstandard_integer_type
2157 (actual_precision, from_unsigned1), rhs1);
3f2ab719 2158 if (actual_precision != TYPE_PRECISION (type2)
2159 || from_unsigned2 != TYPE_UNSIGNED (type2))
03d37e4e 2160 rhs2 = build_and_insert_cast (gsi, loc,
2161 build_nonstandard_integer_type
2162 (actual_precision, from_unsigned2), rhs2);
aff5fb4d 2163
ffebd9c5 2164 /* Handle constants. */
2165 if (TREE_CODE (rhs1) == INTEGER_CST)
2166 rhs1 = fold_convert (type1, rhs1);
2167 if (TREE_CODE (rhs2) == INTEGER_CST)
2168 rhs2 = fold_convert (type2, rhs2);
2169
aff5fb4d 2170 gimple_assign_set_rhs1 (stmt, rhs1);
2171 gimple_assign_set_rhs2 (stmt, rhs2);
00f4f705 2172 gimple_assign_set_rhs_code (stmt, WIDEN_MULT_EXPR);
2173 update_stmt (stmt);
30c4e60d 2174 widen_mul_stats.widen_mults_inserted++;
00f4f705 2175 return true;
2176}
2177
2178/* Process a single gimple statement STMT, which is found at the
2179 iterator GSI and has a either a PLUS_EXPR or a MINUS_EXPR as its
2180 rhs (given by CODE), and try to convert it into a
2181 WIDEN_MULT_PLUS_EXPR or a WIDEN_MULT_MINUS_EXPR. The return value
2182 is true iff we converted the statement. */
2183
2184static bool
2185convert_plusminus_to_widen (gimple_stmt_iterator *gsi, gimple stmt,
2186 enum tree_code code)
2187{
2188 gimple rhs1_stmt = NULL, rhs2_stmt = NULL;
07ea3e5c 2189 gimple conv1_stmt = NULL, conv2_stmt = NULL, conv_stmt;
03d37e4e 2190 tree type, type1, type2, optype;
00f4f705 2191 tree lhs, rhs1, rhs2, mult_rhs1, mult_rhs2, add_rhs;
2192 enum tree_code rhs1_code = ERROR_MARK, rhs2_code = ERROR_MARK;
2193 optab this_optab;
2194 enum tree_code wmult_code;
aff5fb4d 2195 enum insn_code handler;
2196 enum machine_mode to_mode, from_mode, actual_mode;
2197 location_t loc = gimple_location (stmt);
2198 int actual_precision;
3f2ab719 2199 bool from_unsigned1, from_unsigned2;
00f4f705 2200
2201 lhs = gimple_assign_lhs (stmt);
2202 type = TREE_TYPE (lhs);
7e4c867e 2203 if (TREE_CODE (type) != INTEGER_TYPE
2204 && TREE_CODE (type) != FIXED_POINT_TYPE)
00f4f705 2205 return false;
2206
2207 if (code == MINUS_EXPR)
2208 wmult_code = WIDEN_MULT_MINUS_EXPR;
2209 else
2210 wmult_code = WIDEN_MULT_PLUS_EXPR;
2211
00f4f705 2212 rhs1 = gimple_assign_rhs1 (stmt);
2213 rhs2 = gimple_assign_rhs2 (stmt);
2214
2215 if (TREE_CODE (rhs1) == SSA_NAME)
2216 {
2217 rhs1_stmt = SSA_NAME_DEF_STMT (rhs1);
2218 if (is_gimple_assign (rhs1_stmt))
2219 rhs1_code = gimple_assign_rhs_code (rhs1_stmt);
2220 }
00f4f705 2221
2222 if (TREE_CODE (rhs2) == SSA_NAME)
2223 {
2224 rhs2_stmt = SSA_NAME_DEF_STMT (rhs2);
2225 if (is_gimple_assign (rhs2_stmt))
2226 rhs2_code = gimple_assign_rhs_code (rhs2_stmt);
2227 }
00f4f705 2228
07ea3e5c 2229 /* Allow for one conversion statement between the multiply
2230 and addition/subtraction statement. If there are more than
2231 one conversions then we assume they would invalidate this
2232 transformation. If that's not the case then they should have
2233 been folded before now. */
2234 if (CONVERT_EXPR_CODE_P (rhs1_code))
2235 {
2236 conv1_stmt = rhs1_stmt;
2237 rhs1 = gimple_assign_rhs1 (rhs1_stmt);
2238 if (TREE_CODE (rhs1) == SSA_NAME)
2239 {
2240 rhs1_stmt = SSA_NAME_DEF_STMT (rhs1);
2241 if (is_gimple_assign (rhs1_stmt))
2242 rhs1_code = gimple_assign_rhs_code (rhs1_stmt);
2243 }
2244 else
2245 return false;
2246 }
2247 if (CONVERT_EXPR_CODE_P (rhs2_code))
2248 {
2249 conv2_stmt = rhs2_stmt;
2250 rhs2 = gimple_assign_rhs1 (rhs2_stmt);
2251 if (TREE_CODE (rhs2) == SSA_NAME)
2252 {
2253 rhs2_stmt = SSA_NAME_DEF_STMT (rhs2);
2254 if (is_gimple_assign (rhs2_stmt))
2255 rhs2_code = gimple_assign_rhs_code (rhs2_stmt);
2256 }
2257 else
2258 return false;
2259 }
2260
aff5fb4d 2261 /* If code is WIDEN_MULT_EXPR then it would seem unnecessary to call
2262 is_widening_mult_p, but we still need the rhs returns.
2263
2264 It might also appear that it would be sufficient to use the existing
2265 operands of the widening multiply, but that would limit the choice of
2266 multiply-and-accumulate instructions. */
2267 if (code == PLUS_EXPR
2268 && (rhs1_code == MULT_EXPR || rhs1_code == WIDEN_MULT_EXPR))
00f4f705 2269 {
4333b41f 2270 if (!is_widening_mult_p (rhs1_stmt, &type1, &mult_rhs1,
7e4c867e 2271 &type2, &mult_rhs2))
00f4f705 2272 return false;
7e4c867e 2273 add_rhs = rhs2;
07ea3e5c 2274 conv_stmt = conv1_stmt;
00f4f705 2275 }
aff5fb4d 2276 else if (rhs2_code == MULT_EXPR || rhs2_code == WIDEN_MULT_EXPR)
00f4f705 2277 {
4333b41f 2278 if (!is_widening_mult_p (rhs2_stmt, &type1, &mult_rhs1,
7e4c867e 2279 &type2, &mult_rhs2))
00f4f705 2280 return false;
7e4c867e 2281 add_rhs = rhs1;
07ea3e5c 2282 conv_stmt = conv2_stmt;
00f4f705 2283 }
00f4f705 2284 else
2285 return false;
2286
aff5fb4d 2287 to_mode = TYPE_MODE (type);
2288 from_mode = TYPE_MODE (type1);
3f2ab719 2289 from_unsigned1 = TYPE_UNSIGNED (type1);
2290 from_unsigned2 = TYPE_UNSIGNED (type2);
4ccf368d 2291 optype = type1;
aff5fb4d 2292
3f2ab719 2293 /* There's no such thing as a mixed sign madd yet, so use a wider mode. */
2294 if (from_unsigned1 != from_unsigned2)
2295 {
4ccf368d 2296 if (!INTEGRAL_TYPE_P (type))
2297 return false;
22ffd684 2298 /* We can use a signed multiply with unsigned types as long as
2299 there is a wider mode to use, or it is the smaller of the two
2300 types that is unsigned. Note that type1 >= type2, always. */
2301 if ((from_unsigned1
2302 && TYPE_PRECISION (type1) == GET_MODE_PRECISION (from_mode))
2303 || (from_unsigned2
2304 && TYPE_PRECISION (type2) == GET_MODE_PRECISION (from_mode)))
3f2ab719 2305 {
22ffd684 2306 from_mode = GET_MODE_WIDER_MODE (from_mode);
2307 if (GET_MODE_SIZE (from_mode) >= GET_MODE_SIZE (to_mode))
2308 return false;
3f2ab719 2309 }
22ffd684 2310
2311 from_unsigned1 = from_unsigned2 = false;
4ccf368d 2312 optype = build_nonstandard_integer_type (GET_MODE_PRECISION (from_mode),
2313 false);
3f2ab719 2314 }
815a0224 2315
07ea3e5c 2316 /* If there was a conversion between the multiply and addition
2317 then we need to make sure it fits a multiply-and-accumulate.
2318 The should be a single mode change which does not change the
2319 value. */
2320 if (conv_stmt)
2321 {
3f2ab719 2322 /* We use the original, unmodified data types for this. */
07ea3e5c 2323 tree from_type = TREE_TYPE (gimple_assign_rhs1 (conv_stmt));
2324 tree to_type = TREE_TYPE (gimple_assign_lhs (conv_stmt));
2325 int data_size = TYPE_PRECISION (type1) + TYPE_PRECISION (type2);
2326 bool is_unsigned = TYPE_UNSIGNED (type1) && TYPE_UNSIGNED (type2);
2327
2328 if (TYPE_PRECISION (from_type) > TYPE_PRECISION (to_type))
2329 {
2330 /* Conversion is a truncate. */
2331 if (TYPE_PRECISION (to_type) < data_size)
2332 return false;
2333 }
2334 else if (TYPE_PRECISION (from_type) < TYPE_PRECISION (to_type))
2335 {
2336 /* Conversion is an extend. Check it's the right sort. */
2337 if (TYPE_UNSIGNED (from_type) != is_unsigned
2338 && !(is_unsigned && TYPE_PRECISION (from_type) > data_size))
2339 return false;
2340 }
2341 /* else convert is a no-op for our purposes. */
2342 }
2343
815a0224 2344 /* Verify that the machine can perform a widening multiply
2345 accumulate in this mode/signedness combination, otherwise
2346 this transformation is likely to pessimize code. */
3f2ab719 2347 this_optab = optab_for_tree_code (wmult_code, optype, optab_default);
aff5fb4d 2348 handler = find_widening_optab_handler_and_mode (this_optab, to_mode,
2349 from_mode, 0, &actual_mode);
2350
2351 if (handler == CODE_FOR_nothing)
815a0224 2352 return false;
2353
aff5fb4d 2354 /* Ensure that the inputs to the handler are in the correct precison
2355 for the opcode. This will be the full mode size. */
2356 actual_precision = GET_MODE_PRECISION (actual_mode);
3f2ab719 2357 if (actual_precision != TYPE_PRECISION (type1)
2358 || from_unsigned1 != TYPE_UNSIGNED (type1))
03d37e4e 2359 mult_rhs1 = build_and_insert_cast (gsi, loc,
2360 build_nonstandard_integer_type
2361 (actual_precision, from_unsigned1),
2362 mult_rhs1);
3f2ab719 2363 if (actual_precision != TYPE_PRECISION (type2)
2364 || from_unsigned2 != TYPE_UNSIGNED (type2))
03d37e4e 2365 mult_rhs2 = build_and_insert_cast (gsi, loc,
2366 build_nonstandard_integer_type
2367 (actual_precision, from_unsigned2),
2368 mult_rhs2);
00f4f705 2369
12421545 2370 if (!useless_type_conversion_p (type, TREE_TYPE (add_rhs)))
03d37e4e 2371 add_rhs = build_and_insert_cast (gsi, loc, type, add_rhs);
12421545 2372
ffebd9c5 2373 /* Handle constants. */
2374 if (TREE_CODE (mult_rhs1) == INTEGER_CST)
d5a3bb10 2375 mult_rhs1 = fold_convert (type1, mult_rhs1);
ffebd9c5 2376 if (TREE_CODE (mult_rhs2) == INTEGER_CST)
d5a3bb10 2377 mult_rhs2 = fold_convert (type2, mult_rhs2);
ffebd9c5 2378
aff5fb4d 2379 gimple_assign_set_rhs_with_ops_1 (gsi, wmult_code, mult_rhs1, mult_rhs2,
00f4f705 2380 add_rhs);
2381 update_stmt (gsi_stmt (*gsi));
30c4e60d 2382 widen_mul_stats.maccs_inserted++;
00f4f705 2383 return true;
2384}
2385
15dbdc8f 2386/* Combine the multiplication at MUL_STMT with operands MULOP1 and MULOP2
2387 with uses in additions and subtractions to form fused multiply-add
2388 operations. Returns true if successful and MUL_STMT should be removed. */
b9be572e 2389
2390static bool
15dbdc8f 2391convert_mult_to_fma (gimple mul_stmt, tree op1, tree op2)
b9be572e 2392{
15dbdc8f 2393 tree mul_result = gimple_get_lhs (mul_stmt);
b9be572e 2394 tree type = TREE_TYPE (mul_result);
44579526 2395 gimple use_stmt, neguse_stmt, fma_stmt;
b9be572e 2396 use_operand_p use_p;
2397 imm_use_iterator imm_iter;
2398
2399 if (FLOAT_TYPE_P (type)
2400 && flag_fp_contract_mode == FP_CONTRACT_OFF)
2401 return false;
2402
2403 /* We don't want to do bitfield reduction ops. */
2404 if (INTEGRAL_TYPE_P (type)
2405 && (TYPE_PRECISION (type)
2406 != GET_MODE_PRECISION (TYPE_MODE (type))))
2407 return false;
2408
2409 /* If the target doesn't support it, don't generate it. We assume that
2410 if fma isn't available then fms, fnma or fnms are not either. */
2411 if (optab_handler (fma_optab, TYPE_MODE (type)) == CODE_FOR_nothing)
2412 return false;
2413
5ed3d3b8 2414 /* If the multiplication has zero uses, it is kept around probably because
2415 of -fnon-call-exceptions. Don't optimize it away in that case,
2416 it is DCE job. */
2417 if (has_zero_uses (mul_result))
2418 return false;
2419
b9be572e 2420 /* Make sure that the multiplication statement becomes dead after
2421 the transformation, thus that all uses are transformed to FMAs.
2422 This means we assume that an FMA operation has the same cost
2423 as an addition. */
2424 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, mul_result)
2425 {
2426 enum tree_code use_code;
44579526 2427 tree result = mul_result;
2428 bool negate_p = false;
b9be572e 2429
2430 use_stmt = USE_STMT (use_p);
2431
17a2c727 2432 if (is_gimple_debug (use_stmt))
2433 continue;
2434
b9be572e 2435 /* For now restrict this operations to single basic blocks. In theory
2436 we would want to support sinking the multiplication in
2437 m = a*b;
2438 if ()
2439 ma = m + c;
2440 else
2441 d = m;
2442 to form a fma in the then block and sink the multiplication to the
2443 else block. */
2444 if (gimple_bb (use_stmt) != gimple_bb (mul_stmt))
2445 return false;
2446
44579526 2447 if (!is_gimple_assign (use_stmt))
b9be572e 2448 return false;
2449
44579526 2450 use_code = gimple_assign_rhs_code (use_stmt);
2451
2452 /* A negate on the multiplication leads to FNMA. */
2453 if (use_code == NEGATE_EXPR)
2454 {
805ad414 2455 ssa_op_iter iter;
5715c09b 2456 use_operand_p usep;
805ad414 2457
44579526 2458 result = gimple_assign_lhs (use_stmt);
2459
2460 /* Make sure the negate statement becomes dead with this
2461 single transformation. */
2462 if (!single_imm_use (gimple_assign_lhs (use_stmt),
2463 &use_p, &neguse_stmt))
2464 return false;
2465
805ad414 2466 /* Make sure the multiplication isn't also used on that stmt. */
5715c09b 2467 FOR_EACH_PHI_OR_STMT_USE (usep, neguse_stmt, iter, SSA_OP_USE)
2468 if (USE_FROM_PTR (usep) == mul_result)
805ad414 2469 return false;
2470
44579526 2471 /* Re-validate. */
2472 use_stmt = neguse_stmt;
2473 if (gimple_bb (use_stmt) != gimple_bb (mul_stmt))
2474 return false;
2475 if (!is_gimple_assign (use_stmt))
2476 return false;
2477
2478 use_code = gimple_assign_rhs_code (use_stmt);
2479 negate_p = true;
2480 }
b9be572e 2481
44579526 2482 switch (use_code)
2483 {
2484 case MINUS_EXPR:
8a9d0572 2485 if (gimple_assign_rhs2 (use_stmt) == result)
2486 negate_p = !negate_p;
2487 break;
44579526 2488 case PLUS_EXPR:
44579526 2489 break;
44579526 2490 default:
2491 /* FMA can only be formed from PLUS and MINUS. */
2492 return false;
2493 }
b9be572e 2494
44579526 2495 /* We can't handle a * b + a * b. */
2496 if (gimple_assign_rhs1 (use_stmt) == gimple_assign_rhs2 (use_stmt))
2497 return false;
8a9d0572 2498
2499 /* While it is possible to validate whether or not the exact form
2500 that we've recognized is available in the backend, the assumption
2501 is that the transformation is never a loss. For instance, suppose
2502 the target only has the plain FMA pattern available. Consider
2503 a*b-c -> fma(a,b,-c): we've exchanged MUL+SUB for FMA+NEG, which
2504 is still two operations. Consider -(a*b)-c -> fma(-a,b,-c): we
2505 still have 3 operations, but in the FMA form the two NEGs are
9d75589a 2506 independent and could be run in parallel. */
b9be572e 2507 }
2508
2509 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, mul_result)
2510 {
b9be572e 2511 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
17a2c727 2512 enum tree_code use_code;
15dbdc8f 2513 tree addop, mulop1 = op1, result = mul_result;
44579526 2514 bool negate_p = false;
b9be572e 2515
17a2c727 2516 if (is_gimple_debug (use_stmt))
2517 continue;
2518
2519 use_code = gimple_assign_rhs_code (use_stmt);
44579526 2520 if (use_code == NEGATE_EXPR)
2521 {
2522 result = gimple_assign_lhs (use_stmt);
2523 single_imm_use (gimple_assign_lhs (use_stmt), &use_p, &neguse_stmt);
2524 gsi_remove (&gsi, true);
2525 release_defs (use_stmt);
2526
2527 use_stmt = neguse_stmt;
2528 gsi = gsi_for_stmt (use_stmt);
2529 use_code = gimple_assign_rhs_code (use_stmt);
2530 negate_p = true;
2531 }
2532
2533 if (gimple_assign_rhs1 (use_stmt) == result)
b9be572e 2534 {
2535 addop = gimple_assign_rhs2 (use_stmt);
2536 /* a * b - c -> a * b + (-c) */
2537 if (gimple_assign_rhs_code (use_stmt) == MINUS_EXPR)
2538 addop = force_gimple_operand_gsi (&gsi,
2539 build1 (NEGATE_EXPR,
2540 type, addop),
2541 true, NULL_TREE, true,
2542 GSI_SAME_STMT);
2543 }
2544 else
2545 {
2546 addop = gimple_assign_rhs1 (use_stmt);
2547 /* a - b * c -> (-b) * c + a */
2548 if (gimple_assign_rhs_code (use_stmt) == MINUS_EXPR)
44579526 2549 negate_p = !negate_p;
b9be572e 2550 }
2551
44579526 2552 if (negate_p)
2553 mulop1 = force_gimple_operand_gsi (&gsi,
2554 build1 (NEGATE_EXPR,
2555 type, mulop1),
2556 true, NULL_TREE, true,
2557 GSI_SAME_STMT);
2558
b9be572e 2559 fma_stmt = gimple_build_assign_with_ops3 (FMA_EXPR,
2560 gimple_assign_lhs (use_stmt),
15dbdc8f 2561 mulop1, op2,
b9be572e 2562 addop);
2563 gsi_replace (&gsi, fma_stmt, true);
30c4e60d 2564 widen_mul_stats.fmas_inserted++;
b9be572e 2565 }
2566
2567 return true;
2568}
2569
62be004c 2570/* Find integer multiplications where the operands are extended from
2571 smaller types, and replace the MULT_EXPR with a WIDEN_MULT_EXPR
2572 where appropriate. */
2573
2574static unsigned int
2575execute_optimize_widening_mul (void)
2576{
62be004c 2577 basic_block bb;
15dbdc8f 2578 bool cfg_changed = false;
62be004c 2579
30c4e60d 2580 memset (&widen_mul_stats, 0, sizeof (widen_mul_stats));
2581
62be004c 2582 FOR_EACH_BB (bb)
2583 {
2584 gimple_stmt_iterator gsi;
2585
b9be572e 2586 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi);)
62be004c 2587 {
2588 gimple stmt = gsi_stmt (gsi);
00f4f705 2589 enum tree_code code;
62be004c 2590
b9be572e 2591 if (is_gimple_assign (stmt))
2592 {
2593 code = gimple_assign_rhs_code (stmt);
2594 switch (code)
2595 {
2596 case MULT_EXPR:
aff5fb4d 2597 if (!convert_mult_to_widen (stmt, &gsi)
15dbdc8f 2598 && convert_mult_to_fma (stmt,
2599 gimple_assign_rhs1 (stmt),
2600 gimple_assign_rhs2 (stmt)))
b9be572e 2601 {
2602 gsi_remove (&gsi, true);
2603 release_defs (stmt);
2604 continue;
2605 }
2606 break;
2607
2608 case PLUS_EXPR:
2609 case MINUS_EXPR:
2610 convert_plusminus_to_widen (&gsi, stmt, code);
2611 break;
62be004c 2612
b9be572e 2613 default:;
2614 }
2615 }
d4af184a 2616 else if (is_gimple_call (stmt)
2617 && gimple_call_lhs (stmt))
15dbdc8f 2618 {
2619 tree fndecl = gimple_call_fndecl (stmt);
2620 if (fndecl
2621 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
2622 {
2623 switch (DECL_FUNCTION_CODE (fndecl))
2624 {
2625 case BUILT_IN_POWF:
2626 case BUILT_IN_POW:
2627 case BUILT_IN_POWL:
2628 if (TREE_CODE (gimple_call_arg (stmt, 1)) == REAL_CST
2629 && REAL_VALUES_EQUAL
2630 (TREE_REAL_CST (gimple_call_arg (stmt, 1)),
2631 dconst2)
2632 && convert_mult_to_fma (stmt,
2633 gimple_call_arg (stmt, 0),
2634 gimple_call_arg (stmt, 0)))
2635 {
6716f635 2636 unlink_stmt_vdef (stmt);
13ff78a4 2637 if (gsi_remove (&gsi, true)
2638 && gimple_purge_dead_eh_edges (bb))
15dbdc8f 2639 cfg_changed = true;
13ff78a4 2640 release_defs (stmt);
15dbdc8f 2641 continue;
2642 }
2643 break;
2644
2645 default:;
2646 }
2647 }
2648 }
b9be572e 2649 gsi_next (&gsi);
62be004c 2650 }
2651 }
00f4f705 2652
30c4e60d 2653 statistics_counter_event (cfun, "widening multiplications inserted",
2654 widen_mul_stats.widen_mults_inserted);
2655 statistics_counter_event (cfun, "widening maccs inserted",
2656 widen_mul_stats.maccs_inserted);
2657 statistics_counter_event (cfun, "fused multiply-adds inserted",
2658 widen_mul_stats.fmas_inserted);
2659
15dbdc8f 2660 return cfg_changed ? TODO_cleanup_cfg : 0;
62be004c 2661}
2662
2663static bool
2664gate_optimize_widening_mul (void)
2665{
2666 return flag_expensive_optimizations && optimize;
2667}
2668
2669struct gimple_opt_pass pass_optimize_widening_mul =
2670{
2671 {
2672 GIMPLE_PASS,
2673 "widening_mul", /* name */
2674 gate_optimize_widening_mul, /* gate */
2675 execute_optimize_widening_mul, /* execute */
2676 NULL, /* sub */
2677 NULL, /* next */
2678 0, /* static_pass_number */
2679 TV_NONE, /* tv_id */
2680 PROP_ssa, /* properties_required */
2681 0, /* properties_provided */
2682 0, /* properties_destroyed */
2683 0, /* todo_flags_start */
b9be572e 2684 TODO_verify_ssa
2685 | TODO_verify_stmts
b9be572e 2686 | TODO_update_ssa /* todo_flags_finish */
62be004c 2687 }
2688};