re PR middle-end/78153 (strlen return value can be assumed to be less than PTRDIFF_MAX)
[official-gcc.git] / gcc / gimple-fold.c
blob684230161187dc3791f92878e900906b7eed47f3
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2016 Free Software Foundation, Inc.
3 Split out from tree-ssa-ccp.c.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "fold-const.h"
34 #include "stmt.h"
35 #include "expr.h"
36 #include "stor-layout.h"
37 #include "dumpfile.h"
38 #include "gimple-fold.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-into-ssa.h"
42 #include "tree-dfa.h"
43 #include "tree-ssa.h"
44 #include "tree-ssa-propagate.h"
45 #include "ipa-utils.h"
46 #include "tree-ssa-address.h"
47 #include "langhooks.h"
48 #include "gimplify-me.h"
49 #include "dbgcnt.h"
50 #include "builtins.h"
51 #include "tree-eh.h"
52 #include "gimple-match.h"
53 #include "gomp-constants.h"
54 #include "optabs-query.h"
55 #include "omp-low.h"
56 #include "ipa-chkp.h"
57 #include "tree-cfg.h"
58 #include "fold-const-call.h"
60 /* Return true when DECL can be referenced from current unit.
61 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
62 We can get declarations that are not possible to reference for various
63 reasons:
65 1) When analyzing C++ virtual tables.
66 C++ virtual tables do have known constructors even
67 when they are keyed to other compilation unit.
68 Those tables can contain pointers to methods and vars
69 in other units. Those methods have both STATIC and EXTERNAL
70 set.
71 2) In WHOPR mode devirtualization might lead to reference
72 to method that was partitioned elsehwere.
73 In this case we have static VAR_DECL or FUNCTION_DECL
74 that has no corresponding callgraph/varpool node
75 declaring the body.
76 3) COMDAT functions referred by external vtables that
77 we devirtualize only during final compilation stage.
78 At this time we already decided that we will not output
79 the function body and thus we can't reference the symbol
80 directly. */
82 static bool
83 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
85 varpool_node *vnode;
86 struct cgraph_node *node;
87 symtab_node *snode;
89 if (DECL_ABSTRACT_P (decl))
90 return false;
92 /* We are concerned only about static/external vars and functions. */
93 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
94 || !VAR_OR_FUNCTION_DECL_P (decl))
95 return true;
97 /* Static objects can be referred only if they was not optimized out yet. */
98 if (!TREE_PUBLIC (decl) && !DECL_EXTERNAL (decl))
100 /* Before we start optimizing unreachable code we can be sure all
101 static objects are defined. */
102 if (symtab->function_flags_ready)
103 return true;
104 snode = symtab_node::get (decl);
105 if (!snode || !snode->definition)
106 return false;
107 node = dyn_cast <cgraph_node *> (snode);
108 return !node || !node->global.inlined_to;
111 /* We will later output the initializer, so we can refer to it.
112 So we are concerned only when DECL comes from initializer of
113 external var or var that has been optimized out. */
114 if (!from_decl
115 || !VAR_P (from_decl)
116 || (!DECL_EXTERNAL (from_decl)
117 && (vnode = varpool_node::get (from_decl)) != NULL
118 && vnode->definition)
119 || (flag_ltrans
120 && (vnode = varpool_node::get (from_decl)) != NULL
121 && vnode->in_other_partition))
122 return true;
123 /* We are folding reference from external vtable. The vtable may reffer
124 to a symbol keyed to other compilation unit. The other compilation
125 unit may be in separate DSO and the symbol may be hidden. */
126 if (DECL_VISIBILITY_SPECIFIED (decl)
127 && DECL_EXTERNAL (decl)
128 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
129 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
130 return false;
131 /* When function is public, we always can introduce new reference.
132 Exception are the COMDAT functions where introducing a direct
133 reference imply need to include function body in the curren tunit. */
134 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
135 return true;
136 /* We have COMDAT. We are going to check if we still have definition
137 or if the definition is going to be output in other partition.
138 Bypass this when gimplifying; all needed functions will be produced.
140 As observed in PR20991 for already optimized out comdat virtual functions
141 it may be tempting to not necessarily give up because the copy will be
142 output elsewhere when corresponding vtable is output.
143 This is however not possible - ABI specify that COMDATs are output in
144 units where they are used and when the other unit was compiled with LTO
145 it is possible that vtable was kept public while the function itself
146 was privatized. */
147 if (!symtab->function_flags_ready)
148 return true;
150 snode = symtab_node::get (decl);
151 if (!snode
152 || ((!snode->definition || DECL_EXTERNAL (decl))
153 && (!snode->in_other_partition
154 || (!snode->forced_by_abi && !snode->force_output))))
155 return false;
156 node = dyn_cast <cgraph_node *> (snode);
157 return !node || !node->global.inlined_to;
160 /* Create a temporary for TYPE for a statement STMT. If the current function
161 is in SSA form, a SSA name is created. Otherwise a temporary register
162 is made. */
164 static tree
165 create_tmp_reg_or_ssa_name (tree type, gimple *stmt = NULL)
167 if (gimple_in_ssa_p (cfun))
168 return make_ssa_name (type, stmt);
169 else
170 return create_tmp_reg (type);
173 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
174 acceptable form for is_gimple_min_invariant.
175 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
177 tree
178 canonicalize_constructor_val (tree cval, tree from_decl)
180 tree orig_cval = cval;
181 STRIP_NOPS (cval);
182 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
183 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
185 tree ptr = TREE_OPERAND (cval, 0);
186 if (is_gimple_min_invariant (ptr))
187 cval = build1_loc (EXPR_LOCATION (cval),
188 ADDR_EXPR, TREE_TYPE (ptr),
189 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
190 ptr,
191 fold_convert (ptr_type_node,
192 TREE_OPERAND (cval, 1))));
194 if (TREE_CODE (cval) == ADDR_EXPR)
196 tree base = NULL_TREE;
197 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
199 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
200 if (base)
201 TREE_OPERAND (cval, 0) = base;
203 else
204 base = get_base_address (TREE_OPERAND (cval, 0));
205 if (!base)
206 return NULL_TREE;
208 if (VAR_OR_FUNCTION_DECL_P (base)
209 && !can_refer_decl_in_current_unit_p (base, from_decl))
210 return NULL_TREE;
211 if (TREE_TYPE (base) == error_mark_node)
212 return NULL_TREE;
213 if (VAR_P (base))
214 TREE_ADDRESSABLE (base) = 1;
215 else if (TREE_CODE (base) == FUNCTION_DECL)
217 /* Make sure we create a cgraph node for functions we'll reference.
218 They can be non-existent if the reference comes from an entry
219 of an external vtable for example. */
220 cgraph_node::get_create (base);
222 /* Fixup types in global initializers. */
223 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
224 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
226 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
227 cval = fold_convert (TREE_TYPE (orig_cval), cval);
228 return cval;
230 if (TREE_OVERFLOW_P (cval))
231 return drop_tree_overflow (cval);
232 return orig_cval;
235 /* If SYM is a constant variable with known value, return the value.
236 NULL_TREE is returned otherwise. */
238 tree
239 get_symbol_constant_value (tree sym)
241 tree val = ctor_for_folding (sym);
242 if (val != error_mark_node)
244 if (val)
246 val = canonicalize_constructor_val (unshare_expr (val), sym);
247 if (val && is_gimple_min_invariant (val))
248 return val;
249 else
250 return NULL_TREE;
252 /* Variables declared 'const' without an initializer
253 have zero as the initializer if they may not be
254 overridden at link or run time. */
255 if (!val
256 && is_gimple_reg_type (TREE_TYPE (sym)))
257 return build_zero_cst (TREE_TYPE (sym));
260 return NULL_TREE;
265 /* Subroutine of fold_stmt. We perform several simplifications of the
266 memory reference tree EXPR and make sure to re-gimplify them properly
267 after propagation of constant addresses. IS_LHS is true if the
268 reference is supposed to be an lvalue. */
270 static tree
271 maybe_fold_reference (tree expr, bool is_lhs)
273 tree result;
275 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
276 || TREE_CODE (expr) == REALPART_EXPR
277 || TREE_CODE (expr) == IMAGPART_EXPR)
278 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
279 return fold_unary_loc (EXPR_LOCATION (expr),
280 TREE_CODE (expr),
281 TREE_TYPE (expr),
282 TREE_OPERAND (expr, 0));
283 else if (TREE_CODE (expr) == BIT_FIELD_REF
284 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
285 return fold_ternary_loc (EXPR_LOCATION (expr),
286 TREE_CODE (expr),
287 TREE_TYPE (expr),
288 TREE_OPERAND (expr, 0),
289 TREE_OPERAND (expr, 1),
290 TREE_OPERAND (expr, 2));
292 if (!is_lhs
293 && (result = fold_const_aggregate_ref (expr))
294 && is_gimple_min_invariant (result))
295 return result;
297 return NULL_TREE;
301 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
302 replacement rhs for the statement or NULL_TREE if no simplification
303 could be made. It is assumed that the operands have been previously
304 folded. */
306 static tree
307 fold_gimple_assign (gimple_stmt_iterator *si)
309 gimple *stmt = gsi_stmt (*si);
310 enum tree_code subcode = gimple_assign_rhs_code (stmt);
311 location_t loc = gimple_location (stmt);
313 tree result = NULL_TREE;
315 switch (get_gimple_rhs_class (subcode))
317 case GIMPLE_SINGLE_RHS:
319 tree rhs = gimple_assign_rhs1 (stmt);
321 if (TREE_CLOBBER_P (rhs))
322 return NULL_TREE;
324 if (REFERENCE_CLASS_P (rhs))
325 return maybe_fold_reference (rhs, false);
327 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
329 tree val = OBJ_TYPE_REF_EXPR (rhs);
330 if (is_gimple_min_invariant (val))
331 return val;
332 else if (flag_devirtualize && virtual_method_call_p (rhs))
334 bool final;
335 vec <cgraph_node *>targets
336 = possible_polymorphic_call_targets (rhs, stmt, &final);
337 if (final && targets.length () <= 1 && dbg_cnt (devirt))
339 if (dump_enabled_p ())
341 location_t loc = gimple_location_safe (stmt);
342 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
343 "resolving virtual function address "
344 "reference to function %s\n",
345 targets.length () == 1
346 ? targets[0]->name ()
347 : "NULL");
349 if (targets.length () == 1)
351 val = fold_convert (TREE_TYPE (val),
352 build_fold_addr_expr_loc
353 (loc, targets[0]->decl));
354 STRIP_USELESS_TYPE_CONVERSION (val);
356 else
357 /* We can not use __builtin_unreachable here because it
358 can not have address taken. */
359 val = build_int_cst (TREE_TYPE (val), 0);
360 return val;
365 else if (TREE_CODE (rhs) == ADDR_EXPR)
367 tree ref = TREE_OPERAND (rhs, 0);
368 tree tem = maybe_fold_reference (ref, true);
369 if (tem
370 && TREE_CODE (tem) == MEM_REF
371 && integer_zerop (TREE_OPERAND (tem, 1)))
372 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (tem, 0));
373 else if (tem)
374 result = fold_convert (TREE_TYPE (rhs),
375 build_fold_addr_expr_loc (loc, tem));
376 else if (TREE_CODE (ref) == MEM_REF
377 && integer_zerop (TREE_OPERAND (ref, 1)))
378 result = fold_convert (TREE_TYPE (rhs), TREE_OPERAND (ref, 0));
380 if (result)
382 /* Strip away useless type conversions. Both the
383 NON_LVALUE_EXPR that may have been added by fold, and
384 "useless" type conversions that might now be apparent
385 due to propagation. */
386 STRIP_USELESS_TYPE_CONVERSION (result);
388 if (result != rhs && valid_gimple_rhs_p (result))
389 return result;
393 else if (TREE_CODE (rhs) == CONSTRUCTOR
394 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
396 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
397 unsigned i;
398 tree val;
400 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
401 if (! CONSTANT_CLASS_P (val))
402 return NULL_TREE;
404 return build_vector_from_ctor (TREE_TYPE (rhs),
405 CONSTRUCTOR_ELTS (rhs));
408 else if (DECL_P (rhs))
409 return get_symbol_constant_value (rhs);
411 break;
413 case GIMPLE_UNARY_RHS:
414 break;
416 case GIMPLE_BINARY_RHS:
417 break;
419 case GIMPLE_TERNARY_RHS:
420 result = fold_ternary_loc (loc, subcode,
421 TREE_TYPE (gimple_assign_lhs (stmt)),
422 gimple_assign_rhs1 (stmt),
423 gimple_assign_rhs2 (stmt),
424 gimple_assign_rhs3 (stmt));
426 if (result)
428 STRIP_USELESS_TYPE_CONVERSION (result);
429 if (valid_gimple_rhs_p (result))
430 return result;
432 break;
434 case GIMPLE_INVALID_RHS:
435 gcc_unreachable ();
438 return NULL_TREE;
442 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
443 adjusting the replacement stmts location and virtual operands.
444 If the statement has a lhs the last stmt in the sequence is expected
445 to assign to that lhs. */
447 static void
448 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
450 gimple *stmt = gsi_stmt (*si_p);
452 if (gimple_has_location (stmt))
453 annotate_all_with_location (stmts, gimple_location (stmt));
455 /* First iterate over the replacement statements backward, assigning
456 virtual operands to their defining statements. */
457 gimple *laststore = NULL;
458 for (gimple_stmt_iterator i = gsi_last (stmts);
459 !gsi_end_p (i); gsi_prev (&i))
461 gimple *new_stmt = gsi_stmt (i);
462 if ((gimple_assign_single_p (new_stmt)
463 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
464 || (is_gimple_call (new_stmt)
465 && (gimple_call_flags (new_stmt)
466 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
468 tree vdef;
469 if (!laststore)
470 vdef = gimple_vdef (stmt);
471 else
472 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
473 gimple_set_vdef (new_stmt, vdef);
474 if (vdef && TREE_CODE (vdef) == SSA_NAME)
475 SSA_NAME_DEF_STMT (vdef) = new_stmt;
476 laststore = new_stmt;
480 /* Second iterate over the statements forward, assigning virtual
481 operands to their uses. */
482 tree reaching_vuse = gimple_vuse (stmt);
483 for (gimple_stmt_iterator i = gsi_start (stmts);
484 !gsi_end_p (i); gsi_next (&i))
486 gimple *new_stmt = gsi_stmt (i);
487 /* If the new statement possibly has a VUSE, update it with exact SSA
488 name we know will reach this one. */
489 if (gimple_has_mem_ops (new_stmt))
490 gimple_set_vuse (new_stmt, reaching_vuse);
491 gimple_set_modified (new_stmt, true);
492 if (gimple_vdef (new_stmt))
493 reaching_vuse = gimple_vdef (new_stmt);
496 /* If the new sequence does not do a store release the virtual
497 definition of the original statement. */
498 if (reaching_vuse
499 && reaching_vuse == gimple_vuse (stmt))
501 tree vdef = gimple_vdef (stmt);
502 if (vdef
503 && TREE_CODE (vdef) == SSA_NAME)
505 unlink_stmt_vdef (stmt);
506 release_ssa_name (vdef);
510 /* Finally replace the original statement with the sequence. */
511 gsi_replace_with_seq (si_p, stmts, false);
514 /* Convert EXPR into a GIMPLE value suitable for substitution on the
515 RHS of an assignment. Insert the necessary statements before
516 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
517 is replaced. If the call is expected to produces a result, then it
518 is replaced by an assignment of the new RHS to the result variable.
519 If the result is to be ignored, then the call is replaced by a
520 GIMPLE_NOP. A proper VDEF chain is retained by making the first
521 VUSE and the last VDEF of the whole sequence be the same as the replaced
522 statement and using new SSA names for stores in between. */
524 void
525 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
527 tree lhs;
528 gimple *stmt, *new_stmt;
529 gimple_stmt_iterator i;
530 gimple_seq stmts = NULL;
532 stmt = gsi_stmt (*si_p);
534 gcc_assert (is_gimple_call (stmt));
536 push_gimplify_context (gimple_in_ssa_p (cfun));
538 lhs = gimple_call_lhs (stmt);
539 if (lhs == NULL_TREE)
541 gimplify_and_add (expr, &stmts);
542 /* We can end up with folding a memcpy of an empty class assignment
543 which gets optimized away by C++ gimplification. */
544 if (gimple_seq_empty_p (stmts))
546 pop_gimplify_context (NULL);
547 if (gimple_in_ssa_p (cfun))
549 unlink_stmt_vdef (stmt);
550 release_defs (stmt);
552 gsi_replace (si_p, gimple_build_nop (), false);
553 return;
556 else
558 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
559 new_stmt = gimple_build_assign (lhs, tmp);
560 i = gsi_last (stmts);
561 gsi_insert_after_without_update (&i, new_stmt,
562 GSI_CONTINUE_LINKING);
565 pop_gimplify_context (NULL);
567 gsi_replace_with_seq_vops (si_p, stmts);
571 /* Replace the call at *GSI with the gimple value VAL. */
573 static void
574 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
576 gimple *stmt = gsi_stmt (*gsi);
577 tree lhs = gimple_call_lhs (stmt);
578 gimple *repl;
579 if (lhs)
581 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
582 val = fold_convert (TREE_TYPE (lhs), val);
583 repl = gimple_build_assign (lhs, val);
585 else
586 repl = gimple_build_nop ();
587 tree vdef = gimple_vdef (stmt);
588 if (vdef && TREE_CODE (vdef) == SSA_NAME)
590 unlink_stmt_vdef (stmt);
591 release_ssa_name (vdef);
593 gsi_replace (gsi, repl, false);
596 /* Replace the call at *GSI with the new call REPL and fold that
597 again. */
599 static void
600 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
602 gimple *stmt = gsi_stmt (*gsi);
603 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
604 gimple_set_location (repl, gimple_location (stmt));
605 if (gimple_vdef (stmt)
606 && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
608 gimple_set_vdef (repl, gimple_vdef (stmt));
609 gimple_set_vuse (repl, gimple_vuse (stmt));
610 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
612 gsi_replace (gsi, repl, false);
613 fold_stmt (gsi);
616 /* Return true if VAR is a VAR_DECL or a component thereof. */
618 static bool
619 var_decl_component_p (tree var)
621 tree inner = var;
622 while (handled_component_p (inner))
623 inner = TREE_OPERAND (inner, 0);
624 return SSA_VAR_P (inner);
627 /* Fold function call to builtin mem{{,p}cpy,move}. Return
628 false if no simplification can be made.
629 If ENDP is 0, return DEST (like memcpy).
630 If ENDP is 1, return DEST+LEN (like mempcpy).
631 If ENDP is 2, return DEST+LEN-1 (like stpcpy).
632 If ENDP is 3, return DEST, additionally *SRC and *DEST may overlap
633 (memmove). */
635 static bool
636 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
637 tree dest, tree src, int endp)
639 gimple *stmt = gsi_stmt (*gsi);
640 tree lhs = gimple_call_lhs (stmt);
641 tree len = gimple_call_arg (stmt, 2);
642 tree destvar, srcvar;
643 location_t loc = gimple_location (stmt);
645 /* If the LEN parameter is zero, return DEST. */
646 if (integer_zerop (len))
648 gimple *repl;
649 if (gimple_call_lhs (stmt))
650 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
651 else
652 repl = gimple_build_nop ();
653 tree vdef = gimple_vdef (stmt);
654 if (vdef && TREE_CODE (vdef) == SSA_NAME)
656 unlink_stmt_vdef (stmt);
657 release_ssa_name (vdef);
659 gsi_replace (gsi, repl, false);
660 return true;
663 /* If SRC and DEST are the same (and not volatile), return
664 DEST{,+LEN,+LEN-1}. */
665 if (operand_equal_p (src, dest, 0))
667 unlink_stmt_vdef (stmt);
668 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
669 release_ssa_name (gimple_vdef (stmt));
670 if (!lhs)
672 gsi_replace (gsi, gimple_build_nop (), false);
673 return true;
675 goto done;
677 else
679 tree srctype, desttype;
680 unsigned int src_align, dest_align;
681 tree off0;
683 /* Inlining of memcpy/memmove may cause bounds lost (if we copy
684 pointers as wide integer) and also may result in huge function
685 size because of inlined bounds copy. Thus don't inline for
686 functions we want to instrument. */
687 if (flag_check_pointer_bounds
688 && chkp_instrumentable_p (cfun->decl)
689 /* Even if data may contain pointers we can inline if copy
690 less than a pointer size. */
691 && (!tree_fits_uhwi_p (len)
692 || compare_tree_int (len, POINTER_SIZE_UNITS) >= 0))
693 return false;
695 /* Build accesses at offset zero with a ref-all character type. */
696 off0 = build_int_cst (build_pointer_type_for_mode (char_type_node,
697 ptr_mode, true), 0);
699 /* If we can perform the copy efficiently with first doing all loads
700 and then all stores inline it that way. Currently efficiently
701 means that we can load all the memory into a single integer
702 register which is what MOVE_MAX gives us. */
703 src_align = get_pointer_alignment (src);
704 dest_align = get_pointer_alignment (dest);
705 if (tree_fits_uhwi_p (len)
706 && compare_tree_int (len, MOVE_MAX) <= 0
707 /* ??? Don't transform copies from strings with known length this
708 confuses the tree-ssa-strlen.c. This doesn't handle
709 the case in gcc.dg/strlenopt-8.c which is XFAILed for that
710 reason. */
711 && !c_strlen (src, 2))
713 unsigned ilen = tree_to_uhwi (len);
714 if (pow2p_hwi (ilen))
716 tree type = lang_hooks.types.type_for_size (ilen * 8, 1);
717 if (type
718 && TYPE_MODE (type) != BLKmode
719 && (GET_MODE_SIZE (TYPE_MODE (type)) * BITS_PER_UNIT
720 == ilen * 8)
721 /* If the destination pointer is not aligned we must be able
722 to emit an unaligned store. */
723 && (dest_align >= GET_MODE_ALIGNMENT (TYPE_MODE (type))
724 || !SLOW_UNALIGNED_ACCESS (TYPE_MODE (type), dest_align)
725 || (optab_handler (movmisalign_optab, TYPE_MODE (type))
726 != CODE_FOR_nothing)))
728 tree srctype = type;
729 tree desttype = type;
730 if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
731 srctype = build_aligned_type (type, src_align);
732 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
733 tree tem = fold_const_aggregate_ref (srcmem);
734 if (tem)
735 srcmem = tem;
736 else if (src_align < GET_MODE_ALIGNMENT (TYPE_MODE (type))
737 && SLOW_UNALIGNED_ACCESS (TYPE_MODE (type),
738 src_align)
739 && (optab_handler (movmisalign_optab,
740 TYPE_MODE (type))
741 == CODE_FOR_nothing))
742 srcmem = NULL_TREE;
743 if (srcmem)
745 gimple *new_stmt;
746 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
748 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
749 srcmem
750 = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
751 new_stmt);
752 gimple_assign_set_lhs (new_stmt, srcmem);
753 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
754 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
756 if (dest_align < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
757 desttype = build_aligned_type (type, dest_align);
758 new_stmt
759 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
760 dest, off0),
761 srcmem);
762 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
763 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
764 if (gimple_vdef (new_stmt)
765 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
766 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
767 if (!lhs)
769 gsi_replace (gsi, new_stmt, false);
770 return true;
772 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
773 goto done;
779 if (endp == 3)
781 /* Both DEST and SRC must be pointer types.
782 ??? This is what old code did. Is the testing for pointer types
783 really mandatory?
785 If either SRC is readonly or length is 1, we can use memcpy. */
786 if (!dest_align || !src_align)
787 return false;
788 if (readonly_data_expr (src)
789 || (tree_fits_uhwi_p (len)
790 && (MIN (src_align, dest_align) / BITS_PER_UNIT
791 >= tree_to_uhwi (len))))
793 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
794 if (!fn)
795 return false;
796 gimple_call_set_fndecl (stmt, fn);
797 gimple_call_set_arg (stmt, 0, dest);
798 gimple_call_set_arg (stmt, 1, src);
799 fold_stmt (gsi);
800 return true;
803 /* If *src and *dest can't overlap, optimize into memcpy as well. */
804 if (TREE_CODE (src) == ADDR_EXPR
805 && TREE_CODE (dest) == ADDR_EXPR)
807 tree src_base, dest_base, fn;
808 HOST_WIDE_INT src_offset = 0, dest_offset = 0;
809 HOST_WIDE_INT maxsize;
811 srcvar = TREE_OPERAND (src, 0);
812 src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
813 if (src_base == NULL)
814 src_base = srcvar;
815 destvar = TREE_OPERAND (dest, 0);
816 dest_base = get_addr_base_and_unit_offset (destvar,
817 &dest_offset);
818 if (dest_base == NULL)
819 dest_base = destvar;
820 if (tree_fits_uhwi_p (len))
821 maxsize = tree_to_uhwi (len);
822 else
823 maxsize = -1;
824 if (SSA_VAR_P (src_base)
825 && SSA_VAR_P (dest_base))
827 if (operand_equal_p (src_base, dest_base, 0)
828 && ranges_overlap_p (src_offset, maxsize,
829 dest_offset, maxsize))
830 return false;
832 else if (TREE_CODE (src_base) == MEM_REF
833 && TREE_CODE (dest_base) == MEM_REF)
835 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
836 TREE_OPERAND (dest_base, 0), 0))
837 return false;
838 offset_int off = mem_ref_offset (src_base) + src_offset;
839 if (!wi::fits_shwi_p (off))
840 return false;
841 src_offset = off.to_shwi ();
843 off = mem_ref_offset (dest_base) + dest_offset;
844 if (!wi::fits_shwi_p (off))
845 return false;
846 dest_offset = off.to_shwi ();
847 if (ranges_overlap_p (src_offset, maxsize,
848 dest_offset, maxsize))
849 return false;
851 else
852 return false;
854 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
855 if (!fn)
856 return false;
857 gimple_call_set_fndecl (stmt, fn);
858 gimple_call_set_arg (stmt, 0, dest);
859 gimple_call_set_arg (stmt, 1, src);
860 fold_stmt (gsi);
861 return true;
864 /* If the destination and source do not alias optimize into
865 memcpy as well. */
866 if ((is_gimple_min_invariant (dest)
867 || TREE_CODE (dest) == SSA_NAME)
868 && (is_gimple_min_invariant (src)
869 || TREE_CODE (src) == SSA_NAME))
871 ao_ref destr, srcr;
872 ao_ref_init_from_ptr_and_size (&destr, dest, len);
873 ao_ref_init_from_ptr_and_size (&srcr, src, len);
874 if (!refs_may_alias_p_1 (&destr, &srcr, false))
876 tree fn;
877 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
878 if (!fn)
879 return false;
880 gimple_call_set_fndecl (stmt, fn);
881 gimple_call_set_arg (stmt, 0, dest);
882 gimple_call_set_arg (stmt, 1, src);
883 fold_stmt (gsi);
884 return true;
888 return false;
891 if (!tree_fits_shwi_p (len))
892 return false;
893 /* FIXME:
894 This logic lose for arguments like (type *)malloc (sizeof (type)),
895 since we strip the casts of up to VOID return value from malloc.
896 Perhaps we ought to inherit type from non-VOID argument here? */
897 STRIP_NOPS (src);
898 STRIP_NOPS (dest);
899 if (!POINTER_TYPE_P (TREE_TYPE (src))
900 || !POINTER_TYPE_P (TREE_TYPE (dest)))
901 return false;
902 /* In the following try to find a type that is most natural to be
903 used for the memcpy source and destination and that allows
904 the most optimization when memcpy is turned into a plain assignment
905 using that type. In theory we could always use a char[len] type
906 but that only gains us that the destination and source possibly
907 no longer will have their address taken. */
908 /* As we fold (void *)(p + CST) to (void *)p + CST undo this here. */
909 if (TREE_CODE (src) == POINTER_PLUS_EXPR)
911 tree tem = TREE_OPERAND (src, 0);
912 STRIP_NOPS (tem);
913 if (tem != TREE_OPERAND (src, 0))
914 src = build1 (NOP_EXPR, TREE_TYPE (tem), src);
916 if (TREE_CODE (dest) == POINTER_PLUS_EXPR)
918 tree tem = TREE_OPERAND (dest, 0);
919 STRIP_NOPS (tem);
920 if (tem != TREE_OPERAND (dest, 0))
921 dest = build1 (NOP_EXPR, TREE_TYPE (tem), dest);
923 srctype = TREE_TYPE (TREE_TYPE (src));
924 if (TREE_CODE (srctype) == ARRAY_TYPE
925 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
927 srctype = TREE_TYPE (srctype);
928 STRIP_NOPS (src);
929 src = build1 (NOP_EXPR, build_pointer_type (srctype), src);
931 desttype = TREE_TYPE (TREE_TYPE (dest));
932 if (TREE_CODE (desttype) == ARRAY_TYPE
933 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
935 desttype = TREE_TYPE (desttype);
936 STRIP_NOPS (dest);
937 dest = build1 (NOP_EXPR, build_pointer_type (desttype), dest);
939 if (TREE_ADDRESSABLE (srctype)
940 || TREE_ADDRESSABLE (desttype))
941 return false;
943 /* Make sure we are not copying using a floating-point mode or
944 a type whose size possibly does not match its precision. */
945 if (FLOAT_MODE_P (TYPE_MODE (desttype))
946 || TREE_CODE (desttype) == BOOLEAN_TYPE
947 || TREE_CODE (desttype) == ENUMERAL_TYPE)
948 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
949 if (FLOAT_MODE_P (TYPE_MODE (srctype))
950 || TREE_CODE (srctype) == BOOLEAN_TYPE
951 || TREE_CODE (srctype) == ENUMERAL_TYPE)
952 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
953 if (!srctype)
954 srctype = desttype;
955 if (!desttype)
956 desttype = srctype;
957 if (!srctype)
958 return false;
960 src_align = get_pointer_alignment (src);
961 dest_align = get_pointer_alignment (dest);
962 if (dest_align < TYPE_ALIGN (desttype)
963 || src_align < TYPE_ALIGN (srctype))
964 return false;
966 destvar = dest;
967 STRIP_NOPS (destvar);
968 if (TREE_CODE (destvar) == ADDR_EXPR
969 && var_decl_component_p (TREE_OPERAND (destvar, 0))
970 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
971 destvar = fold_build2 (MEM_REF, desttype, destvar, off0);
972 else
973 destvar = NULL_TREE;
975 srcvar = src;
976 STRIP_NOPS (srcvar);
977 if (TREE_CODE (srcvar) == ADDR_EXPR
978 && var_decl_component_p (TREE_OPERAND (srcvar, 0))
979 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
981 if (!destvar
982 || src_align >= TYPE_ALIGN (desttype))
983 srcvar = fold_build2 (MEM_REF, destvar ? desttype : srctype,
984 srcvar, off0);
985 else if (!STRICT_ALIGNMENT)
987 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
988 src_align);
989 srcvar = fold_build2 (MEM_REF, srctype, srcvar, off0);
991 else
992 srcvar = NULL_TREE;
994 else
995 srcvar = NULL_TREE;
997 if (srcvar == NULL_TREE && destvar == NULL_TREE)
998 return false;
1000 if (srcvar == NULL_TREE)
1002 STRIP_NOPS (src);
1003 if (src_align >= TYPE_ALIGN (desttype))
1004 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1005 else
1007 if (STRICT_ALIGNMENT)
1008 return false;
1009 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1010 src_align);
1011 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1014 else if (destvar == NULL_TREE)
1016 STRIP_NOPS (dest);
1017 if (dest_align >= TYPE_ALIGN (srctype))
1018 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1019 else
1021 if (STRICT_ALIGNMENT)
1022 return false;
1023 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1024 dest_align);
1025 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1029 gimple *new_stmt;
1030 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1032 tree tem = fold_const_aggregate_ref (srcvar);
1033 if (tem)
1034 srcvar = tem;
1035 if (! is_gimple_min_invariant (srcvar))
1037 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1038 srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1039 new_stmt);
1040 gimple_assign_set_lhs (new_stmt, srcvar);
1041 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1042 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1045 new_stmt = gimple_build_assign (destvar, srcvar);
1046 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1047 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
1048 if (gimple_vdef (new_stmt)
1049 && TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
1050 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
1051 if (!lhs)
1053 gsi_replace (gsi, new_stmt, false);
1054 return true;
1056 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1059 done:
1060 gimple_seq stmts = NULL;
1061 if (endp == 0 || endp == 3)
1062 len = NULL_TREE;
1063 else if (endp == 2)
1064 len = gimple_build (&stmts, loc, MINUS_EXPR, TREE_TYPE (len), len,
1065 ssize_int (1));
1066 if (endp == 2 || endp == 1)
1068 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1069 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1070 TREE_TYPE (dest), dest, len);
1073 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1074 gimple *repl = gimple_build_assign (lhs, dest);
1075 gsi_replace (gsi, repl, false);
1076 return true;
1079 /* Fold function call to builtin memset or bzero at *GSI setting the
1080 memory of size LEN to VAL. Return whether a simplification was made. */
1082 static bool
1083 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1085 gimple *stmt = gsi_stmt (*gsi);
1086 tree etype;
1087 unsigned HOST_WIDE_INT length, cval;
1089 /* If the LEN parameter is zero, return DEST. */
1090 if (integer_zerop (len))
1092 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1093 return true;
1096 if (! tree_fits_uhwi_p (len))
1097 return false;
1099 if (TREE_CODE (c) != INTEGER_CST)
1100 return false;
1102 tree dest = gimple_call_arg (stmt, 0);
1103 tree var = dest;
1104 if (TREE_CODE (var) != ADDR_EXPR)
1105 return false;
1107 var = TREE_OPERAND (var, 0);
1108 if (TREE_THIS_VOLATILE (var))
1109 return false;
1111 etype = TREE_TYPE (var);
1112 if (TREE_CODE (etype) == ARRAY_TYPE)
1113 etype = TREE_TYPE (etype);
1115 if (!INTEGRAL_TYPE_P (etype)
1116 && !POINTER_TYPE_P (etype))
1117 return NULL_TREE;
1119 if (! var_decl_component_p (var))
1120 return NULL_TREE;
1122 length = tree_to_uhwi (len);
1123 if (GET_MODE_SIZE (TYPE_MODE (etype)) != length
1124 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1125 return NULL_TREE;
1127 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1128 return NULL_TREE;
1130 if (integer_zerop (c))
1131 cval = 0;
1132 else
1134 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1135 return NULL_TREE;
1137 cval = TREE_INT_CST_LOW (c);
1138 cval &= 0xff;
1139 cval |= cval << 8;
1140 cval |= cval << 16;
1141 cval |= (cval << 31) << 1;
1144 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1145 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1146 gimple_set_vuse (store, gimple_vuse (stmt));
1147 tree vdef = gimple_vdef (stmt);
1148 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1150 gimple_set_vdef (store, gimple_vdef (stmt));
1151 SSA_NAME_DEF_STMT (gimple_vdef (stmt)) = store;
1153 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1154 if (gimple_call_lhs (stmt))
1156 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1157 gsi_replace (gsi, asgn, false);
1159 else
1161 gimple_stmt_iterator gsi2 = *gsi;
1162 gsi_prev (gsi);
1163 gsi_remove (&gsi2, true);
1166 return true;
1170 /* Obtain the minimum and maximum string length or minimum and maximum
1171 value of ARG in LENGTH[0] and LENGTH[1], respectively.
1172 If ARG is an SSA name variable, follow its use-def chains. When
1173 TYPE == 0, if LENGTH[1] is not equal to the length we determine or
1174 if we are unable to determine the length or value, return False.
1175 VISITED is a bitmap of visited variables.
1176 TYPE is 0 if string length should be obtained, 1 for maximum string
1177 length and 2 for maximum value ARG can have.
1178 When FUZZY is set and the length of a string cannot be determined,
1179 the function instead considers as the maximum possible length the
1180 size of a character array it may refer to. */
1182 static bool
1183 get_range_strlen (tree arg, tree length[2], bitmap *visited, int type,
1184 bool fuzzy)
1186 tree var, val;
1187 gimple *def_stmt;
1189 /* The minimum and maximum length. The MAXLEN pointer stays unchanged
1190 but MINLEN may be cleared during the execution of the function. */
1191 tree *minlen = length;
1192 tree *const maxlen = length + 1;
1194 if (TREE_CODE (arg) != SSA_NAME)
1196 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1197 if (TREE_CODE (arg) == ADDR_EXPR
1198 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF
1199 && integer_zerop (TREE_OPERAND (TREE_OPERAND (arg, 0), 1)))
1201 tree aop0 = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1202 if (TREE_CODE (aop0) == INDIRECT_REF
1203 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1204 return get_range_strlen (TREE_OPERAND (aop0, 0),
1205 length, visited, type, fuzzy);
1208 if (type == 2)
1210 val = arg;
1211 if (TREE_CODE (val) != INTEGER_CST
1212 || tree_int_cst_sgn (val) < 0)
1213 return false;
1215 else
1216 val = c_strlen (arg, 1);
1218 if (!val && fuzzy)
1220 if (TREE_CODE (arg) == ADDR_EXPR)
1221 return get_range_strlen (TREE_OPERAND (arg, 0), length,
1222 visited, type, fuzzy);
1224 if (TREE_CODE (arg) == COMPONENT_REF
1225 && TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1))) == ARRAY_TYPE)
1227 /* Use the type of the member array to determine the upper
1228 bound on the length of the array. This may be overly
1229 optimistic if the array itself isn't NUL-terminated and
1230 the caller relies on the subsequent member to contain
1231 the NUL. */
1232 arg = TREE_OPERAND (arg, 1);
1233 val = TYPE_SIZE_UNIT (TREE_TYPE (arg));
1234 if (!val || integer_zerop (val))
1235 return false;
1236 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1237 integer_one_node);
1238 /* Avoid using the array size as the minimum. */
1239 minlen = NULL;
1243 if (!val)
1244 return false;
1246 if (minlen
1247 && (!*minlen
1248 || (type > 0
1249 && TREE_CODE (*minlen) == INTEGER_CST
1250 && TREE_CODE (val) == INTEGER_CST
1251 && tree_int_cst_lt (val, *minlen))))
1252 *minlen = val;
1254 if (*maxlen)
1256 if (type > 0)
1258 if (TREE_CODE (*maxlen) != INTEGER_CST
1259 || TREE_CODE (val) != INTEGER_CST)
1260 return false;
1262 if (tree_int_cst_lt (*maxlen, val))
1263 *maxlen = val;
1264 return true;
1266 else if (simple_cst_equal (val, *maxlen) != 1)
1267 return false;
1270 *maxlen = val;
1271 return true;
1274 /* If ARG is registered for SSA update we cannot look at its defining
1275 statement. */
1276 if (name_registered_for_update_p (arg))
1277 return false;
1279 /* If we were already here, break the infinite cycle. */
1280 if (!*visited)
1281 *visited = BITMAP_ALLOC (NULL);
1282 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (arg)))
1283 return true;
1285 var = arg;
1286 def_stmt = SSA_NAME_DEF_STMT (var);
1288 switch (gimple_code (def_stmt))
1290 case GIMPLE_ASSIGN:
1291 /* The RHS of the statement defining VAR must either have a
1292 constant length or come from another SSA_NAME with a constant
1293 length. */
1294 if (gimple_assign_single_p (def_stmt)
1295 || gimple_assign_unary_nop_p (def_stmt))
1297 tree rhs = gimple_assign_rhs1 (def_stmt);
1298 return get_range_strlen (rhs, length, visited, type, fuzzy);
1300 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
1302 tree op2 = gimple_assign_rhs2 (def_stmt);
1303 tree op3 = gimple_assign_rhs3 (def_stmt);
1304 return get_range_strlen (op2, length, visited, type, fuzzy)
1305 && get_range_strlen (op3, length, visited, type, fuzzy);
1307 return false;
1309 case GIMPLE_PHI:
1311 /* All the arguments of the PHI node must have the same constant
1312 length. */
1313 unsigned i;
1315 for (i = 0; i < gimple_phi_num_args (def_stmt); i++)
1317 tree arg = gimple_phi_arg (def_stmt, i)->def;
1319 /* If this PHI has itself as an argument, we cannot
1320 determine the string length of this argument. However,
1321 if we can find a constant string length for the other
1322 PHI args then we can still be sure that this is a
1323 constant string length. So be optimistic and just
1324 continue with the next argument. */
1325 if (arg == gimple_phi_result (def_stmt))
1326 continue;
1328 if (!get_range_strlen (arg, length, visited, type, fuzzy))
1330 if (fuzzy)
1331 *maxlen = build_all_ones_cst (size_type_node);
1332 else
1333 return false;
1337 return true;
1339 default:
1340 return false;
1344 /* Determine the minimum and maximum value or string length that ARG
1345 refers to and store each in the first two elements of MINMAXLEN.
1346 For expressions that point to strings of unknown lengths that are
1347 character arrays, use the upper bound of the array as the maximum
1348 length. For example, given an expression like 'x ? array : "xyz"'
1349 and array declared as 'char array[8]', MINMAXLEN[0] will be set
1350 to 3 and MINMAXLEN[1] to 7, the longest string that could be
1351 stored in array.
1354 void get_range_strlen (tree arg, tree minmaxlen[2])
1356 bitmap visited = NULL;
1358 minmaxlen[0] = NULL_TREE;
1359 minmaxlen[1] = NULL_TREE;
1361 get_range_strlen (arg, minmaxlen, &visited, 1, true);
1363 if (visited)
1364 BITMAP_FREE (visited);
1367 tree
1368 get_maxval_strlen (tree arg, int type)
1370 bitmap visited = NULL;
1371 tree len[2] = { NULL_TREE, NULL_TREE };
1372 if (!get_range_strlen (arg, len, &visited, type, false))
1373 len[1] = NULL_TREE;
1374 if (visited)
1375 BITMAP_FREE (visited);
1377 return len[1];
1381 /* Fold function call to builtin strcpy with arguments DEST and SRC.
1382 If LEN is not NULL, it represents the length of the string to be
1383 copied. Return NULL_TREE if no simplification can be made. */
1385 static bool
1386 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
1387 tree dest, tree src)
1389 location_t loc = gimple_location (gsi_stmt (*gsi));
1390 tree fn;
1392 /* If SRC and DEST are the same (and not volatile), return DEST. */
1393 if (operand_equal_p (src, dest, 0))
1395 replace_call_with_value (gsi, dest);
1396 return true;
1399 if (optimize_function_for_size_p (cfun))
1400 return false;
1402 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1403 if (!fn)
1404 return false;
1406 tree len = get_maxval_strlen (src, 0);
1407 if (!len)
1408 return false;
1410 len = fold_convert_loc (loc, size_type_node, len);
1411 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
1412 len = force_gimple_operand_gsi (gsi, len, true,
1413 NULL_TREE, true, GSI_SAME_STMT);
1414 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1415 replace_call_with_call_and_fold (gsi, repl);
1416 return true;
1419 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
1420 If SLEN is not NULL, it represents the length of the source string.
1421 Return NULL_TREE if no simplification can be made. */
1423 static bool
1424 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
1425 tree dest, tree src, tree len)
1427 location_t loc = gimple_location (gsi_stmt (*gsi));
1428 tree fn;
1430 /* If the LEN parameter is zero, return DEST. */
1431 if (integer_zerop (len))
1433 replace_call_with_value (gsi, dest);
1434 return true;
1437 /* We can't compare slen with len as constants below if len is not a
1438 constant. */
1439 if (TREE_CODE (len) != INTEGER_CST)
1440 return false;
1442 /* Now, we must be passed a constant src ptr parameter. */
1443 tree slen = get_maxval_strlen (src, 0);
1444 if (!slen || TREE_CODE (slen) != INTEGER_CST)
1445 return false;
1447 slen = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
1449 /* We do not support simplification of this case, though we do
1450 support it when expanding trees into RTL. */
1451 /* FIXME: generate a call to __builtin_memset. */
1452 if (tree_int_cst_lt (slen, len))
1453 return false;
1455 /* OK transform into builtin memcpy. */
1456 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1457 if (!fn)
1458 return false;
1460 len = fold_convert_loc (loc, size_type_node, len);
1461 len = force_gimple_operand_gsi (gsi, len, true,
1462 NULL_TREE, true, GSI_SAME_STMT);
1463 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1464 replace_call_with_call_and_fold (gsi, repl);
1465 return true;
1468 /* Fold function call to builtin strchr or strrchr.
1469 If both arguments are constant, evaluate and fold the result,
1470 otherwise simplify str(r)chr (str, 0) into str + strlen (str).
1471 In general strlen is significantly faster than strchr
1472 due to being a simpler operation. */
1473 static bool
1474 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
1476 gimple *stmt = gsi_stmt (*gsi);
1477 tree str = gimple_call_arg (stmt, 0);
1478 tree c = gimple_call_arg (stmt, 1);
1479 location_t loc = gimple_location (stmt);
1480 const char *p;
1481 char ch;
1483 if (!gimple_call_lhs (stmt))
1484 return false;
1486 if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
1488 const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
1490 if (p1 == NULL)
1492 replace_call_with_value (gsi, integer_zero_node);
1493 return true;
1496 tree len = build_int_cst (size_type_node, p1 - p);
1497 gimple_seq stmts = NULL;
1498 gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1499 POINTER_PLUS_EXPR, str, len);
1500 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1501 gsi_replace_with_seq_vops (gsi, stmts);
1502 return true;
1505 if (!integer_zerop (c))
1506 return false;
1508 /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size. */
1509 if (optimize_function_for_size_p (cfun))
1511 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
1513 if (is_strrchr && strchr_fn)
1515 gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
1516 replace_call_with_call_and_fold (gsi, repl);
1517 return true;
1520 return false;
1523 tree len;
1524 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1526 if (!strlen_fn)
1527 return false;
1529 /* Create newstr = strlen (str). */
1530 gimple_seq stmts = NULL;
1531 gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
1532 gimple_set_location (new_stmt, loc);
1533 len = create_tmp_reg_or_ssa_name (size_type_node);
1534 gimple_call_set_lhs (new_stmt, len);
1535 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1537 /* Create (str p+ strlen (str)). */
1538 new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
1539 POINTER_PLUS_EXPR, str, len);
1540 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
1541 gsi_replace_with_seq_vops (gsi, stmts);
1542 /* gsi now points at the assignment to the lhs, get a
1543 stmt iterator to the strlen.
1544 ??? We can't use gsi_for_stmt as that doesn't work when the
1545 CFG isn't built yet. */
1546 gimple_stmt_iterator gsi2 = *gsi;
1547 gsi_prev (&gsi2);
1548 fold_stmt (&gsi2);
1549 return true;
1552 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
1553 to the call.
1555 Return NULL_TREE if no simplification was possible, otherwise return the
1556 simplified form of the call as a tree.
1558 The simplified form may be a constant or other expression which
1559 computes the same value, but in a more efficient manner (including
1560 calls to other builtin functions).
1562 The call may contain arguments which need to be evaluated, but
1563 which are not useful to determine the result of the call. In
1564 this case we return a chain of COMPOUND_EXPRs. The LHS of each
1565 COMPOUND_EXPR will be an argument which must be evaluated.
1566 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
1567 COMPOUND_EXPR in the chain will contain the tree for the simplified
1568 form of the builtin function call. */
1570 static bool
1571 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
1573 gimple *stmt = gsi_stmt (*gsi);
1574 location_t loc = gimple_location (stmt);
1576 const char *p = c_getstr (src);
1578 /* If the string length is zero, return the dst parameter. */
1579 if (p && *p == '\0')
1581 replace_call_with_value (gsi, dst);
1582 return true;
1585 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
1586 return false;
1588 /* See if we can store by pieces into (dst + strlen(dst)). */
1589 tree newdst;
1590 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
1591 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1593 if (!strlen_fn || !memcpy_fn)
1594 return false;
1596 /* If the length of the source string isn't computable don't
1597 split strcat into strlen and memcpy. */
1598 tree len = get_maxval_strlen (src, 0);
1599 if (! len)
1600 return false;
1602 /* Create strlen (dst). */
1603 gimple_seq stmts = NULL, stmts2;
1604 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
1605 gimple_set_location (repl, loc);
1606 newdst = create_tmp_reg_or_ssa_name (size_type_node);
1607 gimple_call_set_lhs (repl, newdst);
1608 gimple_seq_add_stmt_without_update (&stmts, repl);
1610 /* Create (dst p+ strlen (dst)). */
1611 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
1612 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
1613 gimple_seq_add_seq_without_update (&stmts, stmts2);
1615 len = fold_convert_loc (loc, size_type_node, len);
1616 len = size_binop_loc (loc, PLUS_EXPR, len,
1617 build_int_cst (size_type_node, 1));
1618 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
1619 gimple_seq_add_seq_without_update (&stmts, stmts2);
1621 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
1622 gimple_seq_add_stmt_without_update (&stmts, repl);
1623 if (gimple_call_lhs (stmt))
1625 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
1626 gimple_seq_add_stmt_without_update (&stmts, repl);
1627 gsi_replace_with_seq_vops (gsi, stmts);
1628 /* gsi now points at the assignment to the lhs, get a
1629 stmt iterator to the memcpy call.
1630 ??? We can't use gsi_for_stmt as that doesn't work when the
1631 CFG isn't built yet. */
1632 gimple_stmt_iterator gsi2 = *gsi;
1633 gsi_prev (&gsi2);
1634 fold_stmt (&gsi2);
1636 else
1638 gsi_replace_with_seq_vops (gsi, stmts);
1639 fold_stmt (gsi);
1641 return true;
1644 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
1645 are the arguments to the call. */
1647 static bool
1648 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
1650 gimple *stmt = gsi_stmt (*gsi);
1651 tree dest = gimple_call_arg (stmt, 0);
1652 tree src = gimple_call_arg (stmt, 1);
1653 tree size = gimple_call_arg (stmt, 2);
1654 tree fn;
1655 const char *p;
1658 p = c_getstr (src);
1659 /* If the SRC parameter is "", return DEST. */
1660 if (p && *p == '\0')
1662 replace_call_with_value (gsi, dest);
1663 return true;
1666 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
1667 return false;
1669 /* If __builtin_strcat_chk is used, assume strcat is available. */
1670 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
1671 if (!fn)
1672 return false;
1674 gimple *repl = gimple_build_call (fn, 2, dest, src);
1675 replace_call_with_call_and_fold (gsi, repl);
1676 return true;
1679 /* Simplify a call to the strncat builtin. */
1681 static bool
1682 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
1684 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
1685 tree dst = gimple_call_arg (stmt, 0);
1686 tree src = gimple_call_arg (stmt, 1);
1687 tree len = gimple_call_arg (stmt, 2);
1689 const char *p = c_getstr (src);
1691 /* If the requested length is zero, or the src parameter string
1692 length is zero, return the dst parameter. */
1693 if (integer_zerop (len) || (p && *p == '\0'))
1695 replace_call_with_value (gsi, dst);
1696 return true;
1699 /* If the requested len is greater than or equal to the string
1700 length, call strcat. */
1701 if (TREE_CODE (len) == INTEGER_CST && p
1702 && compare_tree_int (len, strlen (p)) >= 0)
1704 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
1706 /* If the replacement _DECL isn't initialized, don't do the
1707 transformation. */
1708 if (!fn)
1709 return false;
1711 gcall *repl = gimple_build_call (fn, 2, dst, src);
1712 replace_call_with_call_and_fold (gsi, repl);
1713 return true;
1716 return false;
1719 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
1720 LEN, and SIZE. */
1722 static bool
1723 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
1725 gimple *stmt = gsi_stmt (*gsi);
1726 tree dest = gimple_call_arg (stmt, 0);
1727 tree src = gimple_call_arg (stmt, 1);
1728 tree len = gimple_call_arg (stmt, 2);
1729 tree size = gimple_call_arg (stmt, 3);
1730 tree fn;
1731 const char *p;
1733 p = c_getstr (src);
1734 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
1735 if ((p && *p == '\0')
1736 || integer_zerop (len))
1738 replace_call_with_value (gsi, dest);
1739 return true;
1742 if (! tree_fits_uhwi_p (size))
1743 return false;
1745 if (! integer_all_onesp (size))
1747 tree src_len = c_strlen (src, 1);
1748 if (src_len
1749 && tree_fits_uhwi_p (src_len)
1750 && tree_fits_uhwi_p (len)
1751 && ! tree_int_cst_lt (len, src_len))
1753 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
1754 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
1755 if (!fn)
1756 return false;
1758 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
1759 replace_call_with_call_and_fold (gsi, repl);
1760 return true;
1762 return false;
1765 /* If __builtin_strncat_chk is used, assume strncat is available. */
1766 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
1767 if (!fn)
1768 return false;
1770 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1771 replace_call_with_call_and_fold (gsi, repl);
1772 return true;
1775 /* Build and append gimple statements to STMTS that would load a first
1776 character of a memory location identified by STR. LOC is location
1777 of the statement. */
1779 static tree
1780 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
1782 tree var;
1784 tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
1785 tree cst_uchar_ptr_node
1786 = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
1787 tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
1789 tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
1790 gassign *stmt = gimple_build_assign (NULL_TREE, temp);
1791 var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
1793 gimple_assign_set_lhs (stmt, var);
1794 gimple_seq_add_stmt_without_update (stmts, stmt);
1796 return var;
1799 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator.
1800 FCODE is the name of the builtin. */
1802 static bool
1803 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
1805 gimple *stmt = gsi_stmt (*gsi);
1806 tree callee = gimple_call_fndecl (stmt);
1807 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
1809 tree type = integer_type_node;
1810 tree str1 = gimple_call_arg (stmt, 0);
1811 tree str2 = gimple_call_arg (stmt, 1);
1812 tree lhs = gimple_call_lhs (stmt);
1813 HOST_WIDE_INT length = -1;
1815 /* Handle strncmp and strncasecmp functions. */
1816 if (gimple_call_num_args (stmt) == 3)
1818 tree len = gimple_call_arg (stmt, 2);
1819 if (tree_fits_uhwi_p (len))
1820 length = tree_to_uhwi (len);
1823 /* If the LEN parameter is zero, return zero. */
1824 if (length == 0)
1826 replace_call_with_value (gsi, integer_zero_node);
1827 return true;
1830 /* If ARG1 and ARG2 are the same (and not volatile), return zero. */
1831 if (operand_equal_p (str1, str2, 0))
1833 replace_call_with_value (gsi, integer_zero_node);
1834 return true;
1837 const char *p1 = c_getstr (str1);
1838 const char *p2 = c_getstr (str2);
1840 /* For known strings, return an immediate value. */
1841 if (p1 && p2)
1843 int r = 0;
1844 bool known_result = false;
1846 switch (fcode)
1848 case BUILT_IN_STRCMP:
1850 r = strcmp (p1, p2);
1851 known_result = true;
1852 break;
1854 case BUILT_IN_STRNCMP:
1856 if (length == -1)
1857 break;
1858 r = strncmp (p1, p2, length);
1859 known_result = true;
1860 break;
1862 /* Only handleable situation is where the string are equal (result 0),
1863 which is already handled by operand_equal_p case. */
1864 case BUILT_IN_STRCASECMP:
1865 break;
1866 case BUILT_IN_STRNCASECMP:
1868 if (length == -1)
1869 break;
1870 r = strncmp (p1, p2, length);
1871 if (r == 0)
1872 known_result = true;
1873 break;;
1875 default:
1876 gcc_unreachable ();
1879 if (known_result)
1881 replace_call_with_value (gsi, build_cmp_result (type, r));
1882 return true;
1886 bool nonzero_length = length >= 1
1887 || fcode == BUILT_IN_STRCMP
1888 || fcode == BUILT_IN_STRCASECMP;
1890 location_t loc = gimple_location (stmt);
1892 /* If the second arg is "", return *(const unsigned char*)arg1. */
1893 if (p2 && *p2 == '\0' && nonzero_length)
1895 gimple_seq stmts = NULL;
1896 tree var = gimple_load_first_char (loc, str1, &stmts);
1897 if (lhs)
1899 stmt = gimple_build_assign (lhs, NOP_EXPR, var);
1900 gimple_seq_add_stmt_without_update (&stmts, stmt);
1903 gsi_replace_with_seq_vops (gsi, stmts);
1904 return true;
1907 /* If the first arg is "", return -*(const unsigned char*)arg2. */
1908 if (p1 && *p1 == '\0' && nonzero_length)
1910 gimple_seq stmts = NULL;
1911 tree var = gimple_load_first_char (loc, str2, &stmts);
1913 if (lhs)
1915 tree c = create_tmp_reg_or_ssa_name (integer_type_node);
1916 stmt = gimple_build_assign (c, NOP_EXPR, var);
1917 gimple_seq_add_stmt_without_update (&stmts, stmt);
1919 stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
1920 gimple_seq_add_stmt_without_update (&stmts, stmt);
1923 gsi_replace_with_seq_vops (gsi, stmts);
1924 return true;
1927 /* If len parameter is one, return an expression corresponding to
1928 (*(const unsigned char*)arg2 - *(const unsigned char*)arg1). */
1929 if (fcode == BUILT_IN_STRNCMP && length == 1)
1931 gimple_seq stmts = NULL;
1932 tree temp1 = gimple_load_first_char (loc, str1, &stmts);
1933 tree temp2 = gimple_load_first_char (loc, str2, &stmts);
1935 if (lhs)
1937 tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
1938 gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
1939 gimple_seq_add_stmt_without_update (&stmts, convert1);
1941 tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
1942 gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
1943 gimple_seq_add_stmt_without_update (&stmts, convert2);
1945 stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
1946 gimple_seq_add_stmt_without_update (&stmts, stmt);
1949 gsi_replace_with_seq_vops (gsi, stmts);
1950 return true;
1953 return false;
1956 /* Fold a call to the memchr pointed by GSI iterator. */
1958 static bool
1959 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
1961 gimple *stmt = gsi_stmt (*gsi);
1962 tree lhs = gimple_call_lhs (stmt);
1963 tree arg1 = gimple_call_arg (stmt, 0);
1964 tree arg2 = gimple_call_arg (stmt, 1);
1965 tree len = gimple_call_arg (stmt, 2);
1967 /* If the LEN parameter is zero, return zero. */
1968 if (integer_zerop (len))
1970 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1971 return true;
1974 char c;
1975 if (TREE_CODE (arg2) != INTEGER_CST
1976 || !tree_fits_uhwi_p (len)
1977 || !target_char_cst_p (arg2, &c))
1978 return false;
1980 unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
1981 unsigned HOST_WIDE_INT string_length;
1982 const char *p1 = c_getstr (arg1, &string_length);
1984 if (p1)
1986 const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
1987 if (r == NULL)
1989 if (length <= string_length)
1991 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
1992 return true;
1995 else
1997 unsigned HOST_WIDE_INT offset = r - p1;
1998 gimple_seq stmts = NULL;
1999 if (lhs != NULL_TREE)
2001 tree offset_cst = build_int_cst (TREE_TYPE (len), offset);
2002 gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
2003 arg1, offset_cst);
2004 gimple_seq_add_stmt_without_update (&stmts, stmt);
2006 else
2007 gimple_seq_add_stmt_without_update (&stmts,
2008 gimple_build_nop ());
2010 gsi_replace_with_seq_vops (gsi, stmts);
2011 return true;
2015 return false;
2018 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
2019 to the call. IGNORE is true if the value returned
2020 by the builtin will be ignored. UNLOCKED is true is true if this
2021 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
2022 the known length of the string. Return NULL_TREE if no simplification
2023 was possible. */
2025 static bool
2026 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
2027 tree arg0, tree arg1,
2028 bool unlocked)
2030 gimple *stmt = gsi_stmt (*gsi);
2032 /* If we're using an unlocked function, assume the other unlocked
2033 functions exist explicitly. */
2034 tree const fn_fputc = (unlocked
2035 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
2036 : builtin_decl_implicit (BUILT_IN_FPUTC));
2037 tree const fn_fwrite = (unlocked
2038 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
2039 : builtin_decl_implicit (BUILT_IN_FWRITE));
2041 /* If the return value is used, don't do the transformation. */
2042 if (gimple_call_lhs (stmt))
2043 return false;
2045 /* Get the length of the string passed to fputs. If the length
2046 can't be determined, punt. */
2047 tree len = get_maxval_strlen (arg0, 0);
2048 if (!len
2049 || TREE_CODE (len) != INTEGER_CST)
2050 return false;
2052 switch (compare_tree_int (len, 1))
2054 case -1: /* length is 0, delete the call entirely . */
2055 replace_call_with_value (gsi, integer_zero_node);
2056 return true;
2058 case 0: /* length is 1, call fputc. */
2060 const char *p = c_getstr (arg0);
2061 if (p != NULL)
2063 if (!fn_fputc)
2064 return false;
2066 gimple *repl = gimple_build_call (fn_fputc, 2,
2067 build_int_cst
2068 (integer_type_node, p[0]), arg1);
2069 replace_call_with_call_and_fold (gsi, repl);
2070 return true;
2073 /* FALLTHROUGH */
2074 case 1: /* length is greater than 1, call fwrite. */
2076 /* If optimizing for size keep fputs. */
2077 if (optimize_function_for_size_p (cfun))
2078 return false;
2079 /* New argument list transforming fputs(string, stream) to
2080 fwrite(string, 1, len, stream). */
2081 if (!fn_fwrite)
2082 return false;
2084 gimple *repl = gimple_build_call (fn_fwrite, 4, arg0,
2085 size_one_node, len, arg1);
2086 replace_call_with_call_and_fold (gsi, repl);
2087 return true;
2089 default:
2090 gcc_unreachable ();
2092 return false;
2095 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
2096 DEST, SRC, LEN, and SIZE are the arguments to the call.
2097 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
2098 code of the builtin. If MAXLEN is not NULL, it is maximum length
2099 passed as third argument. */
2101 static bool
2102 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
2103 tree dest, tree src, tree len, tree size,
2104 enum built_in_function fcode)
2106 gimple *stmt = gsi_stmt (*gsi);
2107 location_t loc = gimple_location (stmt);
2108 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2109 tree fn;
2111 /* If SRC and DEST are the same (and not volatile), return DEST
2112 (resp. DEST+LEN for __mempcpy_chk). */
2113 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
2115 if (fcode != BUILT_IN_MEMPCPY_CHK)
2117 replace_call_with_value (gsi, dest);
2118 return true;
2120 else
2122 gimple_seq stmts = NULL;
2123 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
2124 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
2125 TREE_TYPE (dest), dest, len);
2126 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2127 replace_call_with_value (gsi, temp);
2128 return true;
2132 if (! tree_fits_uhwi_p (size))
2133 return false;
2135 tree maxlen = get_maxval_strlen (len, 2);
2136 if (! integer_all_onesp (size))
2138 if (! tree_fits_uhwi_p (len))
2140 /* If LEN is not constant, try MAXLEN too.
2141 For MAXLEN only allow optimizing into non-_ocs function
2142 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2143 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2145 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
2147 /* (void) __mempcpy_chk () can be optimized into
2148 (void) __memcpy_chk (). */
2149 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2150 if (!fn)
2151 return false;
2153 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2154 replace_call_with_call_and_fold (gsi, repl);
2155 return true;
2157 return false;
2160 else
2161 maxlen = len;
2163 if (tree_int_cst_lt (size, maxlen))
2164 return false;
2167 fn = NULL_TREE;
2168 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
2169 mem{cpy,pcpy,move,set} is available. */
2170 switch (fcode)
2172 case BUILT_IN_MEMCPY_CHK:
2173 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
2174 break;
2175 case BUILT_IN_MEMPCPY_CHK:
2176 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
2177 break;
2178 case BUILT_IN_MEMMOVE_CHK:
2179 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
2180 break;
2181 case BUILT_IN_MEMSET_CHK:
2182 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
2183 break;
2184 default:
2185 break;
2188 if (!fn)
2189 return false;
2191 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2192 replace_call_with_call_and_fold (gsi, repl);
2193 return true;
2196 /* Fold a call to the __st[rp]cpy_chk builtin.
2197 DEST, SRC, and SIZE are the arguments to the call.
2198 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
2199 code of the builtin. If MAXLEN is not NULL, it is maximum length of
2200 strings passed as second argument. */
2202 static bool
2203 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
2204 tree dest,
2205 tree src, tree size,
2206 enum built_in_function fcode)
2208 gimple *stmt = gsi_stmt (*gsi);
2209 location_t loc = gimple_location (stmt);
2210 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2211 tree len, fn;
2213 /* If SRC and DEST are the same (and not volatile), return DEST. */
2214 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
2216 replace_call_with_value (gsi, dest);
2217 return true;
2220 if (! tree_fits_uhwi_p (size))
2221 return false;
2223 tree maxlen = get_maxval_strlen (src, 1);
2224 if (! integer_all_onesp (size))
2226 len = c_strlen (src, 1);
2227 if (! len || ! tree_fits_uhwi_p (len))
2229 /* If LEN is not constant, try MAXLEN too.
2230 For MAXLEN only allow optimizing into non-_ocs function
2231 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2232 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2234 if (fcode == BUILT_IN_STPCPY_CHK)
2236 if (! ignore)
2237 return false;
2239 /* If return value of __stpcpy_chk is ignored,
2240 optimize into __strcpy_chk. */
2241 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
2242 if (!fn)
2243 return false;
2245 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2246 replace_call_with_call_and_fold (gsi, repl);
2247 return true;
2250 if (! len || TREE_SIDE_EFFECTS (len))
2251 return false;
2253 /* If c_strlen returned something, but not a constant,
2254 transform __strcpy_chk into __memcpy_chk. */
2255 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2256 if (!fn)
2257 return false;
2259 gimple_seq stmts = NULL;
2260 len = gimple_convert (&stmts, loc, size_type_node, len);
2261 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
2262 build_int_cst (size_type_node, 1));
2263 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2264 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2265 replace_call_with_call_and_fold (gsi, repl);
2266 return true;
2269 else
2270 maxlen = len;
2272 if (! tree_int_cst_lt (maxlen, size))
2273 return false;
2276 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
2277 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK
2278 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
2279 if (!fn)
2280 return false;
2282 gimple *repl = gimple_build_call (fn, 2, dest, src);
2283 replace_call_with_call_and_fold (gsi, repl);
2284 return true;
2287 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
2288 are the arguments to the call. If MAXLEN is not NULL, it is maximum
2289 length passed as third argument. IGNORE is true if return value can be
2290 ignored. FCODE is the BUILT_IN_* code of the builtin. */
2292 static bool
2293 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
2294 tree dest, tree src,
2295 tree len, tree size,
2296 enum built_in_function fcode)
2298 gimple *stmt = gsi_stmt (*gsi);
2299 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
2300 tree fn;
2302 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
2304 /* If return value of __stpncpy_chk is ignored,
2305 optimize into __strncpy_chk. */
2306 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
2307 if (fn)
2309 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
2310 replace_call_with_call_and_fold (gsi, repl);
2311 return true;
2315 if (! tree_fits_uhwi_p (size))
2316 return false;
2318 tree maxlen = get_maxval_strlen (len, 2);
2319 if (! integer_all_onesp (size))
2321 if (! tree_fits_uhwi_p (len))
2323 /* If LEN is not constant, try MAXLEN too.
2324 For MAXLEN only allow optimizing into non-_ocs function
2325 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2326 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2327 return false;
2329 else
2330 maxlen = len;
2332 if (tree_int_cst_lt (size, maxlen))
2333 return false;
2336 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
2337 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK
2338 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
2339 if (!fn)
2340 return false;
2342 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2343 replace_call_with_call_and_fold (gsi, repl);
2344 return true;
2347 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
2348 Return NULL_TREE if no simplification can be made. */
2350 static bool
2351 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
2353 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2354 location_t loc = gimple_location (stmt);
2355 tree dest = gimple_call_arg (stmt, 0);
2356 tree src = gimple_call_arg (stmt, 1);
2357 tree fn, len, lenp1;
2359 /* If the result is unused, replace stpcpy with strcpy. */
2360 if (gimple_call_lhs (stmt) == NULL_TREE)
2362 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2363 if (!fn)
2364 return false;
2365 gimple_call_set_fndecl (stmt, fn);
2366 fold_stmt (gsi);
2367 return true;
2370 len = c_strlen (src, 1);
2371 if (!len
2372 || TREE_CODE (len) != INTEGER_CST)
2373 return false;
2375 if (optimize_function_for_size_p (cfun)
2376 /* If length is zero it's small enough. */
2377 && !integer_zerop (len))
2378 return false;
2380 /* If the source has a known length replace stpcpy with memcpy. */
2381 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2382 if (!fn)
2383 return false;
2385 gimple_seq stmts = NULL;
2386 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
2387 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
2388 tem, build_int_cst (size_type_node, 1));
2389 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2390 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
2391 gimple_set_vuse (repl, gimple_vuse (stmt));
2392 gimple_set_vdef (repl, gimple_vdef (stmt));
2393 if (gimple_vdef (repl)
2394 && TREE_CODE (gimple_vdef (repl)) == SSA_NAME)
2395 SSA_NAME_DEF_STMT (gimple_vdef (repl)) = repl;
2396 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
2397 /* Replace the result with dest + len. */
2398 stmts = NULL;
2399 tem = gimple_convert (&stmts, loc, sizetype, len);
2400 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2401 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
2402 POINTER_PLUS_EXPR, dest, tem);
2403 gsi_replace (gsi, ret, false);
2404 /* Finally fold the memcpy call. */
2405 gimple_stmt_iterator gsi2 = *gsi;
2406 gsi_prev (&gsi2);
2407 fold_stmt (&gsi2);
2408 return true;
2411 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
2412 NULL_TREE if a normal call should be emitted rather than expanding
2413 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
2414 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
2415 passed as second argument. */
2417 static bool
2418 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
2419 enum built_in_function fcode)
2421 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2422 tree dest, size, len, fn, fmt, flag;
2423 const char *fmt_str;
2425 /* Verify the required arguments in the original call. */
2426 if (gimple_call_num_args (stmt) < 5)
2427 return false;
2429 dest = gimple_call_arg (stmt, 0);
2430 len = gimple_call_arg (stmt, 1);
2431 flag = gimple_call_arg (stmt, 2);
2432 size = gimple_call_arg (stmt, 3);
2433 fmt = gimple_call_arg (stmt, 4);
2435 if (! tree_fits_uhwi_p (size))
2436 return false;
2438 if (! integer_all_onesp (size))
2440 tree maxlen = get_maxval_strlen (len, 2);
2441 if (! tree_fits_uhwi_p (len))
2443 /* If LEN is not constant, try MAXLEN too.
2444 For MAXLEN only allow optimizing into non-_ocs function
2445 if SIZE is >= MAXLEN, never convert to __ocs_fail (). */
2446 if (maxlen == NULL_TREE || ! tree_fits_uhwi_p (maxlen))
2447 return false;
2449 else
2450 maxlen = len;
2452 if (tree_int_cst_lt (size, maxlen))
2453 return false;
2456 if (!init_target_chars ())
2457 return false;
2459 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
2460 or if format doesn't contain % chars or is "%s". */
2461 if (! integer_zerop (flag))
2463 fmt_str = c_getstr (fmt);
2464 if (fmt_str == NULL)
2465 return false;
2466 if (strchr (fmt_str, target_percent) != NULL
2467 && strcmp (fmt_str, target_percent_s))
2468 return false;
2471 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
2472 available. */
2473 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
2474 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
2475 if (!fn)
2476 return false;
2478 /* Replace the called function and the first 5 argument by 3 retaining
2479 trailing varargs. */
2480 gimple_call_set_fndecl (stmt, fn);
2481 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2482 gimple_call_set_arg (stmt, 0, dest);
2483 gimple_call_set_arg (stmt, 1, len);
2484 gimple_call_set_arg (stmt, 2, fmt);
2485 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
2486 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2487 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2488 fold_stmt (gsi);
2489 return true;
2492 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
2493 Return NULL_TREE if a normal call should be emitted rather than
2494 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
2495 or BUILT_IN_VSPRINTF_CHK. */
2497 static bool
2498 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
2499 enum built_in_function fcode)
2501 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2502 tree dest, size, len, fn, fmt, flag;
2503 const char *fmt_str;
2504 unsigned nargs = gimple_call_num_args (stmt);
2506 /* Verify the required arguments in the original call. */
2507 if (nargs < 4)
2508 return false;
2509 dest = gimple_call_arg (stmt, 0);
2510 flag = gimple_call_arg (stmt, 1);
2511 size = gimple_call_arg (stmt, 2);
2512 fmt = gimple_call_arg (stmt, 3);
2514 if (! tree_fits_uhwi_p (size))
2515 return false;
2517 len = NULL_TREE;
2519 if (!init_target_chars ())
2520 return false;
2522 /* Check whether the format is a literal string constant. */
2523 fmt_str = c_getstr (fmt);
2524 if (fmt_str != NULL)
2526 /* If the format doesn't contain % args or %%, we know the size. */
2527 if (strchr (fmt_str, target_percent) == 0)
2529 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
2530 len = build_int_cstu (size_type_node, strlen (fmt_str));
2532 /* If the format is "%s" and first ... argument is a string literal,
2533 we know the size too. */
2534 else if (fcode == BUILT_IN_SPRINTF_CHK
2535 && strcmp (fmt_str, target_percent_s) == 0)
2537 tree arg;
2539 if (nargs == 5)
2541 arg = gimple_call_arg (stmt, 4);
2542 if (POINTER_TYPE_P (TREE_TYPE (arg)))
2544 len = c_strlen (arg, 1);
2545 if (! len || ! tree_fits_uhwi_p (len))
2546 len = NULL_TREE;
2552 if (! integer_all_onesp (size))
2554 if (! len || ! tree_int_cst_lt (len, size))
2555 return false;
2558 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
2559 or if format doesn't contain % chars or is "%s". */
2560 if (! integer_zerop (flag))
2562 if (fmt_str == NULL)
2563 return false;
2564 if (strchr (fmt_str, target_percent) != NULL
2565 && strcmp (fmt_str, target_percent_s))
2566 return false;
2569 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
2570 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
2571 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
2572 if (!fn)
2573 return false;
2575 /* Replace the called function and the first 4 argument by 2 retaining
2576 trailing varargs. */
2577 gimple_call_set_fndecl (stmt, fn);
2578 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
2579 gimple_call_set_arg (stmt, 0, dest);
2580 gimple_call_set_arg (stmt, 1, fmt);
2581 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
2582 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
2583 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
2584 fold_stmt (gsi);
2585 return true;
2588 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
2589 ORIG may be null if this is a 2-argument call. We don't attempt to
2590 simplify calls with more than 3 arguments.
2592 Return NULL_TREE if no simplification was possible, otherwise return the
2593 simplified form of the call as a tree. If IGNORED is true, it means that
2594 the caller does not use the returned value of the function. */
2596 static bool
2597 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
2599 gimple *stmt = gsi_stmt (*gsi);
2600 tree dest = gimple_call_arg (stmt, 0);
2601 tree fmt = gimple_call_arg (stmt, 1);
2602 tree orig = NULL_TREE;
2603 const char *fmt_str = NULL;
2605 /* Verify the required arguments in the original call. We deal with two
2606 types of sprintf() calls: 'sprintf (str, fmt)' and
2607 'sprintf (dest, "%s", orig)'. */
2608 if (gimple_call_num_args (stmt) > 3)
2609 return false;
2611 if (gimple_call_num_args (stmt) == 3)
2612 orig = gimple_call_arg (stmt, 2);
2614 /* Check whether the format is a literal string constant. */
2615 fmt_str = c_getstr (fmt);
2616 if (fmt_str == NULL)
2617 return false;
2619 if (!init_target_chars ())
2620 return false;
2622 /* If the format doesn't contain % args or %%, use strcpy. */
2623 if (strchr (fmt_str, target_percent) == NULL)
2625 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2627 if (!fn)
2628 return false;
2630 /* Don't optimize sprintf (buf, "abc", ptr++). */
2631 if (orig)
2632 return false;
2634 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
2635 'format' is known to contain no % formats. */
2636 gimple_seq stmts = NULL;
2637 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2638 gimple_seq_add_stmt_without_update (&stmts, repl);
2639 if (gimple_call_lhs (stmt))
2641 repl = gimple_build_assign (gimple_call_lhs (stmt),
2642 build_int_cst (integer_type_node,
2643 strlen (fmt_str)));
2644 gimple_seq_add_stmt_without_update (&stmts, repl);
2645 gsi_replace_with_seq_vops (gsi, stmts);
2646 /* gsi now points at the assignment to the lhs, get a
2647 stmt iterator to the memcpy call.
2648 ??? We can't use gsi_for_stmt as that doesn't work when the
2649 CFG isn't built yet. */
2650 gimple_stmt_iterator gsi2 = *gsi;
2651 gsi_prev (&gsi2);
2652 fold_stmt (&gsi2);
2654 else
2656 gsi_replace_with_seq_vops (gsi, stmts);
2657 fold_stmt (gsi);
2659 return true;
2662 /* If the format is "%s", use strcpy if the result isn't used. */
2663 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2665 tree fn;
2666 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2668 if (!fn)
2669 return false;
2671 /* Don't crash on sprintf (str1, "%s"). */
2672 if (!orig)
2673 return false;
2675 tree orig_len = NULL_TREE;
2676 if (gimple_call_lhs (stmt))
2678 orig_len = get_maxval_strlen (orig, 0);
2679 if (!orig_len)
2680 return false;
2683 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
2684 gimple_seq stmts = NULL;
2685 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2686 gimple_seq_add_stmt_without_update (&stmts, repl);
2687 if (gimple_call_lhs (stmt))
2689 if (!useless_type_conversion_p (integer_type_node,
2690 TREE_TYPE (orig_len)))
2691 orig_len = fold_convert (integer_type_node, orig_len);
2692 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2693 gimple_seq_add_stmt_without_update (&stmts, repl);
2694 gsi_replace_with_seq_vops (gsi, stmts);
2695 /* gsi now points at the assignment to the lhs, get a
2696 stmt iterator to the memcpy call.
2697 ??? We can't use gsi_for_stmt as that doesn't work when the
2698 CFG isn't built yet. */
2699 gimple_stmt_iterator gsi2 = *gsi;
2700 gsi_prev (&gsi2);
2701 fold_stmt (&gsi2);
2703 else
2705 gsi_replace_with_seq_vops (gsi, stmts);
2706 fold_stmt (gsi);
2708 return true;
2710 return false;
2713 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
2714 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
2715 attempt to simplify calls with more than 4 arguments.
2717 Return NULL_TREE if no simplification was possible, otherwise return the
2718 simplified form of the call as a tree. If IGNORED is true, it means that
2719 the caller does not use the returned value of the function. */
2721 static bool
2722 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
2724 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2725 tree dest = gimple_call_arg (stmt, 0);
2726 tree destsize = gimple_call_arg (stmt, 1);
2727 tree fmt = gimple_call_arg (stmt, 2);
2728 tree orig = NULL_TREE;
2729 const char *fmt_str = NULL;
2731 if (gimple_call_num_args (stmt) > 4)
2732 return false;
2734 if (gimple_call_num_args (stmt) == 4)
2735 orig = gimple_call_arg (stmt, 3);
2737 if (!tree_fits_uhwi_p (destsize))
2738 return false;
2739 unsigned HOST_WIDE_INT destlen = tree_to_uhwi (destsize);
2741 /* Check whether the format is a literal string constant. */
2742 fmt_str = c_getstr (fmt);
2743 if (fmt_str == NULL)
2744 return false;
2746 if (!init_target_chars ())
2747 return false;
2749 /* If the format doesn't contain % args or %%, use strcpy. */
2750 if (strchr (fmt_str, target_percent) == NULL)
2752 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2753 if (!fn)
2754 return false;
2756 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
2757 if (orig)
2758 return false;
2760 /* We could expand this as
2761 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
2762 or to
2763 memcpy (str, fmt_with_nul_at_cstm1, cst);
2764 but in the former case that might increase code size
2765 and in the latter case grow .rodata section too much.
2766 So punt for now. */
2767 size_t len = strlen (fmt_str);
2768 if (len >= destlen)
2769 return false;
2771 gimple_seq stmts = NULL;
2772 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
2773 gimple_seq_add_stmt_without_update (&stmts, repl);
2774 if (gimple_call_lhs (stmt))
2776 repl = gimple_build_assign (gimple_call_lhs (stmt),
2777 build_int_cst (integer_type_node, len));
2778 gimple_seq_add_stmt_without_update (&stmts, repl);
2779 gsi_replace_with_seq_vops (gsi, stmts);
2780 /* gsi now points at the assignment to the lhs, get a
2781 stmt iterator to the memcpy call.
2782 ??? We can't use gsi_for_stmt as that doesn't work when the
2783 CFG isn't built yet. */
2784 gimple_stmt_iterator gsi2 = *gsi;
2785 gsi_prev (&gsi2);
2786 fold_stmt (&gsi2);
2788 else
2790 gsi_replace_with_seq_vops (gsi, stmts);
2791 fold_stmt (gsi);
2793 return true;
2796 /* If the format is "%s", use strcpy if the result isn't used. */
2797 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
2799 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
2800 if (!fn)
2801 return false;
2803 /* Don't crash on snprintf (str1, cst, "%s"). */
2804 if (!orig)
2805 return false;
2807 tree orig_len = get_maxval_strlen (orig, 0);
2808 if (!orig_len || TREE_CODE (orig_len) != INTEGER_CST)
2809 return false;
2811 /* We could expand this as
2812 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
2813 or to
2814 memcpy (str1, str2_with_nul_at_cstm1, cst);
2815 but in the former case that might increase code size
2816 and in the latter case grow .rodata section too much.
2817 So punt for now. */
2818 if (compare_tree_int (orig_len, destlen) >= 0)
2819 return false;
2821 /* Convert snprintf (str1, cst, "%s", str2) into
2822 strcpy (str1, str2) if strlen (str2) < cst. */
2823 gimple_seq stmts = NULL;
2824 gimple *repl = gimple_build_call (fn, 2, dest, orig);
2825 gimple_seq_add_stmt_without_update (&stmts, repl);
2826 if (gimple_call_lhs (stmt))
2828 if (!useless_type_conversion_p (integer_type_node,
2829 TREE_TYPE (orig_len)))
2830 orig_len = fold_convert (integer_type_node, orig_len);
2831 repl = gimple_build_assign (gimple_call_lhs (stmt), orig_len);
2832 gimple_seq_add_stmt_without_update (&stmts, repl);
2833 gsi_replace_with_seq_vops (gsi, stmts);
2834 /* gsi now points at the assignment to the lhs, get a
2835 stmt iterator to the memcpy call.
2836 ??? We can't use gsi_for_stmt as that doesn't work when the
2837 CFG isn't built yet. */
2838 gimple_stmt_iterator gsi2 = *gsi;
2839 gsi_prev (&gsi2);
2840 fold_stmt (&gsi2);
2842 else
2844 gsi_replace_with_seq_vops (gsi, stmts);
2845 fold_stmt (gsi);
2847 return true;
2849 return false;
2852 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
2853 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
2854 more than 3 arguments, and ARG may be null in the 2-argument case.
2856 Return NULL_TREE if no simplification was possible, otherwise return the
2857 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2858 code of the function to be simplified. */
2860 static bool
2861 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
2862 tree fp, tree fmt, tree arg,
2863 enum built_in_function fcode)
2865 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2866 tree fn_fputc, fn_fputs;
2867 const char *fmt_str = NULL;
2869 /* If the return value is used, don't do the transformation. */
2870 if (gimple_call_lhs (stmt) != NULL_TREE)
2871 return false;
2873 /* Check whether the format is a literal string constant. */
2874 fmt_str = c_getstr (fmt);
2875 if (fmt_str == NULL)
2876 return false;
2878 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
2880 /* If we're using an unlocked function, assume the other
2881 unlocked functions exist explicitly. */
2882 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
2883 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
2885 else
2887 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
2888 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
2891 if (!init_target_chars ())
2892 return false;
2894 /* If the format doesn't contain % args or %%, use strcpy. */
2895 if (strchr (fmt_str, target_percent) == NULL)
2897 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
2898 && arg)
2899 return false;
2901 /* If the format specifier was "", fprintf does nothing. */
2902 if (fmt_str[0] == '\0')
2904 replace_call_with_value (gsi, NULL_TREE);
2905 return true;
2908 /* When "string" doesn't contain %, replace all cases of
2909 fprintf (fp, string) with fputs (string, fp). The fputs
2910 builtin will take care of special cases like length == 1. */
2911 if (fn_fputs)
2913 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
2914 replace_call_with_call_and_fold (gsi, repl);
2915 return true;
2919 /* The other optimizations can be done only on the non-va_list variants. */
2920 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
2921 return false;
2923 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
2924 else if (strcmp (fmt_str, target_percent_s) == 0)
2926 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
2927 return false;
2928 if (fn_fputs)
2930 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
2931 replace_call_with_call_and_fold (gsi, repl);
2932 return true;
2936 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
2937 else if (strcmp (fmt_str, target_percent_c) == 0)
2939 if (!arg
2940 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
2941 return false;
2942 if (fn_fputc)
2944 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
2945 replace_call_with_call_and_fold (gsi, repl);
2946 return true;
2950 return false;
2953 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
2954 FMT and ARG are the arguments to the call; we don't fold cases with
2955 more than 2 arguments, and ARG may be null if this is a 1-argument case.
2957 Return NULL_TREE if no simplification was possible, otherwise return the
2958 simplified form of the call as a tree. FCODE is the BUILT_IN_*
2959 code of the function to be simplified. */
2961 static bool
2962 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
2963 tree arg, enum built_in_function fcode)
2965 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
2966 tree fn_putchar, fn_puts, newarg;
2967 const char *fmt_str = NULL;
2969 /* If the return value is used, don't do the transformation. */
2970 if (gimple_call_lhs (stmt) != NULL_TREE)
2971 return false;
2973 /* Check whether the format is a literal string constant. */
2974 fmt_str = c_getstr (fmt);
2975 if (fmt_str == NULL)
2976 return false;
2978 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
2980 /* If we're using an unlocked function, assume the other
2981 unlocked functions exist explicitly. */
2982 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
2983 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
2985 else
2987 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
2988 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
2991 if (!init_target_chars ())
2992 return false;
2994 if (strcmp (fmt_str, target_percent_s) == 0
2995 || strchr (fmt_str, target_percent) == NULL)
2997 const char *str;
2999 if (strcmp (fmt_str, target_percent_s) == 0)
3001 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3002 return false;
3004 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3005 return false;
3007 str = c_getstr (arg);
3008 if (str == NULL)
3009 return false;
3011 else
3013 /* The format specifier doesn't contain any '%' characters. */
3014 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
3015 && arg)
3016 return false;
3017 str = fmt_str;
3020 /* If the string was "", printf does nothing. */
3021 if (str[0] == '\0')
3023 replace_call_with_value (gsi, NULL_TREE);
3024 return true;
3027 /* If the string has length of 1, call putchar. */
3028 if (str[1] == '\0')
3030 /* Given printf("c"), (where c is any one character,)
3031 convert "c"[0] to an int and pass that to the replacement
3032 function. */
3033 newarg = build_int_cst (integer_type_node, str[0]);
3034 if (fn_putchar)
3036 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
3037 replace_call_with_call_and_fold (gsi, repl);
3038 return true;
3041 else
3043 /* If the string was "string\n", call puts("string"). */
3044 size_t len = strlen (str);
3045 if ((unsigned char)str[len - 1] == target_newline
3046 && (size_t) (int) len == len
3047 && (int) len > 0)
3049 char *newstr;
3050 tree offset_node, string_cst;
3052 /* Create a NUL-terminated string that's one char shorter
3053 than the original, stripping off the trailing '\n'. */
3054 newarg = build_string_literal (len, str);
3055 string_cst = string_constant (newarg, &offset_node);
3056 gcc_checking_assert (string_cst
3057 && (TREE_STRING_LENGTH (string_cst)
3058 == (int) len)
3059 && integer_zerop (offset_node)
3060 && (unsigned char)
3061 TREE_STRING_POINTER (string_cst)[len - 1]
3062 == target_newline);
3063 /* build_string_literal creates a new STRING_CST,
3064 modify it in place to avoid double copying. */
3065 newstr = CONST_CAST (char *, TREE_STRING_POINTER (string_cst));
3066 newstr[len - 1] = '\0';
3067 if (fn_puts)
3069 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
3070 replace_call_with_call_and_fold (gsi, repl);
3071 return true;
3074 else
3075 /* We'd like to arrange to call fputs(string,stdout) here,
3076 but we need stdout and don't have a way to get it yet. */
3077 return false;
3081 /* The other optimizations can be done only on the non-va_list variants. */
3082 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
3083 return false;
3085 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
3086 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
3088 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3089 return false;
3090 if (fn_puts)
3092 gcall *repl = gimple_build_call (fn_puts, 1, arg);
3093 replace_call_with_call_and_fold (gsi, repl);
3094 return true;
3098 /* If the format specifier was "%c", call __builtin_putchar(arg). */
3099 else if (strcmp (fmt_str, target_percent_c) == 0)
3101 if (!arg || ! useless_type_conversion_p (integer_type_node,
3102 TREE_TYPE (arg)))
3103 return false;
3104 if (fn_putchar)
3106 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
3107 replace_call_with_call_and_fold (gsi, repl);
3108 return true;
3112 return false;
3117 /* Fold a call to __builtin_strlen with known length LEN. */
3119 static bool
3120 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
3122 gimple *stmt = gsi_stmt (*gsi);
3123 tree len = get_maxval_strlen (gimple_call_arg (stmt, 0), 0);
3124 if (!len)
3125 return false;
3126 len = force_gimple_operand_gsi (gsi, len, true, NULL, true, GSI_SAME_STMT);
3127 replace_call_with_value (gsi, len);
3128 return true;
3131 /* Fold a call to __builtin_acc_on_device. */
3133 static bool
3134 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
3136 /* Defer folding until we know which compiler we're in. */
3137 if (symtab->state != EXPANSION)
3138 return false;
3140 unsigned val_host = GOMP_DEVICE_HOST;
3141 unsigned val_dev = GOMP_DEVICE_NONE;
3143 #ifdef ACCEL_COMPILER
3144 val_host = GOMP_DEVICE_NOT_HOST;
3145 val_dev = ACCEL_COMPILER_acc_device;
3146 #endif
3148 location_t loc = gimple_location (gsi_stmt (*gsi));
3150 tree host_eq = make_ssa_name (boolean_type_node);
3151 gimple *host_ass = gimple_build_assign
3152 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
3153 gimple_set_location (host_ass, loc);
3154 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
3156 tree dev_eq = make_ssa_name (boolean_type_node);
3157 gimple *dev_ass = gimple_build_assign
3158 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
3159 gimple_set_location (dev_ass, loc);
3160 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
3162 tree result = make_ssa_name (boolean_type_node);
3163 gimple *result_ass = gimple_build_assign
3164 (result, BIT_IOR_EXPR, host_eq, dev_eq);
3165 gimple_set_location (result_ass, loc);
3166 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
3168 replace_call_with_value (gsi, result);
3170 return true;
3173 /* Fold the non-target builtin at *GSI and return whether any simplification
3174 was made. */
3176 static bool
3177 gimple_fold_builtin (gimple_stmt_iterator *gsi)
3179 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
3180 tree callee = gimple_call_fndecl (stmt);
3182 /* Give up for always_inline inline builtins until they are
3183 inlined. */
3184 if (avoid_folding_inline_builtin (callee))
3185 return false;
3187 unsigned n = gimple_call_num_args (stmt);
3188 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
3189 switch (fcode)
3191 case BUILT_IN_BZERO:
3192 return gimple_fold_builtin_memset (gsi, integer_zero_node,
3193 gimple_call_arg (stmt, 1));
3194 case BUILT_IN_MEMSET:
3195 return gimple_fold_builtin_memset (gsi,
3196 gimple_call_arg (stmt, 1),
3197 gimple_call_arg (stmt, 2));
3198 case BUILT_IN_BCOPY:
3199 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 1),
3200 gimple_call_arg (stmt, 0), 3);
3201 case BUILT_IN_MEMCPY:
3202 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3203 gimple_call_arg (stmt, 1), 0);
3204 case BUILT_IN_MEMPCPY:
3205 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3206 gimple_call_arg (stmt, 1), 1);
3207 case BUILT_IN_MEMMOVE:
3208 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
3209 gimple_call_arg (stmt, 1), 3);
3210 case BUILT_IN_SPRINTF_CHK:
3211 case BUILT_IN_VSPRINTF_CHK:
3212 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
3213 case BUILT_IN_STRCAT_CHK:
3214 return gimple_fold_builtin_strcat_chk (gsi);
3215 case BUILT_IN_STRNCAT_CHK:
3216 return gimple_fold_builtin_strncat_chk (gsi);
3217 case BUILT_IN_STRLEN:
3218 return gimple_fold_builtin_strlen (gsi);
3219 case BUILT_IN_STRCPY:
3220 return gimple_fold_builtin_strcpy (gsi,
3221 gimple_call_arg (stmt, 0),
3222 gimple_call_arg (stmt, 1));
3223 case BUILT_IN_STRNCPY:
3224 return gimple_fold_builtin_strncpy (gsi,
3225 gimple_call_arg (stmt, 0),
3226 gimple_call_arg (stmt, 1),
3227 gimple_call_arg (stmt, 2));
3228 case BUILT_IN_STRCAT:
3229 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
3230 gimple_call_arg (stmt, 1));
3231 case BUILT_IN_STRNCAT:
3232 return gimple_fold_builtin_strncat (gsi);
3233 case BUILT_IN_INDEX:
3234 case BUILT_IN_STRCHR:
3235 return gimple_fold_builtin_strchr (gsi, false);
3236 case BUILT_IN_RINDEX:
3237 case BUILT_IN_STRRCHR:
3238 return gimple_fold_builtin_strchr (gsi, true);
3239 case BUILT_IN_STRCMP:
3240 case BUILT_IN_STRCASECMP:
3241 case BUILT_IN_STRNCMP:
3242 case BUILT_IN_STRNCASECMP:
3243 return gimple_fold_builtin_string_compare (gsi);
3244 case BUILT_IN_MEMCHR:
3245 return gimple_fold_builtin_memchr (gsi);
3246 case BUILT_IN_FPUTS:
3247 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3248 gimple_call_arg (stmt, 1), false);
3249 case BUILT_IN_FPUTS_UNLOCKED:
3250 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
3251 gimple_call_arg (stmt, 1), true);
3252 case BUILT_IN_MEMCPY_CHK:
3253 case BUILT_IN_MEMPCPY_CHK:
3254 case BUILT_IN_MEMMOVE_CHK:
3255 case BUILT_IN_MEMSET_CHK:
3256 return gimple_fold_builtin_memory_chk (gsi,
3257 gimple_call_arg (stmt, 0),
3258 gimple_call_arg (stmt, 1),
3259 gimple_call_arg (stmt, 2),
3260 gimple_call_arg (stmt, 3),
3261 fcode);
3262 case BUILT_IN_STPCPY:
3263 return gimple_fold_builtin_stpcpy (gsi);
3264 case BUILT_IN_STRCPY_CHK:
3265 case BUILT_IN_STPCPY_CHK:
3266 return gimple_fold_builtin_stxcpy_chk (gsi,
3267 gimple_call_arg (stmt, 0),
3268 gimple_call_arg (stmt, 1),
3269 gimple_call_arg (stmt, 2),
3270 fcode);
3271 case BUILT_IN_STRNCPY_CHK:
3272 case BUILT_IN_STPNCPY_CHK:
3273 return gimple_fold_builtin_stxncpy_chk (gsi,
3274 gimple_call_arg (stmt, 0),
3275 gimple_call_arg (stmt, 1),
3276 gimple_call_arg (stmt, 2),
3277 gimple_call_arg (stmt, 3),
3278 fcode);
3279 case BUILT_IN_SNPRINTF_CHK:
3280 case BUILT_IN_VSNPRINTF_CHK:
3281 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
3282 case BUILT_IN_SNPRINTF:
3283 return gimple_fold_builtin_snprintf (gsi);
3284 case BUILT_IN_SPRINTF:
3285 return gimple_fold_builtin_sprintf (gsi);
3286 case BUILT_IN_FPRINTF:
3287 case BUILT_IN_FPRINTF_UNLOCKED:
3288 case BUILT_IN_VFPRINTF:
3289 if (n == 2 || n == 3)
3290 return gimple_fold_builtin_fprintf (gsi,
3291 gimple_call_arg (stmt, 0),
3292 gimple_call_arg (stmt, 1),
3293 n == 3
3294 ? gimple_call_arg (stmt, 2)
3295 : NULL_TREE,
3296 fcode);
3297 break;
3298 case BUILT_IN_FPRINTF_CHK:
3299 case BUILT_IN_VFPRINTF_CHK:
3300 if (n == 3 || n == 4)
3301 return gimple_fold_builtin_fprintf (gsi,
3302 gimple_call_arg (stmt, 0),
3303 gimple_call_arg (stmt, 2),
3304 n == 4
3305 ? gimple_call_arg (stmt, 3)
3306 : NULL_TREE,
3307 fcode);
3308 break;
3309 case BUILT_IN_PRINTF:
3310 case BUILT_IN_PRINTF_UNLOCKED:
3311 case BUILT_IN_VPRINTF:
3312 if (n == 1 || n == 2)
3313 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
3314 n == 2
3315 ? gimple_call_arg (stmt, 1)
3316 : NULL_TREE, fcode);
3317 break;
3318 case BUILT_IN_PRINTF_CHK:
3319 case BUILT_IN_VPRINTF_CHK:
3320 if (n == 2 || n == 3)
3321 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
3322 n == 3
3323 ? gimple_call_arg (stmt, 2)
3324 : NULL_TREE, fcode);
3325 break;
3326 case BUILT_IN_ACC_ON_DEVICE:
3327 return gimple_fold_builtin_acc_on_device (gsi,
3328 gimple_call_arg (stmt, 0));
3329 default:;
3332 /* Try the generic builtin folder. */
3333 bool ignore = (gimple_call_lhs (stmt) == NULL);
3334 tree result = fold_call_stmt (stmt, ignore);
3335 if (result)
3337 if (ignore)
3338 STRIP_NOPS (result);
3339 else
3340 result = fold_convert (gimple_call_return_type (stmt), result);
3341 if (!update_call_from_tree (gsi, result))
3342 gimplify_and_update_call_from_tree (gsi, result);
3343 return true;
3346 return false;
3349 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
3350 function calls to constants, where possible. */
3352 static tree
3353 fold_internal_goacc_dim (const gimple *call)
3355 int axis = get_oacc_ifn_dim_arg (call);
3356 int size = get_oacc_fn_dim_size (current_function_decl, axis);
3357 bool is_pos = gimple_call_internal_fn (call) == IFN_GOACC_DIM_POS;
3358 tree result = NULL_TREE;
3360 /* If the size is 1, or we only want the size and it is not dynamic,
3361 we know the answer. */
3362 if (size == 1 || (!is_pos && size))
3364 tree type = TREE_TYPE (gimple_call_lhs (call));
3365 result = build_int_cst (type, size - is_pos);
3368 return result;
3371 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
3372 for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
3373 &var where var is only addressable because of such calls. */
3375 bool
3376 optimize_atomic_compare_exchange_p (gimple *stmt)
3378 if (gimple_call_num_args (stmt) != 6
3379 || !flag_inline_atomics
3380 || !optimize
3381 || (flag_sanitize & (SANITIZE_THREAD | SANITIZE_ADDRESS)) != 0
3382 || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
3383 || !gimple_vdef (stmt)
3384 || !gimple_vuse (stmt))
3385 return false;
3387 tree fndecl = gimple_call_fndecl (stmt);
3388 switch (DECL_FUNCTION_CODE (fndecl))
3390 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
3391 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
3392 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
3393 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
3394 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
3395 break;
3396 default:
3397 return false;
3400 tree expected = gimple_call_arg (stmt, 1);
3401 if (TREE_CODE (expected) != ADDR_EXPR
3402 || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
3403 return false;
3405 tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
3406 if (!is_gimple_reg_type (etype)
3407 || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
3408 || TREE_THIS_VOLATILE (etype)
3409 || VECTOR_TYPE_P (etype)
3410 || TREE_CODE (etype) == COMPLEX_TYPE
3411 /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
3412 might not preserve all the bits. See PR71716. */
3413 || SCALAR_FLOAT_TYPE_P (etype)
3414 || TYPE_PRECISION (etype) != GET_MODE_BITSIZE (TYPE_MODE (etype)))
3415 return false;
3417 tree weak = gimple_call_arg (stmt, 3);
3418 if (!integer_zerop (weak) && !integer_onep (weak))
3419 return false;
3421 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3422 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3423 machine_mode mode = TYPE_MODE (itype);
3425 if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
3426 == CODE_FOR_nothing
3427 && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
3428 return false;
3430 if (int_size_in_bytes (etype) != GET_MODE_SIZE (mode))
3431 return false;
3433 return true;
3436 /* Fold
3437 r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
3438 into
3439 _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
3440 i = IMAGPART_EXPR <t>;
3441 r = (_Bool) i;
3442 e = REALPART_EXPR <t>; */
3444 void
3445 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
3447 gimple *stmt = gsi_stmt (*gsi);
3448 tree fndecl = gimple_call_fndecl (stmt);
3449 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
3450 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
3451 tree ctype = build_complex_type (itype);
3452 tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
3453 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3454 expected);
3455 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3456 gimple_stmt_iterator gsiret = gsi_for_stmt (g);
3457 if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
3459 g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
3460 build1 (VIEW_CONVERT_EXPR, itype,
3461 gimple_assign_lhs (g)));
3462 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3464 int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
3465 + int_size_in_bytes (itype);
3466 g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
3467 gimple_call_arg (stmt, 0),
3468 gimple_assign_lhs (g),
3469 gimple_call_arg (stmt, 2),
3470 build_int_cst (integer_type_node, flag),
3471 gimple_call_arg (stmt, 4),
3472 gimple_call_arg (stmt, 5));
3473 tree lhs = make_ssa_name (ctype);
3474 gimple_call_set_lhs (g, lhs);
3475 gimple_set_vdef (g, gimple_vdef (stmt));
3476 gimple_set_vuse (g, gimple_vuse (stmt));
3477 SSA_NAME_DEF_STMT (gimple_vdef (g)) = g;
3478 if (gimple_call_lhs (stmt))
3480 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3481 g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
3482 build1 (IMAGPART_EXPR, itype, lhs));
3483 gsi_insert_before (gsi, g, GSI_SAME_STMT);
3484 g = gimple_build_assign (gimple_call_lhs (stmt), NOP_EXPR,
3485 gimple_assign_lhs (g));
3487 gsi_replace (gsi, g, true);
3488 g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
3489 build1 (REALPART_EXPR, itype, lhs));
3490 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3491 if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
3493 g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
3494 VIEW_CONVERT_EXPR,
3495 build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
3496 gimple_assign_lhs (g)));
3497 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3499 g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
3500 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3501 *gsi = gsiret;
3504 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
3505 doesn't fit into TYPE. The test for overflow should be regardless of
3506 -fwrapv, and even for unsigned types. */
3508 bool
3509 arith_overflowed_p (enum tree_code code, const_tree type,
3510 const_tree arg0, const_tree arg1)
3512 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) widest2_int;
3513 typedef generic_wide_int <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> >
3514 widest2_int_cst;
3515 widest2_int warg0 = widest2_int_cst (arg0);
3516 widest2_int warg1 = widest2_int_cst (arg1);
3517 widest2_int wres;
3518 switch (code)
3520 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
3521 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
3522 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
3523 default: gcc_unreachable ();
3525 signop sign = TYPE_SIGN (type);
3526 if (sign == UNSIGNED && wi::neg_p (wres))
3527 return true;
3528 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
3531 /* Attempt to fold a call statement referenced by the statement iterator GSI.
3532 The statement may be replaced by another statement, e.g., if the call
3533 simplifies to a constant value. Return true if any changes were made.
3534 It is assumed that the operands have been previously folded. */
3536 static bool
3537 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
3539 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3540 tree callee;
3541 bool changed = false;
3542 unsigned i;
3544 /* Fold *& in call arguments. */
3545 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3546 if (REFERENCE_CLASS_P (gimple_call_arg (stmt, i)))
3548 tree tmp = maybe_fold_reference (gimple_call_arg (stmt, i), false);
3549 if (tmp)
3551 gimple_call_set_arg (stmt, i, tmp);
3552 changed = true;
3556 /* Check for virtual calls that became direct calls. */
3557 callee = gimple_call_fn (stmt);
3558 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
3560 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
3562 if (dump_file && virtual_method_call_p (callee)
3563 && !possible_polymorphic_call_target_p
3564 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
3565 (OBJ_TYPE_REF_EXPR (callee)))))
3567 fprintf (dump_file,
3568 "Type inheritance inconsistent devirtualization of ");
3569 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3570 fprintf (dump_file, " to ");
3571 print_generic_expr (dump_file, callee, TDF_SLIM);
3572 fprintf (dump_file, "\n");
3575 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
3576 changed = true;
3578 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
3580 bool final;
3581 vec <cgraph_node *>targets
3582 = possible_polymorphic_call_targets (callee, stmt, &final);
3583 if (final && targets.length () <= 1 && dbg_cnt (devirt))
3585 tree lhs = gimple_call_lhs (stmt);
3586 if (dump_enabled_p ())
3588 location_t loc = gimple_location_safe (stmt);
3589 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
3590 "folding virtual function call to %s\n",
3591 targets.length () == 1
3592 ? targets[0]->name ()
3593 : "__builtin_unreachable");
3595 if (targets.length () == 1)
3597 tree fndecl = targets[0]->decl;
3598 gimple_call_set_fndecl (stmt, fndecl);
3599 changed = true;
3600 /* If changing the call to __cxa_pure_virtual
3601 or similar noreturn function, adjust gimple_call_fntype
3602 too. */
3603 if (gimple_call_noreturn_p (stmt)
3604 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
3605 && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
3606 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
3607 == void_type_node))
3608 gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
3609 /* If the call becomes noreturn, remove the lhs. */
3610 if (lhs
3611 && gimple_call_noreturn_p (stmt)
3612 && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
3613 || should_remove_lhs_p (lhs)))
3615 if (TREE_CODE (lhs) == SSA_NAME)
3617 tree var = create_tmp_var (TREE_TYPE (lhs));
3618 tree def = get_or_create_ssa_default_def (cfun, var);
3619 gimple *new_stmt = gimple_build_assign (lhs, def);
3620 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3622 gimple_call_set_lhs (stmt, NULL_TREE);
3624 maybe_remove_unused_call_args (cfun, stmt);
3626 else
3628 tree fndecl = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
3629 gimple *new_stmt = gimple_build_call (fndecl, 0);
3630 gimple_set_location (new_stmt, gimple_location (stmt));
3631 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3633 tree var = create_tmp_var (TREE_TYPE (lhs));
3634 tree def = get_or_create_ssa_default_def (cfun, var);
3636 /* To satisfy condition for
3637 cgraph_update_edges_for_call_stmt_node,
3638 we need to preserve GIMPLE_CALL statement
3639 at position of GSI iterator. */
3640 update_call_from_tree (gsi, def);
3641 gsi_insert_before (gsi, new_stmt, GSI_NEW_STMT);
3643 else
3645 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
3646 gimple_set_vdef (new_stmt, gimple_vdef (stmt));
3647 gsi_replace (gsi, new_stmt, false);
3649 return true;
3655 /* Check for indirect calls that became direct calls, and then
3656 no longer require a static chain. */
3657 if (gimple_call_chain (stmt))
3659 tree fn = gimple_call_fndecl (stmt);
3660 if (fn && !DECL_STATIC_CHAIN (fn))
3662 gimple_call_set_chain (stmt, NULL);
3663 changed = true;
3665 else
3667 tree tmp = maybe_fold_reference (gimple_call_chain (stmt), false);
3668 if (tmp)
3670 gimple_call_set_chain (stmt, tmp);
3671 changed = true;
3676 if (inplace)
3677 return changed;
3679 /* Check for builtins that CCP can handle using information not
3680 available in the generic fold routines. */
3681 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3683 if (gimple_fold_builtin (gsi))
3684 changed = true;
3686 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
3688 changed |= targetm.gimple_fold_builtin (gsi);
3690 else if (gimple_call_internal_p (stmt))
3692 enum tree_code subcode = ERROR_MARK;
3693 tree result = NULL_TREE;
3694 bool cplx_result = false;
3695 tree overflow = NULL_TREE;
3696 switch (gimple_call_internal_fn (stmt))
3698 case IFN_BUILTIN_EXPECT:
3699 result = fold_builtin_expect (gimple_location (stmt),
3700 gimple_call_arg (stmt, 0),
3701 gimple_call_arg (stmt, 1),
3702 gimple_call_arg (stmt, 2));
3703 break;
3704 case IFN_UBSAN_OBJECT_SIZE:
3705 if (integer_all_onesp (gimple_call_arg (stmt, 2))
3706 || (TREE_CODE (gimple_call_arg (stmt, 1)) == INTEGER_CST
3707 && TREE_CODE (gimple_call_arg (stmt, 2)) == INTEGER_CST
3708 && tree_int_cst_le (gimple_call_arg (stmt, 1),
3709 gimple_call_arg (stmt, 2))))
3711 gsi_replace (gsi, gimple_build_nop (), false);
3712 unlink_stmt_vdef (stmt);
3713 release_defs (stmt);
3714 return true;
3716 break;
3717 case IFN_GOACC_DIM_SIZE:
3718 case IFN_GOACC_DIM_POS:
3719 result = fold_internal_goacc_dim (stmt);
3720 break;
3721 case IFN_UBSAN_CHECK_ADD:
3722 subcode = PLUS_EXPR;
3723 break;
3724 case IFN_UBSAN_CHECK_SUB:
3725 subcode = MINUS_EXPR;
3726 break;
3727 case IFN_UBSAN_CHECK_MUL:
3728 subcode = MULT_EXPR;
3729 break;
3730 case IFN_ADD_OVERFLOW:
3731 subcode = PLUS_EXPR;
3732 cplx_result = true;
3733 break;
3734 case IFN_SUB_OVERFLOW:
3735 subcode = MINUS_EXPR;
3736 cplx_result = true;
3737 break;
3738 case IFN_MUL_OVERFLOW:
3739 subcode = MULT_EXPR;
3740 cplx_result = true;
3741 break;
3742 default:
3743 break;
3745 if (subcode != ERROR_MARK)
3747 tree arg0 = gimple_call_arg (stmt, 0);
3748 tree arg1 = gimple_call_arg (stmt, 1);
3749 tree type = TREE_TYPE (arg0);
3750 if (cplx_result)
3752 tree lhs = gimple_call_lhs (stmt);
3753 if (lhs == NULL_TREE)
3754 type = NULL_TREE;
3755 else
3756 type = TREE_TYPE (TREE_TYPE (lhs));
3758 if (type == NULL_TREE)
3760 /* x = y + 0; x = y - 0; x = y * 0; */
3761 else if (integer_zerop (arg1))
3762 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
3763 /* x = 0 + y; x = 0 * y; */
3764 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
3765 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
3766 /* x = y - y; */
3767 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
3768 result = integer_zero_node;
3769 /* x = y * 1; x = 1 * y; */
3770 else if (subcode == MULT_EXPR && integer_onep (arg1))
3771 result = arg0;
3772 else if (subcode == MULT_EXPR && integer_onep (arg0))
3773 result = arg1;
3774 else if (TREE_CODE (arg0) == INTEGER_CST
3775 && TREE_CODE (arg1) == INTEGER_CST)
3777 if (cplx_result)
3778 result = int_const_binop (subcode, fold_convert (type, arg0),
3779 fold_convert (type, arg1));
3780 else
3781 result = int_const_binop (subcode, arg0, arg1);
3782 if (result && arith_overflowed_p (subcode, type, arg0, arg1))
3784 if (cplx_result)
3785 overflow = build_one_cst (type);
3786 else
3787 result = NULL_TREE;
3790 if (result)
3792 if (result == integer_zero_node)
3793 result = build_zero_cst (type);
3794 else if (cplx_result && TREE_TYPE (result) != type)
3796 if (TREE_CODE (result) == INTEGER_CST)
3798 if (arith_overflowed_p (PLUS_EXPR, type, result,
3799 integer_zero_node))
3800 overflow = build_one_cst (type);
3802 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
3803 && TYPE_UNSIGNED (type))
3804 || (TYPE_PRECISION (type)
3805 < (TYPE_PRECISION (TREE_TYPE (result))
3806 + (TYPE_UNSIGNED (TREE_TYPE (result))
3807 && !TYPE_UNSIGNED (type)))))
3808 result = NULL_TREE;
3809 if (result)
3810 result = fold_convert (type, result);
3815 if (result)
3817 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
3818 result = drop_tree_overflow (result);
3819 if (cplx_result)
3821 if (overflow == NULL_TREE)
3822 overflow = build_zero_cst (TREE_TYPE (result));
3823 tree ctype = build_complex_type (TREE_TYPE (result));
3824 if (TREE_CODE (result) == INTEGER_CST
3825 && TREE_CODE (overflow) == INTEGER_CST)
3826 result = build_complex (ctype, result, overflow);
3827 else
3828 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
3829 ctype, result, overflow);
3831 if (!update_call_from_tree (gsi, result))
3832 gimplify_and_update_call_from_tree (gsi, result);
3833 changed = true;
3837 return changed;
3841 /* Return true whether NAME has a use on STMT. */
3843 static bool
3844 has_use_on_stmt (tree name, gimple *stmt)
3846 imm_use_iterator iter;
3847 use_operand_p use_p;
3848 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
3849 if (USE_STMT (use_p) == stmt)
3850 return true;
3851 return false;
3854 /* Worker for fold_stmt_1 dispatch to pattern based folding with
3855 gimple_simplify.
3857 Replaces *GSI with the simplification result in RCODE and OPS
3858 and the associated statements in *SEQ. Does the replacement
3859 according to INPLACE and returns true if the operation succeeded. */
3861 static bool
3862 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
3863 code_helper rcode, tree *ops,
3864 gimple_seq *seq, bool inplace)
3866 gimple *stmt = gsi_stmt (*gsi);
3868 /* Play safe and do not allow abnormals to be mentioned in
3869 newly created statements. See also maybe_push_res_to_seq.
3870 As an exception allow such uses if there was a use of the
3871 same SSA name on the old stmt. */
3872 if ((TREE_CODE (ops[0]) == SSA_NAME
3873 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[0])
3874 && !has_use_on_stmt (ops[0], stmt))
3875 || (ops[1]
3876 && TREE_CODE (ops[1]) == SSA_NAME
3877 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[1])
3878 && !has_use_on_stmt (ops[1], stmt))
3879 || (ops[2]
3880 && TREE_CODE (ops[2]) == SSA_NAME
3881 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[2])
3882 && !has_use_on_stmt (ops[2], stmt))
3883 || (COMPARISON_CLASS_P (ops[0])
3884 && ((TREE_CODE (TREE_OPERAND (ops[0], 0)) == SSA_NAME
3885 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 0))
3886 && !has_use_on_stmt (TREE_OPERAND (ops[0], 0), stmt))
3887 || (TREE_CODE (TREE_OPERAND (ops[0], 1)) == SSA_NAME
3888 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], 1))
3889 && !has_use_on_stmt (TREE_OPERAND (ops[0], 1), stmt)))))
3890 return false;
3892 /* Don't insert new statements when INPLACE is true, even if we could
3893 reuse STMT for the final statement. */
3894 if (inplace && !gimple_seq_empty_p (*seq))
3895 return false;
3897 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3899 gcc_assert (rcode.is_tree_code ());
3900 if (TREE_CODE_CLASS ((enum tree_code)rcode) == tcc_comparison
3901 /* GIMPLE_CONDs condition may not throw. */
3902 && (!flag_exceptions
3903 || !cfun->can_throw_non_call_exceptions
3904 || !operation_could_trap_p (rcode,
3905 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
3906 false, NULL_TREE)))
3907 gimple_cond_set_condition (cond_stmt, rcode, ops[0], ops[1]);
3908 else if (rcode == SSA_NAME)
3909 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
3910 build_zero_cst (TREE_TYPE (ops[0])));
3911 else if (rcode == INTEGER_CST)
3913 if (integer_zerop (ops[0]))
3914 gimple_cond_make_false (cond_stmt);
3915 else
3916 gimple_cond_make_true (cond_stmt);
3918 else if (!inplace)
3920 tree res = maybe_push_res_to_seq (rcode, boolean_type_node,
3921 ops, seq);
3922 if (!res)
3923 return false;
3924 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
3925 build_zero_cst (TREE_TYPE (res)));
3927 else
3928 return false;
3929 if (dump_file && (dump_flags & TDF_DETAILS))
3931 fprintf (dump_file, "gimple_simplified to ");
3932 if (!gimple_seq_empty_p (*seq))
3933 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3934 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3935 0, TDF_SLIM);
3937 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3938 return true;
3940 else if (is_gimple_assign (stmt)
3941 && rcode.is_tree_code ())
3943 if (!inplace
3944 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (rcode))
3946 maybe_build_generic_op (rcode,
3947 TREE_TYPE (gimple_assign_lhs (stmt)), ops);
3948 gimple_assign_set_rhs_with_ops (gsi, rcode, ops[0], ops[1], ops[2]);
3949 if (dump_file && (dump_flags & TDF_DETAILS))
3951 fprintf (dump_file, "gimple_simplified to ");
3952 if (!gimple_seq_empty_p (*seq))
3953 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3954 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
3955 0, TDF_SLIM);
3957 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3958 return true;
3961 else if (rcode.is_fn_code ()
3962 && gimple_call_combined_fn (stmt) == rcode)
3964 unsigned i;
3965 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3967 gcc_assert (ops[i] != NULL_TREE);
3968 gimple_call_set_arg (stmt, i, ops[i]);
3970 if (i < 3)
3971 gcc_assert (ops[i] == NULL_TREE);
3972 if (dump_file && (dump_flags & TDF_DETAILS))
3974 fprintf (dump_file, "gimple_simplified to ");
3975 if (!gimple_seq_empty_p (*seq))
3976 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3977 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
3979 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
3980 return true;
3982 else if (!inplace)
3984 if (gimple_has_lhs (stmt))
3986 tree lhs = gimple_get_lhs (stmt);
3987 if (!maybe_push_res_to_seq (rcode, TREE_TYPE (lhs),
3988 ops, seq, lhs))
3989 return false;
3990 if (dump_file && (dump_flags & TDF_DETAILS))
3992 fprintf (dump_file, "gimple_simplified to ");
3993 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
3995 gsi_replace_with_seq_vops (gsi, *seq);
3996 return true;
3998 else
3999 gcc_unreachable ();
4002 return false;
4005 /* Canonicalize MEM_REFs invariant address operand after propagation. */
4007 static bool
4008 maybe_canonicalize_mem_ref_addr (tree *t)
4010 bool res = false;
4012 if (TREE_CODE (*t) == ADDR_EXPR)
4013 t = &TREE_OPERAND (*t, 0);
4015 /* The C and C++ frontends use an ARRAY_REF for indexing with their
4016 generic vector extension. The actual vector referenced is
4017 view-converted to an array type for this purpose. If the index
4018 is constant the canonical representation in the middle-end is a
4019 BIT_FIELD_REF so re-write the former to the latter here. */
4020 if (TREE_CODE (*t) == ARRAY_REF
4021 && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
4022 && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
4023 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
4025 tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
4026 if (VECTOR_TYPE_P (vtype))
4028 tree low = array_ref_low_bound (*t);
4029 if (TREE_CODE (low) == INTEGER_CST)
4031 if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
4033 widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
4034 wi::to_widest (low));
4035 idx = wi::mul (idx, wi::to_widest
4036 (TYPE_SIZE (TREE_TYPE (*t))));
4037 widest_int ext
4038 = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
4039 if (wi::les_p (ext, wi::to_widest (TYPE_SIZE (vtype))))
4041 *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
4042 TREE_TYPE (*t),
4043 TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
4044 TYPE_SIZE (TREE_TYPE (*t)),
4045 wide_int_to_tree (sizetype, idx));
4046 res = true;
4053 while (handled_component_p (*t))
4054 t = &TREE_OPERAND (*t, 0);
4056 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
4057 of invariant addresses into a SSA name MEM_REF address. */
4058 if (TREE_CODE (*t) == MEM_REF
4059 || TREE_CODE (*t) == TARGET_MEM_REF)
4061 tree addr = TREE_OPERAND (*t, 0);
4062 if (TREE_CODE (addr) == ADDR_EXPR
4063 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
4064 || handled_component_p (TREE_OPERAND (addr, 0))))
4066 tree base;
4067 HOST_WIDE_INT coffset;
4068 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
4069 &coffset);
4070 if (!base)
4071 gcc_unreachable ();
4073 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
4074 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
4075 TREE_OPERAND (*t, 1),
4076 size_int (coffset));
4077 res = true;
4079 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
4080 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
4083 /* Canonicalize back MEM_REFs to plain reference trees if the object
4084 accessed is a decl that has the same access semantics as the MEM_REF. */
4085 if (TREE_CODE (*t) == MEM_REF
4086 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
4087 && integer_zerop (TREE_OPERAND (*t, 1))
4088 && MR_DEPENDENCE_CLIQUE (*t) == 0)
4090 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4091 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
4092 if (/* Same volatile qualification. */
4093 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
4094 /* Same TBAA behavior with -fstrict-aliasing. */
4095 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
4096 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
4097 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
4098 /* Same alignment. */
4099 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
4100 /* We have to look out here to not drop a required conversion
4101 from the rhs to the lhs if *t appears on the lhs or vice-versa
4102 if it appears on the rhs. Thus require strict type
4103 compatibility. */
4104 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
4106 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
4107 res = true;
4111 /* Canonicalize TARGET_MEM_REF in particular with respect to
4112 the indexes becoming constant. */
4113 else if (TREE_CODE (*t) == TARGET_MEM_REF)
4115 tree tem = maybe_fold_tmr (*t);
4116 if (tem)
4118 *t = tem;
4119 res = true;
4123 return res;
4126 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
4127 distinguishes both cases. */
4129 static bool
4130 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree))
4132 bool changed = false;
4133 gimple *stmt = gsi_stmt (*gsi);
4134 bool nowarning = gimple_no_warning_p (stmt);
4135 unsigned i;
4136 fold_defer_overflow_warnings ();
4138 /* First do required canonicalization of [TARGET_]MEM_REF addresses
4139 after propagation.
4140 ??? This shouldn't be done in generic folding but in the
4141 propagation helpers which also know whether an address was
4142 propagated.
4143 Also canonicalize operand order. */
4144 switch (gimple_code (stmt))
4146 case GIMPLE_ASSIGN:
4147 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
4149 tree *rhs = gimple_assign_rhs1_ptr (stmt);
4150 if ((REFERENCE_CLASS_P (*rhs)
4151 || TREE_CODE (*rhs) == ADDR_EXPR)
4152 && maybe_canonicalize_mem_ref_addr (rhs))
4153 changed = true;
4154 tree *lhs = gimple_assign_lhs_ptr (stmt);
4155 if (REFERENCE_CLASS_P (*lhs)
4156 && maybe_canonicalize_mem_ref_addr (lhs))
4157 changed = true;
4159 else
4161 /* Canonicalize operand order. */
4162 enum tree_code code = gimple_assign_rhs_code (stmt);
4163 if (TREE_CODE_CLASS (code) == tcc_comparison
4164 || commutative_tree_code (code)
4165 || commutative_ternary_tree_code (code))
4167 tree rhs1 = gimple_assign_rhs1 (stmt);
4168 tree rhs2 = gimple_assign_rhs2 (stmt);
4169 if (tree_swap_operands_p (rhs1, rhs2))
4171 gimple_assign_set_rhs1 (stmt, rhs2);
4172 gimple_assign_set_rhs2 (stmt, rhs1);
4173 if (TREE_CODE_CLASS (code) == tcc_comparison)
4174 gimple_assign_set_rhs_code (stmt,
4175 swap_tree_comparison (code));
4176 changed = true;
4180 break;
4181 case GIMPLE_CALL:
4183 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4185 tree *arg = gimple_call_arg_ptr (stmt, i);
4186 if (REFERENCE_CLASS_P (*arg)
4187 && maybe_canonicalize_mem_ref_addr (arg))
4188 changed = true;
4190 tree *lhs = gimple_call_lhs_ptr (stmt);
4191 if (*lhs
4192 && REFERENCE_CLASS_P (*lhs)
4193 && maybe_canonicalize_mem_ref_addr (lhs))
4194 changed = true;
4195 break;
4197 case GIMPLE_ASM:
4199 gasm *asm_stmt = as_a <gasm *> (stmt);
4200 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4202 tree link = gimple_asm_output_op (asm_stmt, i);
4203 tree op = TREE_VALUE (link);
4204 if (REFERENCE_CLASS_P (op)
4205 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4206 changed = true;
4208 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4210 tree link = gimple_asm_input_op (asm_stmt, i);
4211 tree op = TREE_VALUE (link);
4212 if ((REFERENCE_CLASS_P (op)
4213 || TREE_CODE (op) == ADDR_EXPR)
4214 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
4215 changed = true;
4218 break;
4219 case GIMPLE_DEBUG:
4220 if (gimple_debug_bind_p (stmt))
4222 tree *val = gimple_debug_bind_get_value_ptr (stmt);
4223 if (*val
4224 && (REFERENCE_CLASS_P (*val)
4225 || TREE_CODE (*val) == ADDR_EXPR)
4226 && maybe_canonicalize_mem_ref_addr (val))
4227 changed = true;
4229 break;
4230 case GIMPLE_COND:
4232 /* Canonicalize operand order. */
4233 tree lhs = gimple_cond_lhs (stmt);
4234 tree rhs = gimple_cond_rhs (stmt);
4235 if (tree_swap_operands_p (lhs, rhs))
4237 gcond *gc = as_a <gcond *> (stmt);
4238 gimple_cond_set_lhs (gc, rhs);
4239 gimple_cond_set_rhs (gc, lhs);
4240 gimple_cond_set_code (gc,
4241 swap_tree_comparison (gimple_cond_code (gc)));
4242 changed = true;
4245 default:;
4248 /* Dispatch to pattern-based folding. */
4249 if (!inplace
4250 || is_gimple_assign (stmt)
4251 || gimple_code (stmt) == GIMPLE_COND)
4253 gimple_seq seq = NULL;
4254 code_helper rcode;
4255 tree ops[3] = {};
4256 if (gimple_simplify (stmt, &rcode, ops, inplace ? NULL : &seq,
4257 valueize, valueize))
4259 if (replace_stmt_with_simplification (gsi, rcode, ops, &seq, inplace))
4260 changed = true;
4261 else
4262 gimple_seq_discard (seq);
4266 stmt = gsi_stmt (*gsi);
4268 /* Fold the main computation performed by the statement. */
4269 switch (gimple_code (stmt))
4271 case GIMPLE_ASSIGN:
4273 /* Try to canonicalize for boolean-typed X the comparisons
4274 X == 0, X == 1, X != 0, and X != 1. */
4275 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
4276 || gimple_assign_rhs_code (stmt) == NE_EXPR)
4278 tree lhs = gimple_assign_lhs (stmt);
4279 tree op1 = gimple_assign_rhs1 (stmt);
4280 tree op2 = gimple_assign_rhs2 (stmt);
4281 tree type = TREE_TYPE (op1);
4283 /* Check whether the comparison operands are of the same boolean
4284 type as the result type is.
4285 Check that second operand is an integer-constant with value
4286 one or zero. */
4287 if (TREE_CODE (op2) == INTEGER_CST
4288 && (integer_zerop (op2) || integer_onep (op2))
4289 && useless_type_conversion_p (TREE_TYPE (lhs), type))
4291 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
4292 bool is_logical_not = false;
4294 /* X == 0 and X != 1 is a logical-not.of X
4295 X == 1 and X != 0 is X */
4296 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
4297 || (cmp_code == NE_EXPR && integer_onep (op2)))
4298 is_logical_not = true;
4300 if (is_logical_not == false)
4301 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
4302 /* Only for one-bit precision typed X the transformation
4303 !X -> ~X is valied. */
4304 else if (TYPE_PRECISION (type) == 1)
4305 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
4306 /* Otherwise we use !X -> X ^ 1. */
4307 else
4308 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
4309 build_int_cst (type, 1));
4310 changed = true;
4311 break;
4315 unsigned old_num_ops = gimple_num_ops (stmt);
4316 tree lhs = gimple_assign_lhs (stmt);
4317 tree new_rhs = fold_gimple_assign (gsi);
4318 if (new_rhs
4319 && !useless_type_conversion_p (TREE_TYPE (lhs),
4320 TREE_TYPE (new_rhs)))
4321 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
4322 if (new_rhs
4323 && (!inplace
4324 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
4326 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
4327 changed = true;
4329 break;
4332 case GIMPLE_CALL:
4333 changed |= gimple_fold_call (gsi, inplace);
4334 break;
4336 case GIMPLE_ASM:
4337 /* Fold *& in asm operands. */
4339 gasm *asm_stmt = as_a <gasm *> (stmt);
4340 size_t noutputs;
4341 const char **oconstraints;
4342 const char *constraint;
4343 bool allows_mem, allows_reg;
4345 noutputs = gimple_asm_noutputs (asm_stmt);
4346 oconstraints = XALLOCAVEC (const char *, noutputs);
4348 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
4350 tree link = gimple_asm_output_op (asm_stmt, i);
4351 tree op = TREE_VALUE (link);
4352 oconstraints[i]
4353 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4354 if (REFERENCE_CLASS_P (op)
4355 && (op = maybe_fold_reference (op, true)) != NULL_TREE)
4357 TREE_VALUE (link) = op;
4358 changed = true;
4361 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4363 tree link = gimple_asm_input_op (asm_stmt, i);
4364 tree op = TREE_VALUE (link);
4365 constraint
4366 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4367 parse_input_constraint (&constraint, 0, 0, noutputs, 0,
4368 oconstraints, &allows_mem, &allows_reg);
4369 if (REFERENCE_CLASS_P (op)
4370 && (op = maybe_fold_reference (op, !allows_reg && allows_mem))
4371 != NULL_TREE)
4373 TREE_VALUE (link) = op;
4374 changed = true;
4378 break;
4380 case GIMPLE_DEBUG:
4381 if (gimple_debug_bind_p (stmt))
4383 tree val = gimple_debug_bind_get_value (stmt);
4384 if (val
4385 && REFERENCE_CLASS_P (val))
4387 tree tem = maybe_fold_reference (val, false);
4388 if (tem)
4390 gimple_debug_bind_set_value (stmt, tem);
4391 changed = true;
4394 else if (val
4395 && TREE_CODE (val) == ADDR_EXPR)
4397 tree ref = TREE_OPERAND (val, 0);
4398 tree tem = maybe_fold_reference (ref, false);
4399 if (tem)
4401 tem = build_fold_addr_expr_with_type (tem, TREE_TYPE (val));
4402 gimple_debug_bind_set_value (stmt, tem);
4403 changed = true;
4407 break;
4409 case GIMPLE_RETURN:
4411 greturn *ret_stmt = as_a<greturn *> (stmt);
4412 tree ret = gimple_return_retval(ret_stmt);
4414 if (ret && TREE_CODE (ret) == SSA_NAME && valueize)
4416 tree val = valueize (ret);
4417 if (val && val != ret)
4419 gimple_return_set_retval (ret_stmt, val);
4420 changed = true;
4424 break;
4426 default:;
4429 stmt = gsi_stmt (*gsi);
4431 /* Fold *& on the lhs. */
4432 if (gimple_has_lhs (stmt))
4434 tree lhs = gimple_get_lhs (stmt);
4435 if (lhs && REFERENCE_CLASS_P (lhs))
4437 tree new_lhs = maybe_fold_reference (lhs, true);
4438 if (new_lhs)
4440 gimple_set_lhs (stmt, new_lhs);
4441 changed = true;
4446 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
4447 return changed;
4450 /* Valueziation callback that ends up not following SSA edges. */
4452 tree
4453 no_follow_ssa_edges (tree)
4455 return NULL_TREE;
4458 /* Valueization callback that ends up following single-use SSA edges only. */
4460 tree
4461 follow_single_use_edges (tree val)
4463 if (TREE_CODE (val) == SSA_NAME
4464 && !has_single_use (val))
4465 return NULL_TREE;
4466 return val;
4469 /* Fold the statement pointed to by GSI. In some cases, this function may
4470 replace the whole statement with a new one. Returns true iff folding
4471 makes any changes.
4472 The statement pointed to by GSI should be in valid gimple form but may
4473 be in unfolded state as resulting from for example constant propagation
4474 which can produce *&x = 0. */
4476 bool
4477 fold_stmt (gimple_stmt_iterator *gsi)
4479 return fold_stmt_1 (gsi, false, no_follow_ssa_edges);
4482 bool
4483 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree))
4485 return fold_stmt_1 (gsi, false, valueize);
4488 /* Perform the minimal folding on statement *GSI. Only operations like
4489 *&x created by constant propagation are handled. The statement cannot
4490 be replaced with a new one. Return true if the statement was
4491 changed, false otherwise.
4492 The statement *GSI should be in valid gimple form but may
4493 be in unfolded state as resulting from for example constant propagation
4494 which can produce *&x = 0. */
4496 bool
4497 fold_stmt_inplace (gimple_stmt_iterator *gsi)
4499 gimple *stmt = gsi_stmt (*gsi);
4500 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
4501 gcc_assert (gsi_stmt (*gsi) == stmt);
4502 return changed;
4505 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
4506 if EXPR is null or we don't know how.
4507 If non-null, the result always has boolean type. */
4509 static tree
4510 canonicalize_bool (tree expr, bool invert)
4512 if (!expr)
4513 return NULL_TREE;
4514 else if (invert)
4516 if (integer_nonzerop (expr))
4517 return boolean_false_node;
4518 else if (integer_zerop (expr))
4519 return boolean_true_node;
4520 else if (TREE_CODE (expr) == SSA_NAME)
4521 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
4522 build_int_cst (TREE_TYPE (expr), 0));
4523 else if (COMPARISON_CLASS_P (expr))
4524 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
4525 boolean_type_node,
4526 TREE_OPERAND (expr, 0),
4527 TREE_OPERAND (expr, 1));
4528 else
4529 return NULL_TREE;
4531 else
4533 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4534 return expr;
4535 if (integer_nonzerop (expr))
4536 return boolean_true_node;
4537 else if (integer_zerop (expr))
4538 return boolean_false_node;
4539 else if (TREE_CODE (expr) == SSA_NAME)
4540 return fold_build2 (NE_EXPR, boolean_type_node, expr,
4541 build_int_cst (TREE_TYPE (expr), 0));
4542 else if (COMPARISON_CLASS_P (expr))
4543 return fold_build2 (TREE_CODE (expr),
4544 boolean_type_node,
4545 TREE_OPERAND (expr, 0),
4546 TREE_OPERAND (expr, 1));
4547 else
4548 return NULL_TREE;
4552 /* Check to see if a boolean expression EXPR is logically equivalent to the
4553 comparison (OP1 CODE OP2). Check for various identities involving
4554 SSA_NAMEs. */
4556 static bool
4557 same_bool_comparison_p (const_tree expr, enum tree_code code,
4558 const_tree op1, const_tree op2)
4560 gimple *s;
4562 /* The obvious case. */
4563 if (TREE_CODE (expr) == code
4564 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
4565 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
4566 return true;
4568 /* Check for comparing (name, name != 0) and the case where expr
4569 is an SSA_NAME with a definition matching the comparison. */
4570 if (TREE_CODE (expr) == SSA_NAME
4571 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
4573 if (operand_equal_p (expr, op1, 0))
4574 return ((code == NE_EXPR && integer_zerop (op2))
4575 || (code == EQ_EXPR && integer_nonzerop (op2)));
4576 s = SSA_NAME_DEF_STMT (expr);
4577 if (is_gimple_assign (s)
4578 && gimple_assign_rhs_code (s) == code
4579 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
4580 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
4581 return true;
4584 /* If op1 is of the form (name != 0) or (name == 0), and the definition
4585 of name is a comparison, recurse. */
4586 if (TREE_CODE (op1) == SSA_NAME
4587 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
4589 s = SSA_NAME_DEF_STMT (op1);
4590 if (is_gimple_assign (s)
4591 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
4593 enum tree_code c = gimple_assign_rhs_code (s);
4594 if ((c == NE_EXPR && integer_zerop (op2))
4595 || (c == EQ_EXPR && integer_nonzerop (op2)))
4596 return same_bool_comparison_p (expr, c,
4597 gimple_assign_rhs1 (s),
4598 gimple_assign_rhs2 (s));
4599 if ((c == EQ_EXPR && integer_zerop (op2))
4600 || (c == NE_EXPR && integer_nonzerop (op2)))
4601 return same_bool_comparison_p (expr,
4602 invert_tree_comparison (c, false),
4603 gimple_assign_rhs1 (s),
4604 gimple_assign_rhs2 (s));
4607 return false;
4610 /* Check to see if two boolean expressions OP1 and OP2 are logically
4611 equivalent. */
4613 static bool
4614 same_bool_result_p (const_tree op1, const_tree op2)
4616 /* Simple cases first. */
4617 if (operand_equal_p (op1, op2, 0))
4618 return true;
4620 /* Check the cases where at least one of the operands is a comparison.
4621 These are a bit smarter than operand_equal_p in that they apply some
4622 identifies on SSA_NAMEs. */
4623 if (COMPARISON_CLASS_P (op2)
4624 && same_bool_comparison_p (op1, TREE_CODE (op2),
4625 TREE_OPERAND (op2, 0),
4626 TREE_OPERAND (op2, 1)))
4627 return true;
4628 if (COMPARISON_CLASS_P (op1)
4629 && same_bool_comparison_p (op2, TREE_CODE (op1),
4630 TREE_OPERAND (op1, 0),
4631 TREE_OPERAND (op1, 1)))
4632 return true;
4634 /* Default case. */
4635 return false;
4638 /* Forward declarations for some mutually recursive functions. */
4640 static tree
4641 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4642 enum tree_code code2, tree op2a, tree op2b);
4643 static tree
4644 and_var_with_comparison (tree var, bool invert,
4645 enum tree_code code2, tree op2a, tree op2b);
4646 static tree
4647 and_var_with_comparison_1 (gimple *stmt,
4648 enum tree_code code2, tree op2a, tree op2b);
4649 static tree
4650 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4651 enum tree_code code2, tree op2a, tree op2b);
4652 static tree
4653 or_var_with_comparison (tree var, bool invert,
4654 enum tree_code code2, tree op2a, tree op2b);
4655 static tree
4656 or_var_with_comparison_1 (gimple *stmt,
4657 enum tree_code code2, tree op2a, tree op2b);
4659 /* Helper function for and_comparisons_1: try to simplify the AND of the
4660 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
4661 If INVERT is true, invert the value of the VAR before doing the AND.
4662 Return NULL_EXPR if we can't simplify this to a single expression. */
4664 static tree
4665 and_var_with_comparison (tree var, bool invert,
4666 enum tree_code code2, tree op2a, tree op2b)
4668 tree t;
4669 gimple *stmt = SSA_NAME_DEF_STMT (var);
4671 /* We can only deal with variables whose definitions are assignments. */
4672 if (!is_gimple_assign (stmt))
4673 return NULL_TREE;
4675 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
4676 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
4677 Then we only have to consider the simpler non-inverted cases. */
4678 if (invert)
4679 t = or_var_with_comparison_1 (stmt,
4680 invert_tree_comparison (code2, false),
4681 op2a, op2b);
4682 else
4683 t = and_var_with_comparison_1 (stmt, code2, op2a, op2b);
4684 return canonicalize_bool (t, invert);
4687 /* Try to simplify the AND of the ssa variable defined by the assignment
4688 STMT with the comparison specified by (OP2A CODE2 OP2B).
4689 Return NULL_EXPR if we can't simplify this to a single expression. */
4691 static tree
4692 and_var_with_comparison_1 (gimple *stmt,
4693 enum tree_code code2, tree op2a, tree op2b)
4695 tree var = gimple_assign_lhs (stmt);
4696 tree true_test_var = NULL_TREE;
4697 tree false_test_var = NULL_TREE;
4698 enum tree_code innercode = gimple_assign_rhs_code (stmt);
4700 /* Check for identities like (var AND (var == 0)) => false. */
4701 if (TREE_CODE (op2a) == SSA_NAME
4702 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
4704 if ((code2 == NE_EXPR && integer_zerop (op2b))
4705 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
4707 true_test_var = op2a;
4708 if (var == true_test_var)
4709 return var;
4711 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
4712 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
4714 false_test_var = op2a;
4715 if (var == false_test_var)
4716 return boolean_false_node;
4720 /* If the definition is a comparison, recurse on it. */
4721 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
4723 tree t = and_comparisons_1 (innercode,
4724 gimple_assign_rhs1 (stmt),
4725 gimple_assign_rhs2 (stmt),
4726 code2,
4727 op2a,
4728 op2b);
4729 if (t)
4730 return t;
4733 /* If the definition is an AND or OR expression, we may be able to
4734 simplify by reassociating. */
4735 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
4736 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
4738 tree inner1 = gimple_assign_rhs1 (stmt);
4739 tree inner2 = gimple_assign_rhs2 (stmt);
4740 gimple *s;
4741 tree t;
4742 tree partial = NULL_TREE;
4743 bool is_and = (innercode == BIT_AND_EXPR);
4745 /* Check for boolean identities that don't require recursive examination
4746 of inner1/inner2:
4747 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
4748 inner1 AND (inner1 OR inner2) => inner1
4749 !inner1 AND (inner1 AND inner2) => false
4750 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
4751 Likewise for similar cases involving inner2. */
4752 if (inner1 == true_test_var)
4753 return (is_and ? var : inner1);
4754 else if (inner2 == true_test_var)
4755 return (is_and ? var : inner2);
4756 else if (inner1 == false_test_var)
4757 return (is_and
4758 ? boolean_false_node
4759 : and_var_with_comparison (inner2, false, code2, op2a, op2b));
4760 else if (inner2 == false_test_var)
4761 return (is_and
4762 ? boolean_false_node
4763 : and_var_with_comparison (inner1, false, code2, op2a, op2b));
4765 /* Next, redistribute/reassociate the AND across the inner tests.
4766 Compute the first partial result, (inner1 AND (op2a code op2b)) */
4767 if (TREE_CODE (inner1) == SSA_NAME
4768 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
4769 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4770 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4771 gimple_assign_rhs1 (s),
4772 gimple_assign_rhs2 (s),
4773 code2, op2a, op2b)))
4775 /* Handle the AND case, where we are reassociating:
4776 (inner1 AND inner2) AND (op2a code2 op2b)
4777 => (t AND inner2)
4778 If the partial result t is a constant, we win. Otherwise
4779 continue on to try reassociating with the other inner test. */
4780 if (is_and)
4782 if (integer_onep (t))
4783 return inner2;
4784 else if (integer_zerop (t))
4785 return boolean_false_node;
4788 /* Handle the OR case, where we are redistributing:
4789 (inner1 OR inner2) AND (op2a code2 op2b)
4790 => (t OR (inner2 AND (op2a code2 op2b))) */
4791 else if (integer_onep (t))
4792 return boolean_true_node;
4794 /* Save partial result for later. */
4795 partial = t;
4798 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
4799 if (TREE_CODE (inner2) == SSA_NAME
4800 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
4801 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
4802 && (t = maybe_fold_and_comparisons (gimple_assign_rhs_code (s),
4803 gimple_assign_rhs1 (s),
4804 gimple_assign_rhs2 (s),
4805 code2, op2a, op2b)))
4807 /* Handle the AND case, where we are reassociating:
4808 (inner1 AND inner2) AND (op2a code2 op2b)
4809 => (inner1 AND t) */
4810 if (is_and)
4812 if (integer_onep (t))
4813 return inner1;
4814 else if (integer_zerop (t))
4815 return boolean_false_node;
4816 /* If both are the same, we can apply the identity
4817 (x AND x) == x. */
4818 else if (partial && same_bool_result_p (t, partial))
4819 return t;
4822 /* Handle the OR case. where we are redistributing:
4823 (inner1 OR inner2) AND (op2a code2 op2b)
4824 => (t OR (inner1 AND (op2a code2 op2b)))
4825 => (t OR partial) */
4826 else
4828 if (integer_onep (t))
4829 return boolean_true_node;
4830 else if (partial)
4832 /* We already got a simplification for the other
4833 operand to the redistributed OR expression. The
4834 interesting case is when at least one is false.
4835 Or, if both are the same, we can apply the identity
4836 (x OR x) == x. */
4837 if (integer_zerop (partial))
4838 return t;
4839 else if (integer_zerop (t))
4840 return partial;
4841 else if (same_bool_result_p (t, partial))
4842 return t;
4847 return NULL_TREE;
4850 /* Try to simplify the AND of two comparisons defined by
4851 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
4852 If this can be done without constructing an intermediate value,
4853 return the resulting tree; otherwise NULL_TREE is returned.
4854 This function is deliberately asymmetric as it recurses on SSA_DEFs
4855 in the first comparison but not the second. */
4857 static tree
4858 and_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
4859 enum tree_code code2, tree op2a, tree op2b)
4861 tree truth_type = truth_type_for (TREE_TYPE (op1a));
4863 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
4864 if (operand_equal_p (op1a, op2a, 0)
4865 && operand_equal_p (op1b, op2b, 0))
4867 /* Result will be either NULL_TREE, or a combined comparison. */
4868 tree t = combine_comparisons (UNKNOWN_LOCATION,
4869 TRUTH_ANDIF_EXPR, code1, code2,
4870 truth_type, op1a, op1b);
4871 if (t)
4872 return t;
4875 /* Likewise the swapped case of the above. */
4876 if (operand_equal_p (op1a, op2b, 0)
4877 && operand_equal_p (op1b, op2a, 0))
4879 /* Result will be either NULL_TREE, or a combined comparison. */
4880 tree t = combine_comparisons (UNKNOWN_LOCATION,
4881 TRUTH_ANDIF_EXPR, code1,
4882 swap_tree_comparison (code2),
4883 truth_type, op1a, op1b);
4884 if (t)
4885 return t;
4888 /* If both comparisons are of the same value against constants, we might
4889 be able to merge them. */
4890 if (operand_equal_p (op1a, op2a, 0)
4891 && TREE_CODE (op1b) == INTEGER_CST
4892 && TREE_CODE (op2b) == INTEGER_CST)
4894 int cmp = tree_int_cst_compare (op1b, op2b);
4896 /* If we have (op1a == op1b), we should either be able to
4897 return that or FALSE, depending on whether the constant op1b
4898 also satisfies the other comparison against op2b. */
4899 if (code1 == EQ_EXPR)
4901 bool done = true;
4902 bool val;
4903 switch (code2)
4905 case EQ_EXPR: val = (cmp == 0); break;
4906 case NE_EXPR: val = (cmp != 0); break;
4907 case LT_EXPR: val = (cmp < 0); break;
4908 case GT_EXPR: val = (cmp > 0); break;
4909 case LE_EXPR: val = (cmp <= 0); break;
4910 case GE_EXPR: val = (cmp >= 0); break;
4911 default: done = false;
4913 if (done)
4915 if (val)
4916 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4917 else
4918 return boolean_false_node;
4921 /* Likewise if the second comparison is an == comparison. */
4922 else if (code2 == EQ_EXPR)
4924 bool done = true;
4925 bool val;
4926 switch (code1)
4928 case EQ_EXPR: val = (cmp == 0); break;
4929 case NE_EXPR: val = (cmp != 0); break;
4930 case LT_EXPR: val = (cmp > 0); break;
4931 case GT_EXPR: val = (cmp < 0); break;
4932 case LE_EXPR: val = (cmp >= 0); break;
4933 case GE_EXPR: val = (cmp <= 0); break;
4934 default: done = false;
4936 if (done)
4938 if (val)
4939 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4940 else
4941 return boolean_false_node;
4945 /* Same business with inequality tests. */
4946 else if (code1 == NE_EXPR)
4948 bool val;
4949 switch (code2)
4951 case EQ_EXPR: val = (cmp != 0); break;
4952 case NE_EXPR: val = (cmp == 0); break;
4953 case LT_EXPR: val = (cmp >= 0); break;
4954 case GT_EXPR: val = (cmp <= 0); break;
4955 case LE_EXPR: val = (cmp > 0); break;
4956 case GE_EXPR: val = (cmp < 0); break;
4957 default:
4958 val = false;
4960 if (val)
4961 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4963 else if (code2 == NE_EXPR)
4965 bool val;
4966 switch (code1)
4968 case EQ_EXPR: val = (cmp == 0); break;
4969 case NE_EXPR: val = (cmp != 0); break;
4970 case LT_EXPR: val = (cmp <= 0); break;
4971 case GT_EXPR: val = (cmp >= 0); break;
4972 case LE_EXPR: val = (cmp < 0); break;
4973 case GE_EXPR: val = (cmp > 0); break;
4974 default:
4975 val = false;
4977 if (val)
4978 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4981 /* Chose the more restrictive of two < or <= comparisons. */
4982 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
4983 && (code2 == LT_EXPR || code2 == LE_EXPR))
4985 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
4986 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4987 else
4988 return fold_build2 (code2, boolean_type_node, op2a, op2b);
4991 /* Likewise chose the more restrictive of two > or >= comparisons. */
4992 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
4993 && (code2 == GT_EXPR || code2 == GE_EXPR))
4995 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
4996 return fold_build2 (code1, boolean_type_node, op1a, op1b);
4997 else
4998 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5001 /* Check for singleton ranges. */
5002 else if (cmp == 0
5003 && ((code1 == LE_EXPR && code2 == GE_EXPR)
5004 || (code1 == GE_EXPR && code2 == LE_EXPR)))
5005 return fold_build2 (EQ_EXPR, boolean_type_node, op1a, op2b);
5007 /* Check for disjoint ranges. */
5008 else if (cmp <= 0
5009 && (code1 == LT_EXPR || code1 == LE_EXPR)
5010 && (code2 == GT_EXPR || code2 == GE_EXPR))
5011 return boolean_false_node;
5012 else if (cmp >= 0
5013 && (code1 == GT_EXPR || code1 == GE_EXPR)
5014 && (code2 == LT_EXPR || code2 == LE_EXPR))
5015 return boolean_false_node;
5018 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5019 NAME's definition is a truth value. See if there are any simplifications
5020 that can be done against the NAME's definition. */
5021 if (TREE_CODE (op1a) == SSA_NAME
5022 && (code1 == NE_EXPR || code1 == EQ_EXPR)
5023 && (integer_zerop (op1b) || integer_onep (op1b)))
5025 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5026 || (code1 == NE_EXPR && integer_onep (op1b)));
5027 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5028 switch (gimple_code (stmt))
5030 case GIMPLE_ASSIGN:
5031 /* Try to simplify by copy-propagating the definition. */
5032 return and_var_with_comparison (op1a, invert, code2, op2a, op2b);
5034 case GIMPLE_PHI:
5035 /* If every argument to the PHI produces the same result when
5036 ANDed with the second comparison, we win.
5037 Do not do this unless the type is bool since we need a bool
5038 result here anyway. */
5039 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5041 tree result = NULL_TREE;
5042 unsigned i;
5043 for (i = 0; i < gimple_phi_num_args (stmt); i++)
5045 tree arg = gimple_phi_arg_def (stmt, i);
5047 /* If this PHI has itself as an argument, ignore it.
5048 If all the other args produce the same result,
5049 we're still OK. */
5050 if (arg == gimple_phi_result (stmt))
5051 continue;
5052 else if (TREE_CODE (arg) == INTEGER_CST)
5054 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
5056 if (!result)
5057 result = boolean_false_node;
5058 else if (!integer_zerop (result))
5059 return NULL_TREE;
5061 else if (!result)
5062 result = fold_build2 (code2, boolean_type_node,
5063 op2a, op2b);
5064 else if (!same_bool_comparison_p (result,
5065 code2, op2a, op2b))
5066 return NULL_TREE;
5068 else if (TREE_CODE (arg) == SSA_NAME
5069 && !SSA_NAME_IS_DEFAULT_DEF (arg))
5071 tree temp;
5072 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5073 /* In simple cases we can look through PHI nodes,
5074 but we have to be careful with loops.
5075 See PR49073. */
5076 if (! dom_info_available_p (CDI_DOMINATORS)
5077 || gimple_bb (def_stmt) == gimple_bb (stmt)
5078 || dominated_by_p (CDI_DOMINATORS,
5079 gimple_bb (def_stmt),
5080 gimple_bb (stmt)))
5081 return NULL_TREE;
5082 temp = and_var_with_comparison (arg, invert, code2,
5083 op2a, op2b);
5084 if (!temp)
5085 return NULL_TREE;
5086 else if (!result)
5087 result = temp;
5088 else if (!same_bool_result_p (result, temp))
5089 return NULL_TREE;
5091 else
5092 return NULL_TREE;
5094 return result;
5097 default:
5098 break;
5101 return NULL_TREE;
5104 /* Try to simplify the AND of two comparisons, specified by
5105 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5106 If this can be simplified to a single expression (without requiring
5107 introducing more SSA variables to hold intermediate values),
5108 return the resulting tree. Otherwise return NULL_TREE.
5109 If the result expression is non-null, it has boolean type. */
5111 tree
5112 maybe_fold_and_comparisons (enum tree_code code1, tree op1a, tree op1b,
5113 enum tree_code code2, tree op2a, tree op2b)
5115 tree t = and_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5116 if (t)
5117 return t;
5118 else
5119 return and_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5122 /* Helper function for or_comparisons_1: try to simplify the OR of the
5123 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
5124 If INVERT is true, invert the value of VAR before doing the OR.
5125 Return NULL_EXPR if we can't simplify this to a single expression. */
5127 static tree
5128 or_var_with_comparison (tree var, bool invert,
5129 enum tree_code code2, tree op2a, tree op2b)
5131 tree t;
5132 gimple *stmt = SSA_NAME_DEF_STMT (var);
5134 /* We can only deal with variables whose definitions are assignments. */
5135 if (!is_gimple_assign (stmt))
5136 return NULL_TREE;
5138 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
5139 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
5140 Then we only have to consider the simpler non-inverted cases. */
5141 if (invert)
5142 t = and_var_with_comparison_1 (stmt,
5143 invert_tree_comparison (code2, false),
5144 op2a, op2b);
5145 else
5146 t = or_var_with_comparison_1 (stmt, code2, op2a, op2b);
5147 return canonicalize_bool (t, invert);
5150 /* Try to simplify the OR of the ssa variable defined by the assignment
5151 STMT with the comparison specified by (OP2A CODE2 OP2B).
5152 Return NULL_EXPR if we can't simplify this to a single expression. */
5154 static tree
5155 or_var_with_comparison_1 (gimple *stmt,
5156 enum tree_code code2, tree op2a, tree op2b)
5158 tree var = gimple_assign_lhs (stmt);
5159 tree true_test_var = NULL_TREE;
5160 tree false_test_var = NULL_TREE;
5161 enum tree_code innercode = gimple_assign_rhs_code (stmt);
5163 /* Check for identities like (var OR (var != 0)) => true . */
5164 if (TREE_CODE (op2a) == SSA_NAME
5165 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
5167 if ((code2 == NE_EXPR && integer_zerop (op2b))
5168 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
5170 true_test_var = op2a;
5171 if (var == true_test_var)
5172 return var;
5174 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
5175 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
5177 false_test_var = op2a;
5178 if (var == false_test_var)
5179 return boolean_true_node;
5183 /* If the definition is a comparison, recurse on it. */
5184 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
5186 tree t = or_comparisons_1 (innercode,
5187 gimple_assign_rhs1 (stmt),
5188 gimple_assign_rhs2 (stmt),
5189 code2,
5190 op2a,
5191 op2b);
5192 if (t)
5193 return t;
5196 /* If the definition is an AND or OR expression, we may be able to
5197 simplify by reassociating. */
5198 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
5199 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
5201 tree inner1 = gimple_assign_rhs1 (stmt);
5202 tree inner2 = gimple_assign_rhs2 (stmt);
5203 gimple *s;
5204 tree t;
5205 tree partial = NULL_TREE;
5206 bool is_or = (innercode == BIT_IOR_EXPR);
5208 /* Check for boolean identities that don't require recursive examination
5209 of inner1/inner2:
5210 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
5211 inner1 OR (inner1 AND inner2) => inner1
5212 !inner1 OR (inner1 OR inner2) => true
5213 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
5215 if (inner1 == true_test_var)
5216 return (is_or ? var : inner1);
5217 else if (inner2 == true_test_var)
5218 return (is_or ? var : inner2);
5219 else if (inner1 == false_test_var)
5220 return (is_or
5221 ? boolean_true_node
5222 : or_var_with_comparison (inner2, false, code2, op2a, op2b));
5223 else if (inner2 == false_test_var)
5224 return (is_or
5225 ? boolean_true_node
5226 : or_var_with_comparison (inner1, false, code2, op2a, op2b));
5228 /* Next, redistribute/reassociate the OR across the inner tests.
5229 Compute the first partial result, (inner1 OR (op2a code op2b)) */
5230 if (TREE_CODE (inner1) == SSA_NAME
5231 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
5232 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5233 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5234 gimple_assign_rhs1 (s),
5235 gimple_assign_rhs2 (s),
5236 code2, op2a, op2b)))
5238 /* Handle the OR case, where we are reassociating:
5239 (inner1 OR inner2) OR (op2a code2 op2b)
5240 => (t OR inner2)
5241 If the partial result t is a constant, we win. Otherwise
5242 continue on to try reassociating with the other inner test. */
5243 if (is_or)
5245 if (integer_onep (t))
5246 return boolean_true_node;
5247 else if (integer_zerop (t))
5248 return inner2;
5251 /* Handle the AND case, where we are redistributing:
5252 (inner1 AND inner2) OR (op2a code2 op2b)
5253 => (t AND (inner2 OR (op2a code op2b))) */
5254 else if (integer_zerop (t))
5255 return boolean_false_node;
5257 /* Save partial result for later. */
5258 partial = t;
5261 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
5262 if (TREE_CODE (inner2) == SSA_NAME
5263 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
5264 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
5265 && (t = maybe_fold_or_comparisons (gimple_assign_rhs_code (s),
5266 gimple_assign_rhs1 (s),
5267 gimple_assign_rhs2 (s),
5268 code2, op2a, op2b)))
5270 /* Handle the OR case, where we are reassociating:
5271 (inner1 OR inner2) OR (op2a code2 op2b)
5272 => (inner1 OR t)
5273 => (t OR partial) */
5274 if (is_or)
5276 if (integer_zerop (t))
5277 return inner1;
5278 else if (integer_onep (t))
5279 return boolean_true_node;
5280 /* If both are the same, we can apply the identity
5281 (x OR x) == x. */
5282 else if (partial && same_bool_result_p (t, partial))
5283 return t;
5286 /* Handle the AND case, where we are redistributing:
5287 (inner1 AND inner2) OR (op2a code2 op2b)
5288 => (t AND (inner1 OR (op2a code2 op2b)))
5289 => (t AND partial) */
5290 else
5292 if (integer_zerop (t))
5293 return boolean_false_node;
5294 else if (partial)
5296 /* We already got a simplification for the other
5297 operand to the redistributed AND expression. The
5298 interesting case is when at least one is true.
5299 Or, if both are the same, we can apply the identity
5300 (x AND x) == x. */
5301 if (integer_onep (partial))
5302 return t;
5303 else if (integer_onep (t))
5304 return partial;
5305 else if (same_bool_result_p (t, partial))
5306 return t;
5311 return NULL_TREE;
5314 /* Try to simplify the OR of two comparisons defined by
5315 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
5316 If this can be done without constructing an intermediate value,
5317 return the resulting tree; otherwise NULL_TREE is returned.
5318 This function is deliberately asymmetric as it recurses on SSA_DEFs
5319 in the first comparison but not the second. */
5321 static tree
5322 or_comparisons_1 (enum tree_code code1, tree op1a, tree op1b,
5323 enum tree_code code2, tree op2a, tree op2b)
5325 tree truth_type = truth_type_for (TREE_TYPE (op1a));
5327 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
5328 if (operand_equal_p (op1a, op2a, 0)
5329 && operand_equal_p (op1b, op2b, 0))
5331 /* Result will be either NULL_TREE, or a combined comparison. */
5332 tree t = combine_comparisons (UNKNOWN_LOCATION,
5333 TRUTH_ORIF_EXPR, code1, code2,
5334 truth_type, op1a, op1b);
5335 if (t)
5336 return t;
5339 /* Likewise the swapped case of the above. */
5340 if (operand_equal_p (op1a, op2b, 0)
5341 && operand_equal_p (op1b, op2a, 0))
5343 /* Result will be either NULL_TREE, or a combined comparison. */
5344 tree t = combine_comparisons (UNKNOWN_LOCATION,
5345 TRUTH_ORIF_EXPR, code1,
5346 swap_tree_comparison (code2),
5347 truth_type, op1a, op1b);
5348 if (t)
5349 return t;
5352 /* If both comparisons are of the same value against constants, we might
5353 be able to merge them. */
5354 if (operand_equal_p (op1a, op2a, 0)
5355 && TREE_CODE (op1b) == INTEGER_CST
5356 && TREE_CODE (op2b) == INTEGER_CST)
5358 int cmp = tree_int_cst_compare (op1b, op2b);
5360 /* If we have (op1a != op1b), we should either be able to
5361 return that or TRUE, depending on whether the constant op1b
5362 also satisfies the other comparison against op2b. */
5363 if (code1 == NE_EXPR)
5365 bool done = true;
5366 bool val;
5367 switch (code2)
5369 case EQ_EXPR: val = (cmp == 0); break;
5370 case NE_EXPR: val = (cmp != 0); break;
5371 case LT_EXPR: val = (cmp < 0); break;
5372 case GT_EXPR: val = (cmp > 0); break;
5373 case LE_EXPR: val = (cmp <= 0); break;
5374 case GE_EXPR: val = (cmp >= 0); break;
5375 default: done = false;
5377 if (done)
5379 if (val)
5380 return boolean_true_node;
5381 else
5382 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5385 /* Likewise if the second comparison is a != comparison. */
5386 else if (code2 == NE_EXPR)
5388 bool done = true;
5389 bool val;
5390 switch (code1)
5392 case EQ_EXPR: val = (cmp == 0); break;
5393 case NE_EXPR: val = (cmp != 0); break;
5394 case LT_EXPR: val = (cmp > 0); break;
5395 case GT_EXPR: val = (cmp < 0); break;
5396 case LE_EXPR: val = (cmp >= 0); break;
5397 case GE_EXPR: val = (cmp <= 0); break;
5398 default: done = false;
5400 if (done)
5402 if (val)
5403 return boolean_true_node;
5404 else
5405 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5409 /* See if an equality test is redundant with the other comparison. */
5410 else if (code1 == EQ_EXPR)
5412 bool val;
5413 switch (code2)
5415 case EQ_EXPR: val = (cmp == 0); break;
5416 case NE_EXPR: val = (cmp != 0); break;
5417 case LT_EXPR: val = (cmp < 0); break;
5418 case GT_EXPR: val = (cmp > 0); break;
5419 case LE_EXPR: val = (cmp <= 0); break;
5420 case GE_EXPR: val = (cmp >= 0); break;
5421 default:
5422 val = false;
5424 if (val)
5425 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5427 else if (code2 == EQ_EXPR)
5429 bool val;
5430 switch (code1)
5432 case EQ_EXPR: val = (cmp == 0); break;
5433 case NE_EXPR: val = (cmp != 0); break;
5434 case LT_EXPR: val = (cmp > 0); break;
5435 case GT_EXPR: val = (cmp < 0); break;
5436 case LE_EXPR: val = (cmp >= 0); break;
5437 case GE_EXPR: val = (cmp <= 0); break;
5438 default:
5439 val = false;
5441 if (val)
5442 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5445 /* Chose the less restrictive of two < or <= comparisons. */
5446 else if ((code1 == LT_EXPR || code1 == LE_EXPR)
5447 && (code2 == LT_EXPR || code2 == LE_EXPR))
5449 if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
5450 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5451 else
5452 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5455 /* Likewise chose the less restrictive of two > or >= comparisons. */
5456 else if ((code1 == GT_EXPR || code1 == GE_EXPR)
5457 && (code2 == GT_EXPR || code2 == GE_EXPR))
5459 if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
5460 return fold_build2 (code2, boolean_type_node, op2a, op2b);
5461 else
5462 return fold_build2 (code1, boolean_type_node, op1a, op1b);
5465 /* Check for singleton ranges. */
5466 else if (cmp == 0
5467 && ((code1 == LT_EXPR && code2 == GT_EXPR)
5468 || (code1 == GT_EXPR && code2 == LT_EXPR)))
5469 return fold_build2 (NE_EXPR, boolean_type_node, op1a, op2b);
5471 /* Check for less/greater pairs that don't restrict the range at all. */
5472 else if (cmp >= 0
5473 && (code1 == LT_EXPR || code1 == LE_EXPR)
5474 && (code2 == GT_EXPR || code2 == GE_EXPR))
5475 return boolean_true_node;
5476 else if (cmp <= 0
5477 && (code1 == GT_EXPR || code1 == GE_EXPR)
5478 && (code2 == LT_EXPR || code2 == LE_EXPR))
5479 return boolean_true_node;
5482 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
5483 NAME's definition is a truth value. See if there are any simplifications
5484 that can be done against the NAME's definition. */
5485 if (TREE_CODE (op1a) == SSA_NAME
5486 && (code1 == NE_EXPR || code1 == EQ_EXPR)
5487 && (integer_zerop (op1b) || integer_onep (op1b)))
5489 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
5490 || (code1 == NE_EXPR && integer_onep (op1b)));
5491 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
5492 switch (gimple_code (stmt))
5494 case GIMPLE_ASSIGN:
5495 /* Try to simplify by copy-propagating the definition. */
5496 return or_var_with_comparison (op1a, invert, code2, op2a, op2b);
5498 case GIMPLE_PHI:
5499 /* If every argument to the PHI produces the same result when
5500 ORed with the second comparison, we win.
5501 Do not do this unless the type is bool since we need a bool
5502 result here anyway. */
5503 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
5505 tree result = NULL_TREE;
5506 unsigned i;
5507 for (i = 0; i < gimple_phi_num_args (stmt); i++)
5509 tree arg = gimple_phi_arg_def (stmt, i);
5511 /* If this PHI has itself as an argument, ignore it.
5512 If all the other args produce the same result,
5513 we're still OK. */
5514 if (arg == gimple_phi_result (stmt))
5515 continue;
5516 else if (TREE_CODE (arg) == INTEGER_CST)
5518 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
5520 if (!result)
5521 result = boolean_true_node;
5522 else if (!integer_onep (result))
5523 return NULL_TREE;
5525 else if (!result)
5526 result = fold_build2 (code2, boolean_type_node,
5527 op2a, op2b);
5528 else if (!same_bool_comparison_p (result,
5529 code2, op2a, op2b))
5530 return NULL_TREE;
5532 else if (TREE_CODE (arg) == SSA_NAME
5533 && !SSA_NAME_IS_DEFAULT_DEF (arg))
5535 tree temp;
5536 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
5537 /* In simple cases we can look through PHI nodes,
5538 but we have to be careful with loops.
5539 See PR49073. */
5540 if (! dom_info_available_p (CDI_DOMINATORS)
5541 || gimple_bb (def_stmt) == gimple_bb (stmt)
5542 || dominated_by_p (CDI_DOMINATORS,
5543 gimple_bb (def_stmt),
5544 gimple_bb (stmt)))
5545 return NULL_TREE;
5546 temp = or_var_with_comparison (arg, invert, code2,
5547 op2a, op2b);
5548 if (!temp)
5549 return NULL_TREE;
5550 else if (!result)
5551 result = temp;
5552 else if (!same_bool_result_p (result, temp))
5553 return NULL_TREE;
5555 else
5556 return NULL_TREE;
5558 return result;
5561 default:
5562 break;
5565 return NULL_TREE;
5568 /* Try to simplify the OR of two comparisons, specified by
5569 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
5570 If this can be simplified to a single expression (without requiring
5571 introducing more SSA variables to hold intermediate values),
5572 return the resulting tree. Otherwise return NULL_TREE.
5573 If the result expression is non-null, it has boolean type. */
5575 tree
5576 maybe_fold_or_comparisons (enum tree_code code1, tree op1a, tree op1b,
5577 enum tree_code code2, tree op2a, tree op2b)
5579 tree t = or_comparisons_1 (code1, op1a, op1b, code2, op2a, op2b);
5580 if (t)
5581 return t;
5582 else
5583 return or_comparisons_1 (code2, op2a, op2b, code1, op1a, op1b);
5587 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5589 Either NULL_TREE, a simplified but non-constant or a constant
5590 is returned.
5592 ??? This should go into a gimple-fold-inline.h file to be eventually
5593 privatized with the single valueize function used in the various TUs
5594 to avoid the indirect function call overhead. */
5596 tree
5597 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
5598 tree (*gvalueize) (tree))
5600 code_helper rcode;
5601 tree ops[3] = {};
5602 /* ??? The SSA propagators do not correctly deal with following SSA use-def
5603 edges if there are intermediate VARYING defs. For this reason
5604 do not follow SSA edges here even though SCCVN can technically
5605 just deal fine with that. */
5606 if (gimple_simplify (stmt, &rcode, ops, NULL, gvalueize, valueize))
5608 tree res = NULL_TREE;
5609 if (gimple_simplified_result_is_gimple_val (rcode, ops))
5610 res = ops[0];
5611 else if (mprts_hook)
5612 res = mprts_hook (rcode, gimple_expr_type (stmt), ops);
5613 if (res)
5615 if (dump_file && dump_flags & TDF_DETAILS)
5617 fprintf (dump_file, "Match-and-simplified ");
5618 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
5619 fprintf (dump_file, " to ");
5620 print_generic_expr (dump_file, res, 0);
5621 fprintf (dump_file, "\n");
5623 return res;
5627 location_t loc = gimple_location (stmt);
5628 switch (gimple_code (stmt))
5630 case GIMPLE_ASSIGN:
5632 enum tree_code subcode = gimple_assign_rhs_code (stmt);
5634 switch (get_gimple_rhs_class (subcode))
5636 case GIMPLE_SINGLE_RHS:
5638 tree rhs = gimple_assign_rhs1 (stmt);
5639 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
5641 if (TREE_CODE (rhs) == SSA_NAME)
5643 /* If the RHS is an SSA_NAME, return its known constant value,
5644 if any. */
5645 return (*valueize) (rhs);
5647 /* Handle propagating invariant addresses into address
5648 operations. */
5649 else if (TREE_CODE (rhs) == ADDR_EXPR
5650 && !is_gimple_min_invariant (rhs))
5652 HOST_WIDE_INT offset = 0;
5653 tree base;
5654 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
5655 &offset,
5656 valueize);
5657 if (base
5658 && (CONSTANT_CLASS_P (base)
5659 || decl_address_invariant_p (base)))
5660 return build_invariant_address (TREE_TYPE (rhs),
5661 base, offset);
5663 else if (TREE_CODE (rhs) == CONSTRUCTOR
5664 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
5665 && (CONSTRUCTOR_NELTS (rhs)
5666 == TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
5668 unsigned i;
5669 tree val, *vec;
5671 vec = XALLOCAVEC (tree,
5672 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)));
5673 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
5675 val = (*valueize) (val);
5676 if (TREE_CODE (val) == INTEGER_CST
5677 || TREE_CODE (val) == REAL_CST
5678 || TREE_CODE (val) == FIXED_CST)
5679 vec[i] = val;
5680 else
5681 return NULL_TREE;
5684 return build_vector (TREE_TYPE (rhs), vec);
5686 if (subcode == OBJ_TYPE_REF)
5688 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
5689 /* If callee is constant, we can fold away the wrapper. */
5690 if (is_gimple_min_invariant (val))
5691 return val;
5694 if (kind == tcc_reference)
5696 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
5697 || TREE_CODE (rhs) == REALPART_EXPR
5698 || TREE_CODE (rhs) == IMAGPART_EXPR)
5699 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5701 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5702 return fold_unary_loc (EXPR_LOCATION (rhs),
5703 TREE_CODE (rhs),
5704 TREE_TYPE (rhs), val);
5706 else if (TREE_CODE (rhs) == BIT_FIELD_REF
5707 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5709 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5710 return fold_ternary_loc (EXPR_LOCATION (rhs),
5711 TREE_CODE (rhs),
5712 TREE_TYPE (rhs), val,
5713 TREE_OPERAND (rhs, 1),
5714 TREE_OPERAND (rhs, 2));
5716 else if (TREE_CODE (rhs) == MEM_REF
5717 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
5719 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
5720 if (TREE_CODE (val) == ADDR_EXPR
5721 && is_gimple_min_invariant (val))
5723 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
5724 unshare_expr (val),
5725 TREE_OPERAND (rhs, 1));
5726 if (tem)
5727 rhs = tem;
5730 return fold_const_aggregate_ref_1 (rhs, valueize);
5732 else if (kind == tcc_declaration)
5733 return get_symbol_constant_value (rhs);
5734 return rhs;
5737 case GIMPLE_UNARY_RHS:
5738 return NULL_TREE;
5740 case GIMPLE_BINARY_RHS:
5741 /* Translate &x + CST into an invariant form suitable for
5742 further propagation. */
5743 if (subcode == POINTER_PLUS_EXPR)
5745 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5746 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5747 if (TREE_CODE (op0) == ADDR_EXPR
5748 && TREE_CODE (op1) == INTEGER_CST)
5750 tree off = fold_convert (ptr_type_node, op1);
5751 return build_fold_addr_expr_loc
5752 (loc,
5753 fold_build2 (MEM_REF,
5754 TREE_TYPE (TREE_TYPE (op0)),
5755 unshare_expr (op0), off));
5758 /* Canonicalize bool != 0 and bool == 0 appearing after
5759 valueization. While gimple_simplify handles this
5760 it can get confused by the ~X == 1 -> X == 0 transform
5761 which we cant reduce to a SSA name or a constant
5762 (and we have no way to tell gimple_simplify to not
5763 consider those transforms in the first place). */
5764 else if (subcode == EQ_EXPR
5765 || subcode == NE_EXPR)
5767 tree lhs = gimple_assign_lhs (stmt);
5768 tree op0 = gimple_assign_rhs1 (stmt);
5769 if (useless_type_conversion_p (TREE_TYPE (lhs),
5770 TREE_TYPE (op0)))
5772 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5773 op0 = (*valueize) (op0);
5774 if (TREE_CODE (op0) == INTEGER_CST)
5775 std::swap (op0, op1);
5776 if (TREE_CODE (op1) == INTEGER_CST
5777 && ((subcode == NE_EXPR && integer_zerop (op1))
5778 || (subcode == EQ_EXPR && integer_onep (op1))))
5779 return op0;
5782 return NULL_TREE;
5784 case GIMPLE_TERNARY_RHS:
5786 /* Handle ternary operators that can appear in GIMPLE form. */
5787 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
5788 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
5789 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
5790 return fold_ternary_loc (loc, subcode,
5791 gimple_expr_type (stmt), op0, op1, op2);
5794 default:
5795 gcc_unreachable ();
5799 case GIMPLE_CALL:
5801 tree fn;
5802 gcall *call_stmt = as_a <gcall *> (stmt);
5804 if (gimple_call_internal_p (stmt))
5806 enum tree_code subcode = ERROR_MARK;
5807 switch (gimple_call_internal_fn (stmt))
5809 case IFN_UBSAN_CHECK_ADD:
5810 subcode = PLUS_EXPR;
5811 break;
5812 case IFN_UBSAN_CHECK_SUB:
5813 subcode = MINUS_EXPR;
5814 break;
5815 case IFN_UBSAN_CHECK_MUL:
5816 subcode = MULT_EXPR;
5817 break;
5818 case IFN_BUILTIN_EXPECT:
5820 tree arg0 = gimple_call_arg (stmt, 0);
5821 tree op0 = (*valueize) (arg0);
5822 if (TREE_CODE (op0) == INTEGER_CST)
5823 return op0;
5824 return NULL_TREE;
5826 default:
5827 return NULL_TREE;
5829 tree arg0 = gimple_call_arg (stmt, 0);
5830 tree arg1 = gimple_call_arg (stmt, 1);
5831 tree op0 = (*valueize) (arg0);
5832 tree op1 = (*valueize) (arg1);
5834 if (TREE_CODE (op0) != INTEGER_CST
5835 || TREE_CODE (op1) != INTEGER_CST)
5837 switch (subcode)
5839 case MULT_EXPR:
5840 /* x * 0 = 0 * x = 0 without overflow. */
5841 if (integer_zerop (op0) || integer_zerop (op1))
5842 return build_zero_cst (TREE_TYPE (arg0));
5843 break;
5844 case MINUS_EXPR:
5845 /* y - y = 0 without overflow. */
5846 if (operand_equal_p (op0, op1, 0))
5847 return build_zero_cst (TREE_TYPE (arg0));
5848 break;
5849 default:
5850 break;
5853 tree res
5854 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
5855 if (res
5856 && TREE_CODE (res) == INTEGER_CST
5857 && !TREE_OVERFLOW (res))
5858 return res;
5859 return NULL_TREE;
5862 fn = (*valueize) (gimple_call_fn (stmt));
5863 if (TREE_CODE (fn) == ADDR_EXPR
5864 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5865 && DECL_BUILT_IN (TREE_OPERAND (fn, 0))
5866 && gimple_builtin_call_types_compatible_p (stmt,
5867 TREE_OPERAND (fn, 0)))
5869 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
5870 tree retval;
5871 unsigned i;
5872 for (i = 0; i < gimple_call_num_args (stmt); ++i)
5873 args[i] = (*valueize) (gimple_call_arg (stmt, i));
5874 retval = fold_builtin_call_array (loc,
5875 gimple_call_return_type (call_stmt),
5876 fn, gimple_call_num_args (stmt), args);
5877 if (retval)
5879 /* fold_call_expr wraps the result inside a NOP_EXPR. */
5880 STRIP_NOPS (retval);
5881 retval = fold_convert (gimple_call_return_type (call_stmt),
5882 retval);
5884 return retval;
5886 return NULL_TREE;
5889 default:
5890 return NULL_TREE;
5894 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
5895 Returns NULL_TREE if folding to a constant is not possible, otherwise
5896 returns a constant according to is_gimple_min_invariant. */
5898 tree
5899 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
5901 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
5902 if (res && is_gimple_min_invariant (res))
5903 return res;
5904 return NULL_TREE;
5908 /* The following set of functions are supposed to fold references using
5909 their constant initializers. */
5911 /* See if we can find constructor defining value of BASE.
5912 When we know the consructor with constant offset (such as
5913 base is array[40] and we do know constructor of array), then
5914 BIT_OFFSET is adjusted accordingly.
5916 As a special case, return error_mark_node when constructor
5917 is not explicitly available, but it is known to be zero
5918 such as 'static const int a;'. */
5919 static tree
5920 get_base_constructor (tree base, HOST_WIDE_INT *bit_offset,
5921 tree (*valueize)(tree))
5923 HOST_WIDE_INT bit_offset2, size, max_size;
5924 bool reverse;
5926 if (TREE_CODE (base) == MEM_REF)
5928 if (!integer_zerop (TREE_OPERAND (base, 1)))
5930 if (!tree_fits_shwi_p (TREE_OPERAND (base, 1)))
5931 return NULL_TREE;
5932 *bit_offset += (mem_ref_offset (base).to_short_addr ()
5933 * BITS_PER_UNIT);
5936 if (valueize
5937 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
5938 base = valueize (TREE_OPERAND (base, 0));
5939 if (!base || TREE_CODE (base) != ADDR_EXPR)
5940 return NULL_TREE;
5941 base = TREE_OPERAND (base, 0);
5943 else if (valueize
5944 && TREE_CODE (base) == SSA_NAME)
5945 base = valueize (base);
5947 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
5948 DECL_INITIAL. If BASE is a nested reference into another
5949 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
5950 the inner reference. */
5951 switch (TREE_CODE (base))
5953 case VAR_DECL:
5954 case CONST_DECL:
5956 tree init = ctor_for_folding (base);
5958 /* Our semantic is exact opposite of ctor_for_folding;
5959 NULL means unknown, while error_mark_node is 0. */
5960 if (init == error_mark_node)
5961 return NULL_TREE;
5962 if (!init)
5963 return error_mark_node;
5964 return init;
5967 case VIEW_CONVERT_EXPR:
5968 return get_base_constructor (TREE_OPERAND (base, 0),
5969 bit_offset, valueize);
5971 case ARRAY_REF:
5972 case COMPONENT_REF:
5973 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
5974 &reverse);
5975 if (max_size == -1 || size != max_size)
5976 return NULL_TREE;
5977 *bit_offset += bit_offset2;
5978 return get_base_constructor (base, bit_offset, valueize);
5980 case CONSTRUCTOR:
5981 return base;
5983 default:
5984 if (CONSTANT_CLASS_P (base))
5985 return base;
5987 return NULL_TREE;
5991 /* CTOR is CONSTRUCTOR of an array type. Fold reference of type TYPE and size
5992 SIZE to the memory at bit OFFSET. */
5994 static tree
5995 fold_array_ctor_reference (tree type, tree ctor,
5996 unsigned HOST_WIDE_INT offset,
5997 unsigned HOST_WIDE_INT size,
5998 tree from_decl)
6000 offset_int low_bound;
6001 offset_int elt_size;
6002 offset_int access_index;
6003 tree domain_type = NULL_TREE;
6004 HOST_WIDE_INT inner_offset;
6006 /* Compute low bound and elt size. */
6007 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
6008 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
6009 if (domain_type && TYPE_MIN_VALUE (domain_type))
6011 /* Static constructors for variably sized objects makes no sense. */
6012 if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
6013 return NULL_TREE;
6014 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
6016 else
6017 low_bound = 0;
6018 /* Static constructors for variably sized objects makes no sense. */
6019 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
6020 return NULL_TREE;
6021 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
6023 /* We can handle only constantly sized accesses that are known to not
6024 be larger than size of array element. */
6025 if (!TYPE_SIZE_UNIT (type)
6026 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST
6027 || elt_size < wi::to_offset (TYPE_SIZE_UNIT (type))
6028 || elt_size == 0)
6029 return NULL_TREE;
6031 /* Compute the array index we look for. */
6032 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
6033 elt_size);
6034 access_index += low_bound;
6036 /* And offset within the access. */
6037 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
6039 /* See if the array field is large enough to span whole access. We do not
6040 care to fold accesses spanning multiple array indexes. */
6041 if (inner_offset + size > elt_size.to_uhwi () * BITS_PER_UNIT)
6042 return NULL_TREE;
6043 if (tree val = get_array_ctor_element_at_index (ctor, access_index))
6044 return fold_ctor_reference (type, val, inner_offset, size, from_decl);
6046 /* When memory is not explicitely mentioned in constructor,
6047 it is 0 (or out of range). */
6048 return build_zero_cst (type);
6051 /* CTOR is CONSTRUCTOR of an aggregate or vector.
6052 Fold reference of type TYPE and size SIZE to the memory at bit OFFSET. */
6054 static tree
6055 fold_nonarray_ctor_reference (tree type, tree ctor,
6056 unsigned HOST_WIDE_INT offset,
6057 unsigned HOST_WIDE_INT size,
6058 tree from_decl)
6060 unsigned HOST_WIDE_INT cnt;
6061 tree cfield, cval;
6063 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield,
6064 cval)
6066 tree byte_offset = DECL_FIELD_OFFSET (cfield);
6067 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
6068 tree field_size = DECL_SIZE (cfield);
6069 offset_int bitoffset;
6070 offset_int bitoffset_end, access_end;
6072 /* Variable sized objects in static constructors makes no sense,
6073 but field_size can be NULL for flexible array members. */
6074 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
6075 && TREE_CODE (byte_offset) == INTEGER_CST
6076 && (field_size != NULL_TREE
6077 ? TREE_CODE (field_size) == INTEGER_CST
6078 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
6080 /* Compute bit offset of the field. */
6081 bitoffset = (wi::to_offset (field_offset)
6082 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
6083 /* Compute bit offset where the field ends. */
6084 if (field_size != NULL_TREE)
6085 bitoffset_end = bitoffset + wi::to_offset (field_size);
6086 else
6087 bitoffset_end = 0;
6089 access_end = offset_int (offset) + size;
6091 /* Is there any overlap between [OFFSET, OFFSET+SIZE) and
6092 [BITOFFSET, BITOFFSET_END)? */
6093 if (wi::cmps (access_end, bitoffset) > 0
6094 && (field_size == NULL_TREE
6095 || wi::lts_p (offset, bitoffset_end)))
6097 offset_int inner_offset = offset_int (offset) - bitoffset;
6098 /* We do have overlap. Now see if field is large enough to
6099 cover the access. Give up for accesses spanning multiple
6100 fields. */
6101 if (wi::cmps (access_end, bitoffset_end) > 0)
6102 return NULL_TREE;
6103 if (offset < bitoffset)
6104 return NULL_TREE;
6105 return fold_ctor_reference (type, cval,
6106 inner_offset.to_uhwi (), size,
6107 from_decl);
6110 /* When memory is not explicitely mentioned in constructor, it is 0. */
6111 return build_zero_cst (type);
6114 /* CTOR is value initializing memory, fold reference of type TYPE and size SIZE
6115 to the memory at bit OFFSET. */
6117 tree
6118 fold_ctor_reference (tree type, tree ctor, unsigned HOST_WIDE_INT offset,
6119 unsigned HOST_WIDE_INT size, tree from_decl)
6121 tree ret;
6123 /* We found the field with exact match. */
6124 if (useless_type_conversion_p (type, TREE_TYPE (ctor))
6125 && !offset)
6126 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6128 /* We are at the end of walk, see if we can view convert the
6129 result. */
6130 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
6131 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
6132 && !compare_tree_int (TYPE_SIZE (type), size)
6133 && !compare_tree_int (TYPE_SIZE (TREE_TYPE (ctor)), size))
6135 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
6136 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
6137 if (ret)
6138 STRIP_USELESS_TYPE_CONVERSION (ret);
6139 return ret;
6141 /* For constants and byte-aligned/sized reads try to go through
6142 native_encode/interpret. */
6143 if (CONSTANT_CLASS_P (ctor)
6144 && BITS_PER_UNIT == 8
6145 && offset % BITS_PER_UNIT == 0
6146 && size % BITS_PER_UNIT == 0
6147 && size <= MAX_BITSIZE_MODE_ANY_MODE)
6149 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
6150 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
6151 offset / BITS_PER_UNIT);
6152 if (len > 0)
6153 return native_interpret_expr (type, buf, len);
6155 if (TREE_CODE (ctor) == CONSTRUCTOR)
6158 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
6159 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
6160 return fold_array_ctor_reference (type, ctor, offset, size,
6161 from_decl);
6162 else
6163 return fold_nonarray_ctor_reference (type, ctor, offset, size,
6164 from_decl);
6167 return NULL_TREE;
6170 /* Return the tree representing the element referenced by T if T is an
6171 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
6172 names using VALUEIZE. Return NULL_TREE otherwise. */
6174 tree
6175 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
6177 tree ctor, idx, base;
6178 HOST_WIDE_INT offset, size, max_size;
6179 tree tem;
6180 bool reverse;
6182 if (TREE_THIS_VOLATILE (t))
6183 return NULL_TREE;
6185 if (DECL_P (t))
6186 return get_symbol_constant_value (t);
6188 tem = fold_read_from_constant_string (t);
6189 if (tem)
6190 return tem;
6192 switch (TREE_CODE (t))
6194 case ARRAY_REF:
6195 case ARRAY_RANGE_REF:
6196 /* Constant indexes are handled well by get_base_constructor.
6197 Only special case variable offsets.
6198 FIXME: This code can't handle nested references with variable indexes
6199 (they will be handled only by iteration of ccp). Perhaps we can bring
6200 get_ref_base_and_extent here and make it use a valueize callback. */
6201 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
6202 && valueize
6203 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
6204 && TREE_CODE (idx) == INTEGER_CST)
6206 tree low_bound, unit_size;
6208 /* If the resulting bit-offset is constant, track it. */
6209 if ((low_bound = array_ref_low_bound (t),
6210 TREE_CODE (low_bound) == INTEGER_CST)
6211 && (unit_size = array_ref_element_size (t),
6212 tree_fits_uhwi_p (unit_size)))
6214 offset_int woffset
6215 = wi::sext (wi::to_offset (idx) - wi::to_offset (low_bound),
6216 TYPE_PRECISION (TREE_TYPE (idx)));
6218 if (wi::fits_shwi_p (woffset))
6220 offset = woffset.to_shwi ();
6221 /* TODO: This code seems wrong, multiply then check
6222 to see if it fits. */
6223 offset *= tree_to_uhwi (unit_size);
6224 offset *= BITS_PER_UNIT;
6226 base = TREE_OPERAND (t, 0);
6227 ctor = get_base_constructor (base, &offset, valueize);
6228 /* Empty constructor. Always fold to 0. */
6229 if (ctor == error_mark_node)
6230 return build_zero_cst (TREE_TYPE (t));
6231 /* Out of bound array access. Value is undefined,
6232 but don't fold. */
6233 if (offset < 0)
6234 return NULL_TREE;
6235 /* We can not determine ctor. */
6236 if (!ctor)
6237 return NULL_TREE;
6238 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
6239 tree_to_uhwi (unit_size)
6240 * BITS_PER_UNIT,
6241 base);
6245 /* Fallthru. */
6247 case COMPONENT_REF:
6248 case BIT_FIELD_REF:
6249 case TARGET_MEM_REF:
6250 case MEM_REF:
6251 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
6252 ctor = get_base_constructor (base, &offset, valueize);
6254 /* Empty constructor. Always fold to 0. */
6255 if (ctor == error_mark_node)
6256 return build_zero_cst (TREE_TYPE (t));
6257 /* We do not know precise address. */
6258 if (max_size == -1 || max_size != size)
6259 return NULL_TREE;
6260 /* We can not determine ctor. */
6261 if (!ctor)
6262 return NULL_TREE;
6264 /* Out of bound array access. Value is undefined, but don't fold. */
6265 if (offset < 0)
6266 return NULL_TREE;
6268 return fold_ctor_reference (TREE_TYPE (t), ctor, offset, size,
6269 base);
6271 case REALPART_EXPR:
6272 case IMAGPART_EXPR:
6274 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
6275 if (c && TREE_CODE (c) == COMPLEX_CST)
6276 return fold_build1_loc (EXPR_LOCATION (t),
6277 TREE_CODE (t), TREE_TYPE (t), c);
6278 break;
6281 default:
6282 break;
6285 return NULL_TREE;
6288 tree
6289 fold_const_aggregate_ref (tree t)
6291 return fold_const_aggregate_ref_1 (t, NULL);
6294 /* Lookup virtual method with index TOKEN in a virtual table V
6295 at OFFSET.
6296 Set CAN_REFER if non-NULL to false if method
6297 is not referable or if the virtual table is ill-formed (such as rewriten
6298 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
6300 tree
6301 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
6302 tree v,
6303 unsigned HOST_WIDE_INT offset,
6304 bool *can_refer)
6306 tree vtable = v, init, fn;
6307 unsigned HOST_WIDE_INT size;
6308 unsigned HOST_WIDE_INT elt_size, access_index;
6309 tree domain_type;
6311 if (can_refer)
6312 *can_refer = true;
6314 /* First of all double check we have virtual table. */
6315 if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
6317 /* Pass down that we lost track of the target. */
6318 if (can_refer)
6319 *can_refer = false;
6320 return NULL_TREE;
6323 init = ctor_for_folding (v);
6325 /* The virtual tables should always be born with constructors
6326 and we always should assume that they are avaialble for
6327 folding. At the moment we do not stream them in all cases,
6328 but it should never happen that ctor seem unreachable. */
6329 gcc_assert (init);
6330 if (init == error_mark_node)
6332 gcc_assert (in_lto_p);
6333 /* Pass down that we lost track of the target. */
6334 if (can_refer)
6335 *can_refer = false;
6336 return NULL_TREE;
6338 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
6339 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
6340 offset *= BITS_PER_UNIT;
6341 offset += token * size;
6343 /* Lookup the value in the constructor that is assumed to be array.
6344 This is equivalent to
6345 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
6346 offset, size, NULL);
6347 but in a constant time. We expect that frontend produced a simple
6348 array without indexed initializers. */
6350 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
6351 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
6352 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
6353 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
6355 access_index = offset / BITS_PER_UNIT / elt_size;
6356 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
6358 /* This code makes an assumption that there are no
6359 indexed fileds produced by C++ FE, so we can directly index the array. */
6360 if (access_index < CONSTRUCTOR_NELTS (init))
6362 fn = CONSTRUCTOR_ELT (init, access_index)->value;
6363 gcc_checking_assert (!CONSTRUCTOR_ELT (init, access_index)->index);
6364 STRIP_NOPS (fn);
6366 else
6367 fn = NULL;
6369 /* For type inconsistent program we may end up looking up virtual method
6370 in virtual table that does not contain TOKEN entries. We may overrun
6371 the virtual table and pick up a constant or RTTI info pointer.
6372 In any case the call is undefined. */
6373 if (!fn
6374 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
6375 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
6376 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
6377 else
6379 fn = TREE_OPERAND (fn, 0);
6381 /* When cgraph node is missing and function is not public, we cannot
6382 devirtualize. This can happen in WHOPR when the actual method
6383 ends up in other partition, because we found devirtualization
6384 possibility too late. */
6385 if (!can_refer_decl_in_current_unit_p (fn, vtable))
6387 if (can_refer)
6389 *can_refer = false;
6390 return fn;
6392 return NULL_TREE;
6396 /* Make sure we create a cgraph node for functions we'll reference.
6397 They can be non-existent if the reference comes from an entry
6398 of an external vtable for example. */
6399 cgraph_node::get_create (fn);
6401 return fn;
6404 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
6405 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
6406 KNOWN_BINFO carries the binfo describing the true type of
6407 OBJ_TYPE_REF_OBJECT(REF).
6408 Set CAN_REFER if non-NULL to false if method
6409 is not referable or if the virtual table is ill-formed (such as rewriten
6410 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
6412 tree
6413 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
6414 bool *can_refer)
6416 unsigned HOST_WIDE_INT offset;
6417 tree v;
6419 v = BINFO_VTABLE (known_binfo);
6420 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
6421 if (!v)
6422 return NULL_TREE;
6424 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
6426 if (can_refer)
6427 *can_refer = false;
6428 return NULL_TREE;
6430 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
6433 /* Given a pointer value OP0, return a simplified version of an
6434 indirection through OP0, or NULL_TREE if no simplification is
6435 possible. Note that the resulting type may be different from
6436 the type pointed to in the sense that it is still compatible
6437 from the langhooks point of view. */
6439 tree
6440 gimple_fold_indirect_ref (tree t)
6442 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
6443 tree sub = t;
6444 tree subtype;
6446 STRIP_NOPS (sub);
6447 subtype = TREE_TYPE (sub);
6448 if (!POINTER_TYPE_P (subtype))
6449 return NULL_TREE;
6451 if (TREE_CODE (sub) == ADDR_EXPR)
6453 tree op = TREE_OPERAND (sub, 0);
6454 tree optype = TREE_TYPE (op);
6455 /* *&p => p */
6456 if (useless_type_conversion_p (type, optype))
6457 return op;
6459 /* *(foo *)&fooarray => fooarray[0] */
6460 if (TREE_CODE (optype) == ARRAY_TYPE
6461 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
6462 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6464 tree type_domain = TYPE_DOMAIN (optype);
6465 tree min_val = size_zero_node;
6466 if (type_domain && TYPE_MIN_VALUE (type_domain))
6467 min_val = TYPE_MIN_VALUE (type_domain);
6468 if (TREE_CODE (min_val) == INTEGER_CST)
6469 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
6471 /* *(foo *)&complexfoo => __real__ complexfoo */
6472 else if (TREE_CODE (optype) == COMPLEX_TYPE
6473 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6474 return fold_build1 (REALPART_EXPR, type, op);
6475 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
6476 else if (TREE_CODE (optype) == VECTOR_TYPE
6477 && useless_type_conversion_p (type, TREE_TYPE (optype)))
6479 tree part_width = TYPE_SIZE (type);
6480 tree index = bitsize_int (0);
6481 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
6485 /* *(p + CST) -> ... */
6486 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
6487 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
6489 tree addr = TREE_OPERAND (sub, 0);
6490 tree off = TREE_OPERAND (sub, 1);
6491 tree addrtype;
6493 STRIP_NOPS (addr);
6494 addrtype = TREE_TYPE (addr);
6496 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
6497 if (TREE_CODE (addr) == ADDR_EXPR
6498 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
6499 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
6500 && tree_fits_uhwi_p (off))
6502 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
6503 tree part_width = TYPE_SIZE (type);
6504 unsigned HOST_WIDE_INT part_widthi
6505 = tree_to_shwi (part_width) / BITS_PER_UNIT;
6506 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
6507 tree index = bitsize_int (indexi);
6508 if (offset / part_widthi
6509 < TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype)))
6510 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
6511 part_width, index);
6514 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
6515 if (TREE_CODE (addr) == ADDR_EXPR
6516 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
6517 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
6519 tree size = TYPE_SIZE_UNIT (type);
6520 if (tree_int_cst_equal (size, off))
6521 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
6524 /* *(p + CST) -> MEM_REF <p, CST>. */
6525 if (TREE_CODE (addr) != ADDR_EXPR
6526 || DECL_P (TREE_OPERAND (addr, 0)))
6527 return fold_build2 (MEM_REF, type,
6528 addr,
6529 wide_int_to_tree (ptype, off));
6532 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
6533 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
6534 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
6535 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
6537 tree type_domain;
6538 tree min_val = size_zero_node;
6539 tree osub = sub;
6540 sub = gimple_fold_indirect_ref (sub);
6541 if (! sub)
6542 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
6543 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
6544 if (type_domain && TYPE_MIN_VALUE (type_domain))
6545 min_val = TYPE_MIN_VALUE (type_domain);
6546 if (TREE_CODE (min_val) == INTEGER_CST)
6547 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
6550 return NULL_TREE;
6553 /* Return true if CODE is an operation that when operating on signed
6554 integer types involves undefined behavior on overflow and the
6555 operation can be expressed with unsigned arithmetic. */
6557 bool
6558 arith_code_with_undefined_signed_overflow (tree_code code)
6560 switch (code)
6562 case PLUS_EXPR:
6563 case MINUS_EXPR:
6564 case MULT_EXPR:
6565 case NEGATE_EXPR:
6566 case POINTER_PLUS_EXPR:
6567 return true;
6568 default:
6569 return false;
6573 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
6574 operation that can be transformed to unsigned arithmetic by converting
6575 its operand, carrying out the operation in the corresponding unsigned
6576 type and converting the result back to the original type.
6578 Returns a sequence of statements that replace STMT and also contain
6579 a modified form of STMT itself. */
6581 gimple_seq
6582 rewrite_to_defined_overflow (gimple *stmt)
6584 if (dump_file && (dump_flags & TDF_DETAILS))
6586 fprintf (dump_file, "rewriting stmt with undefined signed "
6587 "overflow ");
6588 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
6591 tree lhs = gimple_assign_lhs (stmt);
6592 tree type = unsigned_type_for (TREE_TYPE (lhs));
6593 gimple_seq stmts = NULL;
6594 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
6596 tree op = gimple_op (stmt, i);
6597 op = gimple_convert (&stmts, type, op);
6598 gimple_set_op (stmt, i, op);
6600 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
6601 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
6602 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
6603 gimple_seq_add_stmt (&stmts, stmt);
6604 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
6605 gimple_seq_add_stmt (&stmts, cvt);
6607 return stmts;
6611 /* The valueization hook we use for the gimple_build API simplification.
6612 This makes us match fold_buildN behavior by only combining with
6613 statements in the sequence(s) we are currently building. */
6615 static tree
6616 gimple_build_valueize (tree op)
6618 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
6619 return op;
6620 return NULL_TREE;
6623 /* Build the expression CODE OP0 of type TYPE with location LOC,
6624 simplifying it first if possible. Returns the built
6625 expression value and appends statements possibly defining it
6626 to SEQ. */
6628 tree
6629 gimple_build (gimple_seq *seq, location_t loc,
6630 enum tree_code code, tree type, tree op0)
6632 tree res = gimple_simplify (code, type, op0, seq, gimple_build_valueize);
6633 if (!res)
6635 res = create_tmp_reg_or_ssa_name (type);
6636 gimple *stmt;
6637 if (code == REALPART_EXPR
6638 || code == IMAGPART_EXPR
6639 || code == VIEW_CONVERT_EXPR)
6640 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
6641 else
6642 stmt = gimple_build_assign (res, code, op0);
6643 gimple_set_location (stmt, loc);
6644 gimple_seq_add_stmt_without_update (seq, stmt);
6646 return res;
6649 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
6650 simplifying it first if possible. Returns the built
6651 expression value and appends statements possibly defining it
6652 to SEQ. */
6654 tree
6655 gimple_build (gimple_seq *seq, location_t loc,
6656 enum tree_code code, tree type, tree op0, tree op1)
6658 tree res = gimple_simplify (code, type, op0, op1, seq, gimple_build_valueize);
6659 if (!res)
6661 res = create_tmp_reg_or_ssa_name (type);
6662 gimple *stmt = gimple_build_assign (res, code, op0, op1);
6663 gimple_set_location (stmt, loc);
6664 gimple_seq_add_stmt_without_update (seq, stmt);
6666 return res;
6669 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
6670 simplifying it first if possible. Returns the built
6671 expression value and appends statements possibly defining it
6672 to SEQ. */
6674 tree
6675 gimple_build (gimple_seq *seq, location_t loc,
6676 enum tree_code code, tree type, tree op0, tree op1, tree op2)
6678 tree res = gimple_simplify (code, type, op0, op1, op2,
6679 seq, gimple_build_valueize);
6680 if (!res)
6682 res = create_tmp_reg_or_ssa_name (type);
6683 gimple *stmt;
6684 if (code == BIT_FIELD_REF)
6685 stmt = gimple_build_assign (res, code,
6686 build3 (code, type, op0, op1, op2));
6687 else
6688 stmt = gimple_build_assign (res, code, op0, op1, op2);
6689 gimple_set_location (stmt, loc);
6690 gimple_seq_add_stmt_without_update (seq, stmt);
6692 return res;
6695 /* Build the call FN (ARG0) with a result of type TYPE
6696 (or no result if TYPE is void) with location LOC,
6697 simplifying it first if possible. Returns the built
6698 expression value (or NULL_TREE if TYPE is void) and appends
6699 statements possibly defining it to SEQ. */
6701 tree
6702 gimple_build (gimple_seq *seq, location_t loc,
6703 enum built_in_function fn, tree type, tree arg0)
6705 tree res = gimple_simplify (fn, type, arg0, seq, gimple_build_valueize);
6706 if (!res)
6708 tree decl = builtin_decl_implicit (fn);
6709 gimple *stmt = gimple_build_call (decl, 1, arg0);
6710 if (!VOID_TYPE_P (type))
6712 res = create_tmp_reg_or_ssa_name (type);
6713 gimple_call_set_lhs (stmt, res);
6715 gimple_set_location (stmt, loc);
6716 gimple_seq_add_stmt_without_update (seq, stmt);
6718 return res;
6721 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
6722 (or no result if TYPE is void) with location LOC,
6723 simplifying it first if possible. Returns the built
6724 expression value (or NULL_TREE if TYPE is void) and appends
6725 statements possibly defining it to SEQ. */
6727 tree
6728 gimple_build (gimple_seq *seq, location_t loc,
6729 enum built_in_function fn, tree type, tree arg0, tree arg1)
6731 tree res = gimple_simplify (fn, type, arg0, arg1, seq, gimple_build_valueize);
6732 if (!res)
6734 tree decl = builtin_decl_implicit (fn);
6735 gimple *stmt = gimple_build_call (decl, 2, arg0, arg1);
6736 if (!VOID_TYPE_P (type))
6738 res = create_tmp_reg_or_ssa_name (type);
6739 gimple_call_set_lhs (stmt, res);
6741 gimple_set_location (stmt, loc);
6742 gimple_seq_add_stmt_without_update (seq, stmt);
6744 return res;
6747 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
6748 (or no result if TYPE is void) with location LOC,
6749 simplifying it first if possible. Returns the built
6750 expression value (or NULL_TREE if TYPE is void) and appends
6751 statements possibly defining it to SEQ. */
6753 tree
6754 gimple_build (gimple_seq *seq, location_t loc,
6755 enum built_in_function fn, tree type,
6756 tree arg0, tree arg1, tree arg2)
6758 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
6759 seq, gimple_build_valueize);
6760 if (!res)
6762 tree decl = builtin_decl_implicit (fn);
6763 gimple *stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
6764 if (!VOID_TYPE_P (type))
6766 res = create_tmp_reg_or_ssa_name (type);
6767 gimple_call_set_lhs (stmt, res);
6769 gimple_set_location (stmt, loc);
6770 gimple_seq_add_stmt_without_update (seq, stmt);
6772 return res;
6775 /* Build the conversion (TYPE) OP with a result of type TYPE
6776 with location LOC if such conversion is neccesary in GIMPLE,
6777 simplifying it first.
6778 Returns the built expression value and appends
6779 statements possibly defining it to SEQ. */
6781 tree
6782 gimple_convert (gimple_seq *seq, location_t loc, tree type, tree op)
6784 if (useless_type_conversion_p (type, TREE_TYPE (op)))
6785 return op;
6786 return gimple_build (seq, loc, NOP_EXPR, type, op);
6789 /* Build the conversion (ptrofftype) OP with a result of a type
6790 compatible with ptrofftype with location LOC if such conversion
6791 is neccesary in GIMPLE, simplifying it first.
6792 Returns the built expression value and appends
6793 statements possibly defining it to SEQ. */
6795 tree
6796 gimple_convert_to_ptrofftype (gimple_seq *seq, location_t loc, tree op)
6798 if (ptrofftype_p (TREE_TYPE (op)))
6799 return op;
6800 return gimple_convert (seq, loc, sizetype, op);
6803 /* Return true if the result of assignment STMT is known to be non-negative.
6804 If the return value is based on the assumption that signed overflow is
6805 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6806 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6808 static bool
6809 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6810 int depth)
6812 enum tree_code code = gimple_assign_rhs_code (stmt);
6813 switch (get_gimple_rhs_class (code))
6815 case GIMPLE_UNARY_RHS:
6816 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6817 gimple_expr_type (stmt),
6818 gimple_assign_rhs1 (stmt),
6819 strict_overflow_p, depth);
6820 case GIMPLE_BINARY_RHS:
6821 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
6822 gimple_expr_type (stmt),
6823 gimple_assign_rhs1 (stmt),
6824 gimple_assign_rhs2 (stmt),
6825 strict_overflow_p, depth);
6826 case GIMPLE_TERNARY_RHS:
6827 return false;
6828 case GIMPLE_SINGLE_RHS:
6829 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
6830 strict_overflow_p, depth);
6831 case GIMPLE_INVALID_RHS:
6832 break;
6834 gcc_unreachable ();
6837 /* Return true if return value of call STMT is known to be non-negative.
6838 If the return value is based on the assumption that signed overflow is
6839 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6840 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6842 static bool
6843 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6844 int depth)
6846 tree arg0 = gimple_call_num_args (stmt) > 0 ?
6847 gimple_call_arg (stmt, 0) : NULL_TREE;
6848 tree arg1 = gimple_call_num_args (stmt) > 1 ?
6849 gimple_call_arg (stmt, 1) : NULL_TREE;
6851 return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
6852 gimple_call_combined_fn (stmt),
6853 arg0,
6854 arg1,
6855 strict_overflow_p, depth);
6858 /* Return true if return value of call STMT is known to be non-negative.
6859 If the return value is based on the assumption that signed overflow is
6860 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6861 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6863 static bool
6864 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6865 int depth)
6867 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6869 tree arg = gimple_phi_arg_def (stmt, i);
6870 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
6871 return false;
6873 return true;
6876 /* Return true if STMT is known to compute a non-negative value.
6877 If the return value is based on the assumption that signed overflow is
6878 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
6879 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
6881 bool
6882 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
6883 int depth)
6885 switch (gimple_code (stmt))
6887 case GIMPLE_ASSIGN:
6888 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
6889 depth);
6890 case GIMPLE_CALL:
6891 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
6892 depth);
6893 case GIMPLE_PHI:
6894 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
6895 depth);
6896 default:
6897 return false;
6901 /* Return true if the floating-point value computed by assignment STMT
6902 is known to have an integer value. We also allow +Inf, -Inf and NaN
6903 to be considered integer values. Return false for signaling NaN.
6905 DEPTH is the current nesting depth of the query. */
6907 static bool
6908 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
6910 enum tree_code code = gimple_assign_rhs_code (stmt);
6911 switch (get_gimple_rhs_class (code))
6913 case GIMPLE_UNARY_RHS:
6914 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
6915 gimple_assign_rhs1 (stmt), depth);
6916 case GIMPLE_BINARY_RHS:
6917 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
6918 gimple_assign_rhs1 (stmt),
6919 gimple_assign_rhs2 (stmt), depth);
6920 case GIMPLE_TERNARY_RHS:
6921 return false;
6922 case GIMPLE_SINGLE_RHS:
6923 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
6924 case GIMPLE_INVALID_RHS:
6925 break;
6927 gcc_unreachable ();
6930 /* Return true if the floating-point value computed by call STMT is known
6931 to have an integer value. We also allow +Inf, -Inf and NaN to be
6932 considered integer values. Return false for signaling NaN.
6934 DEPTH is the current nesting depth of the query. */
6936 static bool
6937 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
6939 tree arg0 = (gimple_call_num_args (stmt) > 0
6940 ? gimple_call_arg (stmt, 0)
6941 : NULL_TREE);
6942 tree arg1 = (gimple_call_num_args (stmt) > 1
6943 ? gimple_call_arg (stmt, 1)
6944 : NULL_TREE);
6945 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
6946 arg0, arg1, depth);
6949 /* Return true if the floating-point result of phi STMT is known to have
6950 an integer value. We also allow +Inf, -Inf and NaN to be considered
6951 integer values. Return false for signaling NaN.
6953 DEPTH is the current nesting depth of the query. */
6955 static bool
6956 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
6958 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
6960 tree arg = gimple_phi_arg_def (stmt, i);
6961 if (!integer_valued_real_single_p (arg, depth + 1))
6962 return false;
6964 return true;
6967 /* Return true if the floating-point value computed by STMT is known
6968 to have an integer value. We also allow +Inf, -Inf and NaN to be
6969 considered integer values. Return false for signaling NaN.
6971 DEPTH is the current nesting depth of the query. */
6973 bool
6974 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
6976 switch (gimple_code (stmt))
6978 case GIMPLE_ASSIGN:
6979 return gimple_assign_integer_valued_real_p (stmt, depth);
6980 case GIMPLE_CALL:
6981 return gimple_call_integer_valued_real_p (stmt, depth);
6982 case GIMPLE_PHI:
6983 return gimple_phi_integer_valued_real_p (stmt, depth);
6984 default:
6985 return false;