Suppress -fstack-protector warning on hppa.
[official-gcc.git] / gcc / tree-ssa-phiopt.cc
blob996700baaf37efe223d9a289c931ddcf06bc1b25
1 /* Optimization of PHI nodes by converting them into straightline code.
2 Copyright (C) 2004-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "insn-codes.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "cfghooks.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "tree-ssa.h"
32 #include "optabs-tree.h"
33 #include "insn-config.h"
34 #include "gimple-pretty-print.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "cfganal.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "tree-cfg.h"
42 #include "tree-dfa.h"
43 #include "domwalk.h"
44 #include "cfgloop.h"
45 #include "tree-data-ref.h"
46 #include "tree-scalar-evolution.h"
47 #include "tree-inline.h"
48 #include "case-cfn-macros.h"
49 #include "tree-eh.h"
50 #include "gimple-fold.h"
51 #include "internal-fn.h"
52 #include "gimple-range.h"
53 #include "gimple-match.h"
54 #include "dbgcnt.h"
55 #include "tree-ssa-propagate.h"
56 #include "tree-ssa-dce.h"
58 static unsigned int tree_ssa_phiopt_worker (bool, bool, bool);
59 static bool two_value_replacement (basic_block, basic_block, edge, gphi *,
60 tree, tree);
61 static bool match_simplify_replacement (basic_block, basic_block,
62 edge, edge, gphi *, tree, tree, bool);
63 static gphi *factor_out_conditional_conversion (edge, edge, gphi *, tree, tree,
64 gimple *);
65 static int value_replacement (basic_block, basic_block,
66 edge, edge, gphi *, tree, tree);
67 static bool minmax_replacement (basic_block, basic_block, basic_block,
68 edge, edge, gphi *, tree, tree, bool);
69 static bool spaceship_replacement (basic_block, basic_block,
70 edge, edge, gphi *, tree, tree);
71 static bool cond_removal_in_builtin_zero_pattern (basic_block, basic_block,
72 edge, edge, gphi *,
73 tree, tree);
74 static bool cond_store_replacement (basic_block, basic_block, edge, edge,
75 hash_set<tree> *);
76 static bool cond_if_else_store_replacement (basic_block, basic_block, basic_block);
77 static hash_set<tree> * get_non_trapping ();
78 static void hoist_adjacent_loads (basic_block, basic_block,
79 basic_block, basic_block);
80 static bool gate_hoist_loads (void);
82 /* This pass tries to transform conditional stores into unconditional
83 ones, enabling further simplifications with the simpler then and else
84 blocks. In particular it replaces this:
86 bb0:
87 if (cond) goto bb2; else goto bb1;
88 bb1:
89 *p = RHS;
90 bb2:
92 with
94 bb0:
95 if (cond) goto bb1; else goto bb2;
96 bb1:
97 condtmp' = *p;
98 bb2:
99 condtmp = PHI <RHS, condtmp'>
100 *p = condtmp;
102 This transformation can only be done under several constraints,
103 documented below. It also replaces:
105 bb0:
106 if (cond) goto bb2; else goto bb1;
107 bb1:
108 *p = RHS1;
109 goto bb3;
110 bb2:
111 *p = RHS2;
112 bb3:
114 with
116 bb0:
117 if (cond) goto bb3; else goto bb1;
118 bb1:
119 bb3:
120 condtmp = PHI <RHS1, RHS2>
121 *p = condtmp; */
123 static unsigned int
124 tree_ssa_cs_elim (void)
126 unsigned todo;
127 /* ??? We are not interested in loop related info, but the following
128 will create it, ICEing as we didn't init loops with pre-headers.
129 An interfacing issue of find_data_references_in_bb. */
130 loop_optimizer_init (LOOPS_NORMAL);
131 scev_initialize ();
132 todo = tree_ssa_phiopt_worker (true, false, false);
133 scev_finalize ();
134 loop_optimizer_finalize ();
135 return todo;
138 /* Return the singleton PHI in the SEQ of PHIs for edges E0 and E1. */
140 static gphi *
141 single_non_singleton_phi_for_edges (gimple_seq seq, edge e0, edge e1)
143 gimple_stmt_iterator i;
144 gphi *phi = NULL;
145 if (gimple_seq_singleton_p (seq))
146 return as_a <gphi *> (gsi_stmt (gsi_start (seq)));
147 for (i = gsi_start (seq); !gsi_end_p (i); gsi_next (&i))
149 gphi *p = as_a <gphi *> (gsi_stmt (i));
150 /* If the PHI arguments are equal then we can skip this PHI. */
151 if (operand_equal_for_phi_arg_p (gimple_phi_arg_def (p, e0->dest_idx),
152 gimple_phi_arg_def (p, e1->dest_idx)))
153 continue;
155 /* If we already have a PHI that has the two edge arguments are
156 different, then return it is not a singleton for these PHIs. */
157 if (phi)
158 return NULL;
160 phi = p;
162 return phi;
165 /* The core routine of conditional store replacement and normal
166 phi optimizations. Both share much of the infrastructure in how
167 to match applicable basic block patterns. DO_STORE_ELIM is true
168 when we want to do conditional store replacement, false otherwise.
169 DO_HOIST_LOADS is true when we want to hoist adjacent loads out
170 of diamond control flow patterns, false otherwise. */
171 static unsigned int
172 tree_ssa_phiopt_worker (bool do_store_elim, bool do_hoist_loads, bool early_p)
174 basic_block bb;
175 basic_block *bb_order;
176 unsigned n, i;
177 bool cfgchanged = false;
178 hash_set<tree> *nontrap = 0;
180 calculate_dominance_info (CDI_DOMINATORS);
182 if (do_store_elim)
183 /* Calculate the set of non-trapping memory accesses. */
184 nontrap = get_non_trapping ();
186 /* Search every basic block for COND_EXPR we may be able to optimize.
188 We walk the blocks in order that guarantees that a block with
189 a single predecessor is processed before the predecessor.
190 This ensures that we collapse inner ifs before visiting the
191 outer ones, and also that we do not try to visit a removed
192 block. */
193 bb_order = single_pred_before_succ_order ();
194 n = n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS;
196 for (i = 0; i < n; i++)
198 gimple *cond_stmt;
199 gphi *phi;
200 basic_block bb1, bb2;
201 edge e1, e2;
202 tree arg0, arg1;
203 bool diamond_p = false;
205 bb = bb_order[i];
207 cond_stmt = last_stmt (bb);
208 /* Check to see if the last statement is a GIMPLE_COND. */
209 if (!cond_stmt
210 || gimple_code (cond_stmt) != GIMPLE_COND)
211 continue;
213 e1 = EDGE_SUCC (bb, 0);
214 bb1 = e1->dest;
215 e2 = EDGE_SUCC (bb, 1);
216 bb2 = e2->dest;
218 /* We cannot do the optimization on abnormal edges. */
219 if ((e1->flags & EDGE_ABNORMAL) != 0
220 || (e2->flags & EDGE_ABNORMAL) != 0)
221 continue;
223 /* If either bb1's succ or bb2 or bb2's succ is non NULL. */
224 if (EDGE_COUNT (bb1->succs) == 0
225 || EDGE_COUNT (bb2->succs) == 0)
226 continue;
228 /* Find the bb which is the fall through to the other. */
229 if (EDGE_SUCC (bb1, 0)->dest == bb2)
231 else if (EDGE_SUCC (bb2, 0)->dest == bb1)
233 std::swap (bb1, bb2);
234 std::swap (e1, e2);
236 else if (do_store_elim
237 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
239 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
241 if (!single_succ_p (bb1)
242 || (EDGE_SUCC (bb1, 0)->flags & EDGE_FALLTHRU) == 0
243 || !single_succ_p (bb2)
244 || (EDGE_SUCC (bb2, 0)->flags & EDGE_FALLTHRU) == 0
245 || EDGE_COUNT (bb3->preds) != 2)
246 continue;
247 if (cond_if_else_store_replacement (bb1, bb2, bb3))
248 cfgchanged = true;
249 continue;
251 else if (do_hoist_loads
252 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
254 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
256 if (!FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond_stmt)))
257 && single_succ_p (bb1)
258 && single_succ_p (bb2)
259 && single_pred_p (bb1)
260 && single_pred_p (bb2)
261 && EDGE_COUNT (bb->succs) == 2
262 && EDGE_COUNT (bb3->preds) == 2
263 /* If one edge or the other is dominant, a conditional move
264 is likely to perform worse than the well-predicted branch. */
265 && !predictable_edge_p (EDGE_SUCC (bb, 0))
266 && !predictable_edge_p (EDGE_SUCC (bb, 1)))
267 hoist_adjacent_loads (bb, bb1, bb2, bb3);
268 continue;
270 else if (EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest
271 && !empty_block_p (bb1))
273 diamond_p = true;
274 e2 = EDGE_SUCC (bb2, 0);
276 else
277 continue;
279 e1 = EDGE_SUCC (bb1, 0);
281 /* Make sure that bb1 is just a fall through. */
282 if (!single_succ_p (bb1)
283 || (e1->flags & EDGE_FALLTHRU) == 0)
284 continue;
286 if (do_store_elim && !diamond_p)
288 /* Also make sure that bb1 only have one predecessor and that it
289 is bb. */
290 if (!single_pred_p (bb1)
291 || single_pred (bb1) != bb)
292 continue;
294 /* bb1 is the middle block, bb2 the join block, bb the split block,
295 e1 the fallthrough edge from bb1 to bb2. We can't do the
296 optimization if the join block has more than two predecessors. */
297 if (EDGE_COUNT (bb2->preds) > 2)
298 continue;
299 if (cond_store_replacement (bb1, bb2, e1, e2, nontrap))
300 cfgchanged = true;
302 else
304 gimple_stmt_iterator gsi;
305 bool candorest = true;
307 /* Check that we're looking for nested phis. */
308 basic_block merge = diamond_p ? EDGE_SUCC (bb2, 0)->dest : bb2;
309 gimple_seq phis = phi_nodes (merge);
311 /* Value replacement can work with more than one PHI
312 so try that first. */
313 if (!early_p && !diamond_p)
314 for (gsi = gsi_start (phis); !gsi_end_p (gsi); gsi_next (&gsi))
316 phi = as_a <gphi *> (gsi_stmt (gsi));
317 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
318 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
319 if (value_replacement (bb, bb1, e1, e2, phi, arg0, arg1) == 2)
321 candorest = false;
322 cfgchanged = true;
323 break;
327 if (!candorest)
328 continue;
330 phi = single_non_singleton_phi_for_edges (phis, e1, e2);
331 if (!phi)
332 continue;
334 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
335 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
337 /* Something is wrong if we cannot find the arguments in the PHI
338 node. */
339 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
341 gphi *newphi;
342 if (single_pred_p (bb1)
343 && !diamond_p
344 && (newphi = factor_out_conditional_conversion (e1, e2, phi,
345 arg0, arg1,
346 cond_stmt)))
348 phi = newphi;
349 /* factor_out_conditional_conversion may create a new PHI in
350 BB2 and eliminate an existing PHI in BB2. Recompute values
351 that may be affected by that change. */
352 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
353 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
354 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
357 /* Do the replacement of conditional if it can be done. */
358 if (!early_p
359 && !diamond_p
360 && two_value_replacement (bb, bb1, e2, phi, arg0, arg1))
361 cfgchanged = true;
362 else if (!diamond_p
363 && match_simplify_replacement (bb, bb1, e1, e2, phi,
364 arg0, arg1, early_p))
365 cfgchanged = true;
366 else if (!early_p
367 && !diamond_p
368 && single_pred_p (bb1)
369 && cond_removal_in_builtin_zero_pattern (bb, bb1, e1, e2,
370 phi, arg0, arg1))
371 cfgchanged = true;
372 else if (minmax_replacement (bb, bb1, bb2, e1, e2, phi, arg0, arg1,
373 diamond_p))
374 cfgchanged = true;
375 else if (single_pred_p (bb1)
376 && !diamond_p
377 && spaceship_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
378 cfgchanged = true;
382 free (bb_order);
384 if (do_store_elim)
385 delete nontrap;
386 /* If the CFG has changed, we should cleanup the CFG. */
387 if (cfgchanged && do_store_elim)
389 /* In cond-store replacement we have added some loads on edges
390 and new VOPS (as we moved the store, and created a load). */
391 gsi_commit_edge_inserts ();
392 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
394 else if (cfgchanged)
395 return TODO_cleanup_cfg;
396 return 0;
399 /* Replace PHI node element whose edge is E in block BB with variable NEW.
400 Remove the edge from COND_BLOCK which does not lead to BB (COND_BLOCK
401 is known to have two edges, one of which must reach BB). */
403 static void
404 replace_phi_edge_with_variable (basic_block cond_block,
405 edge e, gphi *phi, tree new_tree,
406 bitmap dce_ssa_names = auto_bitmap())
408 basic_block bb = gimple_bb (phi);
409 gimple_stmt_iterator gsi;
410 tree phi_result = PHI_RESULT (phi);
412 /* Duplicate range info if they are the only things setting the target PHI.
413 This is needed as later on, the new_tree will be replacing
414 The assignement of the PHI.
415 For an example:
416 bb1:
417 _4 = min<a_1, 255>
418 goto bb2
420 # RANGE [-INF, 255]
421 a_3 = PHI<_4(1)>
422 bb3:
424 use(a_3)
425 And _4 gets propagated into the use of a_3 and losing the range info.
426 This can't be done for more than 2 incoming edges as the propagation
427 won't happen.
428 The new_tree needs to be defined in the same basic block as the conditional. */
429 if (TREE_CODE (new_tree) == SSA_NAME
430 && EDGE_COUNT (gimple_bb (phi)->preds) == 2
431 && INTEGRAL_TYPE_P (TREE_TYPE (phi_result))
432 && !SSA_NAME_RANGE_INFO (new_tree)
433 && SSA_NAME_RANGE_INFO (phi_result)
434 && gimple_bb (SSA_NAME_DEF_STMT (new_tree)) == cond_block
435 && dbg_cnt (phiopt_edge_range))
436 duplicate_ssa_name_range_info (new_tree, phi_result);
438 /* Change the PHI argument to new. */
439 SET_USE (PHI_ARG_DEF_PTR (phi, e->dest_idx), new_tree);
441 /* Remove the empty basic block. */
442 edge edge_to_remove = NULL, keep_edge = NULL;
443 if (EDGE_SUCC (cond_block, 0)->dest == bb)
445 edge_to_remove = EDGE_SUCC (cond_block, 1);
446 keep_edge = EDGE_SUCC (cond_block, 0);
448 else if (EDGE_SUCC (cond_block, 1)->dest == bb)
450 edge_to_remove = EDGE_SUCC (cond_block, 0);
451 keep_edge = EDGE_SUCC (cond_block, 1);
453 else if ((keep_edge = find_edge (cond_block, e->src)))
455 else
456 gcc_unreachable ();
458 if (edge_to_remove && EDGE_COUNT (edge_to_remove->dest->preds) == 1)
460 e->flags |= EDGE_FALLTHRU;
461 e->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
462 e->probability = profile_probability::always ();
463 delete_basic_block (edge_to_remove->dest);
465 /* Eliminate the COND_EXPR at the end of COND_BLOCK. */
466 gsi = gsi_last_bb (cond_block);
467 gsi_remove (&gsi, true);
469 else
471 /* If there are other edges into the middle block make
472 CFG cleanup deal with the edge removal to avoid
473 updating dominators here in a non-trivial way. */
474 gcond *cond = as_a <gcond *> (last_stmt (cond_block));
475 if (keep_edge->flags & EDGE_FALSE_VALUE)
476 gimple_cond_make_false (cond);
477 else if (keep_edge->flags & EDGE_TRUE_VALUE)
478 gimple_cond_make_true (cond);
481 simple_dce_from_worklist (dce_ssa_names);
483 statistics_counter_event (cfun, "Replace PHI with variable", 1);
485 if (dump_file && (dump_flags & TDF_DETAILS))
486 fprintf (dump_file,
487 "COND_EXPR in block %d and PHI in block %d converted to straightline code.\n",
488 cond_block->index,
489 bb->index);
492 /* PR66726: Factor conversion out of COND_EXPR. If the arguments of the PHI
493 stmt are CONVERT_STMT, factor out the conversion and perform the conversion
494 to the result of PHI stmt. COND_STMT is the controlling predicate.
495 Return the newly-created PHI, if any. */
497 static gphi *
498 factor_out_conditional_conversion (edge e0, edge e1, gphi *phi,
499 tree arg0, tree arg1, gimple *cond_stmt)
501 gimple *arg0_def_stmt = NULL, *arg1_def_stmt = NULL, *new_stmt;
502 tree new_arg0 = NULL_TREE, new_arg1 = NULL_TREE;
503 tree temp, result;
504 gphi *newphi;
505 gimple_stmt_iterator gsi, gsi_for_def;
506 location_t locus = gimple_location (phi);
507 enum tree_code convert_code;
509 /* Handle only PHI statements with two arguments. TODO: If all
510 other arguments to PHI are INTEGER_CST or if their defining
511 statement have the same unary operation, we can handle more
512 than two arguments too. */
513 if (gimple_phi_num_args (phi) != 2)
514 return NULL;
516 /* First canonicalize to simplify tests. */
517 if (TREE_CODE (arg0) != SSA_NAME)
519 std::swap (arg0, arg1);
520 std::swap (e0, e1);
523 if (TREE_CODE (arg0) != SSA_NAME
524 || (TREE_CODE (arg1) != SSA_NAME
525 && TREE_CODE (arg1) != INTEGER_CST))
526 return NULL;
528 /* Check if arg0 is an SSA_NAME and the stmt which defines arg0 is
529 a conversion. */
530 arg0_def_stmt = SSA_NAME_DEF_STMT (arg0);
531 if (!gimple_assign_cast_p (arg0_def_stmt))
532 return NULL;
534 /* Use the RHS as new_arg0. */
535 convert_code = gimple_assign_rhs_code (arg0_def_stmt);
536 new_arg0 = gimple_assign_rhs1 (arg0_def_stmt);
537 if (convert_code == VIEW_CONVERT_EXPR)
539 new_arg0 = TREE_OPERAND (new_arg0, 0);
540 if (!is_gimple_reg_type (TREE_TYPE (new_arg0)))
541 return NULL;
543 if (TREE_CODE (new_arg0) == SSA_NAME
544 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_arg0))
545 return NULL;
547 if (TREE_CODE (arg1) == SSA_NAME)
549 /* Check if arg1 is an SSA_NAME and the stmt which defines arg1
550 is a conversion. */
551 arg1_def_stmt = SSA_NAME_DEF_STMT (arg1);
552 if (!is_gimple_assign (arg1_def_stmt)
553 || gimple_assign_rhs_code (arg1_def_stmt) != convert_code)
554 return NULL;
556 /* Either arg1_def_stmt or arg0_def_stmt should be conditional. */
557 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (phi), gimple_bb (arg0_def_stmt))
558 && dominated_by_p (CDI_DOMINATORS,
559 gimple_bb (phi), gimple_bb (arg1_def_stmt)))
560 return NULL;
562 /* Use the RHS as new_arg1. */
563 new_arg1 = gimple_assign_rhs1 (arg1_def_stmt);
564 if (convert_code == VIEW_CONVERT_EXPR)
565 new_arg1 = TREE_OPERAND (new_arg1, 0);
566 if (TREE_CODE (new_arg1) == SSA_NAME
567 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_arg1))
568 return NULL;
570 else
572 /* arg0_def_stmt should be conditional. */
573 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (phi), gimple_bb (arg0_def_stmt)))
574 return NULL;
575 /* If arg1 is an INTEGER_CST, fold it to new type. */
576 if (INTEGRAL_TYPE_P (TREE_TYPE (new_arg0))
577 && int_fits_type_p (arg1, TREE_TYPE (new_arg0)))
579 if (gimple_assign_cast_p (arg0_def_stmt))
581 /* For the INTEGER_CST case, we are just moving the
582 conversion from one place to another, which can often
583 hurt as the conversion moves further away from the
584 statement that computes the value. So, perform this
585 only if new_arg0 is an operand of COND_STMT, or
586 if arg0_def_stmt is the only non-debug stmt in
587 its basic block, because then it is possible this
588 could enable further optimizations (minmax replacement
589 etc.). See PR71016. */
590 if (new_arg0 != gimple_cond_lhs (cond_stmt)
591 && new_arg0 != gimple_cond_rhs (cond_stmt)
592 && gimple_bb (arg0_def_stmt) == e0->src)
594 gsi = gsi_for_stmt (arg0_def_stmt);
595 gsi_prev_nondebug (&gsi);
596 if (!gsi_end_p (gsi))
598 if (gassign *assign
599 = dyn_cast <gassign *> (gsi_stmt (gsi)))
601 tree lhs = gimple_assign_lhs (assign);
602 enum tree_code ass_code
603 = gimple_assign_rhs_code (assign);
604 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
605 return NULL;
606 if (lhs != gimple_assign_rhs1 (arg0_def_stmt))
607 return NULL;
608 gsi_prev_nondebug (&gsi);
609 if (!gsi_end_p (gsi))
610 return NULL;
612 else
613 return NULL;
615 gsi = gsi_for_stmt (arg0_def_stmt);
616 gsi_next_nondebug (&gsi);
617 if (!gsi_end_p (gsi))
618 return NULL;
620 new_arg1 = fold_convert (TREE_TYPE (new_arg0), arg1);
622 else
623 return NULL;
625 else
626 return NULL;
629 /* If arg0/arg1 have > 1 use, then this transformation actually increases
630 the number of expressions evaluated at runtime. */
631 if (!has_single_use (arg0)
632 || (arg1_def_stmt && !has_single_use (arg1)))
633 return NULL;
635 /* If types of new_arg0 and new_arg1 are different bailout. */
636 if (!types_compatible_p (TREE_TYPE (new_arg0), TREE_TYPE (new_arg1)))
637 return NULL;
639 /* Create a new PHI stmt. */
640 result = PHI_RESULT (phi);
641 temp = make_ssa_name (TREE_TYPE (new_arg0), NULL);
642 newphi = create_phi_node (temp, gimple_bb (phi));
644 if (dump_file && (dump_flags & TDF_DETAILS))
646 fprintf (dump_file, "PHI ");
647 print_generic_expr (dump_file, gimple_phi_result (phi));
648 fprintf (dump_file,
649 " changed to factor conversion out from COND_EXPR.\n");
650 fprintf (dump_file, "New stmt with CAST that defines ");
651 print_generic_expr (dump_file, result);
652 fprintf (dump_file, ".\n");
655 /* Remove the old cast(s) that has single use. */
656 gsi_for_def = gsi_for_stmt (arg0_def_stmt);
657 gsi_remove (&gsi_for_def, true);
658 release_defs (arg0_def_stmt);
660 if (arg1_def_stmt)
662 gsi_for_def = gsi_for_stmt (arg1_def_stmt);
663 gsi_remove (&gsi_for_def, true);
664 release_defs (arg1_def_stmt);
667 add_phi_arg (newphi, new_arg0, e0, locus);
668 add_phi_arg (newphi, new_arg1, e1, locus);
670 /* Create the conversion stmt and insert it. */
671 if (convert_code == VIEW_CONVERT_EXPR)
673 temp = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (result), temp);
674 new_stmt = gimple_build_assign (result, temp);
676 else
677 new_stmt = gimple_build_assign (result, convert_code, temp);
678 gsi = gsi_after_labels (gimple_bb (phi));
679 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
681 /* Remove the original PHI stmt. */
682 gsi = gsi_for_stmt (phi);
683 gsi_remove (&gsi, true);
685 statistics_counter_event (cfun, "factored out cast", 1);
687 return newphi;
690 /* Optimize
691 # x_5 in range [cst1, cst2] where cst2 = cst1 + 1
692 if (x_5 op cstN) # where op is == or != and N is 1 or 2
693 goto bb3;
694 else
695 goto bb4;
696 bb3:
697 bb4:
698 # r_6 = PHI<cst3(2), cst4(3)> # where cst3 == cst4 + 1 or cst4 == cst3 + 1
700 to r_6 = x_5 + (min (cst3, cst4) - cst1) or
701 r_6 = (min (cst3, cst4) + cst1) - x_5 depending on op, N and which
702 of cst3 and cst4 is smaller. */
704 static bool
705 two_value_replacement (basic_block cond_bb, basic_block middle_bb,
706 edge e1, gphi *phi, tree arg0, tree arg1)
708 /* Only look for adjacent integer constants. */
709 if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0))
710 || !INTEGRAL_TYPE_P (TREE_TYPE (arg1))
711 || TREE_CODE (arg0) != INTEGER_CST
712 || TREE_CODE (arg1) != INTEGER_CST
713 || (tree_int_cst_lt (arg0, arg1)
714 ? wi::to_widest (arg0) + 1 != wi::to_widest (arg1)
715 : wi::to_widest (arg1) + 1 != wi::to_widest (arg0)))
716 return false;
718 if (!empty_block_p (middle_bb))
719 return false;
721 gimple *stmt = last_stmt (cond_bb);
722 tree lhs = gimple_cond_lhs (stmt);
723 tree rhs = gimple_cond_rhs (stmt);
725 if (TREE_CODE (lhs) != SSA_NAME
726 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs))
727 || TREE_CODE (rhs) != INTEGER_CST)
728 return false;
730 switch (gimple_cond_code (stmt))
732 case EQ_EXPR:
733 case NE_EXPR:
734 break;
735 default:
736 return false;
739 /* Defer boolean x ? 0 : {1,-1} or x ? {1,-1} : 0 to
740 match_simplify_replacement. */
741 if (TREE_CODE (TREE_TYPE (lhs)) == BOOLEAN_TYPE
742 && (integer_zerop (arg0)
743 || integer_zerop (arg1)
744 || TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE
745 || (TYPE_PRECISION (TREE_TYPE (arg0))
746 <= TYPE_PRECISION (TREE_TYPE (lhs)))))
747 return false;
749 wide_int min, max;
750 value_range r;
751 get_range_query (cfun)->range_of_expr (r, lhs);
753 if (r.kind () == VR_RANGE)
755 min = r.lower_bound ();
756 max = r.upper_bound ();
758 else
760 int prec = TYPE_PRECISION (TREE_TYPE (lhs));
761 signop sgn = TYPE_SIGN (TREE_TYPE (lhs));
762 min = wi::min_value (prec, sgn);
763 max = wi::max_value (prec, sgn);
765 if (min + 1 != max
766 || (wi::to_wide (rhs) != min
767 && wi::to_wide (rhs) != max))
768 return false;
770 /* We need to know which is the true edge and which is the false
771 edge so that we know when to invert the condition below. */
772 edge true_edge, false_edge;
773 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
774 if ((gimple_cond_code (stmt) == EQ_EXPR)
775 ^ (wi::to_wide (rhs) == max)
776 ^ (e1 == false_edge))
777 std::swap (arg0, arg1);
779 tree type;
780 if (TYPE_PRECISION (TREE_TYPE (lhs)) == TYPE_PRECISION (TREE_TYPE (arg0)))
782 /* Avoid performing the arithmetics in bool type which has different
783 semantics, otherwise prefer unsigned types from the two with
784 the same precision. */
785 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE
786 || !TYPE_UNSIGNED (TREE_TYPE (arg0)))
787 type = TREE_TYPE (lhs);
788 else
789 type = TREE_TYPE (arg0);
791 else if (TYPE_PRECISION (TREE_TYPE (lhs)) > TYPE_PRECISION (TREE_TYPE (arg0)))
792 type = TREE_TYPE (lhs);
793 else
794 type = TREE_TYPE (arg0);
796 min = wide_int::from (min, TYPE_PRECISION (type),
797 TYPE_SIGN (TREE_TYPE (lhs)));
798 wide_int a = wide_int::from (wi::to_wide (arg0), TYPE_PRECISION (type),
799 TYPE_SIGN (TREE_TYPE (arg0)));
800 enum tree_code code;
801 wi::overflow_type ovf;
802 if (tree_int_cst_lt (arg0, arg1))
804 code = PLUS_EXPR;
805 a -= min;
806 if (!TYPE_UNSIGNED (type))
808 /* lhs is known to be in range [min, min+1] and we want to add a
809 to it. Check if that operation can overflow for those 2 values
810 and if yes, force unsigned type. */
811 wi::add (min + (wi::neg_p (a) ? 0 : 1), a, SIGNED, &ovf);
812 if (ovf)
813 type = unsigned_type_for (type);
816 else
818 code = MINUS_EXPR;
819 a += min;
820 if (!TYPE_UNSIGNED (type))
822 /* lhs is known to be in range [min, min+1] and we want to subtract
823 it from a. Check if that operation can overflow for those 2
824 values and if yes, force unsigned type. */
825 wi::sub (a, min + (wi::neg_p (min) ? 0 : 1), SIGNED, &ovf);
826 if (ovf)
827 type = unsigned_type_for (type);
831 tree arg = wide_int_to_tree (type, a);
832 gimple_seq stmts = NULL;
833 lhs = gimple_convert (&stmts, type, lhs);
834 tree new_rhs;
835 if (code == PLUS_EXPR)
836 new_rhs = gimple_build (&stmts, PLUS_EXPR, type, lhs, arg);
837 else
838 new_rhs = gimple_build (&stmts, MINUS_EXPR, type, arg, lhs);
839 new_rhs = gimple_convert (&stmts, TREE_TYPE (arg0), new_rhs);
840 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
841 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
843 replace_phi_edge_with_variable (cond_bb, e1, phi, new_rhs);
845 /* Note that we optimized this PHI. */
846 return true;
849 /* Return TRUE if SEQ/OP pair should be allowed during early phiopt.
850 Currently this is to allow MIN/MAX and ABS/NEGATE and constants. */
851 static bool
852 phiopt_early_allow (gimple_seq &seq, gimple_match_op &op)
854 /* Don't allow functions. */
855 if (!op.code.is_tree_code ())
856 return false;
857 tree_code code = (tree_code)op.code;
859 /* For non-empty sequence, only allow one statement. */
860 if (!gimple_seq_empty_p (seq))
862 /* Check to make sure op was already a SSA_NAME. */
863 if (code != SSA_NAME)
864 return false;
865 if (!gimple_seq_singleton_p (seq))
866 return false;
867 gimple *stmt = gimple_seq_first_stmt (seq);
868 /* Only allow assignments. */
869 if (!is_gimple_assign (stmt))
870 return false;
871 if (gimple_assign_lhs (stmt) != op.ops[0])
872 return false;
873 code = gimple_assign_rhs_code (stmt);
876 switch (code)
878 case MIN_EXPR:
879 case MAX_EXPR:
880 case ABS_EXPR:
881 case ABSU_EXPR:
882 case NEGATE_EXPR:
883 case SSA_NAME:
884 return true;
885 case INTEGER_CST:
886 case REAL_CST:
887 case VECTOR_CST:
888 case FIXED_CST:
889 return true;
890 default:
891 return false;
895 /* gimple_simplify_phiopt is like gimple_simplify but designed for PHIOPT.
896 Return NULL if nothing can be simplified or the resulting simplified value
897 with parts pushed if EARLY_P was true. Also rejects non allowed tree code
898 if EARLY_P is set.
899 Takes the comparison from COMP_STMT and two args, ARG0 and ARG1 and tries
900 to simplify CMP ? ARG0 : ARG1.
901 Also try to simplify (!CMP) ? ARG1 : ARG0 if the non-inverse failed. */
902 static tree
903 gimple_simplify_phiopt (bool early_p, tree type, gimple *comp_stmt,
904 tree arg0, tree arg1,
905 gimple_seq *seq)
907 tree result;
908 gimple_seq seq1 = NULL;
909 enum tree_code comp_code = gimple_cond_code (comp_stmt);
910 location_t loc = gimple_location (comp_stmt);
911 tree cmp0 = gimple_cond_lhs (comp_stmt);
912 tree cmp1 = gimple_cond_rhs (comp_stmt);
913 /* To handle special cases like floating point comparison, it is easier and
914 less error-prone to build a tree and gimplify it on the fly though it is
915 less efficient.
916 Don't use fold_build2 here as that might create (bool)a instead of just
917 "a != 0". */
918 tree cond = build2_loc (loc, comp_code, boolean_type_node,
919 cmp0, cmp1);
920 gimple_match_op op (gimple_match_cond::UNCOND,
921 COND_EXPR, type, cond, arg0, arg1);
923 if (op.resimplify (&seq1, follow_all_ssa_edges))
925 /* Early we want only to allow some generated tree codes. */
926 if (!early_p
927 || phiopt_early_allow (seq1, op))
929 result = maybe_push_res_to_seq (&op, &seq1);
930 if (result)
932 if (loc != UNKNOWN_LOCATION)
933 annotate_all_with_location (seq1, loc);
934 gimple_seq_add_seq_without_update (seq, seq1);
935 return result;
939 gimple_seq_discard (seq1);
940 seq1 = NULL;
942 /* Try the inverted comparison, that is !COMP ? ARG1 : ARG0. */
943 comp_code = invert_tree_comparison (comp_code, HONOR_NANS (cmp0));
945 if (comp_code == ERROR_MARK)
946 return NULL;
948 cond = build2_loc (loc,
949 comp_code, boolean_type_node,
950 cmp0, cmp1);
951 gimple_match_op op1 (gimple_match_cond::UNCOND,
952 COND_EXPR, type, cond, arg1, arg0);
954 if (op1.resimplify (&seq1, follow_all_ssa_edges))
956 /* Early we want only to allow some generated tree codes. */
957 if (!early_p
958 || phiopt_early_allow (seq1, op1))
960 result = maybe_push_res_to_seq (&op1, &seq1);
961 if (result)
963 if (loc != UNKNOWN_LOCATION)
964 annotate_all_with_location (seq1, loc);
965 gimple_seq_add_seq_without_update (seq, seq1);
966 return result;
970 gimple_seq_discard (seq1);
972 return NULL;
975 /* The function match_simplify_replacement does the main work of doing the
976 replacement using match and simplify. Return true if the replacement is done.
977 Otherwise return false.
978 BB is the basic block where the replacement is going to be done on. ARG0
979 is argument 0 from PHI. Likewise for ARG1. */
981 static bool
982 match_simplify_replacement (basic_block cond_bb, basic_block middle_bb,
983 edge e0, edge e1, gphi *phi,
984 tree arg0, tree arg1, bool early_p)
986 gimple *stmt;
987 gimple_stmt_iterator gsi;
988 edge true_edge, false_edge;
989 gimple_seq seq = NULL;
990 tree result;
991 gimple *stmt_to_move = NULL;
992 auto_bitmap inserted_exprs;
994 /* Special case A ? B : B as this will always simplify to B. */
995 if (operand_equal_for_phi_arg_p (arg0, arg1))
996 return false;
998 /* If the basic block only has a cheap preparation statement,
999 allow it and move it once the transformation is done. */
1000 if (!empty_block_p (middle_bb))
1002 if (!single_pred_p (middle_bb))
1003 return false;
1005 stmt_to_move = last_and_only_stmt (middle_bb);
1006 if (!stmt_to_move)
1007 return false;
1009 if (gimple_vuse (stmt_to_move))
1010 return false;
1012 if (gimple_could_trap_p (stmt_to_move)
1013 || gimple_has_side_effects (stmt_to_move))
1014 return false;
1016 if (gimple_uses_undefined_value_p (stmt_to_move))
1017 return false;
1019 /* Allow assignments and not no calls.
1020 As const calls don't match any of the above, yet they could
1021 still have some side-effects - they could contain
1022 gimple_could_trap_p statements, like floating point
1023 exceptions or integer division by zero. See PR70586.
1024 FIXME: perhaps gimple_has_side_effects or gimple_could_trap_p
1025 should handle this. */
1026 if (!is_gimple_assign (stmt_to_move))
1027 return false;
1029 tree lhs = gimple_assign_lhs (stmt_to_move);
1030 gimple *use_stmt;
1031 use_operand_p use_p;
1033 /* Allow only a statement which feeds into the phi. */
1034 if (!lhs || TREE_CODE (lhs) != SSA_NAME
1035 || !single_imm_use (lhs, &use_p, &use_stmt)
1036 || use_stmt != phi)
1037 return false;
1040 /* At this point we know we have a GIMPLE_COND with two successors.
1041 One successor is BB, the other successor is an empty block which
1042 falls through into BB.
1044 There is a single PHI node at the join point (BB).
1046 So, given the condition COND, and the two PHI arguments, match and simplify
1047 can happen on (COND) ? arg0 : arg1. */
1049 stmt = last_stmt (cond_bb);
1051 /* We need to know which is the true edge and which is the false
1052 edge so that we know when to invert the condition below. */
1053 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1054 if (e1 == true_edge || e0 == false_edge)
1055 std::swap (arg0, arg1);
1057 tree type = TREE_TYPE (gimple_phi_result (phi));
1058 result = gimple_simplify_phiopt (early_p, type, stmt,
1059 arg0, arg1,
1060 &seq);
1061 if (!result)
1062 return false;
1064 gsi = gsi_last_bb (cond_bb);
1065 /* Insert the sequence generated from gimple_simplify_phiopt. */
1066 if (seq)
1068 // Mark the lhs of the new statements maybe for dce
1069 gimple_stmt_iterator gsi1 = gsi_start (seq);
1070 for (; !gsi_end_p (gsi1); gsi_next (&gsi1))
1072 gimple *stmt = gsi_stmt (gsi1);
1073 tree name = gimple_get_lhs (stmt);
1074 if (name && TREE_CODE (name) == SSA_NAME)
1075 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
1077 gsi_insert_seq_before (&gsi, seq, GSI_CONTINUE_LINKING);
1080 /* If there was a statement to move, move it to right before
1081 the original conditional. */
1082 if (stmt_to_move)
1084 if (dump_file && (dump_flags & TDF_DETAILS))
1086 fprintf (dump_file, "statement un-sinked:\n");
1087 print_gimple_stmt (dump_file, stmt_to_move, 0,
1088 TDF_VOPS|TDF_MEMSYMS);
1091 tree name = gimple_get_lhs (stmt_to_move);
1092 // Mark the name to be renamed if there is one.
1093 if (name && TREE_CODE (name) == SSA_NAME)
1094 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
1095 gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt_to_move);
1096 gsi_move_before (&gsi1, &gsi);
1097 reset_flow_sensitive_info (gimple_assign_lhs (stmt_to_move));
1100 replace_phi_edge_with_variable (cond_bb, e1, phi, result, inserted_exprs);
1102 /* Add Statistic here even though replace_phi_edge_with_variable already
1103 does it as we want to be able to count when match-simplify happens vs
1104 the others. */
1105 statistics_counter_event (cfun, "match-simplify PHI replacement", 1);
1107 /* Note that we optimized this PHI. */
1108 return true;
1111 /* Update *ARG which is defined in STMT so that it contains the
1112 computed value if that seems profitable. Return true if the
1113 statement is made dead by that rewriting. */
1115 static bool
1116 jump_function_from_stmt (tree *arg, gimple *stmt)
1118 enum tree_code code = gimple_assign_rhs_code (stmt);
1119 if (code == ADDR_EXPR)
1121 /* For arg = &p->i transform it to p, if possible. */
1122 tree rhs1 = gimple_assign_rhs1 (stmt);
1123 poly_int64 offset;
1124 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs1, 0),
1125 &offset);
1126 if (tem
1127 && TREE_CODE (tem) == MEM_REF
1128 && known_eq (mem_ref_offset (tem) + offset, 0))
1130 *arg = TREE_OPERAND (tem, 0);
1131 return true;
1134 /* TODO: Much like IPA-CP jump-functions we want to handle constant
1135 additions symbolically here, and we'd need to update the comparison
1136 code that compares the arg + cst tuples in our caller. For now the
1137 code above exactly handles the VEC_BASE pattern from vec.h. */
1138 return false;
1141 /* RHS is a source argument in a BIT_AND_EXPR which feeds a conditional
1142 of the form SSA_NAME NE 0.
1144 If RHS is fed by a simple EQ_EXPR comparison of two values, see if
1145 the two input values of the EQ_EXPR match arg0 and arg1.
1147 If so update *code and return TRUE. Otherwise return FALSE. */
1149 static bool
1150 rhs_is_fed_for_value_replacement (const_tree arg0, const_tree arg1,
1151 enum tree_code *code, const_tree rhs)
1153 /* Obviously if RHS is not an SSA_NAME, we can't look at the defining
1154 statement. */
1155 if (TREE_CODE (rhs) == SSA_NAME)
1157 gimple *def1 = SSA_NAME_DEF_STMT (rhs);
1159 /* Verify the defining statement has an EQ_EXPR on the RHS. */
1160 if (is_gimple_assign (def1) && gimple_assign_rhs_code (def1) == EQ_EXPR)
1162 /* Finally verify the source operands of the EQ_EXPR are equal
1163 to arg0 and arg1. */
1164 tree op0 = gimple_assign_rhs1 (def1);
1165 tree op1 = gimple_assign_rhs2 (def1);
1166 if ((operand_equal_for_phi_arg_p (arg0, op0)
1167 && operand_equal_for_phi_arg_p (arg1, op1))
1168 || (operand_equal_for_phi_arg_p (arg0, op1)
1169 && operand_equal_for_phi_arg_p (arg1, op0)))
1171 /* We will perform the optimization. */
1172 *code = gimple_assign_rhs_code (def1);
1173 return true;
1177 return false;
1180 /* Return TRUE if arg0/arg1 are equal to the rhs/lhs or lhs/rhs of COND.
1182 Also return TRUE if arg0/arg1 are equal to the source arguments of a
1183 an EQ comparison feeding a BIT_AND_EXPR which feeds COND.
1185 Return FALSE otherwise. */
1187 static bool
1188 operand_equal_for_value_replacement (const_tree arg0, const_tree arg1,
1189 enum tree_code *code, gimple *cond)
1191 gimple *def;
1192 tree lhs = gimple_cond_lhs (cond);
1193 tree rhs = gimple_cond_rhs (cond);
1195 if ((operand_equal_for_phi_arg_p (arg0, lhs)
1196 && operand_equal_for_phi_arg_p (arg1, rhs))
1197 || (operand_equal_for_phi_arg_p (arg1, lhs)
1198 && operand_equal_for_phi_arg_p (arg0, rhs)))
1199 return true;
1201 /* Now handle more complex case where we have an EQ comparison
1202 which feeds a BIT_AND_EXPR which feeds COND.
1204 First verify that COND is of the form SSA_NAME NE 0. */
1205 if (*code != NE_EXPR || !integer_zerop (rhs)
1206 || TREE_CODE (lhs) != SSA_NAME)
1207 return false;
1209 /* Now ensure that SSA_NAME is set by a BIT_AND_EXPR. */
1210 def = SSA_NAME_DEF_STMT (lhs);
1211 if (!is_gimple_assign (def) || gimple_assign_rhs_code (def) != BIT_AND_EXPR)
1212 return false;
1214 /* Now verify arg0/arg1 correspond to the source arguments of an
1215 EQ comparison feeding the BIT_AND_EXPR. */
1217 tree tmp = gimple_assign_rhs1 (def);
1218 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp))
1219 return true;
1221 tmp = gimple_assign_rhs2 (def);
1222 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp))
1223 return true;
1225 return false;
1228 /* Returns true if ARG is a neutral element for operation CODE
1229 on the RIGHT side. */
1231 static bool
1232 neutral_element_p (tree_code code, tree arg, bool right)
1234 switch (code)
1236 case PLUS_EXPR:
1237 case BIT_IOR_EXPR:
1238 case BIT_XOR_EXPR:
1239 return integer_zerop (arg);
1241 case LROTATE_EXPR:
1242 case RROTATE_EXPR:
1243 case LSHIFT_EXPR:
1244 case RSHIFT_EXPR:
1245 case MINUS_EXPR:
1246 case POINTER_PLUS_EXPR:
1247 return right && integer_zerop (arg);
1249 case MULT_EXPR:
1250 return integer_onep (arg);
1252 case TRUNC_DIV_EXPR:
1253 case CEIL_DIV_EXPR:
1254 case FLOOR_DIV_EXPR:
1255 case ROUND_DIV_EXPR:
1256 case EXACT_DIV_EXPR:
1257 return right && integer_onep (arg);
1259 case BIT_AND_EXPR:
1260 return integer_all_onesp (arg);
1262 default:
1263 return false;
1267 /* Returns true if ARG is an absorbing element for operation CODE. */
1269 static bool
1270 absorbing_element_p (tree_code code, tree arg, bool right, tree rval)
1272 switch (code)
1274 case BIT_IOR_EXPR:
1275 return integer_all_onesp (arg);
1277 case MULT_EXPR:
1278 case BIT_AND_EXPR:
1279 return integer_zerop (arg);
1281 case LSHIFT_EXPR:
1282 case RSHIFT_EXPR:
1283 case LROTATE_EXPR:
1284 case RROTATE_EXPR:
1285 return !right && integer_zerop (arg);
1287 case TRUNC_DIV_EXPR:
1288 case CEIL_DIV_EXPR:
1289 case FLOOR_DIV_EXPR:
1290 case ROUND_DIV_EXPR:
1291 case EXACT_DIV_EXPR:
1292 case TRUNC_MOD_EXPR:
1293 case CEIL_MOD_EXPR:
1294 case FLOOR_MOD_EXPR:
1295 case ROUND_MOD_EXPR:
1296 return (!right
1297 && integer_zerop (arg)
1298 && tree_single_nonzero_warnv_p (rval, NULL));
1300 default:
1301 return false;
1305 /* The function value_replacement does the main work of doing the value
1306 replacement. Return non-zero if the replacement is done. Otherwise return
1307 0. If we remove the middle basic block, return 2.
1308 BB is the basic block where the replacement is going to be done on. ARG0
1309 is argument 0 from the PHI. Likewise for ARG1. */
1311 static int
1312 value_replacement (basic_block cond_bb, basic_block middle_bb,
1313 edge e0, edge e1, gphi *phi, tree arg0, tree arg1)
1315 gimple_stmt_iterator gsi;
1316 gimple *cond;
1317 edge true_edge, false_edge;
1318 enum tree_code code;
1319 bool empty_or_with_defined_p = true;
1321 /* If the type says honor signed zeros we cannot do this
1322 optimization. */
1323 if (HONOR_SIGNED_ZEROS (arg1))
1324 return 0;
1326 /* If there is a statement in MIDDLE_BB that defines one of the PHI
1327 arguments, then adjust arg0 or arg1. */
1328 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
1329 while (!gsi_end_p (gsi))
1331 gimple *stmt = gsi_stmt (gsi);
1332 tree lhs;
1333 gsi_next_nondebug (&gsi);
1334 if (!is_gimple_assign (stmt))
1336 if (gimple_code (stmt) != GIMPLE_PREDICT
1337 && gimple_code (stmt) != GIMPLE_NOP)
1338 empty_or_with_defined_p = false;
1339 continue;
1341 /* Now try to adjust arg0 or arg1 according to the computation
1342 in the statement. */
1343 lhs = gimple_assign_lhs (stmt);
1344 if (!(lhs == arg0
1345 && jump_function_from_stmt (&arg0, stmt))
1346 || (lhs == arg1
1347 && jump_function_from_stmt (&arg1, stmt)))
1348 empty_or_with_defined_p = false;
1351 cond = last_stmt (cond_bb);
1352 code = gimple_cond_code (cond);
1354 /* This transformation is only valid for equality comparisons. */
1355 if (code != NE_EXPR && code != EQ_EXPR)
1356 return 0;
1358 /* We need to know which is the true edge and which is the false
1359 edge so that we know if have abs or negative abs. */
1360 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1362 /* At this point we know we have a COND_EXPR with two successors.
1363 One successor is BB, the other successor is an empty block which
1364 falls through into BB.
1366 The condition for the COND_EXPR is known to be NE_EXPR or EQ_EXPR.
1368 There is a single PHI node at the join point (BB) with two arguments.
1370 We now need to verify that the two arguments in the PHI node match
1371 the two arguments to the equality comparison. */
1373 bool equal_p = operand_equal_for_value_replacement (arg0, arg1, &code, cond);
1374 bool maybe_equal_p = false;
1375 if (!equal_p
1376 && empty_or_with_defined_p
1377 && TREE_CODE (gimple_cond_rhs (cond)) == INTEGER_CST
1378 && (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg0)
1379 ? TREE_CODE (arg1) == INTEGER_CST
1380 : (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg1)
1381 && TREE_CODE (arg0) == INTEGER_CST)))
1382 maybe_equal_p = true;
1383 if (equal_p || maybe_equal_p)
1385 edge e;
1386 tree arg;
1388 /* For NE_EXPR, we want to build an assignment result = arg where
1389 arg is the PHI argument associated with the true edge. For
1390 EQ_EXPR we want the PHI argument associated with the false edge. */
1391 e = (code == NE_EXPR ? true_edge : false_edge);
1393 /* Unfortunately, E may not reach BB (it may instead have gone to
1394 OTHER_BLOCK). If that is the case, then we want the single outgoing
1395 edge from OTHER_BLOCK which reaches BB and represents the desired
1396 path from COND_BLOCK. */
1397 if (e->dest == middle_bb)
1398 e = single_succ_edge (e->dest);
1400 /* Now we know the incoming edge to BB that has the argument for the
1401 RHS of our new assignment statement. */
1402 if (e0 == e)
1403 arg = arg0;
1404 else
1405 arg = arg1;
1407 /* If the middle basic block was empty or is defining the
1408 PHI arguments and this is a single phi where the args are different
1409 for the edges e0 and e1 then we can remove the middle basic block. */
1410 if (empty_or_with_defined_p
1411 && single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)),
1412 e0, e1) == phi)
1414 use_operand_p use_p;
1415 gimple *use_stmt;
1417 /* Even if arg0/arg1 isn't equal to second operand of cond, we
1418 can optimize away the bb if we can prove it doesn't care whether
1419 phi result is arg0/arg1 or second operand of cond. Consider:
1420 <bb 2> [local count: 118111600]:
1421 if (i_2(D) == 4)
1422 goto <bb 4>; [97.00%]
1423 else
1424 goto <bb 3>; [3.00%]
1426 <bb 3> [local count: 3540129]:
1428 <bb 4> [local count: 118111600]:
1429 # i_6 = PHI <i_2(D)(3), 6(2)>
1430 _3 = i_6 != 0;
1431 Here, carg is 4, oarg is 6, crhs is 0, and because
1432 (4 != 0) == (6 != 0), we don't care if i_6 is 4 or 6, both
1433 have the same outcome. So, can can optimize this to:
1434 _3 = i_2(D) != 0;
1435 If the single imm use of phi result >, >=, < or <=, similarly
1436 we can check if both carg and oarg compare the same against
1437 crhs using ccode. */
1438 if (maybe_equal_p
1439 && TREE_CODE (arg) != INTEGER_CST
1440 && single_imm_use (gimple_phi_result (phi), &use_p, &use_stmt))
1442 enum tree_code ccode = ERROR_MARK;
1443 tree clhs = NULL_TREE, crhs = NULL_TREE;
1444 tree carg = gimple_cond_rhs (cond);
1445 tree oarg = e0 == e ? arg1 : arg0;
1446 if (is_gimple_assign (use_stmt)
1447 && (TREE_CODE_CLASS (gimple_assign_rhs_code (use_stmt))
1448 == tcc_comparison))
1450 ccode = gimple_assign_rhs_code (use_stmt);
1451 clhs = gimple_assign_rhs1 (use_stmt);
1452 crhs = gimple_assign_rhs2 (use_stmt);
1454 else if (gimple_code (use_stmt) == GIMPLE_COND)
1456 ccode = gimple_cond_code (use_stmt);
1457 clhs = gimple_cond_lhs (use_stmt);
1458 crhs = gimple_cond_rhs (use_stmt);
1460 if (ccode != ERROR_MARK
1461 && clhs == gimple_phi_result (phi)
1462 && TREE_CODE (crhs) == INTEGER_CST)
1463 switch (ccode)
1465 case EQ_EXPR:
1466 case NE_EXPR:
1467 if (!tree_int_cst_equal (crhs, carg)
1468 && !tree_int_cst_equal (crhs, oarg))
1469 equal_p = true;
1470 break;
1471 case GT_EXPR:
1472 if (tree_int_cst_lt (crhs, carg)
1473 == tree_int_cst_lt (crhs, oarg))
1474 equal_p = true;
1475 break;
1476 case GE_EXPR:
1477 if (tree_int_cst_le (crhs, carg)
1478 == tree_int_cst_le (crhs, oarg))
1479 equal_p = true;
1480 break;
1481 case LT_EXPR:
1482 if (tree_int_cst_lt (carg, crhs)
1483 == tree_int_cst_lt (oarg, crhs))
1484 equal_p = true;
1485 break;
1486 case LE_EXPR:
1487 if (tree_int_cst_le (carg, crhs)
1488 == tree_int_cst_le (oarg, crhs))
1489 equal_p = true;
1490 break;
1491 default:
1492 break;
1494 if (equal_p && MAY_HAVE_DEBUG_BIND_STMTS)
1496 imm_use_iterator imm_iter;
1497 tree phires = gimple_phi_result (phi);
1498 tree temp = NULL_TREE;
1499 bool reset_p = false;
1501 /* Add # DEBUG D#1 => arg != carg ? arg : oarg. */
1502 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, phires)
1504 if (!is_gimple_debug (use_stmt))
1505 continue;
1506 if (temp == NULL_TREE)
1508 if (!single_pred_p (middle_bb)
1509 || EDGE_COUNT (gimple_bb (phi)->preds) != 2)
1511 /* But only if middle_bb has a single
1512 predecessor and phi bb has two, otherwise
1513 we could use a SSA_NAME not usable in that
1514 place or wrong-debug. */
1515 reset_p = true;
1516 break;
1518 gimple_stmt_iterator gsi
1519 = gsi_after_labels (gimple_bb (phi));
1520 tree type = TREE_TYPE (phires);
1521 temp = build_debug_expr_decl (type);
1522 tree t = build2 (NE_EXPR, boolean_type_node,
1523 arg, carg);
1524 t = build3 (COND_EXPR, type, t, arg, oarg);
1525 gimple *g = gimple_build_debug_bind (temp, t, phi);
1526 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
1528 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
1529 replace_exp (use_p, temp);
1530 update_stmt (use_stmt);
1532 if (reset_p)
1533 reset_debug_uses (phi);
1536 if (equal_p)
1538 replace_phi_edge_with_variable (cond_bb, e1, phi, arg);
1539 /* Note that we optimized this PHI. */
1540 return 2;
1543 else if (equal_p)
1545 if (!single_pred_p (middle_bb))
1546 return 0;
1547 statistics_counter_event (cfun, "Replace PHI with "
1548 "variable/value_replacement", 1);
1550 /* Replace the PHI arguments with arg. */
1551 SET_PHI_ARG_DEF (phi, e0->dest_idx, arg);
1552 SET_PHI_ARG_DEF (phi, e1->dest_idx, arg);
1553 if (dump_file && (dump_flags & TDF_DETAILS))
1555 fprintf (dump_file, "PHI ");
1556 print_generic_expr (dump_file, gimple_phi_result (phi));
1557 fprintf (dump_file, " reduced for COND_EXPR in block %d to ",
1558 cond_bb->index);
1559 print_generic_expr (dump_file, arg);
1560 fprintf (dump_file, ".\n");
1562 return 1;
1566 if (!single_pred_p (middle_bb))
1567 return 0;
1569 /* Now optimize (x != 0) ? x + y : y to just x + y. */
1570 gsi = gsi_last_nondebug_bb (middle_bb);
1571 if (gsi_end_p (gsi))
1572 return 0;
1574 gimple *assign = gsi_stmt (gsi);
1575 if (!is_gimple_assign (assign)
1576 || (!INTEGRAL_TYPE_P (TREE_TYPE (arg0))
1577 && !POINTER_TYPE_P (TREE_TYPE (arg0))))
1578 return 0;
1580 if (gimple_assign_rhs_class (assign) != GIMPLE_BINARY_RHS)
1582 /* If last stmt of the middle_bb is a conversion, handle it like
1583 a preparation statement through constant evaluation with
1584 checking for UB. */
1585 enum tree_code sc = gimple_assign_rhs_code (assign);
1586 if (CONVERT_EXPR_CODE_P (sc))
1587 assign = NULL;
1588 else
1589 return 0;
1592 /* Punt if there are (degenerate) PHIs in middle_bb, there should not be. */
1593 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
1594 return 0;
1596 /* Allow up to 2 cheap preparation statements that prepare argument
1597 for assign, e.g.:
1598 if (y_4 != 0)
1599 goto <bb 3>;
1600 else
1601 goto <bb 4>;
1602 <bb 3>:
1603 _1 = (int) y_4;
1604 iftmp.0_6 = x_5(D) r<< _1;
1605 <bb 4>:
1606 # iftmp.0_2 = PHI <iftmp.0_6(3), x_5(D)(2)>
1608 if (y_3(D) == 0)
1609 goto <bb 4>;
1610 else
1611 goto <bb 3>;
1612 <bb 3>:
1613 y_4 = y_3(D) & 31;
1614 _1 = (int) y_4;
1615 _6 = x_5(D) r<< _1;
1616 <bb 4>:
1617 # _2 = PHI <x_5(D)(2), _6(3)> */
1618 gimple *prep_stmt[2] = { NULL, NULL };
1619 int prep_cnt;
1620 for (prep_cnt = 0; ; prep_cnt++)
1622 if (prep_cnt || assign)
1623 gsi_prev_nondebug (&gsi);
1624 if (gsi_end_p (gsi))
1625 break;
1627 gimple *g = gsi_stmt (gsi);
1628 if (gimple_code (g) == GIMPLE_LABEL)
1629 break;
1631 if (prep_cnt == 2 || !is_gimple_assign (g))
1632 return 0;
1634 tree lhs = gimple_assign_lhs (g);
1635 tree rhs1 = gimple_assign_rhs1 (g);
1636 use_operand_p use_p;
1637 gimple *use_stmt;
1638 if (TREE_CODE (lhs) != SSA_NAME
1639 || TREE_CODE (rhs1) != SSA_NAME
1640 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1641 || !INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1642 || !single_imm_use (lhs, &use_p, &use_stmt)
1643 || ((prep_cnt || assign)
1644 && use_stmt != (prep_cnt ? prep_stmt[prep_cnt - 1] : assign)))
1645 return 0;
1646 switch (gimple_assign_rhs_code (g))
1648 CASE_CONVERT:
1649 break;
1650 case PLUS_EXPR:
1651 case BIT_AND_EXPR:
1652 case BIT_IOR_EXPR:
1653 case BIT_XOR_EXPR:
1654 if (TREE_CODE (gimple_assign_rhs2 (g)) != INTEGER_CST)
1655 return 0;
1656 break;
1657 default:
1658 return 0;
1660 prep_stmt[prep_cnt] = g;
1663 /* Only transform if it removes the condition. */
1664 if (!single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)), e0, e1))
1665 return 0;
1667 /* Size-wise, this is always profitable. */
1668 if (optimize_bb_for_speed_p (cond_bb)
1669 /* The special case is useless if it has a low probability. */
1670 && profile_status_for_fn (cfun) != PROFILE_ABSENT
1671 && EDGE_PRED (middle_bb, 0)->probability < profile_probability::even ()
1672 /* If assign is cheap, there is no point avoiding it. */
1673 && estimate_num_insns_seq (bb_seq (middle_bb), &eni_time_weights)
1674 >= 3 * estimate_num_insns (cond, &eni_time_weights))
1675 return 0;
1677 tree cond_lhs = gimple_cond_lhs (cond);
1678 tree cond_rhs = gimple_cond_rhs (cond);
1680 /* Propagate the cond_rhs constant through preparation stmts,
1681 make sure UB isn't invoked while doing that. */
1682 for (int i = prep_cnt - 1; i >= 0; --i)
1684 gimple *g = prep_stmt[i];
1685 tree grhs1 = gimple_assign_rhs1 (g);
1686 if (!operand_equal_for_phi_arg_p (cond_lhs, grhs1))
1687 return 0;
1688 cond_lhs = gimple_assign_lhs (g);
1689 cond_rhs = fold_convert (TREE_TYPE (grhs1), cond_rhs);
1690 if (TREE_CODE (cond_rhs) != INTEGER_CST
1691 || TREE_OVERFLOW (cond_rhs))
1692 return 0;
1693 if (gimple_assign_rhs_class (g) == GIMPLE_BINARY_RHS)
1695 cond_rhs = int_const_binop (gimple_assign_rhs_code (g), cond_rhs,
1696 gimple_assign_rhs2 (g));
1697 if (TREE_OVERFLOW (cond_rhs))
1698 return 0;
1700 cond_rhs = fold_convert (TREE_TYPE (cond_lhs), cond_rhs);
1701 if (TREE_CODE (cond_rhs) != INTEGER_CST
1702 || TREE_OVERFLOW (cond_rhs))
1703 return 0;
1706 tree lhs, rhs1, rhs2;
1707 enum tree_code code_def;
1708 if (assign)
1710 lhs = gimple_assign_lhs (assign);
1711 rhs1 = gimple_assign_rhs1 (assign);
1712 rhs2 = gimple_assign_rhs2 (assign);
1713 code_def = gimple_assign_rhs_code (assign);
1715 else
1717 gcc_assert (prep_cnt > 0);
1718 lhs = cond_lhs;
1719 rhs1 = NULL_TREE;
1720 rhs2 = NULL_TREE;
1721 code_def = ERROR_MARK;
1724 if (((code == NE_EXPR && e1 == false_edge)
1725 || (code == EQ_EXPR && e1 == true_edge))
1726 && arg0 == lhs
1727 && ((assign == NULL
1728 && operand_equal_for_phi_arg_p (arg1, cond_rhs))
1729 || (assign
1730 && arg1 == rhs1
1731 && operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1732 && neutral_element_p (code_def, cond_rhs, true))
1733 || (assign
1734 && arg1 == rhs2
1735 && operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1736 && neutral_element_p (code_def, cond_rhs, false))
1737 || (assign
1738 && operand_equal_for_phi_arg_p (arg1, cond_rhs)
1739 && ((operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1740 && absorbing_element_p (code_def, cond_rhs, true, rhs2))
1741 || (operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1742 && absorbing_element_p (code_def,
1743 cond_rhs, false, rhs2))))))
1745 gsi = gsi_for_stmt (cond);
1746 /* Moving ASSIGN might change VR of lhs, e.g. when moving u_6
1747 def-stmt in:
1748 if (n_5 != 0)
1749 goto <bb 3>;
1750 else
1751 goto <bb 4>;
1753 <bb 3>:
1754 # RANGE [0, 4294967294]
1755 u_6 = n_5 + 4294967295;
1757 <bb 4>:
1758 # u_3 = PHI <u_6(3), 4294967295(2)> */
1759 reset_flow_sensitive_info (lhs);
1760 gimple_stmt_iterator gsi_from;
1761 for (int i = prep_cnt - 1; i >= 0; --i)
1763 tree plhs = gimple_assign_lhs (prep_stmt[i]);
1764 reset_flow_sensitive_info (plhs);
1765 gsi_from = gsi_for_stmt (prep_stmt[i]);
1766 gsi_move_before (&gsi_from, &gsi);
1768 if (assign)
1770 gsi_from = gsi_for_stmt (assign);
1771 gsi_move_before (&gsi_from, &gsi);
1773 replace_phi_edge_with_variable (cond_bb, e1, phi, lhs);
1774 return 2;
1777 return 0;
1780 /* If VAR is an SSA_NAME that points to a BIT_NOT_EXPR then return the TREE for
1781 the value being inverted. */
1783 static tree
1784 strip_bit_not (tree var)
1786 if (TREE_CODE (var) != SSA_NAME)
1787 return NULL_TREE;
1789 gimple *assign = SSA_NAME_DEF_STMT (var);
1790 if (gimple_code (assign) != GIMPLE_ASSIGN)
1791 return NULL_TREE;
1793 if (gimple_assign_rhs_code (assign) != BIT_NOT_EXPR)
1794 return NULL_TREE;
1796 return gimple_assign_rhs1 (assign);
1799 /* Invert a MIN to a MAX or a MAX to a MIN expression CODE. */
1801 enum tree_code
1802 invert_minmax_code (enum tree_code code)
1804 switch (code) {
1805 case MIN_EXPR:
1806 return MAX_EXPR;
1807 case MAX_EXPR:
1808 return MIN_EXPR;
1809 default:
1810 gcc_unreachable ();
1814 /* The function minmax_replacement does the main work of doing the minmax
1815 replacement. Return true if the replacement is done. Otherwise return
1816 false.
1817 BB is the basic block where the replacement is going to be done on. ARG0
1818 is argument 0 from the PHI. Likewise for ARG1.
1820 If THREEWAY_P then expect the BB to be laid out in diamond shape with each
1821 BB containing only a MIN or MAX expression. */
1823 static bool
1824 minmax_replacement (basic_block cond_bb, basic_block middle_bb, basic_block alt_middle_bb,
1825 edge e0, edge e1, gphi *phi, tree arg0, tree arg1, bool threeway_p)
1827 tree result;
1828 edge true_edge, false_edge;
1829 enum tree_code minmax, ass_code;
1830 tree smaller, larger, arg_true, arg_false;
1831 gimple_stmt_iterator gsi, gsi_from;
1833 tree type = TREE_TYPE (PHI_RESULT (phi));
1835 /* The optimization may be unsafe due to NaNs. */
1836 if (HONOR_NANS (type) || HONOR_SIGNED_ZEROS (type))
1837 return false;
1839 gcond *cond = as_a <gcond *> (last_stmt (cond_bb));
1840 enum tree_code cmp = gimple_cond_code (cond);
1841 tree rhs = gimple_cond_rhs (cond);
1843 /* Turn EQ/NE of extreme values to order comparisons. */
1844 if ((cmp == NE_EXPR || cmp == EQ_EXPR)
1845 && TREE_CODE (rhs) == INTEGER_CST
1846 && INTEGRAL_TYPE_P (TREE_TYPE (rhs)))
1848 if (wi::eq_p (wi::to_wide (rhs), wi::min_value (TREE_TYPE (rhs))))
1850 cmp = (cmp == EQ_EXPR) ? LT_EXPR : GE_EXPR;
1851 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1852 wi::min_value (TREE_TYPE (rhs)) + 1);
1854 else if (wi::eq_p (wi::to_wide (rhs), wi::max_value (TREE_TYPE (rhs))))
1856 cmp = (cmp == EQ_EXPR) ? GT_EXPR : LE_EXPR;
1857 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1858 wi::max_value (TREE_TYPE (rhs)) - 1);
1862 /* This transformation is only valid for order comparisons. Record which
1863 operand is smaller/larger if the result of the comparison is true. */
1864 tree alt_smaller = NULL_TREE;
1865 tree alt_larger = NULL_TREE;
1866 if (cmp == LT_EXPR || cmp == LE_EXPR)
1868 smaller = gimple_cond_lhs (cond);
1869 larger = rhs;
1870 /* If we have smaller < CST it is equivalent to smaller <= CST-1.
1871 Likewise smaller <= CST is equivalent to smaller < CST+1. */
1872 if (TREE_CODE (larger) == INTEGER_CST
1873 && INTEGRAL_TYPE_P (TREE_TYPE (larger)))
1875 if (cmp == LT_EXPR)
1877 wi::overflow_type overflow;
1878 wide_int alt = wi::sub (wi::to_wide (larger), 1,
1879 TYPE_SIGN (TREE_TYPE (larger)),
1880 &overflow);
1881 if (! overflow)
1882 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1884 else
1886 wi::overflow_type overflow;
1887 wide_int alt = wi::add (wi::to_wide (larger), 1,
1888 TYPE_SIGN (TREE_TYPE (larger)),
1889 &overflow);
1890 if (! overflow)
1891 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1895 else if (cmp == GT_EXPR || cmp == GE_EXPR)
1897 smaller = rhs;
1898 larger = gimple_cond_lhs (cond);
1899 /* If we have larger > CST it is equivalent to larger >= CST+1.
1900 Likewise larger >= CST is equivalent to larger > CST-1. */
1901 if (TREE_CODE (smaller) == INTEGER_CST
1902 && INTEGRAL_TYPE_P (TREE_TYPE (smaller)))
1904 wi::overflow_type overflow;
1905 if (cmp == GT_EXPR)
1907 wide_int alt = wi::add (wi::to_wide (smaller), 1,
1908 TYPE_SIGN (TREE_TYPE (smaller)),
1909 &overflow);
1910 if (! overflow)
1911 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1913 else
1915 wide_int alt = wi::sub (wi::to_wide (smaller), 1,
1916 TYPE_SIGN (TREE_TYPE (smaller)),
1917 &overflow);
1918 if (! overflow)
1919 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1923 else
1924 return false;
1926 /* Handle the special case of (signed_type)x < 0 being equivalent
1927 to x > MAX_VAL(signed_type) and (signed_type)x >= 0 equivalent
1928 to x <= MAX_VAL(signed_type). */
1929 if ((cmp == GE_EXPR || cmp == LT_EXPR)
1930 && INTEGRAL_TYPE_P (type)
1931 && TYPE_UNSIGNED (type)
1932 && integer_zerop (rhs))
1934 tree op = gimple_cond_lhs (cond);
1935 if (TREE_CODE (op) == SSA_NAME
1936 && INTEGRAL_TYPE_P (TREE_TYPE (op))
1937 && !TYPE_UNSIGNED (TREE_TYPE (op)))
1939 gimple *def_stmt = SSA_NAME_DEF_STMT (op);
1940 if (gimple_assign_cast_p (def_stmt))
1942 tree op1 = gimple_assign_rhs1 (def_stmt);
1943 if (INTEGRAL_TYPE_P (TREE_TYPE (op1))
1944 && TYPE_UNSIGNED (TREE_TYPE (op1))
1945 && (TYPE_PRECISION (TREE_TYPE (op))
1946 == TYPE_PRECISION (TREE_TYPE (op1)))
1947 && useless_type_conversion_p (type, TREE_TYPE (op1)))
1949 wide_int w1 = wi::max_value (TREE_TYPE (op));
1950 wide_int w2 = wi::add (w1, 1);
1951 if (cmp == LT_EXPR)
1953 larger = op1;
1954 smaller = wide_int_to_tree (TREE_TYPE (op1), w1);
1955 alt_smaller = wide_int_to_tree (TREE_TYPE (op1), w2);
1956 alt_larger = NULL_TREE;
1958 else
1960 smaller = op1;
1961 larger = wide_int_to_tree (TREE_TYPE (op1), w1);
1962 alt_larger = wide_int_to_tree (TREE_TYPE (op1), w2);
1963 alt_smaller = NULL_TREE;
1970 /* We need to know which is the true edge and which is the false
1971 edge so that we know if have abs or negative abs. */
1972 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1974 /* Forward the edges over the middle basic block. */
1975 if (true_edge->dest == middle_bb)
1976 true_edge = EDGE_SUCC (true_edge->dest, 0);
1977 if (false_edge->dest == middle_bb)
1978 false_edge = EDGE_SUCC (false_edge->dest, 0);
1980 /* When THREEWAY_P then e1 will point to the edge of the final transition
1981 from middle-bb to end. */
1982 if (true_edge == e0)
1984 if (!threeway_p)
1985 gcc_assert (false_edge == e1);
1986 arg_true = arg0;
1987 arg_false = arg1;
1989 else
1991 gcc_assert (false_edge == e0);
1992 if (!threeway_p)
1993 gcc_assert (true_edge == e1);
1994 arg_true = arg1;
1995 arg_false = arg0;
1998 if (empty_block_p (middle_bb))
2000 if ((operand_equal_for_phi_arg_p (arg_true, smaller)
2001 || (alt_smaller
2002 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2003 && (operand_equal_for_phi_arg_p (arg_false, larger)
2004 || (alt_larger
2005 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2007 /* Case
2009 if (smaller < larger)
2010 rslt = smaller;
2011 else
2012 rslt = larger; */
2013 minmax = MIN_EXPR;
2015 else if ((operand_equal_for_phi_arg_p (arg_false, smaller)
2016 || (alt_smaller
2017 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2018 && (operand_equal_for_phi_arg_p (arg_true, larger)
2019 || (alt_larger
2020 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2021 minmax = MAX_EXPR;
2022 else
2023 return false;
2025 else if (middle_bb != alt_middle_bb && threeway_p)
2027 /* Recognize the following case:
2029 if (smaller < larger)
2030 a = MIN (smaller, c);
2031 else
2032 b = MIN (larger, c);
2033 x = PHI <a, b>
2035 This is equivalent to
2037 a = MIN (smaller, c);
2038 x = MIN (larger, a); */
2040 gimple *assign = last_and_only_stmt (middle_bb);
2041 tree lhs, op0, op1, bound;
2042 tree alt_lhs, alt_op0, alt_op1;
2043 bool invert = false;
2045 if (!single_pred_p (middle_bb)
2046 || !single_pred_p (alt_middle_bb)
2047 || !single_succ_p (middle_bb)
2048 || !single_succ_p (alt_middle_bb))
2049 return false;
2051 /* When THREEWAY_P then e1 will point to the edge of the final transition
2052 from middle-bb to end. */
2053 if (true_edge == e0)
2054 gcc_assert (false_edge == EDGE_PRED (e1->src, 0));
2055 else
2056 gcc_assert (true_edge == EDGE_PRED (e1->src, 0));
2058 bool valid_minmax_p = false;
2059 gimple_stmt_iterator it1
2060 = gsi_start_nondebug_after_labels_bb (middle_bb);
2061 gimple_stmt_iterator it2
2062 = gsi_start_nondebug_after_labels_bb (alt_middle_bb);
2063 if (gsi_one_nondebug_before_end_p (it1)
2064 && gsi_one_nondebug_before_end_p (it2))
2066 gimple *stmt1 = gsi_stmt (it1);
2067 gimple *stmt2 = gsi_stmt (it2);
2068 if (is_gimple_assign (stmt1) && is_gimple_assign (stmt2))
2070 enum tree_code code1 = gimple_assign_rhs_code (stmt1);
2071 enum tree_code code2 = gimple_assign_rhs_code (stmt2);
2072 valid_minmax_p = (code1 == MIN_EXPR || code1 == MAX_EXPR)
2073 && (code2 == MIN_EXPR || code2 == MAX_EXPR);
2077 if (!valid_minmax_p)
2078 return false;
2080 if (!assign
2081 || gimple_code (assign) != GIMPLE_ASSIGN)
2082 return false;
2084 lhs = gimple_assign_lhs (assign);
2085 ass_code = gimple_assign_rhs_code (assign);
2086 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2087 return false;
2089 op0 = gimple_assign_rhs1 (assign);
2090 op1 = gimple_assign_rhs2 (assign);
2092 assign = last_and_only_stmt (alt_middle_bb);
2093 if (!assign
2094 || gimple_code (assign) != GIMPLE_ASSIGN)
2095 return false;
2097 alt_lhs = gimple_assign_lhs (assign);
2098 if (ass_code != gimple_assign_rhs_code (assign))
2099 return false;
2101 if (!operand_equal_for_phi_arg_p (lhs, arg_true)
2102 || !operand_equal_for_phi_arg_p (alt_lhs, arg_false))
2103 return false;
2105 alt_op0 = gimple_assign_rhs1 (assign);
2106 alt_op1 = gimple_assign_rhs2 (assign);
2108 if ((operand_equal_for_phi_arg_p (op0, smaller)
2109 || (alt_smaller
2110 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2111 && (operand_equal_for_phi_arg_p (alt_op0, larger)
2112 || (alt_larger
2113 && operand_equal_for_phi_arg_p (alt_op0, alt_larger))))
2115 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2116 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2117 return false;
2119 if ((arg0 = strip_bit_not (op0)) != NULL
2120 && (arg1 = strip_bit_not (alt_op0)) != NULL
2121 && (bound = strip_bit_not (op1)) != NULL)
2123 minmax = MAX_EXPR;
2124 ass_code = invert_minmax_code (ass_code);
2125 invert = true;
2127 else
2129 bound = op1;
2130 minmax = MIN_EXPR;
2131 arg0 = op0;
2132 arg1 = alt_op0;
2135 else if ((operand_equal_for_phi_arg_p (op0, larger)
2136 || (alt_larger
2137 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2138 && (operand_equal_for_phi_arg_p (alt_op0, smaller)
2139 || (alt_smaller
2140 && operand_equal_for_phi_arg_p (alt_op0, alt_smaller))))
2142 /* We got here if the condition is true, i.e., SMALLER > LARGER. */
2143 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2144 return false;
2146 if ((arg0 = strip_bit_not (op0)) != NULL
2147 && (arg1 = strip_bit_not (alt_op0)) != NULL
2148 && (bound = strip_bit_not (op1)) != NULL)
2150 minmax = MIN_EXPR;
2151 ass_code = invert_minmax_code (ass_code);
2152 invert = true;
2154 else
2156 bound = op1;
2157 minmax = MAX_EXPR;
2158 arg0 = op0;
2159 arg1 = alt_op0;
2162 else
2163 return false;
2165 /* Emit the statement to compute min/max. */
2166 location_t locus = gimple_location (last_stmt (cond_bb));
2167 gimple_seq stmts = NULL;
2168 tree phi_result = PHI_RESULT (phi);
2169 result = gimple_build (&stmts, locus, minmax, TREE_TYPE (phi_result),
2170 arg0, arg1);
2171 result = gimple_build (&stmts, locus, ass_code, TREE_TYPE (phi_result),
2172 result, bound);
2173 if (invert)
2174 result = gimple_build (&stmts, locus, BIT_NOT_EXPR, TREE_TYPE (phi_result),
2175 result);
2177 gsi = gsi_last_bb (cond_bb);
2178 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2180 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2182 return true;
2184 else
2186 /* Recognize the following case, assuming d <= u:
2188 if (a <= u)
2189 b = MAX (a, d);
2190 x = PHI <b, u>
2192 This is equivalent to
2194 b = MAX (a, d);
2195 x = MIN (b, u); */
2197 gimple *assign = last_and_only_stmt (middle_bb);
2198 tree lhs, op0, op1, bound;
2200 if (!single_pred_p (middle_bb))
2201 return false;
2203 if (!assign
2204 || gimple_code (assign) != GIMPLE_ASSIGN)
2205 return false;
2207 lhs = gimple_assign_lhs (assign);
2208 ass_code = gimple_assign_rhs_code (assign);
2209 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2210 return false;
2211 op0 = gimple_assign_rhs1 (assign);
2212 op1 = gimple_assign_rhs2 (assign);
2214 if (true_edge->src == middle_bb)
2216 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2217 if (!operand_equal_for_phi_arg_p (lhs, arg_true))
2218 return false;
2220 if (operand_equal_for_phi_arg_p (arg_false, larger)
2221 || (alt_larger
2222 && operand_equal_for_phi_arg_p (arg_false, alt_larger)))
2224 /* Case
2226 if (smaller < larger)
2228 r' = MAX_EXPR (smaller, bound)
2230 r = PHI <r', larger> --> to be turned to MIN_EXPR. */
2231 if (ass_code != MAX_EXPR)
2232 return false;
2234 minmax = MIN_EXPR;
2235 if (operand_equal_for_phi_arg_p (op0, smaller)
2236 || (alt_smaller
2237 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2238 bound = op1;
2239 else if (operand_equal_for_phi_arg_p (op1, smaller)
2240 || (alt_smaller
2241 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2242 bound = op0;
2243 else
2244 return false;
2246 /* We need BOUND <= LARGER. */
2247 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2248 bound, larger)))
2249 return false;
2251 else if (operand_equal_for_phi_arg_p (arg_false, smaller)
2252 || (alt_smaller
2253 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2255 /* Case
2257 if (smaller < larger)
2259 r' = MIN_EXPR (larger, bound)
2261 r = PHI <r', smaller> --> to be turned to MAX_EXPR. */
2262 if (ass_code != MIN_EXPR)
2263 return false;
2265 minmax = MAX_EXPR;
2266 if (operand_equal_for_phi_arg_p (op0, larger)
2267 || (alt_larger
2268 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2269 bound = op1;
2270 else if (operand_equal_for_phi_arg_p (op1, larger)
2271 || (alt_larger
2272 && operand_equal_for_phi_arg_p (op1, alt_larger)))
2273 bound = op0;
2274 else
2275 return false;
2277 /* We need BOUND >= SMALLER. */
2278 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2279 bound, smaller)))
2280 return false;
2282 else
2283 return false;
2285 else
2287 /* We got here if the condition is false, i.e., SMALLER > LARGER. */
2288 if (!operand_equal_for_phi_arg_p (lhs, arg_false))
2289 return false;
2291 if (operand_equal_for_phi_arg_p (arg_true, larger)
2292 || (alt_larger
2293 && operand_equal_for_phi_arg_p (arg_true, alt_larger)))
2295 /* Case
2297 if (smaller > larger)
2299 r' = MIN_EXPR (smaller, bound)
2301 r = PHI <r', larger> --> to be turned to MAX_EXPR. */
2302 if (ass_code != MIN_EXPR)
2303 return false;
2305 minmax = MAX_EXPR;
2306 if (operand_equal_for_phi_arg_p (op0, smaller)
2307 || (alt_smaller
2308 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2309 bound = op1;
2310 else if (operand_equal_for_phi_arg_p (op1, smaller)
2311 || (alt_smaller
2312 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2313 bound = op0;
2314 else
2315 return false;
2317 /* We need BOUND >= LARGER. */
2318 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2319 bound, larger)))
2320 return false;
2322 else if (operand_equal_for_phi_arg_p (arg_true, smaller)
2323 || (alt_smaller
2324 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2326 /* Case
2328 if (smaller > larger)
2330 r' = MAX_EXPR (larger, bound)
2332 r = PHI <r', smaller> --> to be turned to MIN_EXPR. */
2333 if (ass_code != MAX_EXPR)
2334 return false;
2336 minmax = MIN_EXPR;
2337 if (operand_equal_for_phi_arg_p (op0, larger))
2338 bound = op1;
2339 else if (operand_equal_for_phi_arg_p (op1, larger))
2340 bound = op0;
2341 else
2342 return false;
2344 /* We need BOUND <= SMALLER. */
2345 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2346 bound, smaller)))
2347 return false;
2349 else
2350 return false;
2353 /* Move the statement from the middle block. */
2354 gsi = gsi_last_bb (cond_bb);
2355 gsi_from = gsi_last_nondebug_bb (middle_bb);
2356 reset_flow_sensitive_info (SINGLE_SSA_TREE_OPERAND (gsi_stmt (gsi_from),
2357 SSA_OP_DEF));
2358 gsi_move_before (&gsi_from, &gsi);
2361 /* Emit the statement to compute min/max. */
2362 gimple_seq stmts = NULL;
2363 tree phi_result = PHI_RESULT (phi);
2364 result = gimple_build (&stmts, minmax, TREE_TYPE (phi_result), arg0, arg1);
2366 gsi = gsi_last_bb (cond_bb);
2367 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2369 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2371 return true;
2374 /* Attempt to optimize (x <=> y) cmp 0 and similar comparisons.
2375 For strong ordering <=> try to match something like:
2376 <bb 2> : // cond3_bb (== cond2_bb)
2377 if (x_4(D) != y_5(D))
2378 goto <bb 3>; [INV]
2379 else
2380 goto <bb 6>; [INV]
2382 <bb 3> : // cond_bb
2383 if (x_4(D) < y_5(D))
2384 goto <bb 6>; [INV]
2385 else
2386 goto <bb 4>; [INV]
2388 <bb 4> : // middle_bb
2390 <bb 6> : // phi_bb
2391 # iftmp.0_2 = PHI <1(4), 0(2), -1(3)>
2392 _1 = iftmp.0_2 == 0;
2394 and for partial ordering <=> something like:
2396 <bb 2> : // cond3_bb
2397 if (a_3(D) == b_5(D))
2398 goto <bb 6>; [50.00%]
2399 else
2400 goto <bb 3>; [50.00%]
2402 <bb 3> [local count: 536870913]: // cond2_bb
2403 if (a_3(D) < b_5(D))
2404 goto <bb 6>; [50.00%]
2405 else
2406 goto <bb 4>; [50.00%]
2408 <bb 4> [local count: 268435456]: // cond_bb
2409 if (a_3(D) > b_5(D))
2410 goto <bb 6>; [50.00%]
2411 else
2412 goto <bb 5>; [50.00%]
2414 <bb 5> [local count: 134217728]: // middle_bb
2416 <bb 6> [local count: 1073741824]: // phi_bb
2417 # SR.27_4 = PHI <0(2), -1(3), 1(4), 2(5)>
2418 _2 = SR.27_4 > 0; */
2420 static bool
2421 spaceship_replacement (basic_block cond_bb, basic_block middle_bb,
2422 edge e0, edge e1, gphi *phi,
2423 tree arg0, tree arg1)
2425 tree phires = PHI_RESULT (phi);
2426 if (!INTEGRAL_TYPE_P (TREE_TYPE (phires))
2427 || TYPE_UNSIGNED (TREE_TYPE (phires))
2428 || !tree_fits_shwi_p (arg0)
2429 || !tree_fits_shwi_p (arg1)
2430 || !IN_RANGE (tree_to_shwi (arg0), -1, 2)
2431 || !IN_RANGE (tree_to_shwi (arg1), -1, 2))
2432 return false;
2434 basic_block phi_bb = gimple_bb (phi);
2435 gcc_assert (phi_bb == e0->dest && phi_bb == e1->dest);
2436 if (!IN_RANGE (EDGE_COUNT (phi_bb->preds), 3, 4))
2437 return false;
2439 use_operand_p use_p;
2440 gimple *use_stmt;
2441 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (phires))
2442 return false;
2443 if (!single_imm_use (phires, &use_p, &use_stmt))
2444 return false;
2445 enum tree_code cmp;
2446 tree lhs, rhs;
2447 gimple *orig_use_stmt = use_stmt;
2448 tree orig_use_lhs = NULL_TREE;
2449 int prec = TYPE_PRECISION (TREE_TYPE (phires));
2450 bool is_cast = false;
2452 /* Deal with the case when match.pd has rewritten the (res & ~1) == 0
2453 into res <= 1 and has left a type-cast for signed types. */
2454 if (gimple_assign_cast_p (use_stmt))
2456 orig_use_lhs = gimple_assign_lhs (use_stmt);
2457 /* match.pd would have only done this for a signed type,
2458 so the conversion must be to an unsigned one. */
2459 tree ty1 = TREE_TYPE (gimple_assign_rhs1 (use_stmt));
2460 tree ty2 = TREE_TYPE (orig_use_lhs);
2462 if (!TYPE_UNSIGNED (ty2) || !INTEGRAL_TYPE_P (ty2))
2463 return false;
2464 if (TYPE_PRECISION (ty1) > TYPE_PRECISION (ty2))
2465 return false;
2466 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2467 return false;
2468 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2469 return false;
2471 is_cast = true;
2473 else if (is_gimple_assign (use_stmt)
2474 && gimple_assign_rhs_code (use_stmt) == BIT_AND_EXPR
2475 && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST
2476 && (wi::to_wide (gimple_assign_rhs2 (use_stmt))
2477 == wi::shifted_mask (1, prec - 1, false, prec)))
2479 /* For partial_ordering result operator>= with unspec as second
2480 argument is (res & 1) == res, folded by match.pd into
2481 (res & ~1) == 0. */
2482 orig_use_lhs = gimple_assign_lhs (use_stmt);
2483 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2484 return false;
2485 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2486 return false;
2488 if (gimple_code (use_stmt) == GIMPLE_COND)
2490 cmp = gimple_cond_code (use_stmt);
2491 lhs = gimple_cond_lhs (use_stmt);
2492 rhs = gimple_cond_rhs (use_stmt);
2494 else if (is_gimple_assign (use_stmt))
2496 if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2498 cmp = gimple_assign_rhs_code (use_stmt);
2499 lhs = gimple_assign_rhs1 (use_stmt);
2500 rhs = gimple_assign_rhs2 (use_stmt);
2502 else if (gimple_assign_rhs_code (use_stmt) == COND_EXPR)
2504 tree cond = gimple_assign_rhs1 (use_stmt);
2505 if (!COMPARISON_CLASS_P (cond))
2506 return false;
2507 cmp = TREE_CODE (cond);
2508 lhs = TREE_OPERAND (cond, 0);
2509 rhs = TREE_OPERAND (cond, 1);
2511 else
2512 return false;
2514 else
2515 return false;
2516 switch (cmp)
2518 case EQ_EXPR:
2519 case NE_EXPR:
2520 case LT_EXPR:
2521 case GT_EXPR:
2522 case LE_EXPR:
2523 case GE_EXPR:
2524 break;
2525 default:
2526 return false;
2528 if (lhs != (orig_use_lhs ? orig_use_lhs : phires)
2529 || !tree_fits_shwi_p (rhs)
2530 || !IN_RANGE (tree_to_shwi (rhs), -1, 1))
2531 return false;
2533 if (is_cast)
2535 if (TREE_CODE (rhs) != INTEGER_CST)
2536 return false;
2537 /* As for -ffast-math we assume the 2 return to be
2538 impossible, canonicalize (unsigned) res <= 1U or
2539 (unsigned) res < 2U into res >= 0 and (unsigned) res > 1U
2540 or (unsigned) res >= 2U as res < 0. */
2541 switch (cmp)
2543 case LE_EXPR:
2544 if (!integer_onep (rhs))
2545 return false;
2546 cmp = GE_EXPR;
2547 break;
2548 case LT_EXPR:
2549 if (wi::ne_p (wi::to_widest (rhs), 2))
2550 return false;
2551 cmp = GE_EXPR;
2552 break;
2553 case GT_EXPR:
2554 if (!integer_onep (rhs))
2555 return false;
2556 cmp = LT_EXPR;
2557 break;
2558 case GE_EXPR:
2559 if (wi::ne_p (wi::to_widest (rhs), 2))
2560 return false;
2561 cmp = LT_EXPR;
2562 break;
2563 default:
2564 return false;
2566 rhs = build_zero_cst (TREE_TYPE (phires));
2568 else if (orig_use_lhs)
2570 if ((cmp != EQ_EXPR && cmp != NE_EXPR) || !integer_zerop (rhs))
2571 return false;
2572 /* As for -ffast-math we assume the 2 return to be
2573 impossible, canonicalize (res & ~1) == 0 into
2574 res >= 0 and (res & ~1) != 0 as res < 0. */
2575 cmp = cmp == EQ_EXPR ? GE_EXPR : LT_EXPR;
2578 if (!empty_block_p (middle_bb))
2579 return false;
2581 gcond *cond1 = as_a <gcond *> (last_stmt (cond_bb));
2582 enum tree_code cmp1 = gimple_cond_code (cond1);
2583 switch (cmp1)
2585 case LT_EXPR:
2586 case LE_EXPR:
2587 case GT_EXPR:
2588 case GE_EXPR:
2589 break;
2590 default:
2591 return false;
2593 tree lhs1 = gimple_cond_lhs (cond1);
2594 tree rhs1 = gimple_cond_rhs (cond1);
2595 /* The optimization may be unsafe due to NaNs. */
2596 if (HONOR_NANS (TREE_TYPE (lhs1)))
2597 return false;
2598 if (TREE_CODE (lhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs1))
2599 return false;
2600 if (TREE_CODE (rhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1))
2601 return false;
2603 if (!single_pred_p (cond_bb) || !cond_only_block_p (cond_bb))
2604 return false;
2606 basic_block cond2_bb = single_pred (cond_bb);
2607 if (EDGE_COUNT (cond2_bb->succs) != 2)
2608 return false;
2609 edge cond2_phi_edge;
2610 if (EDGE_SUCC (cond2_bb, 0)->dest == cond_bb)
2612 if (EDGE_SUCC (cond2_bb, 1)->dest != phi_bb)
2613 return false;
2614 cond2_phi_edge = EDGE_SUCC (cond2_bb, 1);
2616 else if (EDGE_SUCC (cond2_bb, 0)->dest != phi_bb)
2617 return false;
2618 else
2619 cond2_phi_edge = EDGE_SUCC (cond2_bb, 0);
2620 tree arg2 = gimple_phi_arg_def (phi, cond2_phi_edge->dest_idx);
2621 if (!tree_fits_shwi_p (arg2))
2622 return false;
2623 gimple *cond2 = last_stmt (cond2_bb);
2624 if (cond2 == NULL || gimple_code (cond2) != GIMPLE_COND)
2625 return false;
2626 enum tree_code cmp2 = gimple_cond_code (cond2);
2627 tree lhs2 = gimple_cond_lhs (cond2);
2628 tree rhs2 = gimple_cond_rhs (cond2);
2629 if (lhs2 == lhs1)
2631 if (!operand_equal_p (rhs2, rhs1, 0))
2633 if ((cmp2 == EQ_EXPR || cmp2 == NE_EXPR)
2634 && TREE_CODE (rhs1) == INTEGER_CST
2635 && TREE_CODE (rhs2) == INTEGER_CST)
2637 /* For integers, we can have cond2 x == 5
2638 and cond1 x < 5, x <= 4, x <= 5, x < 6,
2639 x > 5, x >= 6, x >= 5 or x > 4. */
2640 if (tree_int_cst_lt (rhs1, rhs2))
2642 if (wi::ne_p (wi::to_wide (rhs1) + 1, wi::to_wide (rhs2)))
2643 return false;
2644 if (cmp1 == LE_EXPR)
2645 cmp1 = LT_EXPR;
2646 else if (cmp1 == GT_EXPR)
2647 cmp1 = GE_EXPR;
2648 else
2649 return false;
2651 else
2653 gcc_checking_assert (tree_int_cst_lt (rhs2, rhs1));
2654 if (wi::ne_p (wi::to_wide (rhs2) + 1, wi::to_wide (rhs1)))
2655 return false;
2656 if (cmp1 == LT_EXPR)
2657 cmp1 = LE_EXPR;
2658 else if (cmp1 == GE_EXPR)
2659 cmp1 = GT_EXPR;
2660 else
2661 return false;
2663 rhs1 = rhs2;
2665 else
2666 return false;
2669 else if (lhs2 == rhs1)
2671 if (rhs2 != lhs1)
2672 return false;
2674 else
2675 return false;
2677 tree arg3 = arg2;
2678 basic_block cond3_bb = cond2_bb;
2679 edge cond3_phi_edge = cond2_phi_edge;
2680 gimple *cond3 = cond2;
2681 enum tree_code cmp3 = cmp2;
2682 tree lhs3 = lhs2;
2683 tree rhs3 = rhs2;
2684 if (EDGE_COUNT (phi_bb->preds) == 4)
2686 if (absu_hwi (tree_to_shwi (arg2)) != 1)
2687 return false;
2688 if (e1->flags & EDGE_TRUE_VALUE)
2690 if (tree_to_shwi (arg0) != 2
2691 || absu_hwi (tree_to_shwi (arg1)) != 1
2692 || wi::to_widest (arg1) == wi::to_widest (arg2))
2693 return false;
2695 else if (tree_to_shwi (arg1) != 2
2696 || absu_hwi (tree_to_shwi (arg0)) != 1
2697 || wi::to_widest (arg0) == wi::to_widest (arg1))
2698 return false;
2699 switch (cmp2)
2701 case LT_EXPR:
2702 case LE_EXPR:
2703 case GT_EXPR:
2704 case GE_EXPR:
2705 break;
2706 default:
2707 return false;
2709 /* if (x < y) goto phi_bb; else fallthru;
2710 if (x > y) goto phi_bb; else fallthru;
2711 bbx:;
2712 phi_bb:;
2713 is ok, but if x and y are swapped in one of the comparisons,
2714 or the comparisons are the same and operands not swapped,
2715 or the true and false edges are swapped, it is not. */
2716 if ((lhs2 == lhs1)
2717 ^ (((cond2_phi_edge->flags
2718 & ((cmp2 == LT_EXPR || cmp2 == LE_EXPR)
2719 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0)
2720 != ((e1->flags
2721 & ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2722 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0)))
2723 return false;
2724 if (!single_pred_p (cond2_bb) || !cond_only_block_p (cond2_bb))
2725 return false;
2726 cond3_bb = single_pred (cond2_bb);
2727 if (EDGE_COUNT (cond2_bb->succs) != 2)
2728 return false;
2729 if (EDGE_SUCC (cond3_bb, 0)->dest == cond2_bb)
2731 if (EDGE_SUCC (cond3_bb, 1)->dest != phi_bb)
2732 return false;
2733 cond3_phi_edge = EDGE_SUCC (cond3_bb, 1);
2735 else if (EDGE_SUCC (cond3_bb, 0)->dest != phi_bb)
2736 return false;
2737 else
2738 cond3_phi_edge = EDGE_SUCC (cond3_bb, 0);
2739 arg3 = gimple_phi_arg_def (phi, cond3_phi_edge->dest_idx);
2740 cond3 = last_stmt (cond3_bb);
2741 if (cond3 == NULL || gimple_code (cond3) != GIMPLE_COND)
2742 return false;
2743 cmp3 = gimple_cond_code (cond3);
2744 lhs3 = gimple_cond_lhs (cond3);
2745 rhs3 = gimple_cond_rhs (cond3);
2746 if (lhs3 == lhs1)
2748 if (!operand_equal_p (rhs3, rhs1, 0))
2749 return false;
2751 else if (lhs3 == rhs1)
2753 if (rhs3 != lhs1)
2754 return false;
2756 else
2757 return false;
2759 else if (absu_hwi (tree_to_shwi (arg0)) != 1
2760 || absu_hwi (tree_to_shwi (arg1)) != 1
2761 || wi::to_widest (arg0) == wi::to_widest (arg1))
2762 return false;
2764 if (!integer_zerop (arg3) || (cmp3 != EQ_EXPR && cmp3 != NE_EXPR))
2765 return false;
2766 if ((cond3_phi_edge->flags & (cmp3 == EQ_EXPR
2767 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) == 0)
2768 return false;
2770 /* lhs1 one_cmp rhs1 results in phires of 1. */
2771 enum tree_code one_cmp;
2772 if ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2773 ^ (!integer_onep ((e1->flags & EDGE_TRUE_VALUE) ? arg1 : arg0)))
2774 one_cmp = LT_EXPR;
2775 else
2776 one_cmp = GT_EXPR;
2778 enum tree_code res_cmp;
2779 switch (cmp)
2781 case EQ_EXPR:
2782 if (integer_zerop (rhs))
2783 res_cmp = EQ_EXPR;
2784 else if (integer_minus_onep (rhs))
2785 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2786 else if (integer_onep (rhs))
2787 res_cmp = one_cmp;
2788 else
2789 return false;
2790 break;
2791 case NE_EXPR:
2792 if (integer_zerop (rhs))
2793 res_cmp = NE_EXPR;
2794 else if (integer_minus_onep (rhs))
2795 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2796 else if (integer_onep (rhs))
2797 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2798 else
2799 return false;
2800 break;
2801 case LT_EXPR:
2802 if (integer_onep (rhs))
2803 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2804 else if (integer_zerop (rhs))
2805 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2806 else
2807 return false;
2808 break;
2809 case LE_EXPR:
2810 if (integer_zerop (rhs))
2811 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2812 else if (integer_minus_onep (rhs))
2813 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2814 else
2815 return false;
2816 break;
2817 case GT_EXPR:
2818 if (integer_minus_onep (rhs))
2819 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2820 else if (integer_zerop (rhs))
2821 res_cmp = one_cmp;
2822 else
2823 return false;
2824 break;
2825 case GE_EXPR:
2826 if (integer_zerop (rhs))
2827 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2828 else if (integer_onep (rhs))
2829 res_cmp = one_cmp;
2830 else
2831 return false;
2832 break;
2833 default:
2834 gcc_unreachable ();
2837 if (gimple_code (use_stmt) == GIMPLE_COND)
2839 gcond *use_cond = as_a <gcond *> (use_stmt);
2840 gimple_cond_set_code (use_cond, res_cmp);
2841 gimple_cond_set_lhs (use_cond, lhs1);
2842 gimple_cond_set_rhs (use_cond, rhs1);
2844 else if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2846 gimple_assign_set_rhs_code (use_stmt, res_cmp);
2847 gimple_assign_set_rhs1 (use_stmt, lhs1);
2848 gimple_assign_set_rhs2 (use_stmt, rhs1);
2850 else
2852 tree cond = build2 (res_cmp, TREE_TYPE (gimple_assign_rhs1 (use_stmt)),
2853 lhs1, rhs1);
2854 gimple_assign_set_rhs1 (use_stmt, cond);
2856 update_stmt (use_stmt);
2858 if (MAY_HAVE_DEBUG_BIND_STMTS)
2860 use_operand_p use_p;
2861 imm_use_iterator iter;
2862 bool has_debug_uses = false;
2863 bool has_cast_debug_uses = false;
2864 FOR_EACH_IMM_USE_FAST (use_p, iter, phires)
2866 gimple *use_stmt = USE_STMT (use_p);
2867 if (orig_use_lhs && use_stmt == orig_use_stmt)
2868 continue;
2869 gcc_assert (is_gimple_debug (use_stmt));
2870 has_debug_uses = true;
2871 break;
2873 if (orig_use_lhs)
2875 if (!has_debug_uses || is_cast)
2876 FOR_EACH_IMM_USE_FAST (use_p, iter, orig_use_lhs)
2878 gimple *use_stmt = USE_STMT (use_p);
2879 gcc_assert (is_gimple_debug (use_stmt));
2880 has_debug_uses = true;
2881 if (is_cast)
2882 has_cast_debug_uses = true;
2884 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
2885 tree zero = build_zero_cst (TREE_TYPE (orig_use_lhs));
2886 gimple_assign_set_rhs_with_ops (&gsi, INTEGER_CST, zero);
2887 update_stmt (orig_use_stmt);
2890 if (has_debug_uses)
2892 /* If there are debug uses, emit something like:
2893 # DEBUG D#1 => i_2(D) > j_3(D) ? 1 : -1
2894 # DEBUG D#2 => i_2(D) == j_3(D) ? 0 : D#1
2895 where > stands for the comparison that yielded 1
2896 and replace debug uses of phi result with that D#2.
2897 Ignore the value of 2, because if NaNs aren't expected,
2898 all floating point numbers should be comparable. */
2899 gimple_stmt_iterator gsi = gsi_after_labels (gimple_bb (phi));
2900 tree type = TREE_TYPE (phires);
2901 tree temp1 = build_debug_expr_decl (type);
2902 tree t = build2 (one_cmp, boolean_type_node, lhs1, rhs2);
2903 t = build3 (COND_EXPR, type, t, build_one_cst (type),
2904 build_int_cst (type, -1));
2905 gimple *g = gimple_build_debug_bind (temp1, t, phi);
2906 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2907 tree temp2 = build_debug_expr_decl (type);
2908 t = build2 (EQ_EXPR, boolean_type_node, lhs1, rhs2);
2909 t = build3 (COND_EXPR, type, t, build_zero_cst (type), temp1);
2910 g = gimple_build_debug_bind (temp2, t, phi);
2911 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2912 replace_uses_by (phires, temp2);
2913 if (orig_use_lhs)
2915 if (has_cast_debug_uses)
2917 tree temp3 = make_node (DEBUG_EXPR_DECL);
2918 DECL_ARTIFICIAL (temp3) = 1;
2919 TREE_TYPE (temp3) = TREE_TYPE (orig_use_lhs);
2920 SET_DECL_MODE (temp3, TYPE_MODE (type));
2921 t = fold_convert (TREE_TYPE (temp3), temp2);
2922 g = gimple_build_debug_bind (temp3, t, phi);
2923 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2924 replace_uses_by (orig_use_lhs, temp3);
2926 else
2927 replace_uses_by (orig_use_lhs, temp2);
2932 if (orig_use_lhs)
2934 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
2935 gsi_remove (&gsi, true);
2938 gimple_stmt_iterator psi = gsi_for_stmt (phi);
2939 remove_phi_node (&psi, true);
2940 statistics_counter_event (cfun, "spaceship replacement", 1);
2942 return true;
2945 /* Optimize x ? __builtin_fun (x) : C, where C is __builtin_fun (0).
2946 Convert
2948 <bb 2>
2949 if (b_4(D) != 0)
2950 goto <bb 3>
2951 else
2952 goto <bb 4>
2954 <bb 3>
2955 _2 = (unsigned long) b_4(D);
2956 _9 = __builtin_popcountl (_2);
2958 _9 = __builtin_popcountl (b_4(D));
2960 <bb 4>
2961 c_12 = PHI <0(2), _9(3)>
2963 Into
2964 <bb 2>
2965 _2 = (unsigned long) b_4(D);
2966 _9 = __builtin_popcountl (_2);
2968 _9 = __builtin_popcountl (b_4(D));
2970 <bb 4>
2971 c_12 = PHI <_9(2)>
2973 Similarly for __builtin_clz or __builtin_ctz if
2974 C?Z_DEFINED_VALUE_AT_ZERO is 2, optab is present and
2975 instead of 0 above it uses the value from that macro. */
2977 static bool
2978 cond_removal_in_builtin_zero_pattern (basic_block cond_bb,
2979 basic_block middle_bb,
2980 edge e1, edge e2, gphi *phi,
2981 tree arg0, tree arg1)
2983 gimple *cond;
2984 gimple_stmt_iterator gsi, gsi_from;
2985 gimple *call;
2986 gimple *cast = NULL;
2987 tree lhs, arg;
2989 /* Check that
2990 _2 = (unsigned long) b_4(D);
2991 _9 = __builtin_popcountl (_2);
2993 _9 = __builtin_popcountl (b_4(D));
2994 are the only stmts in the middle_bb. */
2996 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
2997 if (gsi_end_p (gsi))
2998 return false;
2999 cast = gsi_stmt (gsi);
3000 gsi_next_nondebug (&gsi);
3001 if (!gsi_end_p (gsi))
3003 call = gsi_stmt (gsi);
3004 gsi_next_nondebug (&gsi);
3005 if (!gsi_end_p (gsi))
3006 return false;
3008 else
3010 call = cast;
3011 cast = NULL;
3014 /* Check that we have a popcount/clz/ctz builtin. */
3015 if (!is_gimple_call (call) || gimple_call_num_args (call) != 1)
3016 return false;
3018 arg = gimple_call_arg (call, 0);
3019 lhs = gimple_get_lhs (call);
3021 if (lhs == NULL_TREE)
3022 return false;
3024 combined_fn cfn = gimple_call_combined_fn (call);
3025 internal_fn ifn = IFN_LAST;
3026 int val = 0;
3027 switch (cfn)
3029 case CFN_BUILT_IN_BSWAP16:
3030 case CFN_BUILT_IN_BSWAP32:
3031 case CFN_BUILT_IN_BSWAP64:
3032 case CFN_BUILT_IN_BSWAP128:
3033 CASE_CFN_FFS:
3034 CASE_CFN_PARITY:
3035 CASE_CFN_POPCOUNT:
3036 break;
3037 CASE_CFN_CLZ:
3038 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3040 tree type = TREE_TYPE (arg);
3041 if (direct_internal_fn_supported_p (IFN_CLZ, type, OPTIMIZE_FOR_BOTH)
3042 && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3043 val) == 2)
3045 ifn = IFN_CLZ;
3046 break;
3049 return false;
3050 CASE_CFN_CTZ:
3051 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3053 tree type = TREE_TYPE (arg);
3054 if (direct_internal_fn_supported_p (IFN_CTZ, type, OPTIMIZE_FOR_BOTH)
3055 && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3056 val) == 2)
3058 ifn = IFN_CTZ;
3059 break;
3062 return false;
3063 case CFN_BUILT_IN_CLRSB:
3064 val = TYPE_PRECISION (integer_type_node) - 1;
3065 break;
3066 case CFN_BUILT_IN_CLRSBL:
3067 val = TYPE_PRECISION (long_integer_type_node) - 1;
3068 break;
3069 case CFN_BUILT_IN_CLRSBLL:
3070 val = TYPE_PRECISION (long_long_integer_type_node) - 1;
3071 break;
3072 default:
3073 return false;
3076 if (cast)
3078 /* We have a cast stmt feeding popcount/clz/ctz builtin. */
3079 /* Check that we have a cast prior to that. */
3080 if (gimple_code (cast) != GIMPLE_ASSIGN
3081 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (cast)))
3082 return false;
3083 /* Result of the cast stmt is the argument to the builtin. */
3084 if (arg != gimple_assign_lhs (cast))
3085 return false;
3086 arg = gimple_assign_rhs1 (cast);
3089 cond = last_stmt (cond_bb);
3091 /* Cond_bb has a check for b_4 [!=|==] 0 before calling the popcount/clz/ctz
3092 builtin. */
3093 if (gimple_code (cond) != GIMPLE_COND
3094 || (gimple_cond_code (cond) != NE_EXPR
3095 && gimple_cond_code (cond) != EQ_EXPR)
3096 || !integer_zerop (gimple_cond_rhs (cond))
3097 || arg != gimple_cond_lhs (cond))
3098 return false;
3100 /* Canonicalize. */
3101 if ((e2->flags & EDGE_TRUE_VALUE
3102 && gimple_cond_code (cond) == NE_EXPR)
3103 || (e1->flags & EDGE_TRUE_VALUE
3104 && gimple_cond_code (cond) == EQ_EXPR))
3106 std::swap (arg0, arg1);
3107 std::swap (e1, e2);
3110 /* Check PHI arguments. */
3111 if (lhs != arg0
3112 || TREE_CODE (arg1) != INTEGER_CST
3113 || wi::to_wide (arg1) != val)
3114 return false;
3116 /* And insert the popcount/clz/ctz builtin and cast stmt before the
3117 cond_bb. */
3118 gsi = gsi_last_bb (cond_bb);
3119 if (cast)
3121 gsi_from = gsi_for_stmt (cast);
3122 gsi_move_before (&gsi_from, &gsi);
3123 reset_flow_sensitive_info (gimple_get_lhs (cast));
3125 gsi_from = gsi_for_stmt (call);
3126 if (ifn == IFN_LAST || gimple_call_internal_p (call))
3127 gsi_move_before (&gsi_from, &gsi);
3128 else
3130 /* For __builtin_c[lt]z* force .C[LT]Z ifn, because only
3131 the latter is well defined at zero. */
3132 call = gimple_build_call_internal (ifn, 1, gimple_call_arg (call, 0));
3133 gimple_call_set_lhs (call, lhs);
3134 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
3135 gsi_remove (&gsi_from, true);
3137 reset_flow_sensitive_info (lhs);
3139 /* Now update the PHI and remove unneeded bbs. */
3140 replace_phi_edge_with_variable (cond_bb, e2, phi, lhs);
3141 return true;
3144 /* Auxiliary functions to determine the set of memory accesses which
3145 can't trap because they are preceded by accesses to the same memory
3146 portion. We do that for MEM_REFs, so we only need to track
3147 the SSA_NAME of the pointer indirectly referenced. The algorithm
3148 simply is a walk over all instructions in dominator order. When
3149 we see an MEM_REF we determine if we've already seen a same
3150 ref anywhere up to the root of the dominator tree. If we do the
3151 current access can't trap. If we don't see any dominating access
3152 the current access might trap, but might also make later accesses
3153 non-trapping, so we remember it. We need to be careful with loads
3154 or stores, for instance a load might not trap, while a store would,
3155 so if we see a dominating read access this doesn't mean that a later
3156 write access would not trap. Hence we also need to differentiate the
3157 type of access(es) seen.
3159 ??? We currently are very conservative and assume that a load might
3160 trap even if a store doesn't (write-only memory). This probably is
3161 overly conservative.
3163 We currently support a special case that for !TREE_ADDRESSABLE automatic
3164 variables, it could ignore whether something is a load or store because the
3165 local stack should be always writable. */
3167 /* A hash-table of references (MEM_REF/ARRAY_REF/COMPONENT_REF), and in which
3168 basic block an *_REF through it was seen, which would constitute a
3169 no-trap region for same accesses.
3171 Size is needed to support 2 MEM_REFs of different types, like
3172 MEM<double>(s_1) and MEM<long>(s_1), which would compare equal with
3173 OEP_ADDRESS_OF. */
3174 struct ref_to_bb
3176 tree exp;
3177 HOST_WIDE_INT size;
3178 unsigned int phase;
3179 basic_block bb;
3182 /* Hashtable helpers. */
3184 struct refs_hasher : free_ptr_hash<ref_to_bb>
3186 static inline hashval_t hash (const ref_to_bb *);
3187 static inline bool equal (const ref_to_bb *, const ref_to_bb *);
3190 /* Used for quick clearing of the hash-table when we see calls.
3191 Hash entries with phase < nt_call_phase are invalid. */
3192 static unsigned int nt_call_phase;
3194 /* The hash function. */
3196 inline hashval_t
3197 refs_hasher::hash (const ref_to_bb *n)
3199 inchash::hash hstate;
3200 inchash::add_expr (n->exp, hstate, OEP_ADDRESS_OF);
3201 hstate.add_hwi (n->size);
3202 return hstate.end ();
3205 /* The equality function of *P1 and *P2. */
3207 inline bool
3208 refs_hasher::equal (const ref_to_bb *n1, const ref_to_bb *n2)
3210 return operand_equal_p (n1->exp, n2->exp, OEP_ADDRESS_OF)
3211 && n1->size == n2->size;
3214 class nontrapping_dom_walker : public dom_walker
3216 public:
3217 nontrapping_dom_walker (cdi_direction direction, hash_set<tree> *ps)
3218 : dom_walker (direction), m_nontrapping (ps), m_seen_refs (128)
3221 edge before_dom_children (basic_block) final override;
3222 void after_dom_children (basic_block) final override;
3224 private:
3226 /* We see the expression EXP in basic block BB. If it's an interesting
3227 expression (an MEM_REF through an SSA_NAME) possibly insert the
3228 expression into the set NONTRAP or the hash table of seen expressions.
3229 STORE is true if this expression is on the LHS, otherwise it's on
3230 the RHS. */
3231 void add_or_mark_expr (basic_block, tree, bool);
3233 hash_set<tree> *m_nontrapping;
3235 /* The hash table for remembering what we've seen. */
3236 hash_table<refs_hasher> m_seen_refs;
3239 /* Called by walk_dominator_tree, when entering the block BB. */
3240 edge
3241 nontrapping_dom_walker::before_dom_children (basic_block bb)
3243 edge e;
3244 edge_iterator ei;
3245 gimple_stmt_iterator gsi;
3247 /* If we haven't seen all our predecessors, clear the hash-table. */
3248 FOR_EACH_EDGE (e, ei, bb->preds)
3249 if ((((size_t)e->src->aux) & 2) == 0)
3251 nt_call_phase++;
3252 break;
3255 /* Mark this BB as being on the path to dominator root and as visited. */
3256 bb->aux = (void*)(1 | 2);
3258 /* And walk the statements in order. */
3259 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3261 gimple *stmt = gsi_stmt (gsi);
3263 if ((gimple_code (stmt) == GIMPLE_ASM && gimple_vdef (stmt))
3264 || (is_gimple_call (stmt)
3265 && (!nonfreeing_call_p (stmt) || !nonbarrier_call_p (stmt))))
3266 nt_call_phase++;
3267 else if (gimple_assign_single_p (stmt) && !gimple_has_volatile_ops (stmt))
3269 add_or_mark_expr (bb, gimple_assign_lhs (stmt), true);
3270 add_or_mark_expr (bb, gimple_assign_rhs1 (stmt), false);
3273 return NULL;
3276 /* Called by walk_dominator_tree, when basic block BB is exited. */
3277 void
3278 nontrapping_dom_walker::after_dom_children (basic_block bb)
3280 /* This BB isn't on the path to dominator root anymore. */
3281 bb->aux = (void*)2;
3284 /* We see the expression EXP in basic block BB. If it's an interesting
3285 expression of:
3286 1) MEM_REF
3287 2) ARRAY_REF
3288 3) COMPONENT_REF
3289 possibly insert the expression into the set NONTRAP or the hash table
3290 of seen expressions. STORE is true if this expression is on the LHS,
3291 otherwise it's on the RHS. */
3292 void
3293 nontrapping_dom_walker::add_or_mark_expr (basic_block bb, tree exp, bool store)
3295 HOST_WIDE_INT size;
3297 if ((TREE_CODE (exp) == MEM_REF || TREE_CODE (exp) == ARRAY_REF
3298 || TREE_CODE (exp) == COMPONENT_REF)
3299 && (size = int_size_in_bytes (TREE_TYPE (exp))) > 0)
3301 struct ref_to_bb map;
3302 ref_to_bb **slot;
3303 struct ref_to_bb *r2bb;
3304 basic_block found_bb = 0;
3306 if (!store)
3308 tree base = get_base_address (exp);
3309 /* Only record a LOAD of a local variable without address-taken, as
3310 the local stack is always writable. This allows cselim on a STORE
3311 with a dominating LOAD. */
3312 if (!auto_var_p (base) || TREE_ADDRESSABLE (base))
3313 return;
3316 /* Try to find the last seen *_REF, which can trap. */
3317 map.exp = exp;
3318 map.size = size;
3319 slot = m_seen_refs.find_slot (&map, INSERT);
3320 r2bb = *slot;
3321 if (r2bb && r2bb->phase >= nt_call_phase)
3322 found_bb = r2bb->bb;
3324 /* If we've found a trapping *_REF, _and_ it dominates EXP
3325 (it's in a basic block on the path from us to the dominator root)
3326 then we can't trap. */
3327 if (found_bb && (((size_t)found_bb->aux) & 1) == 1)
3329 m_nontrapping->add (exp);
3331 else
3333 /* EXP might trap, so insert it into the hash table. */
3334 if (r2bb)
3336 r2bb->phase = nt_call_phase;
3337 r2bb->bb = bb;
3339 else
3341 r2bb = XNEW (struct ref_to_bb);
3342 r2bb->phase = nt_call_phase;
3343 r2bb->bb = bb;
3344 r2bb->exp = exp;
3345 r2bb->size = size;
3346 *slot = r2bb;
3352 /* This is the entry point of gathering non trapping memory accesses.
3353 It will do a dominator walk over the whole function, and it will
3354 make use of the bb->aux pointers. It returns a set of trees
3355 (the MEM_REFs itself) which can't trap. */
3356 static hash_set<tree> *
3357 get_non_trapping (void)
3359 nt_call_phase = 0;
3360 hash_set<tree> *nontrap = new hash_set<tree>;
3362 nontrapping_dom_walker (CDI_DOMINATORS, nontrap)
3363 .walk (cfun->cfg->x_entry_block_ptr);
3365 clear_aux_for_blocks ();
3366 return nontrap;
3369 /* Do the main work of conditional store replacement. We already know
3370 that the recognized pattern looks like so:
3372 split:
3373 if (cond) goto MIDDLE_BB; else goto JOIN_BB (edge E1)
3374 MIDDLE_BB:
3375 something
3376 fallthrough (edge E0)
3377 JOIN_BB:
3378 some more
3380 We check that MIDDLE_BB contains only one store, that that store
3381 doesn't trap (not via NOTRAP, but via checking if an access to the same
3382 memory location dominates us, or the store is to a local addressable
3383 object) and that the store has a "simple" RHS. */
3385 static bool
3386 cond_store_replacement (basic_block middle_bb, basic_block join_bb,
3387 edge e0, edge e1, hash_set<tree> *nontrap)
3389 gimple *assign = last_and_only_stmt (middle_bb);
3390 tree lhs, rhs, name, name2;
3391 gphi *newphi;
3392 gassign *new_stmt;
3393 gimple_stmt_iterator gsi;
3394 location_t locus;
3396 /* Check if middle_bb contains of only one store. */
3397 if (!assign
3398 || !gimple_assign_single_p (assign)
3399 || gimple_has_volatile_ops (assign))
3400 return false;
3402 /* And no PHI nodes so all uses in the single stmt are also
3403 available where we insert to. */
3404 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
3405 return false;
3407 locus = gimple_location (assign);
3408 lhs = gimple_assign_lhs (assign);
3409 rhs = gimple_assign_rhs1 (assign);
3410 if ((!REFERENCE_CLASS_P (lhs)
3411 && !DECL_P (lhs))
3412 || !is_gimple_reg_type (TREE_TYPE (lhs)))
3413 return false;
3415 /* Prove that we can move the store down. We could also check
3416 TREE_THIS_NOTRAP here, but in that case we also could move stores,
3417 whose value is not available readily, which we want to avoid. */
3418 if (!nontrap->contains (lhs))
3420 /* If LHS is an access to a local variable without address-taken
3421 (or when we allow data races) and known not to trap, we could
3422 always safely move down the store. */
3423 tree base = get_base_address (lhs);
3424 if (!auto_var_p (base)
3425 || (TREE_ADDRESSABLE (base) && !flag_store_data_races)
3426 || tree_could_trap_p (lhs))
3427 return false;
3430 /* Now we've checked the constraints, so do the transformation:
3431 1) Remove the single store. */
3432 gsi = gsi_for_stmt (assign);
3433 unlink_stmt_vdef (assign);
3434 gsi_remove (&gsi, true);
3435 release_defs (assign);
3437 /* Make both store and load use alias-set zero as we have to
3438 deal with the case of the store being a conditional change
3439 of the dynamic type. */
3440 lhs = unshare_expr (lhs);
3441 tree *basep = &lhs;
3442 while (handled_component_p (*basep))
3443 basep = &TREE_OPERAND (*basep, 0);
3444 if (TREE_CODE (*basep) == MEM_REF
3445 || TREE_CODE (*basep) == TARGET_MEM_REF)
3446 TREE_OPERAND (*basep, 1)
3447 = fold_convert (ptr_type_node, TREE_OPERAND (*basep, 1));
3448 else
3449 *basep = build2 (MEM_REF, TREE_TYPE (*basep),
3450 build_fold_addr_expr (*basep),
3451 build_zero_cst (ptr_type_node));
3453 /* 2) Insert a load from the memory of the store to the temporary
3454 on the edge which did not contain the store. */
3455 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3456 new_stmt = gimple_build_assign (name, lhs);
3457 gimple_set_location (new_stmt, locus);
3458 lhs = unshare_expr (lhs);
3460 /* Set the no-warning bit on the rhs of the load to avoid uninit
3461 warnings. */
3462 tree rhs1 = gimple_assign_rhs1 (new_stmt);
3463 suppress_warning (rhs1, OPT_Wuninitialized);
3465 gsi_insert_on_edge (e1, new_stmt);
3467 /* 3) Create a PHI node at the join block, with one argument
3468 holding the old RHS, and the other holding the temporary
3469 where we stored the old memory contents. */
3470 name2 = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3471 newphi = create_phi_node (name2, join_bb);
3472 add_phi_arg (newphi, rhs, e0, locus);
3473 add_phi_arg (newphi, name, e1, locus);
3475 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
3477 /* 4) Insert that PHI node. */
3478 gsi = gsi_after_labels (join_bb);
3479 if (gsi_end_p (gsi))
3481 gsi = gsi_last_bb (join_bb);
3482 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3484 else
3485 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3487 if (dump_file && (dump_flags & TDF_DETAILS))
3489 fprintf (dump_file, "\nConditional store replacement happened!");
3490 fprintf (dump_file, "\nReplaced the store with a load.");
3491 fprintf (dump_file, "\nInserted a new PHI statement in joint block:\n");
3492 print_gimple_stmt (dump_file, new_stmt, 0, TDF_VOPS|TDF_MEMSYMS);
3494 statistics_counter_event (cfun, "conditional store replacement", 1);
3496 return true;
3499 /* Do the main work of conditional store replacement. */
3501 static bool
3502 cond_if_else_store_replacement_1 (basic_block then_bb, basic_block else_bb,
3503 basic_block join_bb, gimple *then_assign,
3504 gimple *else_assign)
3506 tree lhs_base, lhs, then_rhs, else_rhs, name;
3507 location_t then_locus, else_locus;
3508 gimple_stmt_iterator gsi;
3509 gphi *newphi;
3510 gassign *new_stmt;
3512 if (then_assign == NULL
3513 || !gimple_assign_single_p (then_assign)
3514 || gimple_clobber_p (then_assign)
3515 || gimple_has_volatile_ops (then_assign)
3516 || else_assign == NULL
3517 || !gimple_assign_single_p (else_assign)
3518 || gimple_clobber_p (else_assign)
3519 || gimple_has_volatile_ops (else_assign))
3520 return false;
3522 lhs = gimple_assign_lhs (then_assign);
3523 if (!is_gimple_reg_type (TREE_TYPE (lhs))
3524 || !operand_equal_p (lhs, gimple_assign_lhs (else_assign), 0))
3525 return false;
3527 lhs_base = get_base_address (lhs);
3528 if (lhs_base == NULL_TREE
3529 || (!DECL_P (lhs_base) && TREE_CODE (lhs_base) != MEM_REF))
3530 return false;
3532 then_rhs = gimple_assign_rhs1 (then_assign);
3533 else_rhs = gimple_assign_rhs1 (else_assign);
3534 then_locus = gimple_location (then_assign);
3535 else_locus = gimple_location (else_assign);
3537 /* Now we've checked the constraints, so do the transformation:
3538 1) Remove the stores. */
3539 gsi = gsi_for_stmt (then_assign);
3540 unlink_stmt_vdef (then_assign);
3541 gsi_remove (&gsi, true);
3542 release_defs (then_assign);
3544 gsi = gsi_for_stmt (else_assign);
3545 unlink_stmt_vdef (else_assign);
3546 gsi_remove (&gsi, true);
3547 release_defs (else_assign);
3549 /* 2) Create a PHI node at the join block, with one argument
3550 holding the old RHS, and the other holding the temporary
3551 where we stored the old memory contents. */
3552 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3553 newphi = create_phi_node (name, join_bb);
3554 add_phi_arg (newphi, then_rhs, EDGE_SUCC (then_bb, 0), then_locus);
3555 add_phi_arg (newphi, else_rhs, EDGE_SUCC (else_bb, 0), else_locus);
3557 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
3559 /* 3) Insert that PHI node. */
3560 gsi = gsi_after_labels (join_bb);
3561 if (gsi_end_p (gsi))
3563 gsi = gsi_last_bb (join_bb);
3564 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3566 else
3567 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3569 statistics_counter_event (cfun, "if-then-else store replacement", 1);
3571 return true;
3574 /* Return the single store in BB with VDEF or NULL if there are
3575 other stores in the BB or loads following the store. */
3577 static gimple *
3578 single_trailing_store_in_bb (basic_block bb, tree vdef)
3580 if (SSA_NAME_IS_DEFAULT_DEF (vdef))
3581 return NULL;
3582 gimple *store = SSA_NAME_DEF_STMT (vdef);
3583 if (gimple_bb (store) != bb
3584 || gimple_code (store) == GIMPLE_PHI)
3585 return NULL;
3587 /* Verify there is no other store in this BB. */
3588 if (!SSA_NAME_IS_DEFAULT_DEF (gimple_vuse (store))
3589 && gimple_bb (SSA_NAME_DEF_STMT (gimple_vuse (store))) == bb
3590 && gimple_code (SSA_NAME_DEF_STMT (gimple_vuse (store))) != GIMPLE_PHI)
3591 return NULL;
3593 /* Verify there is no load or store after the store. */
3594 use_operand_p use_p;
3595 imm_use_iterator imm_iter;
3596 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, gimple_vdef (store))
3597 if (USE_STMT (use_p) != store
3598 && gimple_bb (USE_STMT (use_p)) == bb)
3599 return NULL;
3601 return store;
3604 /* Conditional store replacement. We already know
3605 that the recognized pattern looks like so:
3607 split:
3608 if (cond) goto THEN_BB; else goto ELSE_BB (edge E1)
3609 THEN_BB:
3611 X = Y;
3613 goto JOIN_BB;
3614 ELSE_BB:
3616 X = Z;
3618 fallthrough (edge E0)
3619 JOIN_BB:
3620 some more
3622 We check that it is safe to sink the store to JOIN_BB by verifying that
3623 there are no read-after-write or write-after-write dependencies in
3624 THEN_BB and ELSE_BB. */
3626 static bool
3627 cond_if_else_store_replacement (basic_block then_bb, basic_block else_bb,
3628 basic_block join_bb)
3630 vec<data_reference_p> then_datarefs, else_datarefs;
3631 vec<ddr_p> then_ddrs, else_ddrs;
3632 gimple *then_store, *else_store;
3633 bool found, ok = false, res;
3634 struct data_dependence_relation *ddr;
3635 data_reference_p then_dr, else_dr;
3636 int i, j;
3637 tree then_lhs, else_lhs;
3638 basic_block blocks[3];
3640 /* Handle the case with single store in THEN_BB and ELSE_BB. That is
3641 cheap enough to always handle as it allows us to elide dependence
3642 checking. */
3643 gphi *vphi = NULL;
3644 for (gphi_iterator si = gsi_start_phis (join_bb); !gsi_end_p (si);
3645 gsi_next (&si))
3646 if (virtual_operand_p (gimple_phi_result (si.phi ())))
3648 vphi = si.phi ();
3649 break;
3651 if (!vphi)
3652 return false;
3653 tree then_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (then_bb));
3654 tree else_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (else_bb));
3655 gimple *then_assign = single_trailing_store_in_bb (then_bb, then_vdef);
3656 if (then_assign)
3658 gimple *else_assign = single_trailing_store_in_bb (else_bb, else_vdef);
3659 if (else_assign)
3660 return cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
3661 then_assign, else_assign);
3664 /* If either vectorization or if-conversion is disabled then do
3665 not sink any stores. */
3666 if (param_max_stores_to_sink == 0
3667 || (!flag_tree_loop_vectorize && !flag_tree_slp_vectorize)
3668 || !flag_tree_loop_if_convert)
3669 return false;
3671 /* Find data references. */
3672 then_datarefs.create (1);
3673 else_datarefs.create (1);
3674 if ((find_data_references_in_bb (NULL, then_bb, &then_datarefs)
3675 == chrec_dont_know)
3676 || !then_datarefs.length ()
3677 || (find_data_references_in_bb (NULL, else_bb, &else_datarefs)
3678 == chrec_dont_know)
3679 || !else_datarefs.length ())
3681 free_data_refs (then_datarefs);
3682 free_data_refs (else_datarefs);
3683 return false;
3686 /* Find pairs of stores with equal LHS. */
3687 auto_vec<gimple *, 1> then_stores, else_stores;
3688 FOR_EACH_VEC_ELT (then_datarefs, i, then_dr)
3690 if (DR_IS_READ (then_dr))
3691 continue;
3693 then_store = DR_STMT (then_dr);
3694 then_lhs = gimple_get_lhs (then_store);
3695 if (then_lhs == NULL_TREE)
3696 continue;
3697 found = false;
3699 FOR_EACH_VEC_ELT (else_datarefs, j, else_dr)
3701 if (DR_IS_READ (else_dr))
3702 continue;
3704 else_store = DR_STMT (else_dr);
3705 else_lhs = gimple_get_lhs (else_store);
3706 if (else_lhs == NULL_TREE)
3707 continue;
3709 if (operand_equal_p (then_lhs, else_lhs, 0))
3711 found = true;
3712 break;
3716 if (!found)
3717 continue;
3719 then_stores.safe_push (then_store);
3720 else_stores.safe_push (else_store);
3723 /* No pairs of stores found. */
3724 if (!then_stores.length ()
3725 || then_stores.length () > (unsigned) param_max_stores_to_sink)
3727 free_data_refs (then_datarefs);
3728 free_data_refs (else_datarefs);
3729 return false;
3732 /* Compute and check data dependencies in both basic blocks. */
3733 then_ddrs.create (1);
3734 else_ddrs.create (1);
3735 if (!compute_all_dependences (then_datarefs, &then_ddrs,
3736 vNULL, false)
3737 || !compute_all_dependences (else_datarefs, &else_ddrs,
3738 vNULL, false))
3740 free_dependence_relations (then_ddrs);
3741 free_dependence_relations (else_ddrs);
3742 free_data_refs (then_datarefs);
3743 free_data_refs (else_datarefs);
3744 return false;
3746 blocks[0] = then_bb;
3747 blocks[1] = else_bb;
3748 blocks[2] = join_bb;
3749 renumber_gimple_stmt_uids_in_blocks (blocks, 3);
3751 /* Check that there are no read-after-write or write-after-write dependencies
3752 in THEN_BB. */
3753 FOR_EACH_VEC_ELT (then_ddrs, i, ddr)
3755 struct data_reference *dra = DDR_A (ddr);
3756 struct data_reference *drb = DDR_B (ddr);
3758 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3759 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3760 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3761 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3762 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3763 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3765 free_dependence_relations (then_ddrs);
3766 free_dependence_relations (else_ddrs);
3767 free_data_refs (then_datarefs);
3768 free_data_refs (else_datarefs);
3769 return false;
3773 /* Check that there are no read-after-write or write-after-write dependencies
3774 in ELSE_BB. */
3775 FOR_EACH_VEC_ELT (else_ddrs, i, ddr)
3777 struct data_reference *dra = DDR_A (ddr);
3778 struct data_reference *drb = DDR_B (ddr);
3780 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3781 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3782 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3783 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3784 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3785 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3787 free_dependence_relations (then_ddrs);
3788 free_dependence_relations (else_ddrs);
3789 free_data_refs (then_datarefs);
3790 free_data_refs (else_datarefs);
3791 return false;
3795 /* Sink stores with same LHS. */
3796 FOR_EACH_VEC_ELT (then_stores, i, then_store)
3798 else_store = else_stores[i];
3799 res = cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
3800 then_store, else_store);
3801 ok = ok || res;
3804 free_dependence_relations (then_ddrs);
3805 free_dependence_relations (else_ddrs);
3806 free_data_refs (then_datarefs);
3807 free_data_refs (else_datarefs);
3809 return ok;
3812 /* Return TRUE if STMT has a VUSE whose corresponding VDEF is in BB. */
3814 static bool
3815 local_mem_dependence (gimple *stmt, basic_block bb)
3817 tree vuse = gimple_vuse (stmt);
3818 gimple *def;
3820 if (!vuse)
3821 return false;
3823 def = SSA_NAME_DEF_STMT (vuse);
3824 return (def && gimple_bb (def) == bb);
3827 /* Given a "diamond" control-flow pattern where BB0 tests a condition,
3828 BB1 and BB2 are "then" and "else" blocks dependent on this test,
3829 and BB3 rejoins control flow following BB1 and BB2, look for
3830 opportunities to hoist loads as follows. If BB3 contains a PHI of
3831 two loads, one each occurring in BB1 and BB2, and the loads are
3832 provably of adjacent fields in the same structure, then move both
3833 loads into BB0. Of course this can only be done if there are no
3834 dependencies preventing such motion.
3836 One of the hoisted loads will always be speculative, so the
3837 transformation is currently conservative:
3839 - The fields must be strictly adjacent.
3840 - The two fields must occupy a single memory block that is
3841 guaranteed to not cross a page boundary.
3843 The last is difficult to prove, as such memory blocks should be
3844 aligned on the minimum of the stack alignment boundary and the
3845 alignment guaranteed by heap allocation interfaces. Thus we rely
3846 on a parameter for the alignment value.
3848 Provided a good value is used for the last case, the first
3849 restriction could possibly be relaxed. */
3851 static void
3852 hoist_adjacent_loads (basic_block bb0, basic_block bb1,
3853 basic_block bb2, basic_block bb3)
3855 int param_align = param_l1_cache_line_size;
3856 unsigned param_align_bits = (unsigned) (param_align * BITS_PER_UNIT);
3857 gphi_iterator gsi;
3859 /* Walk the phis in bb3 looking for an opportunity. We are looking
3860 for phis of two SSA names, one each of which is defined in bb1 and
3861 bb2. */
3862 for (gsi = gsi_start_phis (bb3); !gsi_end_p (gsi); gsi_next (&gsi))
3864 gphi *phi_stmt = gsi.phi ();
3865 gimple *def1, *def2;
3866 tree arg1, arg2, ref1, ref2, field1, field2;
3867 tree tree_offset1, tree_offset2, tree_size2, next;
3868 int offset1, offset2, size2;
3869 unsigned align1;
3870 gimple_stmt_iterator gsi2;
3871 basic_block bb_for_def1, bb_for_def2;
3873 if (gimple_phi_num_args (phi_stmt) != 2
3874 || virtual_operand_p (gimple_phi_result (phi_stmt)))
3875 continue;
3877 arg1 = gimple_phi_arg_def (phi_stmt, 0);
3878 arg2 = gimple_phi_arg_def (phi_stmt, 1);
3880 if (TREE_CODE (arg1) != SSA_NAME
3881 || TREE_CODE (arg2) != SSA_NAME
3882 || SSA_NAME_IS_DEFAULT_DEF (arg1)
3883 || SSA_NAME_IS_DEFAULT_DEF (arg2))
3884 continue;
3886 def1 = SSA_NAME_DEF_STMT (arg1);
3887 def2 = SSA_NAME_DEF_STMT (arg2);
3889 if ((gimple_bb (def1) != bb1 || gimple_bb (def2) != bb2)
3890 && (gimple_bb (def2) != bb1 || gimple_bb (def1) != bb2))
3891 continue;
3893 /* Check the mode of the arguments to be sure a conditional move
3894 can be generated for it. */
3895 if (optab_handler (movcc_optab, TYPE_MODE (TREE_TYPE (arg1)))
3896 == CODE_FOR_nothing)
3897 continue;
3899 /* Both statements must be assignments whose RHS is a COMPONENT_REF. */
3900 if (!gimple_assign_single_p (def1)
3901 || !gimple_assign_single_p (def2)
3902 || gimple_has_volatile_ops (def1)
3903 || gimple_has_volatile_ops (def2))
3904 continue;
3906 ref1 = gimple_assign_rhs1 (def1);
3907 ref2 = gimple_assign_rhs1 (def2);
3909 if (TREE_CODE (ref1) != COMPONENT_REF
3910 || TREE_CODE (ref2) != COMPONENT_REF)
3911 continue;
3913 /* The zeroth operand of the two component references must be
3914 identical. It is not sufficient to compare get_base_address of
3915 the two references, because this could allow for different
3916 elements of the same array in the two trees. It is not safe to
3917 assume that the existence of one array element implies the
3918 existence of a different one. */
3919 if (!operand_equal_p (TREE_OPERAND (ref1, 0), TREE_OPERAND (ref2, 0), 0))
3920 continue;
3922 field1 = TREE_OPERAND (ref1, 1);
3923 field2 = TREE_OPERAND (ref2, 1);
3925 /* Check for field adjacency, and ensure field1 comes first. */
3926 for (next = DECL_CHAIN (field1);
3927 next && TREE_CODE (next) != FIELD_DECL;
3928 next = DECL_CHAIN (next))
3931 if (next != field2)
3933 for (next = DECL_CHAIN (field2);
3934 next && TREE_CODE (next) != FIELD_DECL;
3935 next = DECL_CHAIN (next))
3938 if (next != field1)
3939 continue;
3941 std::swap (field1, field2);
3942 std::swap (def1, def2);
3945 bb_for_def1 = gimple_bb (def1);
3946 bb_for_def2 = gimple_bb (def2);
3948 /* Check for proper alignment of the first field. */
3949 tree_offset1 = bit_position (field1);
3950 tree_offset2 = bit_position (field2);
3951 tree_size2 = DECL_SIZE (field2);
3953 if (!tree_fits_uhwi_p (tree_offset1)
3954 || !tree_fits_uhwi_p (tree_offset2)
3955 || !tree_fits_uhwi_p (tree_size2))
3956 continue;
3958 offset1 = tree_to_uhwi (tree_offset1);
3959 offset2 = tree_to_uhwi (tree_offset2);
3960 size2 = tree_to_uhwi (tree_size2);
3961 align1 = DECL_ALIGN (field1) % param_align_bits;
3963 if (offset1 % BITS_PER_UNIT != 0)
3964 continue;
3966 /* For profitability, the two field references should fit within
3967 a single cache line. */
3968 if (align1 + offset2 - offset1 + size2 > param_align_bits)
3969 continue;
3971 /* The two expressions cannot be dependent upon vdefs defined
3972 in bb1/bb2. */
3973 if (local_mem_dependence (def1, bb_for_def1)
3974 || local_mem_dependence (def2, bb_for_def2))
3975 continue;
3977 /* The conditions are satisfied; hoist the loads from bb1 and bb2 into
3978 bb0. We hoist the first one first so that a cache miss is handled
3979 efficiently regardless of hardware cache-fill policy. */
3980 gsi2 = gsi_for_stmt (def1);
3981 gsi_move_to_bb_end (&gsi2, bb0);
3982 gsi2 = gsi_for_stmt (def2);
3983 gsi_move_to_bb_end (&gsi2, bb0);
3984 statistics_counter_event (cfun, "hoisted loads", 1);
3986 if (dump_file && (dump_flags & TDF_DETAILS))
3988 fprintf (dump_file,
3989 "\nHoisting adjacent loads from %d and %d into %d: \n",
3990 bb_for_def1->index, bb_for_def2->index, bb0->index);
3991 print_gimple_stmt (dump_file, def1, 0, TDF_VOPS|TDF_MEMSYMS);
3992 print_gimple_stmt (dump_file, def2, 0, TDF_VOPS|TDF_MEMSYMS);
3997 /* Determine whether we should attempt to hoist adjacent loads out of
3998 diamond patterns in pass_phiopt. Always hoist loads if
3999 -fhoist-adjacent-loads is specified and the target machine has
4000 both a conditional move instruction and a defined cache line size. */
4002 static bool
4003 gate_hoist_loads (void)
4005 return (flag_hoist_adjacent_loads == 1
4006 && param_l1_cache_line_size
4007 && HAVE_conditional_move);
4010 /* This pass tries to replaces an if-then-else block with an
4011 assignment. We have four kinds of transformations. Some of these
4012 transformations are also performed by the ifcvt RTL optimizer.
4014 Conditional Replacement
4015 -----------------------
4017 This transformation, implemented in match_simplify_replacement,
4018 replaces
4020 bb0:
4021 if (cond) goto bb2; else goto bb1;
4022 bb1:
4023 bb2:
4024 x = PHI <0 (bb1), 1 (bb0), ...>;
4026 with
4028 bb0:
4029 x' = cond;
4030 goto bb2;
4031 bb2:
4032 x = PHI <x' (bb0), ...>;
4034 We remove bb1 as it becomes unreachable. This occurs often due to
4035 gimplification of conditionals.
4037 Value Replacement
4038 -----------------
4040 This transformation, implemented in value_replacement, replaces
4042 bb0:
4043 if (a != b) goto bb2; else goto bb1;
4044 bb1:
4045 bb2:
4046 x = PHI <a (bb1), b (bb0), ...>;
4048 with
4050 bb0:
4051 bb2:
4052 x = PHI <b (bb0), ...>;
4054 This opportunity can sometimes occur as a result of other
4055 optimizations.
4058 Another case caught by value replacement looks like this:
4060 bb0:
4061 t1 = a == CONST;
4062 t2 = b > c;
4063 t3 = t1 & t2;
4064 if (t3 != 0) goto bb1; else goto bb2;
4065 bb1:
4066 bb2:
4067 x = PHI (CONST, a)
4069 Gets replaced with:
4070 bb0:
4071 bb2:
4072 t1 = a == CONST;
4073 t2 = b > c;
4074 t3 = t1 & t2;
4075 x = a;
4077 ABS Replacement
4078 ---------------
4080 This transformation, implemented in match_simplify_replacement, replaces
4082 bb0:
4083 if (a >= 0) goto bb2; else goto bb1;
4084 bb1:
4085 x = -a;
4086 bb2:
4087 x = PHI <x (bb1), a (bb0), ...>;
4089 with
4091 bb0:
4092 x' = ABS_EXPR< a >;
4093 bb2:
4094 x = PHI <x' (bb0), ...>;
4096 MIN/MAX Replacement
4097 -------------------
4099 This transformation, minmax_replacement replaces
4101 bb0:
4102 if (a <= b) goto bb2; else goto bb1;
4103 bb1:
4104 bb2:
4105 x = PHI <b (bb1), a (bb0), ...>;
4107 with
4109 bb0:
4110 x' = MIN_EXPR (a, b)
4111 bb2:
4112 x = PHI <x' (bb0), ...>;
4114 A similar transformation is done for MAX_EXPR.
4117 This pass also performs a fifth transformation of a slightly different
4118 flavor.
4120 Factor conversion in COND_EXPR
4121 ------------------------------
4123 This transformation factors the conversion out of COND_EXPR with
4124 factor_out_conditional_conversion.
4126 For example:
4127 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4128 <bb 3>:
4129 tmp = (int) a;
4130 <bb 4>:
4131 tmp = PHI <tmp, CST>
4133 Into:
4134 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4135 <bb 3>:
4136 <bb 4>:
4137 a = PHI <a, CST>
4138 tmp = (int) a;
4140 Adjacent Load Hoisting
4141 ----------------------
4143 This transformation replaces
4145 bb0:
4146 if (...) goto bb2; else goto bb1;
4147 bb1:
4148 x1 = (<expr>).field1;
4149 goto bb3;
4150 bb2:
4151 x2 = (<expr>).field2;
4152 bb3:
4153 # x = PHI <x1, x2>;
4155 with
4157 bb0:
4158 x1 = (<expr>).field1;
4159 x2 = (<expr>).field2;
4160 if (...) goto bb2; else goto bb1;
4161 bb1:
4162 goto bb3;
4163 bb2:
4164 bb3:
4165 # x = PHI <x1, x2>;
4167 The purpose of this transformation is to enable generation of conditional
4168 move instructions such as Intel CMOVE or PowerPC ISEL. Because one of
4169 the loads is speculative, the transformation is restricted to very
4170 specific cases to avoid introducing a page fault. We are looking for
4171 the common idiom:
4173 if (...)
4174 x = y->left;
4175 else
4176 x = y->right;
4178 where left and right are typically adjacent pointers in a tree structure. */
4180 namespace {
4182 const pass_data pass_data_phiopt =
4184 GIMPLE_PASS, /* type */
4185 "phiopt", /* name */
4186 OPTGROUP_NONE, /* optinfo_flags */
4187 TV_TREE_PHIOPT, /* tv_id */
4188 ( PROP_cfg | PROP_ssa ), /* properties_required */
4189 0, /* properties_provided */
4190 0, /* properties_destroyed */
4191 0, /* todo_flags_start */
4192 0, /* todo_flags_finish */
4195 class pass_phiopt : public gimple_opt_pass
4197 public:
4198 pass_phiopt (gcc::context *ctxt)
4199 : gimple_opt_pass (pass_data_phiopt, ctxt), early_p (false)
4202 /* opt_pass methods: */
4203 opt_pass * clone () final override { return new pass_phiopt (m_ctxt); }
4204 void set_pass_param (unsigned n, bool param) final override
4206 gcc_assert (n == 0);
4207 early_p = param;
4209 bool gate (function *) final override { return flag_ssa_phiopt; }
4210 unsigned int execute (function *) final override
4212 return tree_ssa_phiopt_worker (false,
4213 !early_p ? gate_hoist_loads () : false,
4214 early_p);
4217 private:
4218 bool early_p;
4219 }; // class pass_phiopt
4221 } // anon namespace
4223 gimple_opt_pass *
4224 make_pass_phiopt (gcc::context *ctxt)
4226 return new pass_phiopt (ctxt);
4229 namespace {
4231 const pass_data pass_data_cselim =
4233 GIMPLE_PASS, /* type */
4234 "cselim", /* name */
4235 OPTGROUP_NONE, /* optinfo_flags */
4236 TV_TREE_PHIOPT, /* tv_id */
4237 ( PROP_cfg | PROP_ssa ), /* properties_required */
4238 0, /* properties_provided */
4239 0, /* properties_destroyed */
4240 0, /* todo_flags_start */
4241 0, /* todo_flags_finish */
4244 class pass_cselim : public gimple_opt_pass
4246 public:
4247 pass_cselim (gcc::context *ctxt)
4248 : gimple_opt_pass (pass_data_cselim, ctxt)
4251 /* opt_pass methods: */
4252 bool gate (function *) final override { return flag_tree_cselim; }
4253 unsigned int execute (function *) final override
4255 return tree_ssa_cs_elim ();
4258 }; // class pass_cselim
4260 } // anon namespace
4262 gimple_opt_pass *
4263 make_pass_cselim (gcc::context *ctxt)
4265 return new pass_cselim (ctxt);