Debian Codegraph @

gcc/gimple-fold.cc

raw
1 /* Statement simplification on GIMPLE.
2 Copyright (C) 2010-2025 Free Software Foundation, Inc.
3 Split out from tree-ssa-ccp.cc.
4
5 This file is part of GCC.
6
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.
11
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.
16
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/>. */
20
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 "gimple-ssa-warn-access.h"
34 #include "gimple-ssa-warn-restrict.h"
35 #include "fold-const.h"
36 #include "stmt.h"
37 #include "expr.h"
38 #include "stor-layout.h"
39 #include "dumpfile.h"
40 #include "gimple-iterator.h"
41 #include "gimple-fold.h"
42 #include "gimplify.h"
43 #include "tree-into-ssa.h"
44 #include "tree-dfa.h"
45 #include "tree-object-size.h"
46 #include "tree-ssa.h"
47 #include "tree-ssa-propagate.h"
48 #include "ipa-utils.h"
49 #include "tree-ssa-address.h"
50 #include "langhooks.h"
51 #include "gimplify-me.h"
52 #include "dbgcnt.h"
53 #include "builtins.h"
54 #include "tree-eh.h"
55 #include "gimple-match.h"
56 #include "gomp-constants.h"
57 #include "optabs-query.h"
58 #include "omp-general.h"
59 #include "tree-cfg.h"
60 #include "fold-const-call.h"
61 #include "stringpool.h"
62 #include "attribs.h"
63 #include "asan.h"
64 #include "diagnostic-core.h"
65 #include "intl.h"
66 #include "calls.h"
67 #include "tree-vector-builder.h"
68 #include "tree-ssa-strlen.h"
69 #include "varasm.h"
70 #include "internal-fn.h"
71 #include "gimple-range.h"
72
73 enum strlen_range_kind {
74 /* Compute the exact constant string length. */
75 SRK_STRLEN,
76 /* Compute the maximum constant string length. */
77 SRK_STRLENMAX,
78 /* Compute a range of string lengths bounded by object sizes. When
79 the length of a string cannot be determined, consider as the upper
80 bound the size of the enclosing object the string may be a member
81 or element of. Also determine the size of the largest character
82 array the string may refer to. */
83 SRK_LENRANGE,
84 /* Determine the integer value of the argument (not string length). */
85 SRK_INT_VALUE
86 };
87
88 static bool
89 get_range_strlen (tree, bitmap, strlen_range_kind, c_strlen_data *, unsigned);
90
91 /* Return true when DECL can be referenced from current unit.
92 FROM_DECL (if non-null) specify constructor of variable DECL was taken from.
93 We can get declarations that are not possible to reference for various
94 reasons:
95
96 1) When analyzing C++ virtual tables.
97 C++ virtual tables do have known constructors even
98 when they are keyed to other compilation unit.
99 Those tables can contain pointers to methods and vars
100 in other units. Those methods have both STATIC and EXTERNAL
101 set.
102 2) In WHOPR mode devirtualization might lead to reference
103 to method that was partitioned elsehwere.
104 In this case we have static VAR_DECL or FUNCTION_DECL
105 that has no corresponding callgraph/varpool node
106 declaring the body.
107 3) COMDAT functions referred by external vtables that
108 we devirtualize only during final compilation stage.
109 At this time we already decided that we will not output
110 the function body and thus we can't reference the symbol
111 directly. */
112
113 static bool
114 can_refer_decl_in_current_unit_p (tree decl, tree from_decl)
115 {
116 varpool_node *vnode;
117 struct cgraph_node *node;
118 symtab_node *snode;
119
120 if (DECL_ABSTRACT_P (decl))
121 return false;
122
123 /* We are concerned only about static/external vars and functions. */
124 if ((!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
125 || !VAR_OR_FUNCTION_DECL_P (decl))
126 return true;
127
128 /* Static objects can be referred only if they are defined and not optimized
129 out yet. */
130 if (!TREE_PUBLIC (decl))
131 {
132 if (DECL_EXTERNAL (decl))
133 return false;
134 /* Before we start optimizing unreachable code we can be sure all
135 static objects are defined. */
136 if (symtab->function_flags_ready)
137 return true;
138 snode = symtab_node::get (decl);
139 if (!snode || !snode->definition)
140 return false;
141 node = dyn_cast <cgraph_node *> (snode);
142 return !node || !node->inlined_to;
143 }
144
145 /* We will later output the initializer, so we can refer to it.
146 So we are concerned only when DECL comes from initializer of
147 external var or var that has been optimized out. */
148 if (!from_decl
149 || !VAR_P (from_decl)
150 || (!DECL_EXTERNAL (from_decl)
151 && (vnode = varpool_node::get (from_decl)) != NULL
152 && vnode->definition)
153 || (flag_ltrans
154 && (vnode = varpool_node::get (from_decl)) != NULL
155 && vnode->in_other_partition))
156 return true;
157 /* We are folding reference from external vtable. The vtable may reffer
158 to a symbol keyed to other compilation unit. The other compilation
159 unit may be in separate DSO and the symbol may be hidden. */
160 if (DECL_VISIBILITY_SPECIFIED (decl)
161 && DECL_EXTERNAL (decl)
162 && DECL_VISIBILITY (decl) != VISIBILITY_DEFAULT
163 && (!(snode = symtab_node::get (decl)) || !snode->in_other_partition))
164 return false;
165 /* When function is public, we always can introduce new reference.
166 Exception are the COMDAT functions where introducing a direct
167 reference imply need to include function body in the curren tunit. */
168 if (TREE_PUBLIC (decl) && !DECL_COMDAT (decl))
169 return true;
170 /* We have COMDAT. We are going to check if we still have definition
171 or if the definition is going to be output in other partition.
172 Bypass this when gimplifying; all needed functions will be produced.
173
174 As observed in PR20991 for already optimized out comdat virtual functions
175 it may be tempting to not necessarily give up because the copy will be
176 output elsewhere when corresponding vtable is output.
177 This is however not possible - ABI specify that COMDATs are output in
178 units where they are used and when the other unit was compiled with LTO
179 it is possible that vtable was kept public while the function itself
180 was privatized. */
181 if (!symtab->function_flags_ready)
182 return true;
183
184 snode = symtab_node::get (decl);
185 if (!snode
186 || ((!snode->definition || DECL_EXTERNAL (decl))
187 && (!snode->in_other_partition
188 || (!snode->forced_by_abi && !snode->force_output))))
189 return false;
190 node = dyn_cast <cgraph_node *> (snode);
191 return !node || !node->inlined_to;
192 }
193
194 /* Create a temporary for TYPE for a statement STMT. If the current function
195 is in SSA form, a SSA name is created. Otherwise a temporary register
196 is made. */
197
198 tree
199 create_tmp_reg_or_ssa_name (tree type, gimple *stmt)
200 {
201 if (gimple_in_ssa_p (cfun))
202 return make_ssa_name (type, stmt);
203 else
204 return create_tmp_reg (type);
205 }
206
207 /* CVAL is value taken from DECL_INITIAL of variable. Try to transform it into
208 acceptable form for is_gimple_min_invariant.
209 FROM_DECL (if non-NULL) specify variable whose constructor contains CVAL. */
210
211 tree
212 canonicalize_constructor_val (tree cval, tree from_decl)
213 {
214 if (CONSTANT_CLASS_P (cval))
215 return cval;
216
217 tree orig_cval = cval;
218 STRIP_NOPS (cval);
219 if (TREE_CODE (cval) == POINTER_PLUS_EXPR
220 && TREE_CODE (TREE_OPERAND (cval, 1)) == INTEGER_CST)
221 {
222 tree ptr = TREE_OPERAND (cval, 0);
223 if (is_gimple_min_invariant (ptr))
224 cval = build1_loc (EXPR_LOCATION (cval),
225 ADDR_EXPR, TREE_TYPE (ptr),
226 fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (ptr)),
227 ptr,
228 fold_convert (ptr_type_node,
229 TREE_OPERAND (cval, 1))));
230 }
231 if (TREE_CODE (cval) == ADDR_EXPR)
232 {
233 tree base = NULL_TREE;
234 if (TREE_CODE (TREE_OPERAND (cval, 0)) == COMPOUND_LITERAL_EXPR)
235 {
236 base = COMPOUND_LITERAL_EXPR_DECL (TREE_OPERAND (cval, 0));
237 if (base)
238 TREE_OPERAND (cval, 0) = base;
239 }
240 else
241 base = get_base_address (TREE_OPERAND (cval, 0));
242 if (!base)
243 return NULL_TREE;
244
245 if (VAR_OR_FUNCTION_DECL_P (base)
246 && !can_refer_decl_in_current_unit_p (base, from_decl))
247 return NULL_TREE;
248 if (TREE_TYPE (base) == error_mark_node)
249 return NULL_TREE;
250 if (VAR_P (base))
251 /* ??? We should be able to assert that TREE_ADDRESSABLE is set,
252 but since the use can be in a debug stmt we can't. */
253 ;
254 else if (TREE_CODE (base) == FUNCTION_DECL)
255 {
256 /* Make sure we create a cgraph node for functions we'll reference.
257 They can be non-existent if the reference comes from an entry
258 of an external vtable for example. */
259 cgraph_node::get_create (base);
260 }
261 /* Fixup types in global initializers. */
262 if (TREE_TYPE (TREE_TYPE (cval)) != TREE_TYPE (TREE_OPERAND (cval, 0)))
263 cval = build_fold_addr_expr (TREE_OPERAND (cval, 0));
264
265 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
266 cval = fold_convert (TREE_TYPE (orig_cval), cval);
267 return cval;
268 }
269 /* In CONSTRUCTORs we may see unfolded constants like (int (*) ()) 0. */
270 if (TREE_CODE (cval) == INTEGER_CST)
271 {
272 if (TREE_OVERFLOW_P (cval))
273 cval = drop_tree_overflow (cval);
274 if (!useless_type_conversion_p (TREE_TYPE (orig_cval), TREE_TYPE (cval)))
275 cval = fold_convert (TREE_TYPE (orig_cval), cval);
276 return cval;
277 }
278 return orig_cval;
279 }
280
281 /* If SYM is a constant variable with known value, return the value.
282 NULL_TREE is returned otherwise. */
283
284 tree
285 get_symbol_constant_value (tree sym)
286 {
287 tree val = ctor_for_folding (sym);
288 if (val != error_mark_node)
289 {
290 if (val)
291 {
292 val = canonicalize_constructor_val (unshare_expr (val), sym);
293 if (val
294 && is_gimple_min_invariant (val)
295 && useless_type_conversion_p (TREE_TYPE (sym), TREE_TYPE (val)))
296 return val;
297 else
298 return NULL_TREE;
299 }
300 /* Variables declared 'const' without an initializer
301 have zero as the initializer if they may not be
302 overridden at link or run time. */
303 if (!val
304 && is_gimple_reg_type (TREE_TYPE (sym)))
305 return build_zero_cst (TREE_TYPE (sym));
306 }
307
308 return NULL_TREE;
309 }
310
311
312
313 /* Subroutine of fold_stmt. We perform constant folding of the
314 memory reference tree EXPR. */
315
316 static tree
317 maybe_fold_reference (tree expr)
318 {
319 tree result = NULL_TREE;
320
321 if ((TREE_CODE (expr) == VIEW_CONVERT_EXPR
322 || TREE_CODE (expr) == REALPART_EXPR
323 || TREE_CODE (expr) == IMAGPART_EXPR)
324 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
325 result = fold_unary_loc (EXPR_LOCATION (expr),
326 TREE_CODE (expr),
327 TREE_TYPE (expr),
328 TREE_OPERAND (expr, 0));
329 else if (TREE_CODE (expr) == BIT_FIELD_REF
330 && CONSTANT_CLASS_P (TREE_OPERAND (expr, 0)))
331 result = fold_ternary_loc (EXPR_LOCATION (expr),
332 TREE_CODE (expr),
333 TREE_TYPE (expr),
334 TREE_OPERAND (expr, 0),
335 TREE_OPERAND (expr, 1),
336 TREE_OPERAND (expr, 2));
337 else
338 result = fold_const_aggregate_ref (expr);
339
340 if (result && is_gimple_min_invariant (result))
341 return result;
342
343 return NULL_TREE;
344 }
345
346 /* Return true if EXPR is an acceptable right-hand-side for a
347 GIMPLE assignment. We validate the entire tree, not just
348 the root node, thus catching expressions that embed complex
349 operands that are not permitted in GIMPLE. This function
350 is needed because the folding routines in fold-const.cc
351 may return such expressions in some cases, e.g., an array
352 access with an embedded index addition. It may make more
353 sense to have folding routines that are sensitive to the
354 constraints on GIMPLE operands, rather than abandoning any
355 any attempt to fold if the usual folding turns out to be too
356 aggressive. */
357
358 bool
359 valid_gimple_rhs_p (tree expr)
360 {
361 enum tree_code code = TREE_CODE (expr);
362
363 switch (TREE_CODE_CLASS (code))
364 {
365 case tcc_declaration:
366 if (!is_gimple_variable (expr))
367 return false;
368 break;
369
370 case tcc_constant:
371 /* All constants are ok. */
372 break;
373
374 case tcc_comparison:
375 /* GENERIC allows comparisons with non-boolean types, reject
376 those for GIMPLE. Let vector-typed comparisons pass - rules
377 for GENERIC and GIMPLE are the same here. */
378 if (!(INTEGRAL_TYPE_P (TREE_TYPE (expr))
379 && (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE
380 || TYPE_PRECISION (TREE_TYPE (expr)) == 1))
381 && ! VECTOR_TYPE_P (TREE_TYPE (expr)))
382 return false;
383
384 /* Fallthru. */
385 case tcc_binary:
386 if (!is_gimple_val (TREE_OPERAND (expr, 0))
387 || !is_gimple_val (TREE_OPERAND (expr, 1)))
388 return false;
389 break;
390
391 case tcc_unary:
392 if (!is_gimple_val (TREE_OPERAND (expr, 0)))
393 return false;
394 break;
395
396 case tcc_expression:
397 switch (code)
398 {
399 case ADDR_EXPR:
400 {
401 tree t;
402 if (is_gimple_min_invariant (expr))
403 return true;
404 t = TREE_OPERAND (expr, 0);
405 while (handled_component_p (t))
406 {
407 /* ??? More checks needed, see the GIMPLE verifier. */
408 if ((TREE_CODE (t) == ARRAY_REF
409 || TREE_CODE (t) == ARRAY_RANGE_REF)
410 && !is_gimple_val (TREE_OPERAND (t, 1)))
411 return false;
412 t = TREE_OPERAND (t, 0);
413 }
414 if (!is_gimple_id (t))
415 return false;
416 }
417 break;
418
419 default:
420 if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS)
421 {
422 if (!is_gimple_val (TREE_OPERAND (expr, 0))
423 || !is_gimple_val (TREE_OPERAND (expr, 1))
424 || !is_gimple_val (TREE_OPERAND (expr, 2)))
425 return false;
426 break;
427 }
428 return false;
429 }
430 break;
431
432 case tcc_vl_exp:
433 return false;
434
435 case tcc_exceptional:
436 if (code == CONSTRUCTOR)
437 {
438 unsigned i;
439 tree elt;
440 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
441 if (!is_gimple_val (elt))
442 return false;
443 return true;
444 }
445 if (code != SSA_NAME)
446 return false;
447 break;
448
449 case tcc_reference:
450 if (code == BIT_FIELD_REF)
451 return is_gimple_val (TREE_OPERAND (expr, 0));
452 return false;
453
454 default:
455 return false;
456 }
457
458 return true;
459 }
460
461
462 /* Attempt to fold an assignment statement pointed-to by SI. Returns a
463 replacement rhs for the statement or NULL_TREE if no simplification
464 could be made. It is assumed that the operands have been previously
465 folded. */
466
467 static tree
468 fold_gimple_assign (gimple_stmt_iterator *si)
469 {
470 gimple *stmt = gsi_stmt (*si);
471 enum tree_code subcode = gimple_assign_rhs_code (stmt);
472 location_t loc = gimple_location (stmt);
473
474 tree result = NULL_TREE;
475
476 switch (get_gimple_rhs_class (subcode))
477 {
478 case GIMPLE_SINGLE_RHS:
479 {
480 tree rhs = gimple_assign_rhs1 (stmt);
481
482 if (TREE_CLOBBER_P (rhs))
483 return NULL_TREE;
484
485 if (REFERENCE_CLASS_P (rhs))
486 return maybe_fold_reference (rhs);
487
488 else if (TREE_CODE (rhs) == OBJ_TYPE_REF)
489 {
490 tree val = OBJ_TYPE_REF_EXPR (rhs);
491 if (is_gimple_min_invariant (val))
492 return val;
493 else if (flag_devirtualize && virtual_method_call_p (rhs))
494 {
495 bool final;
496 vec <cgraph_node *>targets
497 = possible_polymorphic_call_targets (rhs, stmt, &final);
498 if (final && targets.length () <= 1 && dbg_cnt (devirt))
499 {
500 if (dump_enabled_p ())
501 {
502 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
503 "resolving virtual function address "
504 "reference to function %s\n",
505 targets.length () == 1
506 ? targets[0]->name ()
507 : "NULL");
508 }
509 if (targets.length () == 1)
510 {
511 val = fold_convert (TREE_TYPE (val),
512 build_fold_addr_expr_loc
513 (loc, targets[0]->decl));
514 STRIP_USELESS_TYPE_CONVERSION (val);
515 }
516 else
517 /* We cannot use __builtin_unreachable here because it
518 cannot have address taken. */
519 val = build_int_cst (TREE_TYPE (val), 0);
520 return val;
521 }
522 }
523 }
524
525 else if (TREE_CODE (rhs) == ADDR_EXPR)
526 {
527 tree ref = TREE_OPERAND (rhs, 0);
528 if (TREE_CODE (ref) == MEM_REF
529 && integer_zerop (TREE_OPERAND (ref, 1)))
530 {
531 result = TREE_OPERAND (ref, 0);
532 if (!useless_type_conversion_p (TREE_TYPE (rhs),
533 TREE_TYPE (result)))
534 result = build1 (NOP_EXPR, TREE_TYPE (rhs), result);
535 return result;
536 }
537 }
538
539 else if (TREE_CODE (rhs) == CONSTRUCTOR
540 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE)
541 {
542 /* Fold a constant vector CONSTRUCTOR to VECTOR_CST. */
543 unsigned i;
544 tree val;
545
546 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
547 if (! CONSTANT_CLASS_P (val))
548 return NULL_TREE;
549
550 return build_vector_from_ctor (TREE_TYPE (rhs),
551 CONSTRUCTOR_ELTS (rhs));
552 }
553
554 else if (DECL_P (rhs)
555 && is_gimple_reg_type (TREE_TYPE (rhs)))
556 return get_symbol_constant_value (rhs);
557 }
558 break;
559
560 case GIMPLE_UNARY_RHS:
561 break;
562
563 case GIMPLE_BINARY_RHS:
564 break;
565
566 case GIMPLE_TERNARY_RHS:
567 result = fold_ternary_loc (loc, subcode,
568 TREE_TYPE (gimple_assign_lhs (stmt)),
569 gimple_assign_rhs1 (stmt),
570 gimple_assign_rhs2 (stmt),
571 gimple_assign_rhs3 (stmt));
572
573 if (result)
574 {
575 STRIP_USELESS_TYPE_CONVERSION (result);
576 if (valid_gimple_rhs_p (result))
577 return result;
578 }
579 break;
580
581 case GIMPLE_INVALID_RHS:
582 gcc_unreachable ();
583 }
584
585 return NULL_TREE;
586 }
587
588
589 /* Replace a statement at *SI_P with a sequence of statements in STMTS,
590 adjusting the replacement stmts location and virtual operands.
591 If the statement has a lhs the last stmt in the sequence is expected
592 to assign to that lhs. */
593
594 void
595 gsi_replace_with_seq_vops (gimple_stmt_iterator *si_p, gimple_seq stmts)
596 {
597 gimple *stmt = gsi_stmt (*si_p);
598
599 if (gimple_has_location (stmt))
600 annotate_all_with_location (stmts, gimple_location (stmt));
601
602 /* First iterate over the replacement statements backward, assigning
603 virtual operands to their defining statements. */
604 gimple *laststore = NULL;
605 for (gimple_stmt_iterator i = gsi_last (stmts);
606 !gsi_end_p (i); gsi_prev (&i))
607 {
608 gimple *new_stmt = gsi_stmt (i);
609 if ((gimple_assign_single_p (new_stmt)
610 && !is_gimple_reg (gimple_assign_lhs (new_stmt)))
611 || (is_gimple_call (new_stmt)
612 && (gimple_call_flags (new_stmt)
613 & (ECF_NOVOPS | ECF_PURE | ECF_CONST | ECF_NORETURN)) == 0))
614 {
615 tree vdef;
616 if (!laststore)
617 vdef = gimple_vdef (stmt);
618 else
619 vdef = make_ssa_name (gimple_vop (cfun), new_stmt);
620 gimple_set_vdef (new_stmt, vdef);
621 if (vdef && TREE_CODE (vdef) == SSA_NAME)
622 SSA_NAME_DEF_STMT (vdef) = new_stmt;
623 laststore = new_stmt;
624 }
625 }
626
627 /* Second iterate over the statements forward, assigning virtual
628 operands to their uses. */
629 tree reaching_vuse = gimple_vuse (stmt);
630 for (gimple_stmt_iterator i = gsi_start (stmts);
631 !gsi_end_p (i); gsi_next (&i))
632 {
633 gimple *new_stmt = gsi_stmt (i);
634 /* If the new statement possibly has a VUSE, update it with exact SSA
635 name we know will reach this one. */
636 if (gimple_has_mem_ops (new_stmt))
637 gimple_set_vuse (new_stmt, reaching_vuse);
638 gimple_set_modified (new_stmt, true);
639 if (gimple_vdef (new_stmt))
640 reaching_vuse = gimple_vdef (new_stmt);
641 }
642
643 /* If the new sequence does not do a store release the virtual
644 definition of the original statement. */
645 if (reaching_vuse
646 && reaching_vuse == gimple_vuse (stmt))
647 {
648 tree vdef = gimple_vdef (stmt);
649 if (vdef
650 && TREE_CODE (vdef) == SSA_NAME)
651 {
652 unlink_stmt_vdef (stmt);
653 release_ssa_name (vdef);
654 }
655 }
656
657 /* Finally replace the original statement with the sequence. */
658 gsi_replace_with_seq (si_p, stmts, false);
659 }
660
661 /* Helper function for update_gimple_call and
662 gimplify_and_update_call_from_tree. A GIMPLE_CALL STMT is being replaced
663 with GIMPLE_CALL NEW_STMT. */
664
665 static void
666 finish_update_gimple_call (gimple_stmt_iterator *si_p, gimple *new_stmt,
667 gimple *stmt)
668 {
669 tree lhs = gimple_call_lhs (stmt);
670 gimple_call_set_lhs (new_stmt, lhs);
671 if (lhs && TREE_CODE (lhs) == SSA_NAME)
672 SSA_NAME_DEF_STMT (lhs) = new_stmt;
673 gimple_move_vops (new_stmt, stmt);
674 gimple_set_location (new_stmt, gimple_location (stmt));
675 if (gimple_block (new_stmt) == NULL_TREE)
676 gimple_set_block (new_stmt, gimple_block (stmt));
677 gsi_replace (si_p, new_stmt, false);
678 }
679
680 /* Update a GIMPLE_CALL statement at iterator *SI_P to call to FN
681 with number of arguments NARGS, where the arguments in GIMPLE form
682 follow NARGS argument. */
683
684 bool
685 update_gimple_call (gimple_stmt_iterator *si_p, tree fn, int nargs, ...)
686 {
687 va_list ap;
688 gcall *new_stmt, *stmt = as_a <gcall *> (gsi_stmt (*si_p));
689
690 gcc_assert (is_gimple_call (stmt));
691 va_start (ap, nargs);
692 new_stmt = gimple_build_call_valist (fn, nargs, ap);
693 finish_update_gimple_call (si_p, new_stmt, stmt);
694 va_end (ap);
695 return true;
696 }
697
698 /* Return true if EXPR is a CALL_EXPR suitable for representation
699 as a single GIMPLE_CALL statement. If the arguments require
700 further gimplification, return false. */
701
702 static bool
703 valid_gimple_call_p (tree expr)
704 {
705 unsigned i, nargs;
706
707 if (TREE_CODE (expr) != CALL_EXPR)
708 return false;
709
710 nargs = call_expr_nargs (expr);
711 for (i = 0; i < nargs; i++)
712 {
713 tree arg = CALL_EXPR_ARG (expr, i);
714 if (is_gimple_reg_type (TREE_TYPE (arg)))
715 {
716 if (!is_gimple_val (arg))
717 return false;
718 }
719 else
720 if (!is_gimple_lvalue (arg))
721 return false;
722 }
723
724 return true;
725 }
726
727 /* Convert EXPR into a GIMPLE value suitable for substitution on the
728 RHS of an assignment. Insert the necessary statements before
729 iterator *SI_P. The statement at *SI_P, which must be a GIMPLE_CALL
730 is replaced. If the call is expected to produces a result, then it
731 is replaced by an assignment of the new RHS to the result variable.
732 If the result is to be ignored, then the call is replaced by a
733 GIMPLE_NOP. A proper VDEF chain is retained by making the first
734 VUSE and the last VDEF of the whole sequence be the same as the replaced
735 statement and using new SSA names for stores in between. */
736
737 void
738 gimplify_and_update_call_from_tree (gimple_stmt_iterator *si_p, tree expr)
739 {
740 tree lhs;
741 gimple *stmt, *new_stmt;
742 gimple_stmt_iterator i;
743 gimple_seq stmts = NULL;
744
745 stmt = gsi_stmt (*si_p);
746
747 gcc_assert (is_gimple_call (stmt));
748
749 if (valid_gimple_call_p (expr))
750 {
751 /* The call has simplified to another call. */
752 tree fn = CALL_EXPR_FN (expr);
753 unsigned i;
754 unsigned nargs = call_expr_nargs (expr);
755 vec<tree> args = vNULL;
756 gcall *new_stmt;
757
758 if (nargs > 0)
759 {
760 args.create (nargs);
761 args.safe_grow_cleared (nargs, true);
762
763 for (i = 0; i < nargs; i++)
764 args[i] = CALL_EXPR_ARG (expr, i);
765 }
766
767 new_stmt = gimple_build_call_vec (fn, args);
768 finish_update_gimple_call (si_p, new_stmt, stmt);
769 args.release ();
770 return;
771 }
772
773 lhs = gimple_call_lhs (stmt);
774 if (lhs == NULL_TREE)
775 {
776 push_gimplify_context (gimple_in_ssa_p (cfun));
777 gimplify_and_add (expr, &stmts);
778 pop_gimplify_context (NULL);
779
780 /* We can end up with folding a memcpy of an empty class assignment
781 which gets optimized away by C++ gimplification. */
782 if (gimple_seq_empty_p (stmts))
783 {
784 if (gimple_in_ssa_p (cfun))
785 {
786 unlink_stmt_vdef (stmt);
787 release_defs (stmt);
788 }
789 gsi_replace (si_p, gimple_build_nop (), false);
790 return;
791 }
792 }
793 else
794 {
795 tree tmp = force_gimple_operand (expr, &stmts, false, NULL_TREE);
796 new_stmt = gimple_build_assign (lhs, tmp);
797 i = gsi_last (stmts);
798 gsi_insert_after_without_update (&i, new_stmt,
799 GSI_CONTINUE_LINKING);
800 }
801
802 gsi_replace_with_seq_vops (si_p, stmts);
803 }
804
805 /* Print a message in the dump file recording transformation of FROM to TO. */
806
807 static void
808 dump_transformation (gcall *from, gcall *to)
809 {
810 if (dump_enabled_p ())
811 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, from, "simplified %T to %T\n",
812 gimple_call_fn (from), gimple_call_fn (to));
813 }
814
815 /* Replace the call at *GSI with the gimple value VAL. */
816
817 void
818 replace_call_with_value (gimple_stmt_iterator *gsi, tree val)
819 {
820 gimple *stmt = gsi_stmt (*gsi);
821 tree lhs = gimple_call_lhs (stmt);
822 gimple *repl;
823 if (lhs)
824 {
825 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (val)))
826 val = fold_convert (TREE_TYPE (lhs), val);
827 repl = gimple_build_assign (lhs, val);
828 }
829 else
830 repl = gimple_build_nop ();
831 tree vdef = gimple_vdef (stmt);
832 if (vdef && TREE_CODE (vdef) == SSA_NAME)
833 {
834 unlink_stmt_vdef (stmt);
835 release_ssa_name (vdef);
836 }
837 gsi_replace (gsi, repl, false);
838 }
839
840 /* Replace the call at *GSI with the new call REPL and fold that
841 again. */
842
843 static void
844 replace_call_with_call_and_fold (gimple_stmt_iterator *gsi, gimple *repl)
845 {
846 gimple *stmt = gsi_stmt (*gsi);
847 dump_transformation (as_a <gcall *> (stmt), as_a <gcall *> (repl));
848 gimple_call_set_lhs (repl, gimple_call_lhs (stmt));
849 gimple_set_location (repl, gimple_location (stmt));
850 gimple_move_vops (repl, stmt);
851 gsi_replace (gsi, repl, false);
852 fold_stmt (gsi);
853 }
854
855 /* Return true if VAR is a VAR_DECL or a component thereof. */
856
857 static bool
858 var_decl_component_p (tree var)
859 {
860 tree inner = var;
861 while (handled_component_p (inner))
862 inner = TREE_OPERAND (inner, 0);
863 return (DECL_P (inner)
864 || (TREE_CODE (inner) == MEM_REF
865 && TREE_CODE (TREE_OPERAND (inner, 0)) == ADDR_EXPR));
866 }
867
868 /* Return TRUE if the SIZE argument, representing the size of an
869 object, is in a range of values of which exactly zero is valid. */
870
871 static bool
872 size_must_be_zero_p (tree size)
873 {
874 if (integer_zerop (size))
875 return true;
876
877 if (TREE_CODE (size) != SSA_NAME || !INTEGRAL_TYPE_P (TREE_TYPE (size)))
878 return false;
879
880 tree type = TREE_TYPE (size);
881 int prec = TYPE_PRECISION (type);
882
883 /* Compute the value of SSIZE_MAX, the largest positive value that
884 can be stored in ssize_t, the signed counterpart of size_t. */
885 wide_int ssize_max = wi::lshift (wi::one (prec), prec - 1) - 1;
886 wide_int zero = wi::zero (TYPE_PRECISION (type));
887 int_range_max valid_range (type, zero, ssize_max);
888 int_range_max vr;
889 get_range_query (cfun)->range_of_expr (vr, size);
890
891 if (vr.undefined_p ())
892 vr.set_varying (TREE_TYPE (size));
893 vr.intersect (valid_range);
894 return vr.zero_p ();
895 }
896
897 /* Optimize
898 a = {};
899 b = a;
900 into
901 a = {};
902 b = {};
903 Similarly for memset (&a, ..., sizeof (a)); instead of a = {};
904 and/or memcpy (&b, &a, sizeof (a)); instead of b = a; */
905
906 static bool
907 optimize_memcpy_to_memset (gimple_stmt_iterator *gsip, tree dest, tree src, tree len)
908 {
909 gimple *stmt = gsi_stmt (*gsip);
910 if (gimple_has_volatile_ops (stmt))
911 return false;
912
913 tree vuse = gimple_vuse (stmt);
914 if (vuse == NULL || TREE_CODE (vuse) != SSA_NAME)
915 return false;
916
917 gimple *defstmt = SSA_NAME_DEF_STMT (vuse);
918 tree src2 = NULL_TREE, len2 = NULL_TREE;
919 poly_int64 offset, offset2;
920 tree val = integer_zero_node;
921 if (gimple_store_p (defstmt)
922 && gimple_assign_single_p (defstmt)
923 && TREE_CODE (gimple_assign_rhs1 (defstmt)) == CONSTRUCTOR
924 && !gimple_clobber_p (defstmt))
925 src2 = gimple_assign_lhs (defstmt);
926 else if (gimple_call_builtin_p (defstmt, BUILT_IN_MEMSET)
927 && TREE_CODE (gimple_call_arg (defstmt, 0)) == ADDR_EXPR
928 && TREE_CODE (gimple_call_arg (defstmt, 1)) == INTEGER_CST)
929 {
930 src2 = TREE_OPERAND (gimple_call_arg (defstmt, 0), 0);
931 len2 = gimple_call_arg (defstmt, 2);
932 val = gimple_call_arg (defstmt, 1);
933 /* For non-0 val, we'd have to transform stmt from assignment
934 into memset (only if dest is addressable). */
935 if (!integer_zerop (val) && is_gimple_assign (stmt))
936 src2 = NULL_TREE;
937 }
938
939 if (src2 == NULL_TREE)
940 return false;
941
942 if (len == NULL_TREE)
943 len = (TREE_CODE (src) == COMPONENT_REF
944 ? DECL_SIZE_UNIT (TREE_OPERAND (src, 1))
945 : TYPE_SIZE_UNIT (TREE_TYPE (src)));
946 if (len2 == NULL_TREE)
947 len2 = (TREE_CODE (src2) == COMPONENT_REF
948 ? DECL_SIZE_UNIT (TREE_OPERAND (src2, 1))
949 : TYPE_SIZE_UNIT (TREE_TYPE (src2)));
950 if (len == NULL_TREE
951 || !poly_int_tree_p (len)
952 || len2 == NULL_TREE
953 || !poly_int_tree_p (len2))
954 return false;
955
956 src = get_addr_base_and_unit_offset (src, &offset);
957 src2 = get_addr_base_and_unit_offset (src2, &offset2);
958 if (src == NULL_TREE
959 || src2 == NULL_TREE
960 || maybe_lt (offset, offset2))
961 return false;
962
963 if (!operand_equal_p (src, src2, 0))
964 return false;
965
966 /* [ src + offset2, src + offset2 + len2 - 1 ] is set to val.
967 Make sure that
968 [ src + offset, src + offset + len - 1 ] is a subset of that. */
969 if (maybe_gt (wi::to_poly_offset (len) + (offset - offset2),
970 wi::to_poly_offset (len2)))
971 return false;
972
973 if (dump_file && (dump_flags & TDF_DETAILS))
974 {
975 fprintf (dump_file, "Simplified\n ");
976 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
977 fprintf (dump_file, "after previous\n ");
978 print_gimple_stmt (dump_file, defstmt, 0, dump_flags);
979 }
980
981 /* For simplicity, don't change the kind of the stmt,
982 turn dest = src; into dest = {}; and memcpy (&dest, &src, len);
983 into memset (&dest, val, len);
984 In theory we could change dest = src into memset if dest
985 is addressable (maybe beneficial if val is not 0), or
986 memcpy (&dest, &src, len) into dest = {} if len is the size
987 of dest, dest isn't volatile. */
988 if (is_gimple_assign (stmt))
989 {
990 tree ctor = build_constructor (TREE_TYPE (dest), NULL);
991 gimple_assign_set_rhs_from_tree (gsip, ctor);
992 update_stmt (stmt);
993 }
994 else /* If stmt is memcpy, transform it into memset. */
995 {
996 gcall *call = as_a <gcall *> (stmt);
997 tree fndecl = builtin_decl_implicit (BUILT_IN_MEMSET);
998 gimple_call_set_fndecl (call, fndecl);
999 gimple_call_set_fntype (call, TREE_TYPE (fndecl));
1000 gimple_call_set_arg (call, 1, val);
1001 update_stmt (stmt);
1002 }
1003
1004 if (dump_file && (dump_flags & TDF_DETAILS))
1005 {
1006 fprintf (dump_file, "into\n ");
1007 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1008 }
1009 return true;
1010 }
1011
1012 /* Fold function call to builtin mem{{,p}cpy,move}. Try to detect and
1013 diagnose (otherwise undefined) overlapping copies without preventing
1014 folding. When folded, GCC guarantees that overlapping memcpy has
1015 the same semantics as memmove. Call to the library memcpy need not
1016 provide the same guarantee. Return false if no simplification can
1017 be made. */
1018
1019 static bool
1020 gimple_fold_builtin_memory_op (gimple_stmt_iterator *gsi,
1021 tree dest, tree src, enum built_in_function code)
1022 {
1023 gimple *stmt = gsi_stmt (*gsi);
1024 tree lhs = gimple_call_lhs (stmt);
1025 tree len = gimple_call_arg (stmt, 2);
1026 location_t loc = gimple_location (stmt);
1027
1028 /* If the LEN parameter is a constant zero or in range where
1029 the only valid value is zero, return DEST. */
1030 if (size_must_be_zero_p (len))
1031 {
1032 gimple *repl;
1033 if (gimple_call_lhs (stmt))
1034 repl = gimple_build_assign (gimple_call_lhs (stmt), dest);
1035 else
1036 repl = gimple_build_nop ();
1037 tree vdef = gimple_vdef (stmt);
1038 if (vdef && TREE_CODE (vdef) == SSA_NAME)
1039 {
1040 unlink_stmt_vdef (stmt);
1041 release_ssa_name (vdef);
1042 }
1043 gsi_replace (gsi, repl, false);
1044 return true;
1045 }
1046
1047 /* If SRC and DEST are the same (and not volatile), return
1048 DEST{,+LEN,+LEN-1}. */
1049 if (operand_equal_p (src, dest, 0))
1050 {
1051 /* Avoid diagnosing exact overlap in calls to __builtin_memcpy.
1052 It's safe and may even be emitted by GCC itself (see bug
1053 32667). */
1054 unlink_stmt_vdef (stmt);
1055 if (gimple_vdef (stmt) && TREE_CODE (gimple_vdef (stmt)) == SSA_NAME)
1056 release_ssa_name (gimple_vdef (stmt));
1057 if (!lhs)
1058 {
1059 gsi_replace (gsi, gimple_build_nop (), false);
1060 return true;
1061 }
1062 goto done;
1063 }
1064 else if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
1065 return false;
1066 else
1067 {
1068 /* We cannot (easily) change the type of the copy if it is a storage
1069 order barrier, i.e. is equivalent to a VIEW_CONVERT_EXPR that can
1070 modify the storage order of objects (see storage_order_barrier_p). */
1071 tree srctype
1072 = POINTER_TYPE_P (TREE_TYPE (src))
1073 ? TREE_TYPE (TREE_TYPE (src)) : NULL_TREE;
1074 tree desttype
1075 = POINTER_TYPE_P (TREE_TYPE (dest))
1076 ? TREE_TYPE (TREE_TYPE (dest)) : NULL_TREE;
1077 tree destvar, srcvar, srcoff;
1078 unsigned int src_align, dest_align;
1079 unsigned HOST_WIDE_INT tmp_len;
1080 const char *tmp_str;
1081
1082 /* Build accesses at offset zero with a ref-all character type. */
1083 tree off0
1084 = build_int_cst (build_pointer_type_for_mode (char_type_node,
1085 ptr_mode, true), 0);
1086
1087 /* If we can perform the copy efficiently with first doing all loads
1088 and then all stores inline it that way. Currently efficiently
1089 means that we can load all the memory into a single integer
1090 register which is what MOVE_MAX gives us. */
1091 src_align = get_pointer_alignment (src);
1092 dest_align = get_pointer_alignment (dest);
1093 if (tree_fits_uhwi_p (len)
1094 && compare_tree_int (len, MOVE_MAX) <= 0
1095 /* FIXME: Don't transform copies from strings with known length.
1096 Until GCC 9 this prevented a case in gcc.dg/strlenopt-8.c
1097 from being handled, and the case was XFAILed for that reason.
1098 Now that it is handled and the XFAIL removed, as soon as other
1099 strlenopt tests that rely on it for passing are adjusted, this
1100 hack can be removed. */
1101 && !c_strlen (src, 1)
1102 && !((tmp_str = getbyterep (src, &tmp_len)) != NULL
1103 && memchr (tmp_str, 0, tmp_len) == NULL)
1104 && !(srctype
1105 && AGGREGATE_TYPE_P (srctype)
1106 && TYPE_REVERSE_STORAGE_ORDER (srctype))
1107 && !(desttype
1108 && AGGREGATE_TYPE_P (desttype)
1109 && TYPE_REVERSE_STORAGE_ORDER (desttype)))
1110 {
1111 unsigned ilen = tree_to_uhwi (len);
1112 if (pow2p_hwi (ilen))
1113 {
1114 /* Detect out-of-bounds accesses without issuing warnings.
1115 Avoid folding out-of-bounds copies but to avoid false
1116 positives for unreachable code defer warning until after
1117 DCE has worked its magic.
1118 -Wrestrict is still diagnosed. */
1119 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
1120 dest, src, len, len,
1121 false, false))
1122 if (warning != OPT_Wrestrict)
1123 return false;
1124
1125 scalar_int_mode imode;
1126 machine_mode mode;
1127 if (int_mode_for_size (ilen * BITS_PER_UNIT, 0).exists (&imode)
1128 && bitwise_mode_for_size (ilen
1129 * BITS_PER_UNIT).exists (&mode)
1130 && known_eq (GET_MODE_BITSIZE (mode), ilen * BITS_PER_UNIT)
1131 /* If the destination pointer is not aligned we must be able
1132 to emit an unaligned store. */
1133 && (dest_align >= GET_MODE_ALIGNMENT (mode)
1134 || !targetm.slow_unaligned_access (mode, dest_align)
1135 || (optab_handler (movmisalign_optab, mode)
1136 != CODE_FOR_nothing)))
1137 {
1138 tree type = bitwise_type_for_mode (mode);
1139 tree srctype = type;
1140 tree desttype = type;
1141 if (src_align < GET_MODE_ALIGNMENT (mode))
1142 srctype = build_aligned_type (type, src_align);
1143 tree srcmem = fold_build2 (MEM_REF, srctype, src, off0);
1144 tree tem = fold_const_aggregate_ref (srcmem);
1145 if (tem)
1146 srcmem = tem;
1147 else if (src_align < GET_MODE_ALIGNMENT (mode)
1148 && targetm.slow_unaligned_access (mode, src_align)
1149 && (optab_handler (movmisalign_optab, mode)
1150 == CODE_FOR_nothing))
1151 srcmem = NULL_TREE;
1152 if (srcmem)
1153 {
1154 gimple *new_stmt;
1155 if (is_gimple_reg_type (TREE_TYPE (srcmem)))
1156 {
1157 new_stmt = gimple_build_assign (NULL_TREE, srcmem);
1158 srcmem
1159 = create_tmp_reg_or_ssa_name (TREE_TYPE (srcmem),
1160 new_stmt);
1161 gimple_assign_set_lhs (new_stmt, srcmem);
1162 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1163 gimple_set_location (new_stmt, loc);
1164 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1165 }
1166 if (dest_align < GET_MODE_ALIGNMENT (mode))
1167 desttype = build_aligned_type (type, dest_align);
1168 new_stmt
1169 = gimple_build_assign (fold_build2 (MEM_REF, desttype,
1170 dest, off0),
1171 srcmem);
1172 gimple_move_vops (new_stmt, stmt);
1173 if (!lhs)
1174 {
1175 gsi_replace (gsi, new_stmt, false);
1176 return true;
1177 }
1178 gimple_set_location (new_stmt, loc);
1179 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1180 goto done;
1181 }
1182 }
1183 }
1184 }
1185
1186 if (code == BUILT_IN_MEMMOVE)
1187 {
1188 /* Both DEST and SRC must be pointer types.
1189 ??? This is what old code did. Is the testing for pointer types
1190 really mandatory?
1191
1192 If either SRC is readonly or length is 1, we can use memcpy. */
1193 if (!dest_align || !src_align)
1194 return false;
1195 if (readonly_data_expr (src)
1196 || (tree_fits_uhwi_p (len)
1197 && (MIN (src_align, dest_align) / BITS_PER_UNIT
1198 >= tree_to_uhwi (len))))
1199 {
1200 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1201 if (!fn)
1202 return false;
1203 gimple_call_set_fndecl (stmt, fn);
1204 gimple_call_set_arg (stmt, 0, dest);
1205 gimple_call_set_arg (stmt, 1, src);
1206 fold_stmt (gsi);
1207 return true;
1208 }
1209
1210 /* If *src and *dest can't overlap, optimize into memcpy as well. */
1211 if (TREE_CODE (src) == ADDR_EXPR
1212 && TREE_CODE (dest) == ADDR_EXPR)
1213 {
1214 tree src_base, dest_base, fn;
1215 poly_int64 src_offset = 0, dest_offset = 0;
1216 poly_uint64 maxsize;
1217
1218 srcvar = TREE_OPERAND (src, 0);
1219 src_base = get_addr_base_and_unit_offset (srcvar, &src_offset);
1220 if (src_base == NULL)
1221 src_base = srcvar;
1222 destvar = TREE_OPERAND (dest, 0);
1223 dest_base = get_addr_base_and_unit_offset (destvar,
1224 &dest_offset);
1225 if (dest_base == NULL)
1226 dest_base = destvar;
1227 if (!poly_int_tree_p (len, &maxsize))
1228 maxsize = -1;
1229 if (SSA_VAR_P (src_base)
1230 && SSA_VAR_P (dest_base))
1231 {
1232 if (operand_equal_p (src_base, dest_base, 0)
1233 && ranges_maybe_overlap_p (src_offset, maxsize,
1234 dest_offset, maxsize))
1235 return false;
1236 }
1237 else if (TREE_CODE (src_base) == MEM_REF
1238 && TREE_CODE (dest_base) == MEM_REF)
1239 {
1240 if (! operand_equal_p (TREE_OPERAND (src_base, 0),
1241 TREE_OPERAND (dest_base, 0), 0))
1242 return false;
1243 poly_offset_int full_src_offset
1244 = mem_ref_offset (src_base) + src_offset;
1245 poly_offset_int full_dest_offset
1246 = mem_ref_offset (dest_base) + dest_offset;
1247 if (ranges_maybe_overlap_p (full_src_offset, maxsize,
1248 full_dest_offset, maxsize))
1249 return false;
1250 }
1251 else
1252 return false;
1253
1254 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1255 if (!fn)
1256 return false;
1257 gimple_call_set_fndecl (stmt, fn);
1258 gimple_call_set_arg (stmt, 0, dest);
1259 gimple_call_set_arg (stmt, 1, src);
1260 fold_stmt (gsi);
1261 return true;
1262 }
1263
1264 /* If the destination and source do not alias optimize into
1265 memcpy as well. */
1266 if ((is_gimple_min_invariant (dest)
1267 || TREE_CODE (dest) == SSA_NAME)
1268 && (is_gimple_min_invariant (src)
1269 || TREE_CODE (src) == SSA_NAME))
1270 {
1271 ao_ref destr, srcr;
1272 ao_ref_init_from_ptr_and_size (&destr, dest, len);
1273 ao_ref_init_from_ptr_and_size (&srcr, src, len);
1274 if (!refs_may_alias_p_1 (&destr, &srcr, false))
1275 {
1276 tree fn;
1277 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
1278 if (!fn)
1279 return false;
1280 gimple_call_set_fndecl (stmt, fn);
1281 gimple_call_set_arg (stmt, 0, dest);
1282 gimple_call_set_arg (stmt, 1, src);
1283 fold_stmt (gsi);
1284 return true;
1285 }
1286 }
1287
1288 return false;
1289 }
1290
1291 /* Try to optimize the memcpy to memset if src and dest are addresses. */
1292 if (code != BUILT_IN_MEMPCPY
1293 && TREE_CODE (dest) == ADDR_EXPR
1294 && TREE_CODE (src) == ADDR_EXPR
1295 && TREE_CODE (len) == INTEGER_CST
1296 && optimize_memcpy_to_memset (gsi, TREE_OPERAND (dest, 0),
1297 TREE_OPERAND (src, 0), len))
1298 return true;
1299
1300 if (!tree_fits_shwi_p (len))
1301 return false;
1302 if (!srctype
1303 || (AGGREGATE_TYPE_P (srctype)
1304 && TYPE_REVERSE_STORAGE_ORDER (srctype)))
1305 return false;
1306 if (!desttype
1307 || (AGGREGATE_TYPE_P (desttype)
1308 && TYPE_REVERSE_STORAGE_ORDER (desttype)))
1309 return false;
1310 /* In the following try to find a type that is most natural to be
1311 used for the memcpy source and destination and that allows
1312 the most optimization when memcpy is turned into a plain assignment
1313 using that type. In theory we could always use a char[len] type
1314 but that only gains us that the destination and source possibly
1315 no longer will have their address taken. */
1316 if (TREE_CODE (srctype) == ARRAY_TYPE
1317 && !tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len))
1318 srctype = TREE_TYPE (srctype);
1319 if (TREE_CODE (desttype) == ARRAY_TYPE
1320 && !tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len))
1321 desttype = TREE_TYPE (desttype);
1322 if (TREE_ADDRESSABLE (srctype)
1323 || TREE_ADDRESSABLE (desttype))
1324 return false;
1325
1326 /* Make sure we are not copying using a floating-point mode or
1327 a type whose size possibly does not match its precision. */
1328 if (FLOAT_MODE_P (TYPE_MODE (desttype))
1329 || TREE_CODE (desttype) == BOOLEAN_TYPE
1330 || TREE_CODE (desttype) == ENUMERAL_TYPE)
1331 desttype = bitwise_type_for_mode (TYPE_MODE (desttype));
1332 if (FLOAT_MODE_P (TYPE_MODE (srctype))
1333 || TREE_CODE (srctype) == BOOLEAN_TYPE
1334 || TREE_CODE (srctype) == ENUMERAL_TYPE)
1335 srctype = bitwise_type_for_mode (TYPE_MODE (srctype));
1336 if (!srctype)
1337 srctype = desttype;
1338 if (!desttype)
1339 desttype = srctype;
1340 if (!srctype)
1341 return false;
1342
1343 src_align = get_pointer_alignment (src);
1344 dest_align = get_pointer_alignment (dest);
1345
1346 /* Choose between src and destination type for the access based
1347 on alignment, whether the access constitutes a register access
1348 and whether it may actually expose a declaration for SSA rewrite
1349 or SRA decomposition. Also try to expose a string constant, we
1350 might be able to concatenate several of them later into a single
1351 string store. */
1352 destvar = NULL_TREE;
1353 srcvar = NULL_TREE;
1354 if (TREE_CODE (dest) == ADDR_EXPR
1355 && var_decl_component_p (TREE_OPERAND (dest, 0))
1356 && tree_int_cst_equal (TYPE_SIZE_UNIT (desttype), len)
1357 && dest_align >= TYPE_ALIGN (desttype)
1358 && (is_gimple_reg_type (desttype)
1359 || src_align >= TYPE_ALIGN (desttype)))
1360 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1361 else if (TREE_CODE (src) == ADDR_EXPR
1362 && var_decl_component_p (TREE_OPERAND (src, 0))
1363 && tree_int_cst_equal (TYPE_SIZE_UNIT (srctype), len)
1364 && src_align >= TYPE_ALIGN (srctype)
1365 && (is_gimple_reg_type (srctype)
1366 || dest_align >= TYPE_ALIGN (srctype)))
1367 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1368 /* FIXME: Don't transform copies from strings with known original length.
1369 As soon as strlenopt tests that rely on it for passing are adjusted,
1370 this hack can be removed. */
1371 else if (gimple_call_alloca_for_var_p (stmt)
1372 && (srcvar = string_constant (src, &srcoff, NULL, NULL))
1373 && integer_zerop (srcoff)
1374 && tree_int_cst_equal (TYPE_SIZE_UNIT (TREE_TYPE (srcvar)), len)
1375 && dest_align >= TYPE_ALIGN (TREE_TYPE (srcvar)))
1376 srctype = TREE_TYPE (srcvar);
1377 else
1378 return false;
1379
1380 /* Now that we chose an access type express the other side in
1381 terms of it if the target allows that with respect to alignment
1382 constraints. */
1383 if (srcvar == NULL_TREE)
1384 {
1385 if (src_align >= TYPE_ALIGN (desttype))
1386 srcvar = fold_build2 (MEM_REF, desttype, src, off0);
1387 else
1388 {
1389 enum machine_mode mode = TYPE_MODE (desttype);
1390 if ((mode == BLKmode && STRICT_ALIGNMENT)
1391 || (targetm.slow_unaligned_access (mode, src_align)
1392 && (optab_handler (movmisalign_optab, mode)
1393 == CODE_FOR_nothing)))
1394 return false;
1395 srctype = build_aligned_type (TYPE_MAIN_VARIANT (desttype),
1396 src_align);
1397 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1398 }
1399 }
1400 else if (destvar == NULL_TREE)
1401 {
1402 if (dest_align >= TYPE_ALIGN (srctype))
1403 destvar = fold_build2 (MEM_REF, srctype, dest, off0);
1404 else
1405 {
1406 enum machine_mode mode = TYPE_MODE (srctype);
1407 if ((mode == BLKmode && STRICT_ALIGNMENT)
1408 || (targetm.slow_unaligned_access (mode, dest_align)
1409 && (optab_handler (movmisalign_optab, mode)
1410 == CODE_FOR_nothing)))
1411 return false;
1412 desttype = build_aligned_type (TYPE_MAIN_VARIANT (srctype),
1413 dest_align);
1414 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1415 }
1416 }
1417
1418 /* Same as above, detect out-of-bounds accesses without issuing
1419 warnings. Avoid folding out-of-bounds copies but to avoid
1420 false positives for unreachable code defer warning until
1421 after DCE has worked its magic.
1422 -Wrestrict is still diagnosed. */
1423 if (int warning = check_bounds_or_overlap (as_a <gcall *>(stmt),
1424 dest, src, len, len,
1425 false, false))
1426 if (warning != OPT_Wrestrict)
1427 return false;
1428
1429 gimple *new_stmt;
1430 if (is_gimple_reg_type (TREE_TYPE (srcvar)))
1431 {
1432 tree tem = fold_const_aggregate_ref (srcvar);
1433 if (tem)
1434 srcvar = tem;
1435 if (! is_gimple_min_invariant (srcvar))
1436 {
1437 new_stmt = gimple_build_assign (NULL_TREE, srcvar);
1438 srcvar = create_tmp_reg_or_ssa_name (TREE_TYPE (srcvar),
1439 new_stmt);
1440 gimple_assign_set_lhs (new_stmt, srcvar);
1441 gimple_set_vuse (new_stmt, gimple_vuse (stmt));
1442 gimple_set_location (new_stmt, loc);
1443 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1444 }
1445 new_stmt = gimple_build_assign (destvar, srcvar);
1446 goto set_vop_and_replace;
1447 }
1448
1449 /* We get an aggregate copy. If the source is a STRING_CST, then
1450 directly use its type to perform the copy. */
1451 if (TREE_CODE (srcvar) == STRING_CST)
1452 desttype = srctype;
1453
1454 /* Or else, use an unsigned char[] type to perform the copy in order
1455 to preserve padding and to avoid any issues with TREE_ADDRESSABLE
1456 types or float modes behavior on copying. */
1457 else
1458 {
1459 desttype = build_array_type_nelts (unsigned_char_type_node,
1460 tree_to_uhwi (len));
1461 srctype = desttype;
1462 if (src_align > TYPE_ALIGN (srctype))
1463 srctype = build_aligned_type (srctype, src_align);
1464 srcvar = fold_build2 (MEM_REF, srctype, src, off0);
1465 }
1466
1467 if (dest_align > TYPE_ALIGN (desttype))
1468 desttype = build_aligned_type (desttype, dest_align);
1469 destvar = fold_build2 (MEM_REF, desttype, dest, off0);
1470 new_stmt = gimple_build_assign (destvar, srcvar);
1471
1472 set_vop_and_replace:
1473 gimple_move_vops (new_stmt, stmt);
1474 if (!lhs)
1475 {
1476 gsi_replace (gsi, new_stmt, false);
1477 return true;
1478 }
1479 gimple_set_location (new_stmt, loc);
1480 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1481 }
1482
1483 done:
1484 gimple_seq stmts = NULL;
1485 if (code == BUILT_IN_MEMCPY || code == BUILT_IN_MEMMOVE)
1486 len = NULL_TREE;
1487 else if (code == BUILT_IN_MEMPCPY)
1488 {
1489 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
1490 dest = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
1491 TREE_TYPE (dest), dest, len);
1492 }
1493 else
1494 gcc_unreachable ();
1495
1496 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
1497 gimple *repl = gimple_build_assign (lhs, dest);
1498 gsi_replace (gsi, repl, false);
1499 return true;
1500 }
1501
1502 /* Transform a call to built-in bcmp(a, b, len) at *GSI into one
1503 to built-in memcmp (a, b, len). */
1504
1505 static bool
1506 gimple_fold_builtin_bcmp (gimple_stmt_iterator *gsi)
1507 {
1508 tree fn = builtin_decl_implicit (BUILT_IN_MEMCMP);
1509
1510 if (!fn)
1511 return false;
1512
1513 /* Transform bcmp (a, b, len) into memcmp (a, b, len). */
1514
1515 gimple *stmt = gsi_stmt (*gsi);
1516 if (!gimple_vuse (stmt) && gimple_in_ssa_p (cfun))
1517 return false;
1518 tree a = gimple_call_arg (stmt, 0);
1519 tree b = gimple_call_arg (stmt, 1);
1520 tree len = gimple_call_arg (stmt, 2);
1521
1522 gimple *repl = gimple_build_call (fn, 3, a, b, len);
1523 replace_call_with_call_and_fold (gsi, repl);
1524
1525 return true;
1526 }
1527
1528 /* Transform a call to built-in bcopy (src, dest, len) at *GSI into one
1529 to built-in memmove (dest, src, len). */
1530
1531 static bool
1532 gimple_fold_builtin_bcopy (gimple_stmt_iterator *gsi)
1533 {
1534 tree fn = builtin_decl_implicit (BUILT_IN_MEMMOVE);
1535
1536 if (!fn)
1537 return false;
1538
1539 /* bcopy has been removed from POSIX in Issue 7 but Issue 6 specifies
1540 it's quivalent to memmove (not memcpy). Transform bcopy (src, dest,
1541 len) into memmove (dest, src, len). */
1542
1543 gimple *stmt = gsi_stmt (*gsi);
1544 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
1545 return false;
1546 tree src = gimple_call_arg (stmt, 0);
1547 tree dest = gimple_call_arg (stmt, 1);
1548 tree len = gimple_call_arg (stmt, 2);
1549
1550 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
1551 gimple_call_set_fntype (as_a <gcall *> (stmt), TREE_TYPE (fn));
1552 replace_call_with_call_and_fold (gsi, repl);
1553
1554 return true;
1555 }
1556
1557 /* Transform a call to built-in bzero (dest, len) at *GSI into one
1558 to built-in memset (dest, 0, len). */
1559
1560 static bool
1561 gimple_fold_builtin_bzero (gimple_stmt_iterator *gsi)
1562 {
1563 tree fn = builtin_decl_implicit (BUILT_IN_MEMSET);
1564
1565 if (!fn)
1566 return false;
1567
1568 /* Transform bzero (dest, len) into memset (dest, 0, len). */
1569
1570 gimple *stmt = gsi_stmt (*gsi);
1571 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
1572 return false;
1573 tree dest = gimple_call_arg (stmt, 0);
1574 tree len = gimple_call_arg (stmt, 1);
1575
1576 gimple_seq seq = NULL;
1577 gimple *repl = gimple_build_call (fn, 3, dest, integer_zero_node, len);
1578 gimple_seq_add_stmt_without_update (&seq, repl);
1579 gsi_replace_with_seq_vops (gsi, seq);
1580 fold_stmt (gsi);
1581
1582 return true;
1583 }
1584
1585 /* Fold function call to builtin memset or bzero at *GSI setting the
1586 memory of size LEN to VAL. Return whether a simplification was made. */
1587
1588 static bool
1589 gimple_fold_builtin_memset (gimple_stmt_iterator *gsi, tree c, tree len)
1590 {
1591 gimple *stmt = gsi_stmt (*gsi);
1592 tree etype;
1593 unsigned HOST_WIDE_INT length, cval;
1594
1595 /* If the LEN parameter is zero, return DEST. */
1596 if (integer_zerop (len))
1597 {
1598 replace_call_with_value (gsi, gimple_call_arg (stmt, 0));
1599 return true;
1600 }
1601
1602 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
1603 return false;
1604
1605 if (! tree_fits_uhwi_p (len))
1606 return false;
1607
1608 if (TREE_CODE (c) != INTEGER_CST)
1609 return false;
1610
1611 tree dest = gimple_call_arg (stmt, 0);
1612 tree var = dest;
1613 if (TREE_CODE (var) != ADDR_EXPR)
1614 return false;
1615
1616 var = TREE_OPERAND (var, 0);
1617 if (TREE_THIS_VOLATILE (var))
1618 return false;
1619
1620 etype = TREE_TYPE (var);
1621 if (TREE_CODE (etype) == ARRAY_TYPE)
1622 etype = TREE_TYPE (etype);
1623
1624 if ((!INTEGRAL_TYPE_P (etype)
1625 && !POINTER_TYPE_P (etype))
1626 || TREE_CODE (etype) == BITINT_TYPE)
1627 return false;
1628
1629 if (! var_decl_component_p (var))
1630 return false;
1631
1632 length = tree_to_uhwi (len);
1633 if (GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (etype)) != length
1634 || (GET_MODE_PRECISION (SCALAR_INT_TYPE_MODE (etype))
1635 != GET_MODE_BITSIZE (SCALAR_INT_TYPE_MODE (etype)))
1636 || get_pointer_alignment (dest) / BITS_PER_UNIT < length)
1637 return false;
1638
1639 if (length > HOST_BITS_PER_WIDE_INT / BITS_PER_UNIT)
1640 return false;
1641
1642 if (!type_has_mode_precision_p (etype))
1643 etype = lang_hooks.types.type_for_mode (SCALAR_INT_TYPE_MODE (etype),
1644 TYPE_UNSIGNED (etype));
1645
1646 if (integer_zerop (c))
1647 cval = 0;
1648 else
1649 {
1650 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || HOST_BITS_PER_WIDE_INT > 64)
1651 return NULL_TREE;
1652
1653 cval = TREE_INT_CST_LOW (c);
1654 cval &= 0xff;
1655 cval |= cval << 8;
1656 cval |= cval << 16;
1657 cval |= (cval << 31) << 1;
1658 }
1659
1660 var = fold_build2 (MEM_REF, etype, dest, build_int_cst (ptr_type_node, 0));
1661 gimple *store = gimple_build_assign (var, build_int_cst_type (etype, cval));
1662 gimple_move_vops (store, stmt);
1663 gimple_set_location (store, gimple_location (stmt));
1664 gsi_insert_before (gsi, store, GSI_SAME_STMT);
1665 if (gimple_call_lhs (stmt))
1666 {
1667 gimple *asgn = gimple_build_assign (gimple_call_lhs (stmt), dest);
1668 gsi_replace (gsi, asgn, false);
1669 }
1670 else
1671 {
1672 gimple_stmt_iterator gsi2 = *gsi;
1673 gsi_prev (gsi);
1674 gsi_remove (&gsi2, true);
1675 }
1676
1677 return true;
1678 }
1679
1680 /* Helper of get_range_strlen for ARG that is not an SSA_NAME. */
1681
1682 static bool
1683 get_range_strlen_tree (tree arg, bitmap visited, strlen_range_kind rkind,
1684 c_strlen_data *pdata, unsigned eltsize)
1685 {
1686 gcc_assert (TREE_CODE (arg) != SSA_NAME);
1687
1688 /* The length computed by this invocation of the function. */
1689 tree val = NULL_TREE;
1690
1691 /* True if VAL is an optimistic (tight) bound determined from
1692 the size of the character array in which the string may be
1693 stored. In that case, the computed VAL is used to set
1694 PDATA->MAXBOUND. */
1695 bool tight_bound = false;
1696
1697 /* We can end up with &(*iftmp_1)[0] here as well, so handle it. */
1698 if (TREE_CODE (arg) == ADDR_EXPR
1699 && TREE_CODE (TREE_OPERAND (arg, 0)) == ARRAY_REF)
1700 {
1701 tree op = TREE_OPERAND (arg, 0);
1702 if (integer_zerop (TREE_OPERAND (op, 1)))
1703 {
1704 tree aop0 = TREE_OPERAND (op, 0);
1705 if (TREE_CODE (aop0) == INDIRECT_REF
1706 && TREE_CODE (TREE_OPERAND (aop0, 0)) == SSA_NAME)
1707 return get_range_strlen (TREE_OPERAND (aop0, 0), visited, rkind,
1708 pdata, eltsize);
1709 }
1710 else if (TREE_CODE (TREE_OPERAND (op, 0)) == COMPONENT_REF
1711 && rkind == SRK_LENRANGE)
1712 {
1713 /* Fail if an array is the last member of a struct object
1714 since it could be treated as a (fake) flexible array
1715 member. */
1716 tree idx = TREE_OPERAND (op, 1);
1717
1718 arg = TREE_OPERAND (op, 0);
1719 tree optype = TREE_TYPE (arg);
1720 if (tree dom = TYPE_DOMAIN (optype))
1721 if (tree bound = TYPE_MAX_VALUE (dom))
1722 if (TREE_CODE (bound) == INTEGER_CST
1723 && TREE_CODE (idx) == INTEGER_CST
1724 && tree_int_cst_lt (bound, idx))
1725 return false;
1726 }
1727 }
1728
1729 if (rkind == SRK_INT_VALUE)
1730 {
1731 /* We are computing the maximum value (not string length). */
1732 val = arg;
1733 if (TREE_CODE (val) != INTEGER_CST
1734 || tree_int_cst_sgn (val) < 0)
1735 return false;
1736 }
1737 else
1738 {
1739 c_strlen_data lendata = { };
1740 val = c_strlen (arg, 1, &lendata, eltsize);
1741
1742 if (!val && lendata.decl)
1743 {
1744 /* ARG refers to an unterminated const character array.
1745 DATA.DECL with size DATA.LEN. */
1746 val = lendata.minlen;
1747 pdata->decl = lendata.decl;
1748 }
1749 }
1750
1751 /* Set if VAL represents the maximum length based on array size (set
1752 when exact length cannot be determined). */
1753 bool maxbound = false;
1754
1755 if (!val && rkind == SRK_LENRANGE)
1756 {
1757 if (TREE_CODE (arg) == ADDR_EXPR)
1758 return get_range_strlen (TREE_OPERAND (arg, 0), visited, rkind,
1759 pdata, eltsize);
1760
1761 if (TREE_CODE (arg) == ARRAY_REF)
1762 {
1763 tree optype = TREE_TYPE (TREE_OPERAND (arg, 0));
1764
1765 /* Determine the "innermost" array type. */
1766 while (TREE_CODE (optype) == ARRAY_TYPE
1767 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1768 optype = TREE_TYPE (optype);
1769
1770 /* Avoid arrays of pointers. */
1771 tree eltype = TREE_TYPE (optype);
1772 if (TREE_CODE (optype) != ARRAY_TYPE
1773 || !INTEGRAL_TYPE_P (eltype))
1774 return false;
1775
1776 /* Fail when the array bound is unknown or zero. */
1777 val = TYPE_SIZE_UNIT (optype);
1778 if (!val
1779 || TREE_CODE (val) != INTEGER_CST
1780 || integer_zerop (val))
1781 return false;
1782
1783 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1784 integer_one_node);
1785
1786 /* Set the minimum size to zero since the string in
1787 the array could have zero length. */
1788 pdata->minlen = ssize_int (0);
1789
1790 tight_bound = true;
1791 }
1792 else if (TREE_CODE (arg) == COMPONENT_REF
1793 && (TREE_CODE (TREE_TYPE (TREE_OPERAND (arg, 1)))
1794 == ARRAY_TYPE))
1795 {
1796 /* Use the type of the member array to determine the upper
1797 bound on the length of the array. This may be overly
1798 optimistic if the array itself isn't NUL-terminated and
1799 the caller relies on the subsequent member to contain
1800 the NUL but that would only be considered valid if
1801 the array were the last member of a struct. */
1802
1803 tree fld = TREE_OPERAND (arg, 1);
1804
1805 tree optype = TREE_TYPE (fld);
1806
1807 /* Determine the "innermost" array type. */
1808 while (TREE_CODE (optype) == ARRAY_TYPE
1809 && TREE_CODE (TREE_TYPE (optype)) == ARRAY_TYPE)
1810 optype = TREE_TYPE (optype);
1811
1812 /* Fail when the array bound is unknown or zero. */
1813 val = TYPE_SIZE_UNIT (optype);
1814 if (!val
1815 || TREE_CODE (val) != INTEGER_CST
1816 || integer_zerop (val))
1817 return false;
1818 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1819 integer_one_node);
1820
1821 /* Set the minimum size to zero since the string in
1822 the array could have zero length. */
1823 pdata->minlen = ssize_int (0);
1824
1825 /* The array size determined above is an optimistic bound
1826 on the length. If the array isn't nul-terminated the
1827 length computed by the library function would be greater.
1828 Even though using strlen to cross the subobject boundary
1829 is undefined, avoid drawing conclusions from the member
1830 type about the length here. */
1831 tight_bound = true;
1832 }
1833 else if (TREE_CODE (arg) == MEM_REF
1834 && TREE_CODE (TREE_TYPE (arg)) == ARRAY_TYPE
1835 && TREE_CODE (TREE_TYPE (TREE_TYPE (arg))) == INTEGER_TYPE
1836 && TREE_CODE (TREE_OPERAND (arg, 0)) == ADDR_EXPR)
1837 {
1838 /* Handle a MEM_REF into a DECL accessing an array of integers,
1839 being conservative about references to extern structures with
1840 flexible array members that can be initialized to arbitrary
1841 numbers of elements as an extension (static structs are okay). */
1842 tree ref = TREE_OPERAND (TREE_OPERAND (arg, 0), 0);
1843 if ((TREE_CODE (ref) == PARM_DECL || VAR_P (ref))
1844 && (decl_binds_to_current_def_p (ref)
1845 || !array_ref_flexible_size_p (arg)))
1846 {
1847 /* Fail if the offset is out of bounds. Such accesses
1848 should be diagnosed at some point. */
1849 val = DECL_SIZE_UNIT (ref);
1850 if (!val
1851 || TREE_CODE (val) != INTEGER_CST
1852 || integer_zerop (val))
1853 return false;
1854
1855 poly_offset_int psiz = wi::to_offset (val);
1856 poly_offset_int poff = mem_ref_offset (arg);
1857 if (known_le (psiz, poff))
1858 return false;
1859
1860 pdata->minlen = ssize_int (0);
1861
1862 /* Subtract the offset and one for the terminating nul. */
1863 psiz -= poff;
1864 psiz -= 1;
1865 val = wide_int_to_tree (TREE_TYPE (val), psiz);
1866 /* Since VAL reflects the size of a declared object
1867 rather the type of the access it is not a tight bound. */
1868 }
1869 }
1870 else if (TREE_CODE (arg) == PARM_DECL || VAR_P (arg))
1871 {
1872 /* Avoid handling pointers to arrays. GCC might misuse
1873 a pointer to an array of one bound to point to an array
1874 object of a greater bound. */
1875 tree argtype = TREE_TYPE (arg);
1876 if (TREE_CODE (argtype) == ARRAY_TYPE)
1877 {
1878 val = TYPE_SIZE_UNIT (argtype);
1879 if (!val
1880 || TREE_CODE (val) != INTEGER_CST
1881 || integer_zerop (val))
1882 return false;
1883 val = wide_int_to_tree (TREE_TYPE (val),
1884 wi::sub (wi::to_wide (val), 1));
1885
1886 /* Set the minimum size to zero since the string in
1887 the array could have zero length. */
1888 pdata->minlen = ssize_int (0);
1889 }
1890 }
1891 maxbound = true;
1892 }
1893
1894 if (!val)
1895 return false;
1896
1897 /* Adjust the lower bound on the string length as necessary. */
1898 if (!pdata->minlen
1899 || (rkind != SRK_STRLEN
1900 && TREE_CODE (pdata->minlen) == INTEGER_CST
1901 && TREE_CODE (val) == INTEGER_CST
1902 && tree_int_cst_lt (val, pdata->minlen)))
1903 pdata->minlen = val;
1904
1905 if (pdata->maxbound && TREE_CODE (pdata->maxbound) == INTEGER_CST)
1906 {
1907 /* Adjust the tighter (more optimistic) string length bound
1908 if necessary and proceed to adjust the more conservative
1909 bound. */
1910 if (TREE_CODE (val) == INTEGER_CST)
1911 {
1912 if (tree_int_cst_lt (pdata->maxbound, val))
1913 pdata->maxbound = val;
1914 }
1915 else
1916 pdata->maxbound = val;
1917 }
1918 else if (pdata->maxbound || maxbound)
1919 /* Set PDATA->MAXBOUND only if it either isn't INTEGER_CST or
1920 if VAL corresponds to the maximum length determined based
1921 on the type of the object. */
1922 pdata->maxbound = val;
1923
1924 if (tight_bound)
1925 {
1926 /* VAL computed above represents an optimistically tight bound
1927 on the length of the string based on the referenced object's
1928 or subobject's type. Determine the conservative upper bound
1929 based on the enclosing object's size if possible. */
1930 if (rkind == SRK_LENRANGE)
1931 {
1932 poly_int64 offset;
1933 tree base = get_addr_base_and_unit_offset (arg, &offset);
1934 if (!base)
1935 {
1936 /* When the call above fails due to a non-constant offset
1937 assume the offset is zero and use the size of the whole
1938 enclosing object instead. */
1939 base = get_base_address (arg);
1940 offset = 0;
1941 }
1942 /* If the base object is a pointer no upper bound on the length
1943 can be determined. Otherwise the maximum length is equal to
1944 the size of the enclosing object minus the offset of
1945 the referenced subobject minus 1 (for the terminating nul). */
1946 tree type = TREE_TYPE (base);
1947 if (TREE_CODE (type) == POINTER_TYPE
1948 || (TREE_CODE (base) != PARM_DECL && !VAR_P (base))
1949 || !(val = DECL_SIZE_UNIT (base)))
1950 val = build_all_ones_cst (size_type_node);
1951 else
1952 {
1953 val = DECL_SIZE_UNIT (base);
1954 val = fold_build2 (MINUS_EXPR, TREE_TYPE (val), val,
1955 size_int (offset + 1));
1956 }
1957 }
1958 else
1959 return false;
1960 }
1961
1962 if (pdata->maxlen)
1963 {
1964 /* Adjust the more conservative bound if possible/necessary
1965 and fail otherwise. */
1966 if (rkind != SRK_STRLEN)
1967 {
1968 if (TREE_CODE (pdata->maxlen) != INTEGER_CST
1969 || TREE_CODE (val) != INTEGER_CST)
1970 return false;
1971
1972 if (tree_int_cst_lt (pdata->maxlen, val))
1973 pdata->maxlen = val;
1974 return true;
1975 }
1976 else if (simple_cst_equal (val, pdata->maxlen) != 1)
1977 {
1978 /* Fail if the length of this ARG is different from that
1979 previously determined from another ARG. */
1980 return false;
1981 }
1982 }
1983
1984 pdata->maxlen = val;
1985 return rkind == SRK_LENRANGE || !integer_all_onesp (val);
1986 }
1987
1988 /* For an ARG referencing one or more strings, try to obtain the range
1989 of their lengths, or the size of the largest array ARG referes to if
1990 the range of lengths cannot be determined, and store all in *PDATA.
1991 For an integer ARG (when RKIND == SRK_INT_VALUE), try to determine
1992 the maximum constant value.
1993 If ARG is an SSA_NAME, follow its use-def chains. When RKIND ==
1994 SRK_STRLEN, then if PDATA->MAXLEN is not equal to the determined
1995 length or if we are unable to determine the length, return false.
1996 VISITED is a bitmap of visited variables.
1997 RKIND determines the kind of value or range to obtain (see
1998 strlen_range_kind).
1999 Set PDATA->DECL if ARG refers to an unterminated constant array.
2000 On input, set ELTSIZE to 1 for normal single byte character strings,
2001 and either 2 or 4 for wide characer strings (the size of wchar_t).
2002 Return true if *PDATA was successfully populated and false otherwise. */
2003
2004 static bool
2005 get_range_strlen (tree arg, bitmap visited,
2006 strlen_range_kind rkind,
2007 c_strlen_data *pdata, unsigned eltsize)
2008 {
2009
2010 if (TREE_CODE (arg) != SSA_NAME)
2011 return get_range_strlen_tree (arg, visited, rkind, pdata, eltsize);
2012
2013 /* If ARG is registered for SSA update we cannot look at its defining
2014 statement. */
2015 if (name_registered_for_update_p (arg))
2016 return false;
2017
2018 /* If we were already here, break the infinite cycle. */
2019 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (arg)))
2020 return true;
2021
2022 tree var = arg;
2023 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
2024
2025 switch (gimple_code (def_stmt))
2026 {
2027 case GIMPLE_ASSIGN:
2028 /* The RHS of the statement defining VAR must either have a
2029 constant length or come from another SSA_NAME with a constant
2030 length. */
2031 if (gimple_assign_single_p (def_stmt)
2032 || gimple_assign_unary_nop_p (def_stmt))
2033 {
2034 tree rhs = gimple_assign_rhs1 (def_stmt);
2035 return get_range_strlen (rhs, visited, rkind, pdata, eltsize);
2036 }
2037 else if (gimple_assign_rhs_code (def_stmt) == COND_EXPR)
2038 {
2039 tree ops[2] = { gimple_assign_rhs2 (def_stmt),
2040 gimple_assign_rhs3 (def_stmt) };
2041
2042 for (unsigned int i = 0; i < 2; i++)
2043 if (!get_range_strlen (ops[i], visited, rkind, pdata, eltsize))
2044 {
2045 if (rkind != SRK_LENRANGE)
2046 return false;
2047 /* Set the upper bound to the maximum to prevent
2048 it from being adjusted in the next iteration but
2049 leave MINLEN and the more conservative MAXBOUND
2050 determined so far alone (or leave them null if
2051 they haven't been set yet). That the MINLEN is
2052 in fact zero can be determined from MAXLEN being
2053 unbounded but the discovered minimum is used for
2054 diagnostics. */
2055 pdata->maxlen = build_all_ones_cst (size_type_node);
2056 }
2057 return true;
2058 }
2059 return false;
2060
2061 case GIMPLE_PHI:
2062 /* Unless RKIND == SRK_LENRANGE, all arguments of the PHI node
2063 must have a constant length. */
2064 for (unsigned i = 0; i < gimple_phi_num_args (def_stmt); i++)
2065 {
2066 tree arg = gimple_phi_arg (def_stmt, i)->def;
2067
2068 /* If this PHI has itself as an argument, we cannot
2069 determine the string length of this argument. However,
2070 if we can find a constant string length for the other
2071 PHI args then we can still be sure that this is a
2072 constant string length. So be optimistic and just
2073 continue with the next argument. */
2074 if (arg == gimple_phi_result (def_stmt))
2075 continue;
2076
2077 if (!get_range_strlen (arg, visited, rkind, pdata, eltsize))
2078 {
2079 if (rkind != SRK_LENRANGE)
2080 return false;
2081 /* Set the upper bound to the maximum to prevent
2082 it from being adjusted in the next iteration but
2083 leave MINLEN and the more conservative MAXBOUND
2084 determined so far alone (or leave them null if
2085 they haven't been set yet). That the MINLEN is
2086 in fact zero can be determined from MAXLEN being
2087 unbounded but the discovered minimum is used for
2088 diagnostics. */
2089 pdata->maxlen = build_all_ones_cst (size_type_node);
2090 }
2091 }
2092 return true;
2093
2094 default:
2095 return false;
2096 }
2097 }
2098
2099 /* Try to obtain the range of the lengths of the string(s) referenced
2100 by ARG, or the size of the largest array ARG refers to if the range
2101 of lengths cannot be determined, and store all in *PDATA which must
2102 be zero-initialized on input except PDATA->MAXBOUND may be set to
2103 a non-null tree node other than INTEGER_CST to request to have it
2104 set to the length of the longest string in a PHI. ELTSIZE is
2105 the expected size of the string element in bytes: 1 for char and
2106 some power of 2 for wide characters.
2107 Return true if the range [PDATA->MINLEN, PDATA->MAXLEN] is suitable
2108 for optimization. Returning false means that a nonzero PDATA->MINLEN
2109 doesn't reflect the true lower bound of the range when PDATA->MAXLEN
2110 is -1 (in that case, the actual range is indeterminate, i.e.,
2111 [0, PTRDIFF_MAX - 2]. */
2112
2113 bool
2114 get_range_strlen (tree arg, c_strlen_data *pdata, unsigned eltsize)
2115 {
2116 auto_bitmap visited;
2117 tree maxbound = pdata->maxbound;
2118
2119 if (!get_range_strlen (arg, visited, SRK_LENRANGE, pdata, eltsize))
2120 {
2121 /* On failure extend the length range to an impossible maximum
2122 (a valid MAXLEN must be less than PTRDIFF_MAX - 1). Other
2123 members can stay unchanged regardless. */
2124 pdata->minlen = ssize_int (0);
2125 pdata->maxlen = build_all_ones_cst (size_type_node);
2126 }
2127 else if (!pdata->minlen)
2128 pdata->minlen = ssize_int (0);
2129
2130 /* If it's unchanged from it initial non-null value, set the conservative
2131 MAXBOUND to SIZE_MAX. Otherwise leave it null (if it is null). */
2132 if (maxbound && pdata->maxbound == maxbound)
2133 pdata->maxbound = build_all_ones_cst (size_type_node);
2134
2135 return !integer_all_onesp (pdata->maxlen);
2136 }
2137
2138 /* Return the maximum value for ARG given RKIND (see strlen_range_kind).
2139 For ARG of pointer types, NONSTR indicates if the caller is prepared
2140 to handle unterminated strings. For integer ARG and when RKIND ==
2141 SRK_INT_VALUE, NONSTR must be null.
2142
2143 If an unterminated array is discovered and our caller handles
2144 unterminated arrays, then bubble up the offending DECL and
2145 return the maximum size. Otherwise return NULL. */
2146
2147 static tree
2148 get_maxval_strlen (tree arg, strlen_range_kind rkind, tree *nonstr = NULL)
2149 {
2150 /* A non-null NONSTR is meaningless when determining the maximum
2151 value of an integer ARG. */
2152 gcc_assert (rkind != SRK_INT_VALUE || nonstr == NULL);
2153 /* ARG must have an integral type when RKIND says so. */
2154 gcc_assert (rkind != SRK_INT_VALUE || INTEGRAL_TYPE_P (TREE_TYPE (arg)));
2155
2156 auto_bitmap visited;
2157
2158 /* Reset DATA.MAXLEN if the call fails or when DATA.MAXLEN
2159 is unbounded. */
2160 c_strlen_data lendata = { };
2161 if (!get_range_strlen (arg, visited, rkind, &lendata, /* eltsize = */1))
2162 lendata.maxlen = NULL_TREE;
2163 else if (lendata.maxlen && integer_all_onesp (lendata.maxlen))
2164 lendata.maxlen = NULL_TREE;
2165
2166 if (nonstr)
2167 {
2168 /* For callers prepared to handle unterminated arrays set
2169 *NONSTR to point to the declaration of the array and return
2170 the maximum length/size. */
2171 *nonstr = lendata.decl;
2172 return lendata.maxlen;
2173 }
2174
2175 /* Fail if the constant array isn't nul-terminated. */
2176 return lendata.decl ? NULL_TREE : lendata.maxlen;
2177 }
2178
2179 /* Return true if LEN is known to be less than or equal to (or if STRICT is
2180 true, strictly less than) the lower bound of SIZE at compile time and false
2181 otherwise. */
2182
2183 static bool
2184 known_lower (gimple *stmt, tree len, tree size, bool strict = false)
2185 {
2186 if (len == NULL_TREE)
2187 return false;
2188
2189 wide_int size_range[2];
2190 wide_int len_range[2];
2191 if (get_range (len, stmt, len_range) && get_range (size, stmt, size_range))
2192 {
2193 if (strict)
2194 return wi::ltu_p (len_range[1], size_range[0]);
2195 else
2196 return wi::leu_p (len_range[1], size_range[0]);
2197 }
2198
2199 return false;
2200 }
2201
2202 /* Fold function call to builtin strcpy with arguments DEST and SRC.
2203 If LEN is not NULL, it represents the length of the string to be
2204 copied. Return NULL_TREE if no simplification can be made. */
2205
2206 static bool
2207 gimple_fold_builtin_strcpy (gimple_stmt_iterator *gsi,
2208 tree dest, tree src)
2209 {
2210 gimple *stmt = gsi_stmt (*gsi);
2211 location_t loc = gimple_location (stmt);
2212 tree fn;
2213
2214 /* If SRC and DEST are the same (and not volatile), return DEST. */
2215 if (operand_equal_p (src, dest, 0))
2216 {
2217 /* Issue -Wrestrict unless the pointers are null (those do
2218 not point to objects and so do not indicate an overlap;
2219 such calls could be the result of sanitization and jump
2220 threading). */
2221 if (!integer_zerop (dest) && !warning_suppressed_p (stmt, OPT_Wrestrict))
2222 {
2223 tree func = gimple_call_fndecl (stmt);
2224
2225 warning_at (loc, OPT_Wrestrict,
2226 "%qD source argument is the same as destination",
2227 func);
2228 }
2229
2230 replace_call_with_value (gsi, dest);
2231 return true;
2232 }
2233
2234 if (optimize_function_for_size_p (cfun))
2235 return false;
2236
2237 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2238 if (!fn)
2239 return false;
2240
2241 /* Set to non-null if ARG refers to an unterminated array. */
2242 tree nonstr = NULL;
2243 tree len = get_maxval_strlen (src, SRK_STRLEN, &nonstr);
2244
2245 if (nonstr)
2246 {
2247 /* Avoid folding calls with unterminated arrays. */
2248 if (!warning_suppressed_p (stmt, OPT_Wstringop_overread))
2249 warn_string_no_nul (loc, stmt, "strcpy", src, nonstr);
2250 suppress_warning (stmt, OPT_Wstringop_overread);
2251 return false;
2252 }
2253
2254 if (!len || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
2255 return false;
2256
2257 len = fold_convert_loc (loc, size_type_node, len);
2258 len = size_binop_loc (loc, PLUS_EXPR, len, build_int_cst (size_type_node, 1));
2259 len = force_gimple_operand_gsi (gsi, len, true,
2260 NULL_TREE, true, GSI_SAME_STMT);
2261 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2262 replace_call_with_call_and_fold (gsi, repl);
2263 return true;
2264 }
2265
2266 /* Fold function call to builtin strncpy with arguments DEST, SRC, and LEN.
2267 If SLEN is not NULL, it represents the length of the source string.
2268 Return NULL_TREE if no simplification can be made. */
2269
2270 static bool
2271 gimple_fold_builtin_strncpy (gimple_stmt_iterator *gsi,
2272 tree dest, tree src, tree len)
2273 {
2274 gimple *stmt = gsi_stmt (*gsi);
2275 location_t loc = gimple_location (stmt);
2276 bool nonstring = get_attr_nonstring_decl (dest) != NULL_TREE;
2277
2278 /* If the LEN parameter is zero, return DEST. */
2279 if (integer_zerop (len))
2280 {
2281 /* Avoid warning if the destination refers to an array/pointer
2282 decorate with attribute nonstring. */
2283 if (!nonstring)
2284 {
2285 tree fndecl = gimple_call_fndecl (stmt);
2286
2287 /* Warn about the lack of nul termination: the result is not
2288 a (nul-terminated) string. */
2289 tree slen = get_maxval_strlen (src, SRK_STRLEN);
2290 if (slen && !integer_zerop (slen))
2291 warning_at (loc, OPT_Wstringop_truncation,
2292 "%qD destination unchanged after copying no bytes "
2293 "from a string of length %E",
2294 fndecl, slen);
2295 else
2296 warning_at (loc, OPT_Wstringop_truncation,
2297 "%qD destination unchanged after copying no bytes",
2298 fndecl);
2299 }
2300
2301 replace_call_with_value (gsi, dest);
2302 return true;
2303 }
2304
2305 /* We can't compare slen with len as constants below if len is not a
2306 constant. */
2307 if (TREE_CODE (len) != INTEGER_CST)
2308 return false;
2309
2310 /* Now, we must be passed a constant src ptr parameter. */
2311 tree slen = get_maxval_strlen (src, SRK_STRLEN);
2312 if (!slen || TREE_CODE (slen) != INTEGER_CST)
2313 return false;
2314
2315 /* The size of the source string including the terminating nul. */
2316 tree ssize = size_binop_loc (loc, PLUS_EXPR, slen, ssize_int (1));
2317
2318 /* We do not support simplification of this case, though we do
2319 support it when expanding trees into RTL. */
2320 /* FIXME: generate a call to __builtin_memset. */
2321 if (tree_int_cst_lt (ssize, len))
2322 return false;
2323
2324 /* Diagnose truncation that leaves the copy unterminated. */
2325 maybe_diag_stxncpy_trunc (*gsi, src, len);
2326
2327 /* OK transform into builtin memcpy. */
2328 tree fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2329 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
2330 return false;
2331
2332 len = fold_convert_loc (loc, size_type_node, len);
2333 len = force_gimple_operand_gsi (gsi, len, true,
2334 NULL_TREE, true, GSI_SAME_STMT);
2335 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2336 replace_call_with_call_and_fold (gsi, repl);
2337
2338 return true;
2339 }
2340
2341 /* Fold function call to builtin strchr or strrchr.
2342 If both arguments are constant, evaluate and fold the result,
2343 otherwise simplify str(r)chr (str, 0) into str + strlen (str).
2344 In general strlen is significantly faster than strchr
2345 due to being a simpler operation. */
2346 static bool
2347 gimple_fold_builtin_strchr (gimple_stmt_iterator *gsi, bool is_strrchr)
2348 {
2349 gimple *stmt = gsi_stmt (*gsi);
2350 tree str = gimple_call_arg (stmt, 0);
2351 tree c = gimple_call_arg (stmt, 1);
2352 location_t loc = gimple_location (stmt);
2353 const char *p;
2354 char ch;
2355
2356 if (!gimple_call_lhs (stmt))
2357 return false;
2358
2359 /* Avoid folding if the first argument is not a nul-terminated array.
2360 Defer warning until later. */
2361 if (!check_nul_terminated_array (NULL_TREE, str))
2362 return false;
2363
2364 if ((p = c_getstr (str)) && target_char_cst_p (c, &ch))
2365 {
2366 const char *p1 = is_strrchr ? strrchr (p, ch) : strchr (p, ch);
2367
2368 if (p1 == NULL)
2369 {
2370 replace_call_with_value (gsi, integer_zero_node);
2371 return true;
2372 }
2373
2374 tree len = build_int_cst (size_type_node, p1 - p);
2375 gimple_seq stmts = NULL;
2376 gimple *new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
2377 POINTER_PLUS_EXPR, str, len);
2378 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2379 gsi_replace_with_seq_vops (gsi, stmts);
2380 return true;
2381 }
2382
2383 if (!integer_zerop (c) || (!gimple_vuse (stmt) && gimple_in_ssa_p (cfun)))
2384 return false;
2385
2386 /* Transform strrchr (s, 0) to strchr (s, 0) when optimizing for size. */
2387 if (is_strrchr && optimize_function_for_size_p (cfun))
2388 {
2389 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
2390
2391 if (strchr_fn)
2392 {
2393 gimple *repl = gimple_build_call (strchr_fn, 2, str, c);
2394 replace_call_with_call_and_fold (gsi, repl);
2395 return true;
2396 }
2397
2398 return false;
2399 }
2400
2401 tree len;
2402 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
2403
2404 if (!strlen_fn)
2405 return false;
2406
2407 /* Create newstr = strlen (str). */
2408 gimple_seq stmts = NULL;
2409 gimple *new_stmt = gimple_build_call (strlen_fn, 1, str);
2410 gimple_set_location (new_stmt, loc);
2411 len = create_tmp_reg_or_ssa_name (size_type_node);
2412 gimple_call_set_lhs (new_stmt, len);
2413 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2414
2415 /* Create (str p+ strlen (str)). */
2416 new_stmt = gimple_build_assign (gimple_call_lhs (stmt),
2417 POINTER_PLUS_EXPR, str, len);
2418 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2419 gsi_replace_with_seq_vops (gsi, stmts);
2420 /* gsi now points at the assignment to the lhs, get a
2421 stmt iterator to the strlen.
2422 ??? We can't use gsi_for_stmt as that doesn't work when the
2423 CFG isn't built yet. */
2424 gimple_stmt_iterator gsi2 = *gsi;
2425 gsi_prev (&gsi2);
2426 fold_stmt (&gsi2);
2427 return true;
2428 }
2429
2430 /* Fold function call to builtin strstr.
2431 If both arguments are constant, evaluate and fold the result,
2432 additionally fold strstr (x, "") into x and strstr (x, "c")
2433 into strchr (x, 'c'). */
2434 static bool
2435 gimple_fold_builtin_strstr (gimple_stmt_iterator *gsi)
2436 {
2437 gimple *stmt = gsi_stmt (*gsi);
2438 if (!gimple_call_lhs (stmt))
2439 return false;
2440
2441 tree haystack = gimple_call_arg (stmt, 0);
2442 tree needle = gimple_call_arg (stmt, 1);
2443
2444 /* Avoid folding if either argument is not a nul-terminated array.
2445 Defer warning until later. */
2446 if (!check_nul_terminated_array (NULL_TREE, haystack)
2447 || !check_nul_terminated_array (NULL_TREE, needle))
2448 return false;
2449
2450 const char *q = c_getstr (needle);
2451 if (q == NULL)
2452 return false;
2453
2454 if (const char *p = c_getstr (haystack))
2455 {
2456 const char *r = strstr (p, q);
2457
2458 if (r == NULL)
2459 {
2460 replace_call_with_value (gsi, integer_zero_node);
2461 return true;
2462 }
2463
2464 tree len = build_int_cst (size_type_node, r - p);
2465 gimple_seq stmts = NULL;
2466 gimple *new_stmt
2467 = gimple_build_assign (gimple_call_lhs (stmt), POINTER_PLUS_EXPR,
2468 haystack, len);
2469 gimple_seq_add_stmt_without_update (&stmts, new_stmt);
2470 gsi_replace_with_seq_vops (gsi, stmts);
2471 return true;
2472 }
2473
2474 /* For strstr (x, "") return x. */
2475 if (q[0] == '\0')
2476 {
2477 replace_call_with_value (gsi, haystack);
2478 return true;
2479 }
2480
2481 if (!gimple_vuse (stmt) && gimple_in_ssa_p (cfun))
2482 return false;
2483
2484 /* Transform strstr (x, "c") into strchr (x, 'c'). */
2485 if (q[1] == '\0')
2486 {
2487 tree strchr_fn = builtin_decl_implicit (BUILT_IN_STRCHR);
2488 if (strchr_fn)
2489 {
2490 tree c = build_int_cst (integer_type_node, q[0]);
2491 gimple *repl = gimple_build_call (strchr_fn, 2, haystack, c);
2492 replace_call_with_call_and_fold (gsi, repl);
2493 return true;
2494 }
2495 }
2496
2497 return false;
2498 }
2499
2500 /* Simplify a call to the strcat builtin. DST and SRC are the arguments
2501 to the call.
2502
2503 Return NULL_TREE if no simplification was possible, otherwise return the
2504 simplified form of the call as a tree.
2505
2506 The simplified form may be a constant or other expression which
2507 computes the same value, but in a more efficient manner (including
2508 calls to other builtin functions).
2509
2510 The call may contain arguments which need to be evaluated, but
2511 which are not useful to determine the result of the call. In
2512 this case we return a chain of COMPOUND_EXPRs. The LHS of each
2513 COMPOUND_EXPR will be an argument which must be evaluated.
2514 COMPOUND_EXPRs are chained through their RHS. The RHS of the last
2515 COMPOUND_EXPR in the chain will contain the tree for the simplified
2516 form of the builtin function call. */
2517
2518 static bool
2519 gimple_fold_builtin_strcat (gimple_stmt_iterator *gsi, tree dst, tree src)
2520 {
2521 gimple *stmt = gsi_stmt (*gsi);
2522 location_t loc = gimple_location (stmt);
2523
2524 const char *p = c_getstr (src);
2525
2526 /* If the string length is zero, return the dst parameter. */
2527 if (p && *p == '\0')
2528 {
2529 replace_call_with_value (gsi, dst);
2530 return true;
2531 }
2532
2533 if (!optimize_bb_for_speed_p (gimple_bb (stmt)))
2534 return false;
2535
2536 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
2537 return false;
2538
2539 /* See if we can store by pieces into (dst + strlen(dst)). */
2540 tree newdst;
2541 tree strlen_fn = builtin_decl_implicit (BUILT_IN_STRLEN);
2542 tree memcpy_fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2543
2544 if (!strlen_fn || !memcpy_fn)
2545 return false;
2546
2547 /* If the length of the source string isn't computable don't
2548 split strcat into strlen and memcpy. */
2549 tree len = get_maxval_strlen (src, SRK_STRLEN);
2550 if (! len)
2551 return false;
2552
2553 /* Create strlen (dst). */
2554 gimple_seq stmts = NULL, stmts2;
2555 gimple *repl = gimple_build_call (strlen_fn, 1, dst);
2556 gimple_set_location (repl, loc);
2557 newdst = create_tmp_reg_or_ssa_name (size_type_node);
2558 gimple_call_set_lhs (repl, newdst);
2559 gimple_seq_add_stmt_without_update (&stmts, repl);
2560
2561 /* Create (dst p+ strlen (dst)). */
2562 newdst = fold_build_pointer_plus_loc (loc, dst, newdst);
2563 newdst = force_gimple_operand (newdst, &stmts2, true, NULL_TREE);
2564 gimple_seq_add_seq_without_update (&stmts, stmts2);
2565
2566 len = fold_convert_loc (loc, size_type_node, len);
2567 len = size_binop_loc (loc, PLUS_EXPR, len,
2568 build_int_cst (size_type_node, 1));
2569 len = force_gimple_operand (len, &stmts2, true, NULL_TREE);
2570 gimple_seq_add_seq_without_update (&stmts, stmts2);
2571
2572 repl = gimple_build_call (memcpy_fn, 3, newdst, src, len);
2573 gimple_seq_add_stmt_without_update (&stmts, repl);
2574 if (gimple_call_lhs (stmt))
2575 {
2576 repl = gimple_build_assign (gimple_call_lhs (stmt), dst);
2577 gimple_seq_add_stmt_without_update (&stmts, repl);
2578 gsi_replace_with_seq_vops (gsi, stmts);
2579 /* gsi now points at the assignment to the lhs, get a
2580 stmt iterator to the memcpy call.
2581 ??? We can't use gsi_for_stmt as that doesn't work when the
2582 CFG isn't built yet. */
2583 gimple_stmt_iterator gsi2 = *gsi;
2584 gsi_prev (&gsi2);
2585 fold_stmt (&gsi2);
2586 }
2587 else
2588 {
2589 gsi_replace_with_seq_vops (gsi, stmts);
2590 fold_stmt (gsi);
2591 }
2592 return true;
2593 }
2594
2595 /* Fold a call to the __strcat_chk builtin FNDECL. DEST, SRC, and SIZE
2596 are the arguments to the call. */
2597
2598 static bool
2599 gimple_fold_builtin_strcat_chk (gimple_stmt_iterator *gsi)
2600 {
2601 gimple *stmt = gsi_stmt (*gsi);
2602 tree dest = gimple_call_arg (stmt, 0);
2603 tree src = gimple_call_arg (stmt, 1);
2604 tree size = gimple_call_arg (stmt, 2);
2605 tree fn;
2606 const char *p;
2607
2608 p = c_getstr (src);
2609 /* If the SRC parameter is "", return DEST. */
2610 if (p && *p == '\0')
2611 {
2612 replace_call_with_value (gsi, dest);
2613 return true;
2614 }
2615
2616 if (! tree_fits_uhwi_p (size) || ! integer_all_onesp (size))
2617 return false;
2618
2619 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
2620 return false;
2621
2622 /* If __builtin_strcat_chk is used, assume strcat is available. */
2623 fn = builtin_decl_explicit (BUILT_IN_STRCAT);
2624 if (!fn)
2625 return false;
2626
2627 gimple *repl = gimple_build_call (fn, 2, dest, src);
2628 replace_call_with_call_and_fold (gsi, repl);
2629 return true;
2630 }
2631
2632 /* Simplify a call to the strncat builtin. */
2633
2634 static bool
2635 gimple_fold_builtin_strncat (gimple_stmt_iterator *gsi)
2636 {
2637 gimple *stmt = gsi_stmt (*gsi);
2638 tree dst = gimple_call_arg (stmt, 0);
2639 tree src = gimple_call_arg (stmt, 1);
2640 tree len = gimple_call_arg (stmt, 2);
2641 tree src_len = c_strlen (src, 1);
2642
2643 /* If the requested length is zero, or the src parameter string
2644 length is zero, return the dst parameter. */
2645 if (integer_zerop (len) || (src_len && integer_zerop (src_len)))
2646 {
2647 replace_call_with_value (gsi, dst);
2648 return true;
2649 }
2650
2651 /* Return early if the requested len is less than the string length.
2652 Warnings will be issued elsewhere later. */
2653 if (!src_len || known_lower (stmt, len, src_len, true))
2654 return false;
2655
2656 /* Warn on constant LEN. */
2657 if (TREE_CODE (len) == INTEGER_CST)
2658 {
2659 bool nowarn = warning_suppressed_p (stmt, OPT_Wstringop_overflow_);
2660 tree dstsize;
2661
2662 if (!nowarn && compute_builtin_object_size (dst, 1, &dstsize)
2663 && TREE_CODE (dstsize) == INTEGER_CST)
2664 {
2665 int cmpdst = tree_int_cst_compare (len, dstsize);
2666
2667 if (cmpdst >= 0)
2668 {
2669 tree fndecl = gimple_call_fndecl (stmt);
2670
2671 /* Strncat copies (at most) LEN bytes and always appends
2672 the terminating NUL so the specified bound should never
2673 be equal to (or greater than) the size of the destination.
2674 If it is, the copy could overflow. */
2675 location_t loc = gimple_location (stmt);
2676 nowarn = warning_at (loc, OPT_Wstringop_overflow_,
2677 cmpdst == 0
2678 ? G_("%qD specified bound %E equals "
2679 "destination size")
2680 : G_("%qD specified bound %E exceeds "
2681 "destination size %E"),
2682 fndecl, len, dstsize);
2683 if (nowarn)
2684 suppress_warning (stmt, OPT_Wstringop_overflow_);
2685 }
2686 }
2687
2688 if (!nowarn && TREE_CODE (src_len) == INTEGER_CST
2689 && tree_int_cst_compare (src_len, len) == 0)
2690 {
2691 tree fndecl = gimple_call_fndecl (stmt);
2692 location_t loc = gimple_location (stmt);
2693
2694 /* To avoid possible overflow the specified bound should also
2695 not be equal to the length of the source, even when the size
2696 of the destination is unknown (it's not an uncommon mistake
2697 to specify as the bound to strncpy the length of the source). */
2698 if (warning_at (loc, OPT_Wstringop_overflow_,
2699 "%qD specified bound %E equals source length",
2700 fndecl, len))
2701 suppress_warning (stmt, OPT_Wstringop_overflow_);
2702 }
2703 }
2704
2705 if (!known_lower (stmt, src_len, len))
2706 return false;
2707
2708 tree fn = builtin_decl_implicit (BUILT_IN_STRCAT);
2709
2710 /* If the replacement _DECL isn't initialized, don't do the
2711 transformation. */
2712 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
2713 return false;
2714
2715 /* Otherwise, emit a call to strcat. */
2716 gcall *repl = gimple_build_call (fn, 2, dst, src);
2717 replace_call_with_call_and_fold (gsi, repl);
2718 return true;
2719 }
2720
2721 /* Fold a call to the __strncat_chk builtin with arguments DEST, SRC,
2722 LEN, and SIZE. */
2723
2724 static bool
2725 gimple_fold_builtin_strncat_chk (gimple_stmt_iterator *gsi)
2726 {
2727 gimple *stmt = gsi_stmt (*gsi);
2728 tree dest = gimple_call_arg (stmt, 0);
2729 tree src = gimple_call_arg (stmt, 1);
2730 tree len = gimple_call_arg (stmt, 2);
2731 tree size = gimple_call_arg (stmt, 3);
2732 tree fn;
2733 const char *p;
2734
2735 p = c_getstr (src);
2736 /* If the SRC parameter is "" or if LEN is 0, return DEST. */
2737 if ((p && *p == '\0')
2738 || integer_zerop (len))
2739 {
2740 replace_call_with_value (gsi, dest);
2741 return true;
2742 }
2743
2744 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
2745 return false;
2746
2747 if (! integer_all_onesp (size))
2748 {
2749 tree src_len = c_strlen (src, 1);
2750 if (known_lower (stmt, src_len, len))
2751 {
2752 /* If LEN >= strlen (SRC), optimize into __strcat_chk. */
2753 fn = builtin_decl_explicit (BUILT_IN_STRCAT_CHK);
2754 if (!fn)
2755 return false;
2756
2757 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
2758 replace_call_with_call_and_fold (gsi, repl);
2759 return true;
2760 }
2761 return false;
2762 }
2763
2764 /* If __builtin_strncat_chk is used, assume strncat is available. */
2765 fn = builtin_decl_explicit (BUILT_IN_STRNCAT);
2766 if (!fn)
2767 return false;
2768
2769 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
2770 replace_call_with_call_and_fold (gsi, repl);
2771 return true;
2772 }
2773
2774 /* Build and append gimple statements to STMTS that would load a first
2775 character of a memory location identified by STR. LOC is location
2776 of the statement. */
2777
2778 static tree
2779 gimple_load_first_char (location_t loc, tree str, gimple_seq *stmts)
2780 {
2781 tree var;
2782
2783 tree cst_uchar_node = build_type_variant (unsigned_char_type_node, 1, 0);
2784 tree cst_uchar_ptr_node
2785 = build_pointer_type_for_mode (cst_uchar_node, ptr_mode, true);
2786 tree off0 = build_int_cst (cst_uchar_ptr_node, 0);
2787
2788 tree temp = fold_build2_loc (loc, MEM_REF, cst_uchar_node, str, off0);
2789 gassign *stmt = gimple_build_assign (NULL_TREE, temp);
2790 var = create_tmp_reg_or_ssa_name (cst_uchar_node, stmt);
2791
2792 gimple_assign_set_lhs (stmt, var);
2793 gimple_seq_add_stmt_without_update (stmts, stmt);
2794
2795 return var;
2796 }
2797
2798 /* Fold a call to the str{n}{case}cmp builtin pointed by GSI iterator. */
2799
2800 static bool
2801 gimple_fold_builtin_string_compare (gimple_stmt_iterator *gsi)
2802 {
2803 gimple *stmt = gsi_stmt (*gsi);
2804 tree callee = gimple_call_fndecl (stmt);
2805 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
2806
2807 tree type = integer_type_node;
2808 tree str1 = gimple_call_arg (stmt, 0);
2809 tree str2 = gimple_call_arg (stmt, 1);
2810 tree lhs = gimple_call_lhs (stmt);
2811
2812 tree bound_node = NULL_TREE;
2813 unsigned HOST_WIDE_INT bound = HOST_WIDE_INT_M1U;
2814
2815 /* Handle strncmp and strncasecmp functions. */
2816 if (gimple_call_num_args (stmt) == 3)
2817 {
2818 bound_node = gimple_call_arg (stmt, 2);
2819 if (tree_fits_uhwi_p (bound_node))
2820 bound = tree_to_uhwi (bound_node);
2821 }
2822
2823 /* If the BOUND parameter is zero, return zero. */
2824 if (bound == 0)
2825 {
2826 replace_call_with_value (gsi, integer_zero_node);
2827 return true;
2828 }
2829
2830 /* If ARG1 and ARG2 are the same (and not volatile), return zero. */
2831 if (operand_equal_p (str1, str2, 0))
2832 {
2833 replace_call_with_value (gsi, integer_zero_node);
2834 return true;
2835 }
2836
2837 if (!gimple_vuse (stmt) && gimple_in_ssa_p (cfun))
2838 return false;
2839
2840 /* Initially set to the number of characters, including the terminating
2841 nul if each array has one. LENx == strnlen (Sx, LENx) implies that
2842 the array Sx is not terminated by a nul.
2843 For nul-terminated strings then adjusted to their length so that
2844 LENx == NULPOSx holds. */
2845 unsigned HOST_WIDE_INT len1 = HOST_WIDE_INT_MAX, len2 = len1;
2846 const char *p1 = getbyterep (str1, &len1);
2847 const char *p2 = getbyterep (str2, &len2);
2848
2849 /* The position of the terminating nul character if one exists, otherwise
2850 a value greater than LENx. */
2851 unsigned HOST_WIDE_INT nulpos1 = HOST_WIDE_INT_MAX, nulpos2 = nulpos1;
2852
2853 if (p1)
2854 {
2855 size_t n = strnlen (p1, len1);
2856 if (n < len1)
2857 len1 = nulpos1 = n;
2858 }
2859
2860 if (p2)
2861 {
2862 size_t n = strnlen (p2, len2);
2863 if (n < len2)
2864 len2 = nulpos2 = n;
2865 }
2866
2867 /* For known strings, return an immediate value. */
2868 if (p1 && p2)
2869 {
2870 int r = 0;
2871 bool known_result = false;
2872
2873 switch (fcode)
2874 {
2875 case BUILT_IN_STRCMP:
2876 case BUILT_IN_STRCMP_EQ:
2877 if (len1 != nulpos1 || len2 != nulpos2)
2878 break;
2879
2880 r = strcmp (p1, p2);
2881 known_result = true;
2882 break;
2883
2884 case BUILT_IN_STRNCMP:
2885 case BUILT_IN_STRNCMP_EQ:
2886 {
2887 if (bound == HOST_WIDE_INT_M1U)
2888 break;
2889
2890 /* Reduce the bound to be no more than the length
2891 of the shorter of the two strings, or the sizes
2892 of the unterminated arrays. */
2893 unsigned HOST_WIDE_INT n = bound;
2894
2895 if (len1 == nulpos1 && len1 < n)
2896 n = len1 + 1;
2897 if (len2 == nulpos2 && len2 < n)
2898 n = len2 + 1;
2899
2900 if (MIN (nulpos1, nulpos2) + 1 < n)
2901 break;
2902
2903 r = strncmp (p1, p2, n);
2904 known_result = true;
2905 break;
2906 }
2907 /* Only handleable situation is where the string are equal (result 0),
2908 which is already handled by operand_equal_p case. */
2909 case BUILT_IN_STRCASECMP:
2910 break;
2911 case BUILT_IN_STRNCASECMP:
2912 {
2913 if (bound == HOST_WIDE_INT_M1U)
2914 break;
2915 r = strncmp (p1, p2, bound);
2916 if (r == 0)
2917 known_result = true;
2918 break;
2919 }
2920 default:
2921 gcc_unreachable ();
2922 }
2923
2924 if (known_result)
2925 {
2926 replace_call_with_value (gsi, build_cmp_result (type, r));
2927 return true;
2928 }
2929 }
2930
2931 bool nonzero_bound = (bound >= 1 && bound < HOST_WIDE_INT_M1U)
2932 || fcode == BUILT_IN_STRCMP
2933 || fcode == BUILT_IN_STRCMP_EQ
2934 || fcode == BUILT_IN_STRCASECMP;
2935
2936 location_t loc = gimple_location (stmt);
2937
2938 /* If the second arg is "", return *(const unsigned char*)arg1. */
2939 if (p2 && *p2 == '\0' && nonzero_bound)
2940 {
2941 gimple_seq stmts = NULL;
2942 tree var = gimple_load_first_char (loc, str1, &stmts);
2943 if (lhs)
2944 {
2945 stmt = gimple_build_assign (lhs, NOP_EXPR, var);
2946 gimple_seq_add_stmt_without_update (&stmts, stmt);
2947 }
2948
2949 gsi_replace_with_seq_vops (gsi, stmts);
2950 return true;
2951 }
2952
2953 /* If the first arg is "", return -*(const unsigned char*)arg2. */
2954 if (p1 && *p1 == '\0' && nonzero_bound)
2955 {
2956 gimple_seq stmts = NULL;
2957 tree var = gimple_load_first_char (loc, str2, &stmts);
2958
2959 if (lhs)
2960 {
2961 tree c = create_tmp_reg_or_ssa_name (integer_type_node);
2962 stmt = gimple_build_assign (c, NOP_EXPR, var);
2963 gimple_seq_add_stmt_without_update (&stmts, stmt);
2964
2965 stmt = gimple_build_assign (lhs, NEGATE_EXPR, c);
2966 gimple_seq_add_stmt_without_update (&stmts, stmt);
2967 }
2968
2969 gsi_replace_with_seq_vops (gsi, stmts);
2970 return true;
2971 }
2972
2973 /* If BOUND is one, return an expression corresponding to
2974 (*(const unsigned char*)arg2 - *(const unsigned char*)arg1). */
2975 if (fcode == BUILT_IN_STRNCMP && bound == 1)
2976 {
2977 gimple_seq stmts = NULL;
2978 tree temp1 = gimple_load_first_char (loc, str1, &stmts);
2979 tree temp2 = gimple_load_first_char (loc, str2, &stmts);
2980
2981 if (lhs)
2982 {
2983 tree c1 = create_tmp_reg_or_ssa_name (integer_type_node);
2984 gassign *convert1 = gimple_build_assign (c1, NOP_EXPR, temp1);
2985 gimple_seq_add_stmt_without_update (&stmts, convert1);
2986
2987 tree c2 = create_tmp_reg_or_ssa_name (integer_type_node);
2988 gassign *convert2 = gimple_build_assign (c2, NOP_EXPR, temp2);
2989 gimple_seq_add_stmt_without_update (&stmts, convert2);
2990
2991 stmt = gimple_build_assign (lhs, MINUS_EXPR, c1, c2);
2992 gimple_seq_add_stmt_without_update (&stmts, stmt);
2993 }
2994
2995 gsi_replace_with_seq_vops (gsi, stmts);
2996 return true;
2997 }
2998
2999 /* If BOUND is greater than the length of one constant string,
3000 and the other argument is also a nul-terminated string, replace
3001 strncmp with strcmp. */
3002 if (fcode == BUILT_IN_STRNCMP
3003 && bound > 0 && bound < HOST_WIDE_INT_M1U
3004 && ((p2 && len2 < bound && len2 == nulpos2)
3005 || (p1 && len1 < bound && len1 == nulpos1)))
3006 {
3007 tree fn = builtin_decl_implicit (BUILT_IN_STRCMP);
3008 if (!fn)
3009 return false;
3010 gimple *repl = gimple_build_call (fn, 2, str1, str2);
3011 replace_call_with_call_and_fold (gsi, repl);
3012 return true;
3013 }
3014
3015 return false;
3016 }
3017
3018 /* Fold a call to the memchr pointed by GSI iterator. */
3019
3020 static bool
3021 gimple_fold_builtin_memchr (gimple_stmt_iterator *gsi)
3022 {
3023 gimple *stmt = gsi_stmt (*gsi);
3024 tree lhs = gimple_call_lhs (stmt);
3025 tree arg1 = gimple_call_arg (stmt, 0);
3026 tree arg2 = gimple_call_arg (stmt, 1);
3027 tree len = gimple_call_arg (stmt, 2);
3028
3029 /* If the LEN parameter is zero, return zero. */
3030 if (integer_zerop (len))
3031 {
3032 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
3033 return true;
3034 }
3035
3036 char c;
3037 if (TREE_CODE (arg2) != INTEGER_CST
3038 || !tree_fits_uhwi_p (len)
3039 || !target_char_cst_p (arg2, &c))
3040 return false;
3041
3042 unsigned HOST_WIDE_INT length = tree_to_uhwi (len);
3043 unsigned HOST_WIDE_INT string_length;
3044 const char *p1 = getbyterep (arg1, &string_length);
3045
3046 if (p1)
3047 {
3048 const char *r = (const char *)memchr (p1, c, MIN (length, string_length));
3049 if (r == NULL)
3050 {
3051 tree mem_size, offset_node;
3052 byte_representation (arg1, &offset_node, &mem_size, NULL);
3053 unsigned HOST_WIDE_INT offset = (offset_node == NULL_TREE)
3054 ? 0 : tree_to_uhwi (offset_node);
3055 /* MEM_SIZE is the size of the array the string literal
3056 is stored in. */
3057 unsigned HOST_WIDE_INT string_size = tree_to_uhwi (mem_size) - offset;
3058 gcc_checking_assert (string_length <= string_size);
3059 if (length <= string_size)
3060 {
3061 replace_call_with_value (gsi, build_int_cst (ptr_type_node, 0));
3062 return true;
3063 }
3064 }
3065 else
3066 {
3067 unsigned HOST_WIDE_INT offset = r - p1;
3068 gimple_seq stmts = NULL;
3069 if (lhs != NULL_TREE)
3070 {
3071 tree offset_cst = build_int_cst (sizetype, offset);
3072 gassign *stmt = gimple_build_assign (lhs, POINTER_PLUS_EXPR,
3073 arg1, offset_cst);
3074 gimple_seq_add_stmt_without_update (&stmts, stmt);
3075 }
3076 else
3077 gimple_seq_add_stmt_without_update (&stmts,
3078 gimple_build_nop ());
3079
3080 gsi_replace_with_seq_vops (gsi, stmts);
3081 return true;
3082 }
3083 }
3084
3085 return false;
3086 }
3087
3088 /* Fold a call to the fputs builtin. ARG0 and ARG1 are the arguments
3089 to the call. IGNORE is true if the value returned
3090 by the builtin will be ignored. UNLOCKED is true is true if this
3091 actually a call to fputs_unlocked. If LEN in non-NULL, it represents
3092 the known length of the string. Return NULL_TREE if no simplification
3093 was possible. */
3094
3095 static bool
3096 gimple_fold_builtin_fputs (gimple_stmt_iterator *gsi,
3097 tree arg0, tree arg1,
3098 bool unlocked)
3099 {
3100 gimple *stmt = gsi_stmt (*gsi);
3101
3102 /* If we're using an unlocked function, assume the other unlocked
3103 functions exist explicitly. */
3104 tree const fn_fputc = (unlocked
3105 ? builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED)
3106 : builtin_decl_implicit (BUILT_IN_FPUTC));
3107 tree const fn_fwrite = (unlocked
3108 ? builtin_decl_explicit (BUILT_IN_FWRITE_UNLOCKED)
3109 : builtin_decl_implicit (BUILT_IN_FWRITE));
3110
3111 /* If the return value is used, don't do the transformation. */
3112 if (gimple_call_lhs (stmt))
3113 return false;
3114
3115 /* Get the length of the string passed to fputs. If the length
3116 can't be determined, punt. */
3117 tree len = get_maxval_strlen (arg0, SRK_STRLEN);
3118 if (!len || TREE_CODE (len) != INTEGER_CST)
3119 return false;
3120
3121 switch (compare_tree_int (len, 1))
3122 {
3123 case -1: /* length is 0, delete the call entirely . */
3124 replace_call_with_value (gsi, integer_zero_node);
3125 return true;
3126
3127 case 0: /* length is 1, call fputc. */
3128 {
3129 const char *p = c_getstr (arg0);
3130 if (p != NULL)
3131 {
3132 if (!fn_fputc || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3133 return false;
3134
3135 gimple *repl
3136 = gimple_build_call (fn_fputc, 2,
3137 build_int_cst (integer_type_node, p[0]),
3138 arg1);
3139 replace_call_with_call_and_fold (gsi, repl);
3140 return true;
3141 }
3142 }
3143 /* FALLTHROUGH */
3144 case 1: /* length is greater than 1, call fwrite. */
3145 {
3146 /* If optimizing for size keep fputs. */
3147 if (optimize_function_for_size_p (cfun))
3148 return false;
3149 /* New argument list transforming fputs(string, stream) to
3150 fwrite(string, 1, len, stream). */
3151 if (!fn_fwrite || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3152 return false;
3153
3154 gimple *repl
3155 = gimple_build_call (fn_fwrite, 4, arg0, size_one_node,
3156 fold_convert (size_type_node, len), arg1);
3157 replace_call_with_call_and_fold (gsi, repl);
3158 return true;
3159 }
3160 default:
3161 gcc_unreachable ();
3162 }
3163 }
3164
3165 /* Fold a call to the __mem{cpy,pcpy,move,set}_chk builtin.
3166 DEST, SRC, LEN, and SIZE are the arguments to the call.
3167 IGNORE is true, if return value can be ignored. FCODE is the BUILT_IN_*
3168 code of the builtin. If MAXLEN is not NULL, it is maximum length
3169 passed as third argument. */
3170
3171 static bool
3172 gimple_fold_builtin_memory_chk (gimple_stmt_iterator *gsi,
3173 tree dest, tree src, tree len, tree size,
3174 enum built_in_function fcode)
3175 {
3176 gimple *stmt = gsi_stmt (*gsi);
3177 location_t loc = gimple_location (stmt);
3178 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3179 tree fn;
3180
3181 /* If SRC and DEST are the same (and not volatile), return DEST
3182 (resp. DEST+LEN for __mempcpy_chk). */
3183 if (fcode != BUILT_IN_MEMSET_CHK && operand_equal_p (src, dest, 0))
3184 {
3185 if (fcode != BUILT_IN_MEMPCPY_CHK)
3186 {
3187 replace_call_with_value (gsi, dest);
3188 return true;
3189 }
3190 else
3191 {
3192 gimple_seq stmts = NULL;
3193 len = gimple_convert_to_ptrofftype (&stmts, loc, len);
3194 tree temp = gimple_build (&stmts, loc, POINTER_PLUS_EXPR,
3195 TREE_TYPE (dest), dest, len);
3196 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3197 replace_call_with_value (gsi, temp);
3198 return true;
3199 }
3200 }
3201
3202 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
3203 return false;
3204
3205 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3206 if (! integer_all_onesp (size)
3207 && !known_lower (stmt, len, size)
3208 && !known_lower (stmt, maxlen, size))
3209 {
3210 /* MAXLEN and LEN both cannot be proved to be less than SIZE, at
3211 least try to optimize (void) __mempcpy_chk () into
3212 (void) __memcpy_chk () */
3213 if (fcode == BUILT_IN_MEMPCPY_CHK && ignore)
3214 {
3215 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3216 if (!fn)
3217 return false;
3218
3219 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3220 replace_call_with_call_and_fold (gsi, repl);
3221 return true;
3222 }
3223 return false;
3224 }
3225
3226 fn = NULL_TREE;
3227 /* If __builtin_mem{cpy,pcpy,move,set}_chk is used, assume
3228 mem{cpy,pcpy,move,set} is available. */
3229 switch (fcode)
3230 {
3231 case BUILT_IN_MEMCPY_CHK:
3232 fn = builtin_decl_explicit (BUILT_IN_MEMCPY);
3233 break;
3234 case BUILT_IN_MEMPCPY_CHK:
3235 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY);
3236 break;
3237 case BUILT_IN_MEMMOVE_CHK:
3238 fn = builtin_decl_explicit (BUILT_IN_MEMMOVE);
3239 break;
3240 case BUILT_IN_MEMSET_CHK:
3241 fn = builtin_decl_explicit (BUILT_IN_MEMSET);
3242 break;
3243 default:
3244 break;
3245 }
3246
3247 if (!fn)
3248 return false;
3249
3250 gimple *repl = gimple_build_call (fn, 3, dest, src, len);
3251 replace_call_with_call_and_fold (gsi, repl);
3252 return true;
3253 }
3254
3255 /* Fold a call to the __st[rp]cpy_chk builtin.
3256 DEST, SRC, and SIZE are the arguments to the call.
3257 IGNORE is true if return value can be ignored. FCODE is the BUILT_IN_*
3258 code of the builtin. If MAXLEN is not NULL, it is maximum length of
3259 strings passed as second argument. */
3260
3261 static bool
3262 gimple_fold_builtin_stxcpy_chk (gimple_stmt_iterator *gsi,
3263 tree dest,
3264 tree src, tree size,
3265 enum built_in_function fcode)
3266 {
3267 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3268 location_t loc = gimple_location (stmt);
3269 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3270 tree len, fn;
3271
3272 /* If SRC and DEST are the same (and not volatile), return DEST. */
3273 if (fcode == BUILT_IN_STRCPY_CHK && operand_equal_p (src, dest, 0))
3274 {
3275 /* Issue -Wrestrict unless the pointers are null (those do
3276 not point to objects and so do not indicate an overlap;
3277 such calls could be the result of sanitization and jump
3278 threading). */
3279 if (!integer_zerop (dest)
3280 && !warning_suppressed_p (stmt, OPT_Wrestrict))
3281 {
3282 tree func = gimple_call_fndecl (stmt);
3283
3284 warning_at (loc, OPT_Wrestrict,
3285 "%qD source argument is the same as destination",
3286 func);
3287 }
3288
3289 replace_call_with_value (gsi, dest);
3290 return true;
3291 }
3292
3293 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
3294 return false;
3295
3296 tree maxlen = get_maxval_strlen (src, SRK_STRLENMAX);
3297 if (! integer_all_onesp (size))
3298 {
3299 len = c_strlen (src, 1);
3300 if (!known_lower (stmt, len, size, true)
3301 && !known_lower (stmt, maxlen, size, true))
3302 {
3303 if (fcode == BUILT_IN_STPCPY_CHK)
3304 {
3305 if (! ignore)
3306 return false;
3307
3308 /* If return value of __stpcpy_chk is ignored,
3309 optimize into __strcpy_chk. */
3310 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
3311 if (!fn)
3312 return false;
3313
3314 gimple *repl = gimple_build_call (fn, 3, dest, src, size);
3315 replace_call_with_call_and_fold (gsi, repl);
3316 return true;
3317 }
3318
3319 if (! len || TREE_SIDE_EFFECTS (len))
3320 return false;
3321
3322 /* If c_strlen returned something, but not provably less than size,
3323 transform __strcpy_chk into __memcpy_chk. */
3324 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3325 if (!fn)
3326 return false;
3327
3328 gimple_seq stmts = NULL;
3329 len = force_gimple_operand (len, &stmts, true, NULL_TREE);
3330 len = gimple_convert (&stmts, loc, size_type_node, len);
3331 len = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node, len,
3332 build_int_cst (size_type_node, 1));
3333 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3334 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3335 replace_call_with_call_and_fold (gsi, repl);
3336 return true;
3337 }
3338 }
3339
3340 /* If __builtin_st{r,p}cpy_chk is used, assume st{r,p}cpy is available. */
3341 fn = builtin_decl_explicit (fcode == BUILT_IN_STPCPY_CHK && !ignore
3342 ? BUILT_IN_STPCPY : BUILT_IN_STRCPY);
3343 if (!fn)
3344 return false;
3345
3346 gcall *repl = gimple_build_call (fn, 2, dest, src);
3347 replace_call_with_call_and_fold (gsi, repl);
3348 return true;
3349 }
3350
3351 /* Fold a call to the __st{r,p}ncpy_chk builtin. DEST, SRC, LEN, and SIZE
3352 are the arguments to the call. If MAXLEN is not NULL, it is maximum
3353 length passed as third argument. IGNORE is true if return value can be
3354 ignored. FCODE is the BUILT_IN_* code of the builtin. */
3355
3356 static bool
3357 gimple_fold_builtin_stxncpy_chk (gimple_stmt_iterator *gsi,
3358 tree dest, tree src,
3359 tree len, tree size,
3360 enum built_in_function fcode)
3361 {
3362 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3363 bool ignore = gimple_call_lhs (stmt) == NULL_TREE;
3364 tree fn;
3365
3366 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3367 if (! integer_all_onesp (size)
3368 && !known_lower (stmt, len, size) && !known_lower (stmt, maxlen, size))
3369 {
3370 if (fcode == BUILT_IN_STPNCPY_CHK && ignore)
3371 {
3372 /* If return value of __stpncpy_chk is ignored,
3373 optimize into __strncpy_chk. */
3374 fn = builtin_decl_explicit (BUILT_IN_STRNCPY_CHK);
3375 if (fn)
3376 {
3377 gimple *repl = gimple_build_call (fn, 4, dest, src, len, size);
3378 replace_call_with_call_and_fold (gsi, repl);
3379 return true;
3380 }
3381 }
3382 return false;
3383 }
3384
3385 /* If __builtin_st{r,p}ncpy_chk is used, assume st{r,p}ncpy is available. */
3386 fn = builtin_decl_explicit (fcode == BUILT_IN_STPNCPY_CHK && !ignore
3387 ? BUILT_IN_STPNCPY : BUILT_IN_STRNCPY);
3388 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3389 return false;
3390
3391 gcall *repl = gimple_build_call (fn, 3, dest, src, len);
3392 replace_call_with_call_and_fold (gsi, repl);
3393 return true;
3394 }
3395
3396 /* Fold function call to builtin stpcpy with arguments DEST and SRC.
3397 Return NULL_TREE if no simplification can be made. */
3398
3399 static bool
3400 gimple_fold_builtin_stpcpy (gimple_stmt_iterator *gsi)
3401 {
3402 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3403 location_t loc = gimple_location (stmt);
3404 tree dest = gimple_call_arg (stmt, 0);
3405 tree src = gimple_call_arg (stmt, 1);
3406 tree fn, lenp1;
3407
3408 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
3409 return false;
3410
3411 /* If the result is unused, replace stpcpy with strcpy. */
3412 if (gimple_call_lhs (stmt) == NULL_TREE)
3413 {
3414 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3415 if (!fn)
3416 return false;
3417 gimple_call_set_fndecl (stmt, fn);
3418 fold_stmt (gsi);
3419 return true;
3420 }
3421
3422 /* Set to non-null if ARG refers to an unterminated array. */
3423 c_strlen_data data = { };
3424 /* The size of the unterminated array if SRC referes to one. */
3425 tree size;
3426 /* True if the size is exact/constant, false if it's the lower bound
3427 of a range. */
3428 bool exact;
3429 tree len = c_strlen (src, 1, &data, 1);
3430 if (!len
3431 || TREE_CODE (len) != INTEGER_CST)
3432 {
3433 data.decl = unterminated_array (src, &size, &exact);
3434 if (!data.decl)
3435 return false;
3436 }
3437
3438 if (data.decl)
3439 {
3440 /* Avoid folding calls with unterminated arrays. */
3441 if (!warning_suppressed_p (stmt, OPT_Wstringop_overread))
3442 warn_string_no_nul (loc, stmt, "stpcpy", src, data.decl, size,
3443 exact);
3444 suppress_warning (stmt, OPT_Wstringop_overread);
3445 return false;
3446 }
3447
3448 if (optimize_function_for_size_p (cfun)
3449 /* If length is zero it's small enough. */
3450 && !integer_zerop (len))
3451 return false;
3452
3453 /* If the source has a known length replace stpcpy with memcpy. */
3454 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3455 if (!fn)
3456 return false;
3457
3458 gimple_seq stmts = NULL;
3459 tree tem = gimple_convert (&stmts, loc, size_type_node, len);
3460 lenp1 = gimple_build (&stmts, loc, PLUS_EXPR, size_type_node,
3461 tem, build_int_cst (size_type_node, 1));
3462 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3463 gcall *repl = gimple_build_call (fn, 3, dest, src, lenp1);
3464 gimple_move_vops (repl, stmt);
3465 gsi_insert_before (gsi, repl, GSI_SAME_STMT);
3466 /* Replace the result with dest + len. */
3467 stmts = NULL;
3468 tem = gimple_convert (&stmts, loc, sizetype, len);
3469 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3470 gassign *ret = gimple_build_assign (gimple_call_lhs (stmt),
3471 POINTER_PLUS_EXPR, dest, tem);
3472 gsi_replace (gsi, ret, false);
3473 /* Finally fold the memcpy call. */
3474 gimple_stmt_iterator gsi2 = *gsi;
3475 gsi_prev (&gsi2);
3476 fold_stmt (&gsi2);
3477 return true;
3478 }
3479
3480 /* Fold a call EXP to {,v}snprintf having NARGS passed as ARGS. Return
3481 NULL_TREE if a normal call should be emitted rather than expanding
3482 the function inline. FCODE is either BUILT_IN_SNPRINTF_CHK or
3483 BUILT_IN_VSNPRINTF_CHK. If MAXLEN is not NULL, it is maximum length
3484 passed as second argument. */
3485
3486 static bool
3487 gimple_fold_builtin_snprintf_chk (gimple_stmt_iterator *gsi,
3488 enum built_in_function fcode)
3489 {
3490 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3491 tree dest, size, len, fn, fmt, flag;
3492 const char *fmt_str;
3493
3494 /* Verify the required arguments in the original call. */
3495 if (gimple_call_num_args (stmt) < 5)
3496 return false;
3497
3498 dest = gimple_call_arg (stmt, 0);
3499 len = gimple_call_arg (stmt, 1);
3500 flag = gimple_call_arg (stmt, 2);
3501 size = gimple_call_arg (stmt, 3);
3502 fmt = gimple_call_arg (stmt, 4);
3503
3504 tree maxlen = get_maxval_strlen (len, SRK_INT_VALUE);
3505 if (! integer_all_onesp (size)
3506 && !known_lower (stmt, len, size) && !known_lower (stmt, maxlen, size))
3507 return false;
3508
3509 if (!init_target_chars ())
3510 return false;
3511
3512 /* Only convert __{,v}snprintf_chk to {,v}snprintf if flag is 0
3513 or if format doesn't contain % chars or is "%s". */
3514 if (! integer_zerop (flag))
3515 {
3516 fmt_str = c_getstr (fmt);
3517 if (fmt_str == NULL)
3518 return false;
3519 if (strchr (fmt_str, target_percent) != NULL
3520 && strcmp (fmt_str, target_percent_s))
3521 return false;
3522 }
3523
3524 /* If __builtin_{,v}snprintf_chk is used, assume {,v}snprintf is
3525 available. */
3526 fn = builtin_decl_explicit (fcode == BUILT_IN_VSNPRINTF_CHK
3527 ? BUILT_IN_VSNPRINTF : BUILT_IN_SNPRINTF);
3528 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3529 return false;
3530
3531 /* Replace the called function and the first 5 argument by 3 retaining
3532 trailing varargs. */
3533 gimple_call_set_fndecl (stmt, fn);
3534 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3535 gimple_call_set_arg (stmt, 0, dest);
3536 gimple_call_set_arg (stmt, 1, len);
3537 gimple_call_set_arg (stmt, 2, fmt);
3538 for (unsigned i = 3; i < gimple_call_num_args (stmt) - 2; ++i)
3539 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3540 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3541 fold_stmt (gsi);
3542 return true;
3543 }
3544
3545 /* Fold a call EXP to __{,v}sprintf_chk having NARGS passed as ARGS.
3546 Return NULL_TREE if a normal call should be emitted rather than
3547 expanding the function inline. FCODE is either BUILT_IN_SPRINTF_CHK
3548 or BUILT_IN_VSPRINTF_CHK. */
3549
3550 static bool
3551 gimple_fold_builtin_sprintf_chk (gimple_stmt_iterator *gsi,
3552 enum built_in_function fcode)
3553 {
3554 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3555 tree dest, size, len, fn, fmt, flag;
3556 const char *fmt_str;
3557 unsigned nargs = gimple_call_num_args (stmt);
3558
3559 /* Verify the required arguments in the original call. */
3560 if (nargs < 4)
3561 return false;
3562 dest = gimple_call_arg (stmt, 0);
3563 flag = gimple_call_arg (stmt, 1);
3564 size = gimple_call_arg (stmt, 2);
3565 fmt = gimple_call_arg (stmt, 3);
3566
3567 len = NULL_TREE;
3568
3569 if (!init_target_chars ())
3570 return false;
3571
3572 /* Check whether the format is a literal string constant. */
3573 fmt_str = c_getstr (fmt);
3574 if (fmt_str != NULL)
3575 {
3576 /* If the format doesn't contain % args or %%, we know the size. */
3577 if (strchr (fmt_str, target_percent) == 0)
3578 {
3579 if (fcode != BUILT_IN_SPRINTF_CHK || nargs == 4)
3580 len = build_int_cstu (size_type_node, strlen (fmt_str));
3581 }
3582 /* If the format is "%s" and first ... argument is a string literal,
3583 we know the size too. */
3584 else if (fcode == BUILT_IN_SPRINTF_CHK
3585 && strcmp (fmt_str, target_percent_s) == 0)
3586 {
3587 tree arg;
3588
3589 if (nargs == 5)
3590 {
3591 arg = gimple_call_arg (stmt, 4);
3592 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3593 len = c_strlen (arg, 1);
3594 }
3595 }
3596 }
3597
3598 if (! integer_all_onesp (size) && !known_lower (stmt, len, size, true))
3599 return false;
3600
3601 /* Only convert __{,v}sprintf_chk to {,v}sprintf if flag is 0
3602 or if format doesn't contain % chars or is "%s". */
3603 if (! integer_zerop (flag))
3604 {
3605 if (fmt_str == NULL)
3606 return false;
3607 if (strchr (fmt_str, target_percent) != NULL
3608 && strcmp (fmt_str, target_percent_s))
3609 return false;
3610 }
3611
3612 /* If __builtin_{,v}sprintf_chk is used, assume {,v}sprintf is available. */
3613 fn = builtin_decl_explicit (fcode == BUILT_IN_VSPRINTF_CHK
3614 ? BUILT_IN_VSPRINTF : BUILT_IN_SPRINTF);
3615 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3616 return false;
3617
3618 /* Replace the called function and the first 4 argument by 2 retaining
3619 trailing varargs. */
3620 gimple_call_set_fndecl (stmt, fn);
3621 gimple_call_set_fntype (stmt, TREE_TYPE (fn));
3622 gimple_call_set_arg (stmt, 0, dest);
3623 gimple_call_set_arg (stmt, 1, fmt);
3624 for (unsigned i = 2; i < gimple_call_num_args (stmt) - 2; ++i)
3625 gimple_call_set_arg (stmt, i, gimple_call_arg (stmt, i + 2));
3626 gimple_set_num_ops (stmt, gimple_num_ops (stmt) - 2);
3627 fold_stmt (gsi);
3628 return true;
3629 }
3630
3631 /* Simplify a call to the sprintf builtin with arguments DEST, FMT, and ORIG.
3632 ORIG may be null if this is a 2-argument call. We don't attempt to
3633 simplify calls with more than 3 arguments.
3634
3635 Return true if simplification was possible, otherwise false. */
3636
3637 bool
3638 gimple_fold_builtin_sprintf (gimple_stmt_iterator *gsi)
3639 {
3640 gimple *stmt = gsi_stmt (*gsi);
3641
3642 /* Verify the required arguments in the original call. We deal with two
3643 types of sprintf() calls: 'sprintf (str, fmt)' and
3644 'sprintf (dest, "%s", orig)'. */
3645 if (gimple_call_num_args (stmt) > 3)
3646 return false;
3647
3648 tree orig = NULL_TREE;
3649 if (gimple_call_num_args (stmt) == 3)
3650 orig = gimple_call_arg (stmt, 2);
3651
3652 /* Check whether the format is a literal string constant. */
3653 tree fmt = gimple_call_arg (stmt, 1);
3654 const char *fmt_str = c_getstr (fmt);
3655 if (fmt_str == NULL)
3656 return false;
3657
3658 tree dest = gimple_call_arg (stmt, 0);
3659
3660 if (!init_target_chars ())
3661 return false;
3662
3663 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3664 if (!fn || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3665 return false;
3666
3667 /* If the format doesn't contain % args or %%, use strcpy. */
3668 if (strchr (fmt_str, target_percent) == NULL)
3669 {
3670 /* Don't optimize sprintf (buf, "abc", ptr++). */
3671 if (orig)
3672 return false;
3673
3674 /* Convert sprintf (str, fmt) into strcpy (str, fmt) when
3675 'format' is known to contain no % formats. */
3676 gimple_seq stmts = NULL;
3677 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3678
3679 /* Propagate the NO_WARNING bit to avoid issuing the same
3680 warning more than once. */
3681 copy_warning (repl, stmt);
3682
3683 gimple_seq_add_stmt_without_update (&stmts, repl);
3684 if (tree lhs = gimple_call_lhs (stmt))
3685 {
3686 repl = gimple_build_assign (lhs, build_int_cst (TREE_TYPE (lhs),
3687 strlen (fmt_str)));
3688 gimple_seq_add_stmt_without_update (&stmts, repl);
3689 gsi_replace_with_seq_vops (gsi, stmts);
3690 /* gsi now points at the assignment to the lhs, get a
3691 stmt iterator to the memcpy call.
3692 ??? We can't use gsi_for_stmt as that doesn't work when the
3693 CFG isn't built yet. */
3694 gimple_stmt_iterator gsi2 = *gsi;
3695 gsi_prev (&gsi2);
3696 fold_stmt (&gsi2);
3697 }
3698 else
3699 {
3700 gsi_replace_with_seq_vops (gsi, stmts);
3701 fold_stmt (gsi);
3702 }
3703 return true;
3704 }
3705
3706 /* If the format is "%s", use strcpy if the result isn't used. */
3707 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3708 {
3709 /* Don't crash on sprintf (str1, "%s"). */
3710 if (!orig)
3711 return false;
3712
3713 /* Don't fold calls with source arguments of invalid (nonpointer)
3714 types. */
3715 if (!POINTER_TYPE_P (TREE_TYPE (orig)))
3716 return false;
3717
3718 tree orig_len = NULL_TREE;
3719 if (gimple_call_lhs (stmt))
3720 {
3721 orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3722 if (!orig_len)
3723 return false;
3724 }
3725
3726 /* Convert sprintf (str1, "%s", str2) into strcpy (str1, str2). */
3727 gimple_seq stmts = NULL;
3728 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3729
3730 /* Propagate the NO_WARNING bit to avoid issuing the same
3731 warning more than once. */
3732 copy_warning (repl, stmt);
3733
3734 gimple_seq_add_stmt_without_update (&stmts, repl);
3735 if (tree lhs = gimple_call_lhs (stmt))
3736 {
3737 if (!useless_type_conversion_p (TREE_TYPE (lhs),
3738 TREE_TYPE (orig_len)))
3739 orig_len = fold_convert (TREE_TYPE (lhs), orig_len);
3740 repl = gimple_build_assign (lhs, orig_len);
3741 gimple_seq_add_stmt_without_update (&stmts, repl);
3742 gsi_replace_with_seq_vops (gsi, stmts);
3743 /* gsi now points at the assignment to the lhs, get a
3744 stmt iterator to the memcpy call.
3745 ??? We can't use gsi_for_stmt as that doesn't work when the
3746 CFG isn't built yet. */
3747 gimple_stmt_iterator gsi2 = *gsi;
3748 gsi_prev (&gsi2);
3749 fold_stmt (&gsi2);
3750 }
3751 else
3752 {
3753 gsi_replace_with_seq_vops (gsi, stmts);
3754 fold_stmt (gsi);
3755 }
3756 return true;
3757 }
3758 return false;
3759 }
3760
3761 /* Simplify a call to the snprintf builtin with arguments DEST, DESTSIZE,
3762 FMT, and ORIG. ORIG may be null if this is a 3-argument call. We don't
3763 attempt to simplify calls with more than 4 arguments.
3764
3765 Return true if simplification was possible, otherwise false. */
3766
3767 bool
3768 gimple_fold_builtin_snprintf (gimple_stmt_iterator *gsi)
3769 {
3770 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3771 tree dest = gimple_call_arg (stmt, 0);
3772 tree destsize = gimple_call_arg (stmt, 1);
3773 tree fmt = gimple_call_arg (stmt, 2);
3774 tree orig = NULL_TREE;
3775 const char *fmt_str = NULL;
3776
3777 if (gimple_call_num_args (stmt) > 4
3778 || (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun)))
3779 return false;
3780
3781 if (gimple_call_num_args (stmt) == 4)
3782 orig = gimple_call_arg (stmt, 3);
3783
3784 /* Check whether the format is a literal string constant. */
3785 fmt_str = c_getstr (fmt);
3786 if (fmt_str == NULL)
3787 return false;
3788
3789 if (!init_target_chars ())
3790 return false;
3791
3792 /* If the format doesn't contain % args or %%, use strcpy. */
3793 if (strchr (fmt_str, target_percent) == NULL)
3794 {
3795 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3796 if (!fn)
3797 return false;
3798
3799 /* Don't optimize snprintf (buf, 4, "abc", ptr++). */
3800 if (orig)
3801 return false;
3802
3803 tree len = build_int_cstu (TREE_TYPE (destsize), strlen (fmt_str));
3804
3805 /* We could expand this as
3806 memcpy (str, fmt, cst - 1); str[cst - 1] = '\0';
3807 or to
3808 memcpy (str, fmt_with_nul_at_cstm1, cst);
3809 but in the former case that might increase code size
3810 and in the latter case grow .rodata section too much.
3811 So punt for now. */
3812 if (!known_lower (stmt, len, destsize, true))
3813 return false;
3814
3815 gimple_seq stmts = NULL;
3816 gimple *repl = gimple_build_call (fn, 2, dest, fmt);
3817 gimple_seq_add_stmt_without_update (&stmts, repl);
3818 if (tree lhs = gimple_call_lhs (stmt))
3819 {
3820 repl = gimple_build_assign (lhs,
3821 fold_convert (TREE_TYPE (lhs), len));
3822 gimple_seq_add_stmt_without_update (&stmts, repl);
3823 gsi_replace_with_seq_vops (gsi, stmts);
3824 /* gsi now points at the assignment to the lhs, get a
3825 stmt iterator to the memcpy call.
3826 ??? We can't use gsi_for_stmt as that doesn't work when the
3827 CFG isn't built yet. */
3828 gimple_stmt_iterator gsi2 = *gsi;
3829 gsi_prev (&gsi2);
3830 fold_stmt (&gsi2);
3831 }
3832 else
3833 {
3834 gsi_replace_with_seq_vops (gsi, stmts);
3835 fold_stmt (gsi);
3836 }
3837 return true;
3838 }
3839
3840 /* If the format is "%s", use strcpy if the result isn't used. */
3841 else if (fmt_str && strcmp (fmt_str, target_percent_s) == 0)
3842 {
3843 tree fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3844 if (!fn)
3845 return false;
3846
3847 /* Don't crash on snprintf (str1, cst, "%s"). */
3848 if (!orig)
3849 return false;
3850
3851 tree orig_len = get_maxval_strlen (orig, SRK_STRLEN);
3852
3853 /* We could expand this as
3854 memcpy (str1, str2, cst - 1); str1[cst - 1] = '\0';
3855 or to
3856 memcpy (str1, str2_with_nul_at_cstm1, cst);
3857 but in the former case that might increase code size
3858 and in the latter case grow .rodata section too much.
3859 So punt for now. */
3860 if (!known_lower (stmt, orig_len, destsize, true))
3861 return false;
3862
3863 /* Convert snprintf (str1, cst, "%s", str2) into
3864 strcpy (str1, str2) if strlen (str2) < cst. */
3865 gimple_seq stmts = NULL;
3866 gimple *repl = gimple_build_call (fn, 2, dest, orig);
3867 gimple_seq_add_stmt_without_update (&stmts, repl);
3868 if (tree lhs = gimple_call_lhs (stmt))
3869 {
3870 if (!useless_type_conversion_p (TREE_TYPE (lhs),
3871 TREE_TYPE (orig_len)))
3872 orig_len = fold_convert (TREE_TYPE (lhs), orig_len);
3873 repl = gimple_build_assign (lhs, orig_len);
3874 gimple_seq_add_stmt_without_update (&stmts, repl);
3875 gsi_replace_with_seq_vops (gsi, stmts);
3876 /* gsi now points at the assignment to the lhs, get a
3877 stmt iterator to the memcpy call.
3878 ??? We can't use gsi_for_stmt as that doesn't work when the
3879 CFG isn't built yet. */
3880 gimple_stmt_iterator gsi2 = *gsi;
3881 gsi_prev (&gsi2);
3882 fold_stmt (&gsi2);
3883 }
3884 else
3885 {
3886 gsi_replace_with_seq_vops (gsi, stmts);
3887 fold_stmt (gsi);
3888 }
3889 return true;
3890 }
3891 return false;
3892 }
3893
3894 /* Fold a call to the {,v}fprintf{,_unlocked} and __{,v}printf_chk builtins.
3895 FP, FMT, and ARG are the arguments to the call. We don't fold calls with
3896 more than 3 arguments, and ARG may be null in the 2-argument case.
3897
3898 Return NULL_TREE if no simplification was possible, otherwise return the
3899 simplified form of the call as a tree. FCODE is the BUILT_IN_*
3900 code of the function to be simplified. */
3901
3902 static bool
3903 gimple_fold_builtin_fprintf (gimple_stmt_iterator *gsi,
3904 tree fp, tree fmt, tree arg,
3905 enum built_in_function fcode)
3906 {
3907 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3908 tree fn_fputc, fn_fputs;
3909 const char *fmt_str = NULL;
3910
3911 /* If the return value is used, don't do the transformation. */
3912 if (gimple_call_lhs (stmt) != NULL_TREE)
3913 return false;
3914
3915 /* Check whether the format is a literal string constant. */
3916 fmt_str = c_getstr (fmt);
3917 if (fmt_str == NULL)
3918 return false;
3919
3920 if (fcode == BUILT_IN_FPRINTF_UNLOCKED)
3921 {
3922 /* If we're using an unlocked function, assume the other
3923 unlocked functions exist explicitly. */
3924 fn_fputc = builtin_decl_explicit (BUILT_IN_FPUTC_UNLOCKED);
3925 fn_fputs = builtin_decl_explicit (BUILT_IN_FPUTS_UNLOCKED);
3926 }
3927 else
3928 {
3929 fn_fputc = builtin_decl_implicit (BUILT_IN_FPUTC);
3930 fn_fputs = builtin_decl_implicit (BUILT_IN_FPUTS);
3931 }
3932
3933 if (!init_target_chars ())
3934 return false;
3935
3936 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
3937 return false;
3938
3939 /* If the format doesn't contain % args or %%, use strcpy. */
3940 if (strchr (fmt_str, target_percent) == NULL)
3941 {
3942 if (fcode != BUILT_IN_VFPRINTF && fcode != BUILT_IN_VFPRINTF_CHK
3943 && arg)
3944 return false;
3945
3946 /* If the format specifier was "", fprintf does nothing. */
3947 if (fmt_str[0] == '\0')
3948 {
3949 replace_call_with_value (gsi, NULL_TREE);
3950 return true;
3951 }
3952
3953 /* When "string" doesn't contain %, replace all cases of
3954 fprintf (fp, string) with fputs (string, fp). The fputs
3955 builtin will take care of special cases like length == 1. */
3956 if (fn_fputs)
3957 {
3958 gcall *repl = gimple_build_call (fn_fputs, 2, fmt, fp);
3959 replace_call_with_call_and_fold (gsi, repl);
3960 return true;
3961 }
3962 }
3963
3964 /* The other optimizations can be done only on the non-va_list variants. */
3965 else if (fcode == BUILT_IN_VFPRINTF || fcode == BUILT_IN_VFPRINTF_CHK)
3966 return false;
3967
3968 /* If the format specifier was "%s", call __builtin_fputs (arg, fp). */
3969 else if (strcmp (fmt_str, target_percent_s) == 0)
3970 {
3971 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
3972 return false;
3973 if (fn_fputs)
3974 {
3975 gcall *repl = gimple_build_call (fn_fputs, 2, arg, fp);
3976 replace_call_with_call_and_fold (gsi, repl);
3977 return true;
3978 }
3979 }
3980
3981 /* If the format specifier was "%c", call __builtin_fputc (arg, fp). */
3982 else if (strcmp (fmt_str, target_percent_c) == 0)
3983 {
3984 if (!arg
3985 || ! useless_type_conversion_p (integer_type_node, TREE_TYPE (arg)))
3986 return false;
3987 if (fn_fputc)
3988 {
3989 gcall *repl = gimple_build_call (fn_fputc, 2, arg, fp);
3990 replace_call_with_call_and_fold (gsi, repl);
3991 return true;
3992 }
3993 }
3994
3995 return false;
3996 }
3997
3998 /* Fold a call to the {,v}printf{,_unlocked} and __{,v}printf_chk builtins.
3999 FMT and ARG are the arguments to the call; we don't fold cases with
4000 more than 2 arguments, and ARG may be null if this is a 1-argument case.
4001
4002 Return NULL_TREE if no simplification was possible, otherwise return the
4003 simplified form of the call as a tree. FCODE is the BUILT_IN_*
4004 code of the function to be simplified. */
4005
4006 static bool
4007 gimple_fold_builtin_printf (gimple_stmt_iterator *gsi, tree fmt,
4008 tree arg, enum built_in_function fcode)
4009 {
4010 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
4011 tree fn_putchar, fn_puts, newarg;
4012 const char *fmt_str = NULL;
4013
4014 /* If the return value is used, don't do the transformation. */
4015 if (gimple_call_lhs (stmt) != NULL_TREE)
4016 return false;
4017
4018 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
4019 return false;
4020
4021 /* Check whether the format is a literal string constant. */
4022 fmt_str = c_getstr (fmt);
4023 if (fmt_str == NULL)
4024 return false;
4025
4026 if (fcode == BUILT_IN_PRINTF_UNLOCKED)
4027 {
4028 /* If we're using an unlocked function, assume the other
4029 unlocked functions exist explicitly. */
4030 fn_putchar = builtin_decl_explicit (BUILT_IN_PUTCHAR_UNLOCKED);
4031 fn_puts = builtin_decl_explicit (BUILT_IN_PUTS_UNLOCKED);
4032 }
4033 else
4034 {
4035 fn_putchar = builtin_decl_implicit (BUILT_IN_PUTCHAR);
4036 fn_puts = builtin_decl_implicit (BUILT_IN_PUTS);
4037 }
4038
4039 if (!init_target_chars ())
4040 return false;
4041
4042 if (strcmp (fmt_str, target_percent_s) == 0
4043 || strchr (fmt_str, target_percent) == NULL)
4044 {
4045 const char *str;
4046
4047 if (strcmp (fmt_str, target_percent_s) == 0)
4048 {
4049 if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
4050 return false;
4051
4052 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
4053 return false;
4054
4055 str = c_getstr (arg);
4056 if (str == NULL)
4057 return false;
4058 }
4059 else
4060 {
4061 /* The format specifier doesn't contain any '%' characters. */
4062 if (fcode != BUILT_IN_VPRINTF && fcode != BUILT_IN_VPRINTF_CHK
4063 && arg)
4064 return false;
4065 str = fmt_str;
4066 }
4067
4068 /* If the string was "", printf does nothing. */
4069 if (str[0] == '\0')
4070 {
4071 replace_call_with_value (gsi, NULL_TREE);
4072 return true;
4073 }
4074
4075 /* If the string has length of 1, call putchar. */
4076 if (str[1] == '\0')
4077 {
4078 /* Given printf("c"), (where c is any one character,)
4079 convert "c"[0] to an int and pass that to the replacement
4080 function. */
4081 newarg = build_int_cst (integer_type_node, str[0]);
4082 if (fn_putchar)
4083 {
4084 gcall *repl = gimple_build_call (fn_putchar, 1, newarg);
4085 replace_call_with_call_and_fold (gsi, repl);
4086 return true;
4087 }
4088 }
4089 else
4090 {
4091 /* If the string was "string\n", call puts("string"). */
4092 size_t len = strlen (str);
4093 if ((unsigned char)str[len - 1] == target_newline
4094 && (size_t) (int) len == len
4095 && (int) len > 0)
4096 {
4097 char *newstr;
4098
4099 /* Create a NUL-terminated string that's one char shorter
4100 than the original, stripping off the trailing '\n'. */
4101 newstr = xstrdup (str);
4102 newstr[len - 1] = '\0';
4103 newarg = build_string_literal (len, newstr);
4104 free (newstr);
4105 if (fn_puts)
4106 {
4107 gcall *repl = gimple_build_call (fn_puts, 1, newarg);
4108 replace_call_with_call_and_fold (gsi, repl);
4109 return true;
4110 }
4111 }
4112 else
4113 /* We'd like to arrange to call fputs(string,stdout) here,
4114 but we need stdout and don't have a way to get it yet. */
4115 return false;
4116 }
4117 }
4118
4119 /* The other optimizations can be done only on the non-va_list variants. */
4120 else if (fcode == BUILT_IN_VPRINTF || fcode == BUILT_IN_VPRINTF_CHK)
4121 return false;
4122
4123 /* If the format specifier was "%s\n", call __builtin_puts(arg). */
4124 else if (strcmp (fmt_str, target_percent_s_newline) == 0)
4125 {
4126 if (!arg || ! POINTER_TYPE_P (TREE_TYPE (arg)))
4127 return false;
4128 if (fn_puts)
4129 {
4130 gcall *repl = gimple_build_call (fn_puts, 1, arg);
4131 replace_call_with_call_and_fold (gsi, repl);
4132 return true;
4133 }
4134 }
4135
4136 /* If the format specifier was "%c", call __builtin_putchar(arg). */
4137 else if (strcmp (fmt_str, target_percent_c) == 0)
4138 {
4139 if (!arg || ! useless_type_conversion_p (integer_type_node,
4140 TREE_TYPE (arg)))
4141 return false;
4142 if (fn_putchar)
4143 {
4144 gcall *repl = gimple_build_call (fn_putchar, 1, arg);
4145 replace_call_with_call_and_fold (gsi, repl);
4146 return true;
4147 }
4148 }
4149
4150 return false;
4151 }
4152
4153
4154
4155 /* Fold a call to __builtin_strlen with known length LEN. */
4156
4157 static bool
4158 gimple_fold_builtin_strlen (gimple_stmt_iterator *gsi)
4159 {
4160 gimple *stmt = gsi_stmt (*gsi);
4161 tree arg = gimple_call_arg (stmt, 0);
4162
4163 wide_int minlen;
4164 wide_int maxlen;
4165
4166 c_strlen_data lendata = { };
4167 if (get_range_strlen (arg, &lendata, /* eltsize = */ 1)
4168 && !lendata.decl
4169 && lendata.minlen && TREE_CODE (lendata.minlen) == INTEGER_CST
4170 && lendata.maxlen && TREE_CODE (lendata.maxlen) == INTEGER_CST)
4171 {
4172 /* The range of lengths refers to either a single constant
4173 string or to the longest and shortest constant string
4174 referenced by the argument of the strlen() call, or to
4175 the strings that can possibly be stored in the arrays
4176 the argument refers to. */
4177 minlen = wi::to_wide (lendata.minlen);
4178 maxlen = wi::to_wide (lendata.maxlen);
4179 }
4180 else
4181 {
4182 unsigned prec = TYPE_PRECISION (sizetype);
4183
4184 minlen = wi::shwi (0, prec);
4185 maxlen = wi::to_wide (max_object_size (), prec) - 2;
4186 }
4187
4188 /* For -fsanitize=address, don't optimize the upper bound of the
4189 length to be able to diagnose UB on non-zero terminated arrays. */
4190 if (sanitize_flags_p (SANITIZE_ADDRESS))
4191 maxlen = wi::max_value (TYPE_PRECISION (sizetype), UNSIGNED);
4192
4193 if (minlen == maxlen)
4194 {
4195 /* Fold the strlen call to a constant. */
4196 tree type = TREE_TYPE (lendata.minlen);
4197 tree len = force_gimple_operand_gsi (gsi,
4198 wide_int_to_tree (type, minlen),
4199 true, NULL, true, GSI_SAME_STMT);
4200 replace_call_with_value (gsi, len);
4201 return true;
4202 }
4203
4204 /* Set the strlen() range to [0, MAXLEN]. */
4205 if (tree lhs = gimple_call_lhs (stmt))
4206 set_strlen_range (lhs, minlen, maxlen);
4207
4208 return false;
4209 }
4210
4211 static bool
4212 gimple_fold_builtin_omp_is_initial_device (gimple_stmt_iterator *gsi)
4213 {
4214 #if ACCEL_COMPILER
4215 replace_call_with_value (gsi, integer_zero_node);
4216 return true;
4217 #else
4218 if (!ENABLE_OFFLOADING || symtab->state == EXPANSION)
4219 {
4220 replace_call_with_value (gsi, integer_one_node);
4221 return true;
4222 }
4223 #endif
4224 return false;
4225 }
4226
4227
4228 /* Fold a call to __builtin_acc_on_device. */
4229
4230 static bool
4231 gimple_fold_builtin_acc_on_device (gimple_stmt_iterator *gsi, tree arg0)
4232 {
4233 /* Defer folding until we know which compiler we're in. */
4234 if (symtab->state != EXPANSION)
4235 return false;
4236
4237 unsigned val_host = GOMP_DEVICE_HOST;
4238 unsigned val_dev = GOMP_DEVICE_NONE;
4239
4240 #ifdef ACCEL_COMPILER
4241 val_host = GOMP_DEVICE_NOT_HOST;
4242 val_dev = ACCEL_COMPILER_acc_device;
4243 #endif
4244
4245 location_t loc = gimple_location (gsi_stmt (*gsi));
4246
4247 tree host_eq = make_ssa_name (boolean_type_node);
4248 gimple *host_ass = gimple_build_assign
4249 (host_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_host));
4250 gimple_set_location (host_ass, loc);
4251 gsi_insert_before (gsi, host_ass, GSI_SAME_STMT);
4252
4253 tree dev_eq = make_ssa_name (boolean_type_node);
4254 gimple *dev_ass = gimple_build_assign
4255 (dev_eq, EQ_EXPR, arg0, build_int_cst (TREE_TYPE (arg0), val_dev));
4256 gimple_set_location (dev_ass, loc);
4257 gsi_insert_before (gsi, dev_ass, GSI_SAME_STMT);
4258
4259 tree result = make_ssa_name (boolean_type_node);
4260 gimple *result_ass = gimple_build_assign
4261 (result, BIT_IOR_EXPR, host_eq, dev_eq);
4262 gimple_set_location (result_ass, loc);
4263 gsi_insert_before (gsi, result_ass, GSI_SAME_STMT);
4264
4265 replace_call_with_value (gsi, result);
4266
4267 return true;
4268 }
4269
4270 /* Fold realloc (0, n) -> malloc (n). */
4271
4272 static bool
4273 gimple_fold_builtin_realloc (gimple_stmt_iterator *gsi)
4274 {
4275 gimple *stmt = gsi_stmt (*gsi);
4276 tree arg = gimple_call_arg (stmt, 0);
4277 tree size = gimple_call_arg (stmt, 1);
4278
4279 if (!gimple_vdef (stmt) && gimple_in_ssa_p (cfun))
4280 return false;
4281
4282 if (operand_equal_p (arg, null_pointer_node, 0))
4283 {
4284 tree fn_malloc = builtin_decl_implicit (BUILT_IN_MALLOC);
4285 if (fn_malloc)
4286 {
4287 gcall *repl = gimple_build_call (fn_malloc, 1, size);
4288 replace_call_with_call_and_fold (gsi, repl);
4289 return true;
4290 }
4291 }
4292 return false;
4293 }
4294
4295 /* Number of bytes into which any type but aggregate, vector or
4296 _BitInt types should fit. */
4297 static constexpr size_t clear_padding_unit
4298 = MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT;
4299 /* Buffer size on which __builtin_clear_padding folding code works. */
4300 static const size_t clear_padding_buf_size = 32 * clear_padding_unit;
4301
4302 /* Data passed through __builtin_clear_padding folding. */
4303 struct clear_padding_struct {
4304 location_t loc;
4305 /* 0 during __builtin_clear_padding folding, nonzero during
4306 clear_type_padding_in_mask. In that case, instead of clearing the
4307 non-padding bits in union_ptr array clear the padding bits in there. */
4308 bool clear_in_mask;
4309 tree base;
4310 tree alias_type;
4311 gimple_stmt_iterator *gsi;
4312 /* Alignment of buf->base + 0. */
4313 unsigned align;
4314 /* Offset from buf->base. Should be always a multiple of UNITS_PER_WORD. */
4315 HOST_WIDE_INT off;
4316 /* Number of padding bytes before buf->off that don't have padding clear
4317 code emitted yet. */
4318 HOST_WIDE_INT padding_bytes;
4319 /* The size of the whole object. Never emit code to touch
4320 buf->base + buf->sz or following bytes. */
4321 HOST_WIDE_INT sz;
4322 /* Number of bytes recorded in buf->buf. */
4323 size_t size;
4324 /* When inside union, instead of emitting code we and bits inside of
4325 the union_ptr array. */
4326 unsigned char *union_ptr;
4327 /* Set bits mean padding bits that need to be cleared by the builtin. */
4328 unsigned char buf[clear_padding_buf_size + clear_padding_unit];
4329 };
4330
4331 /* Emit code to clear padding requested in BUF->buf - set bits
4332 in there stand for padding that should be cleared. FULL is true
4333 if everything from the buffer should be flushed, otherwise
4334 it can leave up to 2 * clear_padding_unit bytes for further
4335 processing. */
4336
4337 static void
4338 clear_padding_flush (clear_padding_struct *buf, bool full)
4339 {
4340 gcc_assert ((clear_padding_unit % UNITS_PER_WORD) == 0);
4341 if (!full && buf->size < 2 * clear_padding_unit)
4342 return;
4343 gcc_assert ((buf->off % UNITS_PER_WORD) == 0);
4344 size_t end = buf->size;
4345 if (!full)
4346 end = ((end - clear_padding_unit - 1) / clear_padding_unit
4347 * clear_padding_unit);
4348 size_t padding_bytes = buf->padding_bytes;
4349 if (buf->union_ptr)
4350 {
4351 if (buf->clear_in_mask)
4352 {
4353 /* During clear_type_padding_in_mask, clear the padding
4354 bits set in buf->buf in the buf->union_ptr mask. */
4355 for (size_t i = 0; i < end; i++)
4356 {
4357 if (buf->buf[i] == (unsigned char) ~0)
4358 padding_bytes++;
4359 else
4360 {
4361 memset (&buf->union_ptr[buf->off + i - padding_bytes],
4362 0, padding_bytes);
4363 padding_bytes = 0;
4364 buf->union_ptr[buf->off + i] &= ~buf->buf[i];
4365 }
4366 }
4367 if (full)
4368 {
4369 memset (&buf->union_ptr[buf->off + end - padding_bytes],
4370 0, padding_bytes);
4371 buf->off = 0;
4372 buf->size = 0;
4373 buf->padding_bytes = 0;
4374 }
4375 else
4376 {
4377 memmove (buf->buf, buf->buf + end, buf->size - end);
4378 buf->off += end;
4379 buf->size -= end;
4380 buf->padding_bytes = padding_bytes;
4381 }
4382 return;
4383 }
4384 /* Inside of a union, instead of emitting any code, instead
4385 clear all bits in the union_ptr buffer that are clear
4386 in buf. Whole padding bytes don't clear anything. */
4387 for (size_t i = 0; i < end; i++)
4388 {
4389 if (buf->buf[i] == (unsigned char) ~0)
4390 padding_bytes++;
4391 else
4392 {
4393 padding_bytes = 0;
4394 buf->union_ptr[buf->off + i] &= buf->buf[i];
4395 }
4396 }
4397 if (full)
4398 {
4399 buf->off = 0;
4400 buf->size = 0;
4401 buf->padding_bytes = 0;
4402 }
4403 else
4404 {
4405 memmove (buf->buf, buf->buf + end, buf->size - end);
4406 buf->off += end;
4407 buf->size -= end;
4408 buf->padding_bytes = padding_bytes;
4409 }
4410 return;
4411 }
4412 size_t wordsize = UNITS_PER_WORD;
4413 for (size_t i = 0; i < end; i += wordsize)
4414 {
4415 size_t nonzero_first = wordsize;
4416 size_t nonzero_last = 0;
4417 size_t zero_first = wordsize;
4418 size_t zero_last = 0;
4419 bool all_ones = true, bytes_only = true;
4420 if ((unsigned HOST_WIDE_INT) (buf->off + i + wordsize)
4421 > (unsigned HOST_WIDE_INT) buf->sz)
4422 {
4423 gcc_assert (wordsize > 1);
4424 wordsize /= 2;
4425 i -= wordsize;
4426 continue;
4427 }
4428 size_t endsize = end - i > wordsize ? wordsize : end - i;
4429 for (size_t j = i; j < i + endsize; j++)
4430 {
4431 if (buf->buf[j])
4432 {
4433 if (nonzero_first == wordsize)
4434 {
4435 nonzero_first = j - i;
4436 nonzero_last = j - i;
4437 }
4438 if (nonzero_last != j - i)
4439 all_ones = false;
4440 nonzero_last = j + 1 - i;
4441 }
4442 else
4443 {
4444 if (zero_first == wordsize)
4445 zero_first = j - i;
4446 zero_last = j + 1 - i;
4447 }
4448 if (buf->buf[j] != 0 && buf->buf[j] != (unsigned char) ~0)
4449 {
4450 all_ones = false;
4451 bytes_only = false;
4452 }
4453 }
4454 size_t padding_end = i;
4455 if (padding_bytes)
4456 {
4457 if (nonzero_first == 0
4458 && nonzero_last == endsize
4459 && all_ones)
4460 {
4461 /* All bits are padding and we had some padding
4462 before too. Just extend it. */
4463 padding_bytes += endsize;
4464 continue;
4465 }
4466 if (all_ones && nonzero_first == 0)
4467 {
4468 padding_bytes += nonzero_last;
4469 padding_end += nonzero_last;
4470 nonzero_first = wordsize;
4471 nonzero_last = 0;
4472 }
4473 else if (bytes_only && nonzero_first == 0)
4474 {
4475 gcc_assert (zero_first && zero_first != wordsize);
4476 padding_bytes += zero_first;
4477 padding_end += zero_first;
4478 }
4479 tree atype, src;
4480 if (padding_bytes == 1)
4481 {
4482 atype = char_type_node;
4483 src = build_zero_cst (char_type_node);
4484 }
4485 else
4486 {
4487 atype = build_array_type_nelts (char_type_node, padding_bytes);
4488 src = build_constructor (atype, NULL);
4489 }
4490 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4491 build_int_cst (buf->alias_type,
4492 buf->off + padding_end
4493 - padding_bytes));
4494 gimple *g = gimple_build_assign (dst, src);
4495 gimple_set_location (g, buf->loc);
4496 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4497 padding_bytes = 0;
4498 buf->padding_bytes = 0;
4499 }
4500 if (nonzero_first == wordsize)
4501 /* All bits in a word are 0, there are no padding bits. */
4502 continue;
4503 if (all_ones && nonzero_last == endsize)
4504 {
4505 /* All bits between nonzero_first and end of word are padding
4506 bits, start counting padding_bytes. */
4507 padding_bytes = nonzero_last - nonzero_first;
4508 continue;
4509 }
4510 if (bytes_only)
4511 {
4512 /* If bitfields aren't involved in this word, prefer storing
4513 individual bytes or groups of them over performing a RMW
4514 operation on the whole word. */
4515 gcc_assert (i + zero_last <= end);
4516 for (size_t j = padding_end; j < i + zero_last; j++)
4517 {
4518 if (buf->buf[j])
4519 {
4520 size_t k;
4521 for (k = j; k < i + zero_last; k++)
4522 if (buf->buf[k] == 0)
4523 break;
4524 HOST_WIDE_INT off = buf->off + j;
4525 tree atype, src;
4526 if (k - j == 1)
4527 {
4528 atype = char_type_node;
4529 src = build_zero_cst (char_type_node);
4530 }
4531 else
4532 {
4533 atype = build_array_type_nelts (char_type_node, k - j);
4534 src = build_constructor (atype, NULL);
4535 }
4536 tree dst = build2_loc (buf->loc, MEM_REF, atype,
4537 buf->base,
4538 build_int_cst (buf->alias_type, off));
4539 gimple *g = gimple_build_assign (dst, src);
4540 gimple_set_location (g, buf->loc);
4541 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4542 j = k;
4543 }
4544 }
4545 if (nonzero_last == endsize)
4546 padding_bytes = nonzero_last - zero_last;
4547 continue;
4548 }
4549 for (size_t eltsz = 1; eltsz <= wordsize; eltsz <<= 1)
4550 {
4551 if (nonzero_last - nonzero_first <= eltsz
4552 && ((nonzero_first & ~(eltsz - 1))
4553 == ((nonzero_last - 1) & ~(eltsz - 1))))
4554 {
4555 tree type;
4556 if (eltsz == 1)
4557 type = char_type_node;
4558 else
4559 type = lang_hooks.types.type_for_size (eltsz * BITS_PER_UNIT,
4560 0);
4561 size_t start = nonzero_first & ~(eltsz - 1);
4562 HOST_WIDE_INT off = buf->off + i + start;
4563 tree atype = type;
4564 if (eltsz > 1 && buf->align < TYPE_ALIGN (type))
4565 atype = build_aligned_type (type, buf->align);
4566 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4567 build_int_cst (buf->alias_type, off));
4568 tree src;
4569 gimple *g;
4570 if (all_ones
4571 && nonzero_first == start
4572 && nonzero_last == start + eltsz)
4573 src = build_zero_cst (type);
4574 else
4575 {
4576 src = make_ssa_name (type);
4577 tree tmp_dst = unshare_expr (dst);
4578 /* The folding introduces a read from the tmp_dst, we should
4579 prevent uninitialized warning analysis from issuing warning
4580 for such fake read. In order to suppress warning only for
4581 this expr, we should set the location of tmp_dst to
4582 UNKNOWN_LOCATION first, then suppress_warning will call
4583 set_no_warning_bit to set the no_warning flag only for
4584 tmp_dst. */
4585 SET_EXPR_LOCATION (tmp_dst, UNKNOWN_LOCATION);
4586 suppress_warning (tmp_dst, OPT_Wuninitialized);
4587 g = gimple_build_assign (src, tmp_dst);
4588 gimple_set_location (g, buf->loc);
4589 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4590 tree mask = native_interpret_expr (type,
4591 buf->buf + i + start,
4592 eltsz);
4593 gcc_assert (mask && TREE_CODE (mask) == INTEGER_CST);
4594 mask = fold_build1 (BIT_NOT_EXPR, type, mask);
4595 tree src_masked = make_ssa_name (type);
4596 g = gimple_build_assign (src_masked, BIT_AND_EXPR,
4597 src, mask);
4598 gimple_set_location (g, buf->loc);
4599 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4600 src = src_masked;
4601 }
4602 g = gimple_build_assign (dst, src);
4603 gimple_set_location (g, buf->loc);
4604 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4605 break;
4606 }
4607 }
4608 }
4609 if (full)
4610 {
4611 if (padding_bytes)
4612 {
4613 tree atype, src;
4614 if (padding_bytes == 1)
4615 {
4616 atype = char_type_node;
4617 src = build_zero_cst (char_type_node);
4618 }
4619 else
4620 {
4621 atype = build_array_type_nelts (char_type_node, padding_bytes);
4622 src = build_constructor (atype, NULL);
4623 }
4624 tree dst = build2_loc (buf->loc, MEM_REF, atype, buf->base,
4625 build_int_cst (buf->alias_type,
4626 buf->off + end
4627 - padding_bytes));
4628 gimple *g = gimple_build_assign (dst, src);
4629 gimple_set_location (g, buf->loc);
4630 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4631 }
4632 size_t end_rem = end % UNITS_PER_WORD;
4633 buf->off += end - end_rem;
4634 buf->size = end_rem;
4635 memset (buf->buf, 0, buf->size);
4636 buf->padding_bytes = 0;
4637 }
4638 else
4639 {
4640 memmove (buf->buf, buf->buf + end, buf->size - end);
4641 buf->off += end;
4642 buf->size -= end;
4643 buf->padding_bytes = padding_bytes;
4644 }
4645 }
4646
4647 /* Append PADDING_BYTES padding bytes. */
4648
4649 static void
4650 clear_padding_add_padding (clear_padding_struct *buf,
4651 HOST_WIDE_INT padding_bytes)
4652 {
4653 if (padding_bytes == 0)
4654 return;
4655 if ((unsigned HOST_WIDE_INT) padding_bytes + buf->size
4656 > (unsigned HOST_WIDE_INT) clear_padding_buf_size)
4657 clear_padding_flush (buf, false);
4658 if ((unsigned HOST_WIDE_INT) padding_bytes + buf->size
4659 > (unsigned HOST_WIDE_INT) clear_padding_buf_size)
4660 {
4661 memset (buf->buf + buf->size, ~0, clear_padding_buf_size - buf->size);
4662 padding_bytes -= clear_padding_buf_size - buf->size;
4663 buf->size = clear_padding_buf_size;
4664 clear_padding_flush (buf, false);
4665 gcc_assert (buf->padding_bytes);
4666 /* At this point buf->buf[0] through buf->buf[buf->size - 1]
4667 is guaranteed to be all ones. */
4668 padding_bytes += buf->size;
4669 buf->size = padding_bytes % UNITS_PER_WORD;
4670 memset (buf->buf, ~0, buf->size);
4671 buf->off += padding_bytes - buf->size;
4672 buf->padding_bytes += padding_bytes - buf->size;
4673 }
4674 else
4675 {
4676 memset (buf->buf + buf->size, ~0, padding_bytes);
4677 buf->size += padding_bytes;
4678 }
4679 }
4680
4681 static void clear_padding_type (clear_padding_struct *, tree,
4682 HOST_WIDE_INT, bool);
4683
4684 /* Clear padding bits of union type TYPE. */
4685
4686 static void
4687 clear_padding_union (clear_padding_struct *buf, tree type,
4688 HOST_WIDE_INT sz, bool for_auto_init)
4689 {
4690 clear_padding_struct *union_buf;
4691 HOST_WIDE_INT start_off = 0, next_off = 0;
4692 size_t start_size = 0;
4693 if (buf->union_ptr)
4694 {
4695 start_off = buf->off + buf->size;
4696 next_off = start_off + sz;
4697 start_size = start_off % UNITS_PER_WORD;
4698 start_off -= start_size;
4699 clear_padding_flush (buf, true);
4700 union_buf = buf;
4701 }
4702 else
4703 {
4704 if (sz + buf->size > clear_padding_buf_size)
4705 clear_padding_flush (buf, false);
4706 union_buf = XALLOCA (clear_padding_struct);
4707 union_buf->loc = buf->loc;
4708 union_buf->clear_in_mask = buf->clear_in_mask;
4709 union_buf->base = NULL_TREE;
4710 union_buf->alias_type = NULL_TREE;
4711 union_buf->gsi = NULL;
4712 union_buf->align = 0;
4713 union_buf->off = 0;
4714 union_buf->padding_bytes = 0;
4715 union_buf->sz = sz;
4716 union_buf->size = 0;
4717 if (sz + buf->size <= clear_padding_buf_size)
4718 union_buf->union_ptr = buf->buf + buf->size;
4719 else
4720 union_buf->union_ptr = XNEWVEC (unsigned char, sz);
4721 memset (union_buf->union_ptr, ~0, sz);
4722 }
4723
4724 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4725 if (TREE_CODE (field) == FIELD_DECL && !DECL_PADDING_P (field))
4726 {
4727 if (DECL_SIZE_UNIT (field) == NULL_TREE)
4728 {
4729 if (TREE_TYPE (field) == error_mark_node)
4730 continue;
4731 gcc_assert (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE
4732 && !COMPLETE_TYPE_P (TREE_TYPE (field)));
4733 if (!buf->clear_in_mask && !for_auto_init)
4734 error_at (buf->loc, "flexible array member %qD does not have "
4735 "well defined padding bits for %qs",
4736 field, "__builtin_clear_padding");
4737 continue;
4738 }
4739 HOST_WIDE_INT fldsz = tree_to_shwi (DECL_SIZE_UNIT (field));
4740 gcc_assert (union_buf->size == 0);
4741 union_buf->off = start_off;
4742 union_buf->size = start_size;
4743 memset (union_buf->buf, ~0, start_size);
4744 clear_padding_type (union_buf, TREE_TYPE (field), fldsz, for_auto_init);
4745 clear_padding_add_padding (union_buf, sz - fldsz);
4746 clear_padding_flush (union_buf, true);
4747 }
4748
4749 if (buf == union_buf)
4750 {
4751 buf->off = next_off;
4752 buf->size = next_off % UNITS_PER_WORD;
4753 buf->off -= buf->size;
4754 memset (buf->buf, ~0, buf->size);
4755 }
4756 else if (sz + buf->size <= clear_padding_buf_size)
4757 buf->size += sz;
4758 else
4759 {
4760 unsigned char *union_ptr = union_buf->union_ptr;
4761 while (sz)
4762 {
4763 clear_padding_flush (buf, false);
4764 HOST_WIDE_INT this_sz
4765 = MIN ((unsigned HOST_WIDE_INT) sz,
4766 clear_padding_buf_size - buf->size);
4767 memcpy (buf->buf + buf->size, union_ptr, this_sz);
4768 buf->size += this_sz;
4769 union_ptr += this_sz;
4770 sz -= this_sz;
4771 }
4772 XDELETE (union_buf->union_ptr);
4773 }
4774 }
4775
4776 /* The only known floating point formats with padding bits are the
4777 IEEE extended ones. */
4778
4779 static bool
4780 clear_padding_real_needs_padding_p (tree type)
4781 {
4782 const struct real_format *fmt = REAL_MODE_FORMAT (TYPE_MODE (type));
4783 return (fmt->b == 2
4784 && fmt->signbit_ro == fmt->signbit_rw
4785 && (fmt->signbit_ro == 79 || fmt->signbit_ro == 95));
4786 }
4787
4788 /* _BitInt has padding bits if it isn't extended in the ABI and has smaller
4789 precision than bits in limb or corresponding number of limbs. */
4790
4791 static bool
4792 clear_padding_bitint_needs_padding_p (tree type)
4793 {
4794 struct bitint_info info;
4795 bool ok = targetm.c.bitint_type_info (TYPE_PRECISION (type), &info);
4796 gcc_assert (ok);
4797 if (info.extended)
4798 return false;
4799 scalar_int_mode limb_mode = as_a <scalar_int_mode> (info.abi_limb_mode);
4800 if (TYPE_PRECISION (type) < GET_MODE_PRECISION (limb_mode))
4801 return true;
4802 else if (TYPE_PRECISION (type) == GET_MODE_PRECISION (limb_mode))
4803 return false;
4804 else
4805 return (((unsigned) TYPE_PRECISION (type))
4806 % GET_MODE_PRECISION (limb_mode)) != 0;
4807 }
4808
4809 /* Return true if TYPE might contain any padding bits. */
4810
4811 bool
4812 clear_padding_type_may_have_padding_p (tree type)
4813 {
4814 switch (TREE_CODE (type))
4815 {
4816 case RECORD_TYPE:
4817 case UNION_TYPE:
4818 return true;
4819 case ARRAY_TYPE:
4820 case COMPLEX_TYPE:
4821 case VECTOR_TYPE:
4822 return clear_padding_type_may_have_padding_p (TREE_TYPE (type));
4823 case REAL_TYPE:
4824 return clear_padding_real_needs_padding_p (type);
4825 case BITINT_TYPE:
4826 return clear_padding_bitint_needs_padding_p (type);
4827 default:
4828 return false;
4829 }
4830 }
4831
4832 /* Return true if TYPE has padding bits aside from those in fields,
4833 elements, etc. */
4834
4835 bool
4836 type_has_padding_at_level_p (tree type)
4837 {
4838 switch (TREE_CODE (type))
4839 {
4840 case RECORD_TYPE:
4841 {
4842 tree bitpos = size_zero_node;
4843 /* Expect fields to be sorted by bit position. */
4844 for (tree f = TYPE_FIELDS (type); f; f = DECL_CHAIN (f))
4845 if (TREE_CODE (f) == FIELD_DECL)
4846 {
4847 if (DECL_PADDING_P (f))
4848 return true;
4849 tree pos = bit_position (f);
4850 if (simple_cst_equal (bitpos, pos) != 1)
4851 return true;
4852 if (!DECL_SIZE (f))
4853 return true;
4854 bitpos = int_const_binop (PLUS_EXPR, pos, DECL_SIZE (f));
4855 }
4856 if (simple_cst_equal (bitpos, TYPE_SIZE (type)) != 1)
4857 return true;
4858 return false;
4859 }
4860 case UNION_TYPE:
4861 case QUAL_UNION_TYPE:
4862 bool any_fields;
4863 any_fields = false;
4864 /* If any of the fields is smaller than the whole, there is padding. */
4865 for (tree f = TYPE_FIELDS (type); f; f = DECL_CHAIN (f))
4866 if (TREE_CODE (f) != FIELD_DECL || TREE_TYPE (f) == error_mark_node)
4867 continue;
4868 else if (simple_cst_equal (TYPE_SIZE (TREE_TYPE (f)),
4869 TYPE_SIZE (type)) != 1)
4870 return true;
4871 else
4872 any_fields = true;
4873 /* If the union doesn't have any fields and still has non-zero size,
4874 all of it is padding. */
4875 if (!any_fields && !integer_zerop (TYPE_SIZE (type)))
4876 return true;
4877 return false;
4878 case ARRAY_TYPE:
4879 case COMPLEX_TYPE:
4880 case VECTOR_TYPE:
4881 /* No recursing here, no padding at this level. */
4882 return false;
4883 case REAL_TYPE:
4884 return clear_padding_real_needs_padding_p (type);
4885 case BITINT_TYPE:
4886 return clear_padding_bitint_needs_padding_p (type);
4887 default:
4888 return false;
4889 }
4890 }
4891
4892 /* Emit a runtime loop:
4893 for (; buf.base != end; buf.base += sz)
4894 __builtin_clear_padding (buf.base); */
4895
4896 static void
4897 clear_padding_emit_loop (clear_padding_struct *buf, tree type,
4898 tree end, bool for_auto_init)
4899 {
4900 tree l1 = create_artificial_label (buf->loc);
4901 tree l2 = create_artificial_label (buf->loc);
4902 tree l3 = create_artificial_label (buf->loc);
4903 gimple *g = gimple_build_goto (l2);
4904 gimple_set_location (g, buf->loc);
4905 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4906 g = gimple_build_label (l1);
4907 gimple_set_location (g, buf->loc);
4908 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4909 clear_padding_type (buf, type, buf->sz, for_auto_init);
4910 clear_padding_flush (buf, true);
4911 g = gimple_build_assign (buf->base, POINTER_PLUS_EXPR, buf->base,
4912 size_int (buf->sz));
4913 gimple_set_location (g, buf->loc);
4914 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4915 g = gimple_build_label (l2);
4916 gimple_set_location (g, buf->loc);
4917 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4918 g = gimple_build_cond (NE_EXPR, buf->base, end, l1, l3);
4919 gimple_set_location (g, buf->loc);
4920 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4921 g = gimple_build_label (l3);
4922 gimple_set_location (g, buf->loc);
4923 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
4924 }
4925
4926 /* Clear padding bits for TYPE. Called recursively from
4927 gimple_fold_builtin_clear_padding. If FOR_AUTO_INIT is true,
4928 the __builtin_clear_padding is not called by the end user,
4929 instead, it's inserted by the compiler to initialize the
4930 paddings of automatic variable. Therefore, we should not
4931 emit the error messages for flexible array members to confuse
4932 the end user. */
4933
4934 static void
4935 clear_padding_type (clear_padding_struct *buf, tree type,
4936 HOST_WIDE_INT sz, bool for_auto_init)
4937 {
4938 switch (TREE_CODE (type))
4939 {
4940 case RECORD_TYPE:
4941 HOST_WIDE_INT cur_pos;
4942 cur_pos = 0;
4943 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4944 if (TREE_CODE (field) == FIELD_DECL && !DECL_PADDING_P (field))
4945 {
4946 tree ftype = TREE_TYPE (field);
4947 if (DECL_BIT_FIELD (field))
4948 {
4949 HOST_WIDE_INT fldsz = TYPE_PRECISION (ftype);
4950 if (fldsz == 0)
4951 continue;
4952 HOST_WIDE_INT pos = int_byte_position (field);
4953 if (pos >= sz)
4954 continue;
4955 HOST_WIDE_INT bpos
4956 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
4957 bpos %= BITS_PER_UNIT;
4958 HOST_WIDE_INT end
4959 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4960 if (pos + end > cur_pos)
4961 {
4962 clear_padding_add_padding (buf, pos + end - cur_pos);
4963 cur_pos = pos + end;
4964 }
4965 gcc_assert (cur_pos > pos
4966 && ((unsigned HOST_WIDE_INT) buf->size
4967 >= (unsigned HOST_WIDE_INT) cur_pos - pos));
4968 unsigned char *p = buf->buf + buf->size - (cur_pos - pos);
4969 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4970 sorry_at (buf->loc, "PDP11 bit-field handling unsupported"
4971 " in %qs", "__builtin_clear_padding");
4972 else if (BYTES_BIG_ENDIAN)
4973 {
4974 /* Big endian. */
4975 if (bpos + fldsz <= BITS_PER_UNIT)
4976 *p &= ~(((1 << fldsz) - 1)
4977 << (BITS_PER_UNIT - bpos - fldsz));
4978 else
4979 {
4980 if (bpos)
4981 {
4982 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4983 p++;
4984 fldsz -= BITS_PER_UNIT - bpos;
4985 }
4986 memset (p, 0, fldsz / BITS_PER_UNIT);
4987 p += fldsz / BITS_PER_UNIT;
4988 fldsz %= BITS_PER_UNIT;
4989 if (fldsz)
4990 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4991 }
4992 }
4993 else
4994 {
4995 /* Little endian. */
4996 if (bpos + fldsz <= BITS_PER_UNIT)
4997 *p &= ~(((1 << fldsz) - 1) << bpos);
4998 else
4999 {
5000 if (bpos)
5001 {
5002 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
5003 p++;
5004 fldsz -= BITS_PER_UNIT - bpos;
5005 }
5006 memset (p, 0, fldsz / BITS_PER_UNIT);
5007 p += fldsz / BITS_PER_UNIT;
5008 fldsz %= BITS_PER_UNIT;
5009 if (fldsz)
5010 *p &= ~((1 << fldsz) - 1);
5011 }
5012 }
5013 }
5014 else if (DECL_SIZE_UNIT (field) == NULL_TREE)
5015 {
5016 if (ftype == error_mark_node)
5017 continue;
5018 gcc_assert (TREE_CODE (ftype) == ARRAY_TYPE
5019 && !COMPLETE_TYPE_P (ftype));
5020 if (!buf->clear_in_mask && !for_auto_init)
5021 error_at (buf->loc, "flexible array member %qD does not "
5022 "have well defined padding bits for %qs",
5023 field, "__builtin_clear_padding");
5024 }
5025 else if (is_empty_type (ftype))
5026 continue;
5027 else
5028 {
5029 HOST_WIDE_INT pos = int_byte_position (field);
5030 if (pos >= sz)
5031 continue;
5032 HOST_WIDE_INT fldsz = tree_to_shwi (DECL_SIZE_UNIT (field));
5033 gcc_assert (pos >= 0 && fldsz >= 0 && pos >= cur_pos);
5034 clear_padding_add_padding (buf, pos - cur_pos);
5035 cur_pos = pos;
5036 if (tree asbase = lang_hooks.types.classtype_as_base (field))
5037 ftype = asbase;
5038 clear_padding_type (buf, ftype, fldsz, for_auto_init);
5039 cur_pos += fldsz;
5040 }
5041 }
5042 gcc_assert (sz >= cur_pos);
5043 clear_padding_add_padding (buf, sz - cur_pos);
5044 break;
5045 case ARRAY_TYPE:
5046 HOST_WIDE_INT nelts, fldsz;
5047 fldsz = int_size_in_bytes (TREE_TYPE (type));
5048 if (fldsz == 0)
5049 break;
5050 nelts = sz / fldsz;
5051 if (nelts > 1
5052 && sz > 8 * UNITS_PER_WORD
5053 && buf->union_ptr == NULL
5054 && clear_padding_type_may_have_padding_p (TREE_TYPE (type)))
5055 {
5056 /* For sufficiently large array of more than one elements,
5057 emit a runtime loop to keep code size manageable. */
5058 tree base = buf->base;
5059 unsigned int prev_align = buf->align;
5060 HOST_WIDE_INT off = buf->off + buf->size;
5061 HOST_WIDE_INT prev_sz = buf->sz;
5062 clear_padding_flush (buf, true);
5063 tree elttype = TREE_TYPE (type);
5064 buf->base = create_tmp_var (build_pointer_type (elttype));
5065 tree end = make_ssa_name (TREE_TYPE (buf->base));
5066 gimple *g = gimple_build_assign (buf->base, POINTER_PLUS_EXPR,
5067 base, size_int (off));
5068 gimple_set_location (g, buf->loc);
5069 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
5070 g = gimple_build_assign (end, POINTER_PLUS_EXPR, buf->base,
5071 size_int (sz));
5072 gimple_set_location (g, buf->loc);
5073 gsi_insert_before (buf->gsi, g, GSI_SAME_STMT);
5074 buf->sz = fldsz;
5075 buf->align = TYPE_ALIGN (elttype);
5076 buf->off = 0;
5077 buf->size = 0;
5078 clear_padding_emit_loop (buf, elttype, end, for_auto_init);
5079 off += sz;
5080 buf->base = base;
5081 buf->sz = prev_sz;
5082 buf->align = prev_align;
5083 buf->size = off % UNITS_PER_WORD;
5084 buf->off = off - buf->size;
5085 memset (buf->buf, 0, buf->size);
5086 break;
5087 }
5088 for (HOST_WIDE_INT i = 0; i < nelts; i++)
5089 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
5090 break;
5091 case UNION_TYPE:
5092 clear_padding_union (buf, type, sz, for_auto_init);
5093 break;
5094 case REAL_TYPE:
5095 gcc_assert ((size_t) sz <= clear_padding_unit);
5096 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
5097 clear_padding_flush (buf, false);
5098 if (clear_padding_real_needs_padding_p (type))
5099 {
5100 /* Use native_interpret_real + native_encode_expr to figure out
5101 which bits are padding. */
5102 memset (buf->buf + buf->size, ~0, sz);
5103 tree cst = native_interpret_real (type, buf->buf + buf->size, sz);
5104 gcc_assert (cst && TREE_CODE (cst) == REAL_CST);
5105 int len = native_encode_expr (cst, buf->buf + buf->size, sz);
5106 gcc_assert (len > 0 && (size_t) len == (size_t) sz);
5107 for (size_t i = 0; i < (size_t) sz; i++)
5108 buf->buf[buf->size + i] ^= ~0;
5109 }
5110 else
5111 memset (buf->buf + buf->size, 0, sz);
5112 buf->size += sz;
5113 break;
5114 case COMPLEX_TYPE:
5115 fldsz = int_size_in_bytes (TREE_TYPE (type));
5116 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
5117 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
5118 break;
5119 case VECTOR_TYPE:
5120 nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
5121 fldsz = int_size_in_bytes (TREE_TYPE (type));
5122 for (HOST_WIDE_INT i = 0; i < nelts; i++)
5123 clear_padding_type (buf, TREE_TYPE (type), fldsz, for_auto_init);
5124 break;
5125 case NULLPTR_TYPE:
5126 gcc_assert ((size_t) sz <= clear_padding_unit);
5127 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
5128 clear_padding_flush (buf, false);
5129 memset (buf->buf + buf->size, ~0, sz);
5130 buf->size += sz;
5131 break;
5132 case BITINT_TYPE:
5133 {
5134 struct bitint_info info;
5135 bool ok = targetm.c.bitint_type_info (TYPE_PRECISION (type), &info);
5136 gcc_assert (ok);
5137 scalar_int_mode limb_mode
5138 = as_a <scalar_int_mode> (info.abi_limb_mode);
5139 if (TYPE_PRECISION (type) <= GET_MODE_PRECISION (limb_mode))
5140 {
5141 gcc_assert ((size_t) sz <= clear_padding_unit);
5142 if ((unsigned HOST_WIDE_INT) sz + buf->size
5143 > clear_padding_buf_size)
5144 clear_padding_flush (buf, false);
5145 if (!info.extended
5146 && TYPE_PRECISION (type) < GET_MODE_PRECISION (limb_mode))
5147 {
5148 int tprec = GET_MODE_PRECISION (limb_mode);
5149 int prec = TYPE_PRECISION (type);
5150 tree t = build_nonstandard_integer_type (tprec, 1);
5151 tree cst = wide_int_to_tree (t, wi::mask (prec, true, tprec));
5152 int len = native_encode_expr (cst, buf->buf + buf->size, sz);
5153 gcc_assert (len > 0 && (size_t) len == (size_t) sz);
5154 }
5155 else
5156 memset (buf->buf + buf->size, 0, sz);
5157 buf->size += sz;
5158 break;
5159 }
5160 tree limbtype
5161 = build_nonstandard_integer_type (GET_MODE_PRECISION (limb_mode), 1);
5162 fldsz = int_size_in_bytes (limbtype);
5163 nelts = int_size_in_bytes (type) / fldsz;
5164 for (HOST_WIDE_INT i = 0; i < nelts; i++)
5165 {
5166 if (!info.extended
5167 && i == (info.big_endian ? 0 : nelts - 1)
5168 && (((unsigned) TYPE_PRECISION (type))
5169 % TYPE_PRECISION (limbtype)) != 0)
5170 {
5171 int tprec = GET_MODE_PRECISION (limb_mode);
5172 int prec = (((unsigned) TYPE_PRECISION (type)) % tprec);
5173 tree cst = wide_int_to_tree (limbtype,
5174 wi::mask (prec, true, tprec));
5175 int len = native_encode_expr (cst, buf->buf + buf->size,
5176 fldsz);
5177 gcc_assert (len > 0 && (size_t) len == (size_t) fldsz);
5178 buf->size += fldsz;
5179 }
5180 else
5181 clear_padding_type (buf, limbtype, fldsz, for_auto_init);
5182 }
5183 break;
5184 }
5185 default:
5186 gcc_assert ((size_t) sz <= clear_padding_unit);
5187 if ((unsigned HOST_WIDE_INT) sz + buf->size > clear_padding_buf_size)
5188 clear_padding_flush (buf, false);
5189 memset (buf->buf + buf->size, 0, sz);
5190 buf->size += sz;
5191 break;
5192 }
5193 }
5194
5195 /* Clear padding bits of TYPE in MASK. */
5196
5197 void
5198 clear_type_padding_in_mask (tree type, unsigned char *mask)
5199 {
5200 clear_padding_struct buf;
5201 buf.loc = UNKNOWN_LOCATION;
5202 buf.clear_in_mask = true;
5203 buf.base = NULL_TREE;
5204 buf.alias_type = NULL_TREE;
5205 buf.gsi = NULL;
5206 buf.align = 0;
5207 buf.off = 0;
5208 buf.padding_bytes = 0;
5209 buf.sz = int_size_in_bytes (type);
5210 buf.size = 0;
5211 buf.union_ptr = mask;
5212 clear_padding_type (&buf, type, buf.sz, false);
5213 clear_padding_flush (&buf, true);
5214 }
5215
5216 /* Fold __builtin_clear_padding builtin. */
5217
5218 static bool
5219 gimple_fold_builtin_clear_padding (gimple_stmt_iterator *gsi)
5220 {
5221 gimple *stmt = gsi_stmt (*gsi);
5222 gcc_assert (gimple_call_num_args (stmt) == 2);
5223 tree ptr = gimple_call_arg (stmt, 0);
5224 tree typearg = gimple_call_arg (stmt, 1);
5225 /* The 2nd argument of __builtin_clear_padding's value is used to
5226 distinguish whether this call is made by the user or by the compiler
5227 for automatic variable initialization. */
5228 bool for_auto_init = (bool) TREE_INT_CST_LOW (typearg);
5229 tree type = TREE_TYPE (TREE_TYPE (typearg));
5230 location_t loc = gimple_location (stmt);
5231 clear_padding_struct buf;
5232 gimple_stmt_iterator gsiprev = *gsi;
5233 /* This should be folded during the lower pass. */
5234 gcc_assert (!gimple_in_ssa_p (cfun) && cfun->cfg == NULL);
5235 gcc_assert (COMPLETE_TYPE_P (type));
5236 gsi_prev (&gsiprev);
5237
5238 buf.loc = loc;
5239 buf.clear_in_mask = false;
5240 buf.base = ptr;
5241 buf.alias_type = NULL_TREE;
5242 buf.gsi = gsi;
5243 buf.align = get_pointer_alignment (ptr);
5244 unsigned int talign = min_align_of_type (type) * BITS_PER_UNIT;
5245 buf.align = MAX (buf.align, talign);
5246 buf.off = 0;
5247 buf.padding_bytes = 0;
5248 buf.size = 0;
5249 buf.sz = int_size_in_bytes (type);
5250 buf.union_ptr = NULL;
5251 if (buf.sz < 0 && int_size_in_bytes (strip_array_types (type)) < 0)
5252 sorry_at (loc, "%s not supported for variable length aggregates",
5253 "__builtin_clear_padding");
5254 /* The implementation currently assumes 8-bit host and target
5255 chars which is the case for all currently supported targets
5256 and hosts and is required e.g. for native_{encode,interpret}* APIs. */
5257 else if (CHAR_BIT != 8 || BITS_PER_UNIT != 8)
5258 sorry_at (loc, "%s not supported on this target",
5259 "__builtin_clear_padding");
5260 else if (!clear_padding_type_may_have_padding_p (type))
5261 ;
5262 else if (TREE_CODE (type) == ARRAY_TYPE && buf.sz < 0)
5263 {
5264 tree sz = TYPE_SIZE_UNIT (type);
5265 tree elttype = type;
5266 /* Only supports C/C++ VLAs and flattens all the VLA levels. */
5267 while (TREE_CODE (elttype) == ARRAY_TYPE
5268 && int_size_in_bytes (elttype) < 0)
5269 elttype = TREE_TYPE (elttype);
5270 HOST_WIDE_INT eltsz = int_size_in_bytes (elttype);
5271 gcc_assert (eltsz >= 0);
5272 if (eltsz)
5273 {
5274 buf.base = create_tmp_var (build_pointer_type (elttype));
5275 tree end = make_ssa_name (TREE_TYPE (buf.base));
5276 gimple *g = gimple_build_assign (buf.base, ptr);
5277 gimple_set_location (g, loc);
5278 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5279 g = gimple_build_assign (end, POINTER_PLUS_EXPR, buf.base, sz);
5280 gimple_set_location (g, loc);
5281 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5282 buf.sz = eltsz;
5283 buf.align = TYPE_ALIGN (elttype);
5284 buf.alias_type = build_pointer_type (elttype);
5285 clear_padding_emit_loop (&buf, elttype, end, for_auto_init);
5286 }
5287 }
5288 else
5289 {
5290 if (!is_gimple_mem_ref_addr (buf.base))
5291 {
5292 buf.base = make_ssa_name (TREE_TYPE (ptr));
5293 gimple *g = gimple_build_assign (buf.base, ptr);
5294 gimple_set_location (g, loc);
5295 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5296 }
5297 buf.alias_type = build_pointer_type (type);
5298 clear_padding_type (&buf, type, buf.sz, for_auto_init);
5299 clear_padding_flush (&buf, true);
5300 }
5301
5302 gimple_stmt_iterator gsiprev2 = *gsi;
5303 gsi_prev (&gsiprev2);
5304 if (gsi_stmt (gsiprev) == gsi_stmt (gsiprev2))
5305 gsi_replace (gsi, gimple_build_nop (), true);
5306 else
5307 {
5308 gsi_remove (gsi, true);
5309 *gsi = gsiprev2;
5310 }
5311 return true;
5312 }
5313
5314 /* Fold the non-target builtin at *GSI and return whether any simplification
5315 was made. */
5316
5317 static bool
5318 gimple_fold_builtin (gimple_stmt_iterator *gsi)
5319 {
5320 gcall *stmt = as_a <gcall *>(gsi_stmt (*gsi));
5321 tree callee = gimple_call_fndecl (stmt);
5322
5323 /* Give up for always_inline inline builtins until they are
5324 inlined. */
5325 if (avoid_folding_inline_builtin (callee))
5326 return false;
5327
5328 unsigned n = gimple_call_num_args (stmt);
5329 enum built_in_function fcode = DECL_FUNCTION_CODE (callee);
5330 switch (fcode)
5331 {
5332 case BUILT_IN_BCMP:
5333 return gimple_fold_builtin_bcmp (gsi);
5334 case BUILT_IN_BCOPY:
5335 return gimple_fold_builtin_bcopy (gsi);
5336 case BUILT_IN_BZERO:
5337 return gimple_fold_builtin_bzero (gsi);
5338
5339 case BUILT_IN_MEMSET:
5340 return gimple_fold_builtin_memset (gsi,
5341 gimple_call_arg (stmt, 1),
5342 gimple_call_arg (stmt, 2));
5343 case BUILT_IN_MEMCPY:
5344 case BUILT_IN_MEMPCPY:
5345 case BUILT_IN_MEMMOVE:
5346 return gimple_fold_builtin_memory_op (gsi, gimple_call_arg (stmt, 0),
5347 gimple_call_arg (stmt, 1), fcode);
5348 case BUILT_IN_SPRINTF_CHK:
5349 case BUILT_IN_VSPRINTF_CHK:
5350 return gimple_fold_builtin_sprintf_chk (gsi, fcode);
5351 case BUILT_IN_STRCAT_CHK:
5352 return gimple_fold_builtin_strcat_chk (gsi);
5353 case BUILT_IN_STRNCAT_CHK:
5354 return gimple_fold_builtin_strncat_chk (gsi);
5355 case BUILT_IN_STRLEN:
5356 return gimple_fold_builtin_strlen (gsi);
5357 case BUILT_IN_STRCPY:
5358 return gimple_fold_builtin_strcpy (gsi,
5359 gimple_call_arg (stmt, 0),
5360 gimple_call_arg (stmt, 1));
5361 case BUILT_IN_STRNCPY:
5362 return gimple_fold_builtin_strncpy (gsi,
5363 gimple_call_arg (stmt, 0),
5364 gimple_call_arg (stmt, 1),
5365 gimple_call_arg (stmt, 2));
5366 case BUILT_IN_STRCAT:
5367 return gimple_fold_builtin_strcat (gsi, gimple_call_arg (stmt, 0),
5368 gimple_call_arg (stmt, 1));
5369 case BUILT_IN_STRNCAT:
5370 return gimple_fold_builtin_strncat (gsi);
5371 case BUILT_IN_INDEX:
5372 case BUILT_IN_STRCHR:
5373 return gimple_fold_builtin_strchr (gsi, false);
5374 case BUILT_IN_RINDEX:
5375 case BUILT_IN_STRRCHR:
5376 return gimple_fold_builtin_strchr (gsi, true);
5377 case BUILT_IN_STRSTR:
5378 return gimple_fold_builtin_strstr (gsi);
5379 case BUILT_IN_STRCMP:
5380 case BUILT_IN_STRCMP_EQ:
5381 case BUILT_IN_STRCASECMP:
5382 case BUILT_IN_STRNCMP:
5383 case BUILT_IN_STRNCMP_EQ:
5384 case BUILT_IN_STRNCASECMP:
5385 return gimple_fold_builtin_string_compare (gsi);
5386 case BUILT_IN_MEMCHR:
5387 return gimple_fold_builtin_memchr (gsi);
5388 case BUILT_IN_FPUTS:
5389 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
5390 gimple_call_arg (stmt, 1), false);
5391 case BUILT_IN_FPUTS_UNLOCKED:
5392 return gimple_fold_builtin_fputs (gsi, gimple_call_arg (stmt, 0),
5393 gimple_call_arg (stmt, 1), true);
5394 case BUILT_IN_MEMCPY_CHK:
5395 case BUILT_IN_MEMPCPY_CHK:
5396 case BUILT_IN_MEMMOVE_CHK:
5397 case BUILT_IN_MEMSET_CHK:
5398 return gimple_fold_builtin_memory_chk (gsi,
5399 gimple_call_arg (stmt, 0),
5400 gimple_call_arg (stmt, 1),
5401 gimple_call_arg (stmt, 2),
5402 gimple_call_arg (stmt, 3),
5403 fcode);
5404 case BUILT_IN_STPCPY:
5405 return gimple_fold_builtin_stpcpy (gsi);
5406 case BUILT_IN_STRCPY_CHK:
5407 case BUILT_IN_STPCPY_CHK:
5408 return gimple_fold_builtin_stxcpy_chk (gsi,
5409 gimple_call_arg (stmt, 0),
5410 gimple_call_arg (stmt, 1),
5411 gimple_call_arg (stmt, 2),
5412 fcode);
5413 case BUILT_IN_STRNCPY_CHK:
5414 case BUILT_IN_STPNCPY_CHK:
5415 return gimple_fold_builtin_stxncpy_chk (gsi,
5416 gimple_call_arg (stmt, 0),
5417 gimple_call_arg (stmt, 1),
5418 gimple_call_arg (stmt, 2),
5419 gimple_call_arg (stmt, 3),
5420 fcode);
5421 case BUILT_IN_SNPRINTF_CHK:
5422 case BUILT_IN_VSNPRINTF_CHK:
5423 return gimple_fold_builtin_snprintf_chk (gsi, fcode);
5424
5425 case BUILT_IN_FPRINTF:
5426 case BUILT_IN_FPRINTF_UNLOCKED:
5427 case BUILT_IN_VFPRINTF:
5428 if (n == 2 || n == 3)
5429 return gimple_fold_builtin_fprintf (gsi,
5430 gimple_call_arg (stmt, 0),
5431 gimple_call_arg (stmt, 1),
5432 n == 3
5433 ? gimple_call_arg (stmt, 2)
5434 : NULL_TREE,
5435 fcode);
5436 break;
5437 case BUILT_IN_FPRINTF_CHK:
5438 case BUILT_IN_VFPRINTF_CHK:
5439 if (n == 3 || n == 4)
5440 return gimple_fold_builtin_fprintf (gsi,
5441 gimple_call_arg (stmt, 0),
5442 gimple_call_arg (stmt, 2),
5443 n == 4
5444 ? gimple_call_arg (stmt, 3)
5445 : NULL_TREE,
5446 fcode);
5447 break;
5448 case BUILT_IN_PRINTF:
5449 case BUILT_IN_PRINTF_UNLOCKED:
5450 case BUILT_IN_VPRINTF:
5451 if (n == 1 || n == 2)
5452 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 0),
5453 n == 2
5454 ? gimple_call_arg (stmt, 1)
5455 : NULL_TREE, fcode);
5456 break;
5457 case BUILT_IN_PRINTF_CHK:
5458 case BUILT_IN_VPRINTF_CHK:
5459 if (n == 2 || n == 3)
5460 return gimple_fold_builtin_printf (gsi, gimple_call_arg (stmt, 1),
5461 n == 3
5462 ? gimple_call_arg (stmt, 2)
5463 : NULL_TREE, fcode);
5464 break;
5465 case BUILT_IN_ACC_ON_DEVICE:
5466 return gimple_fold_builtin_acc_on_device (gsi,
5467 gimple_call_arg (stmt, 0));
5468 case BUILT_IN_OMP_IS_INITIAL_DEVICE:
5469 return gimple_fold_builtin_omp_is_initial_device (gsi);
5470
5471 case BUILT_IN_REALLOC:
5472 return gimple_fold_builtin_realloc (gsi);
5473
5474 case BUILT_IN_CLEAR_PADDING:
5475 return gimple_fold_builtin_clear_padding (gsi);
5476
5477 default:;
5478 }
5479
5480 /* Try the generic builtin folder. */
5481 bool ignore = (gimple_call_lhs (stmt) == NULL);
5482 tree result = fold_call_stmt (stmt, ignore);
5483 if (result)
5484 {
5485 if (ignore)
5486 STRIP_NOPS (result);
5487 else
5488 result = fold_convert (gimple_call_return_type (stmt), result);
5489 gimplify_and_update_call_from_tree (gsi, result);
5490 return true;
5491 }
5492
5493 return false;
5494 }
5495
5496 /* Transform IFN_GOACC_DIM_SIZE and IFN_GOACC_DIM_POS internal
5497 function calls to constants, where possible. */
5498
5499 static tree
5500 fold_internal_goacc_dim (const gimple *call)
5501 {
5502 int axis = oacc_get_ifn_dim_arg (call);
5503 int size = oacc_get_fn_dim_size (current_function_decl, axis);
5504 tree result = NULL_TREE;
5505 tree type = TREE_TYPE (gimple_call_lhs (call));
5506
5507 switch (gimple_call_internal_fn (call))
5508 {
5509 case IFN_GOACC_DIM_POS:
5510 /* If the size is 1, we know the answer. */
5511 if (size == 1)
5512 result = build_int_cst (type, 0);
5513 break;
5514 case IFN_GOACC_DIM_SIZE:
5515 /* If the size is not dynamic, we know the answer. */
5516 if (size)
5517 result = build_int_cst (type, size);
5518 break;
5519 default:
5520 break;
5521 }
5522
5523 return result;
5524 }
5525
5526 /* Return true if stmt is __atomic_compare_exchange_N call which is suitable
5527 for conversion into ATOMIC_COMPARE_EXCHANGE if the second argument is
5528 &var where var is only addressable because of such calls. */
5529
5530 bool
5531 optimize_atomic_compare_exchange_p (gimple *stmt)
5532 {
5533 if (gimple_call_num_args (stmt) != 6
5534 || !flag_inline_atomics
5535 || !optimize
5536 || sanitize_flags_p (SANITIZE_THREAD | SANITIZE_ADDRESS)
5537 || !gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
5538 || !gimple_vdef (stmt)
5539 || !gimple_vuse (stmt))
5540 return false;
5541
5542 tree fndecl = gimple_call_fndecl (stmt);
5543 switch (DECL_FUNCTION_CODE (fndecl))
5544 {
5545 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
5546 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
5547 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
5548 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
5549 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
5550 break;
5551 default:
5552 return false;
5553 }
5554
5555 tree expected = gimple_call_arg (stmt, 1);
5556 if (TREE_CODE (expected) != ADDR_EXPR
5557 || !SSA_VAR_P (TREE_OPERAND (expected, 0)))
5558 return false;
5559
5560 tree etype = TREE_TYPE (TREE_OPERAND (expected, 0));
5561 if (!is_gimple_reg_type (etype)
5562 || !auto_var_in_fn_p (TREE_OPERAND (expected, 0), current_function_decl)
5563 || TREE_THIS_VOLATILE (etype)
5564 || VECTOR_TYPE_P (etype)
5565 || TREE_CODE (etype) == COMPLEX_TYPE
5566 /* Don't optimize floating point expected vars, VIEW_CONVERT_EXPRs
5567 might not preserve all the bits. See PR71716. */
5568 || SCALAR_FLOAT_TYPE_P (etype)
5569 || maybe_ne (TYPE_PRECISION (etype),
5570 GET_MODE_BITSIZE (TYPE_MODE (etype))))
5571 return false;
5572
5573 tree weak = gimple_call_arg (stmt, 3);
5574 if (!integer_zerop (weak) && !integer_onep (weak))
5575 return false;
5576
5577 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
5578 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
5579 machine_mode mode = TYPE_MODE (itype);
5580
5581 if (direct_optab_handler (atomic_compare_and_swap_optab, mode)
5582 == CODE_FOR_nothing
5583 && optab_handler (sync_compare_and_swap_optab, mode) == CODE_FOR_nothing)
5584 return false;
5585
5586 if (maybe_ne (int_size_in_bytes (etype), GET_MODE_SIZE (mode)))
5587 return false;
5588
5589 return true;
5590 }
5591
5592 /* Fold
5593 r = __atomic_compare_exchange_N (p, &e, d, w, s, f);
5594 into
5595 _Complex uintN_t t = ATOMIC_COMPARE_EXCHANGE (p, e, d, w * 256 + N, s, f);
5596 i = IMAGPART_EXPR <t>;
5597 r = (_Bool) i;
5598 e = REALPART_EXPR <t>; */
5599
5600 void
5601 fold_builtin_atomic_compare_exchange (gimple_stmt_iterator *gsi)
5602 {
5603 gimple *stmt = gsi_stmt (*gsi);
5604 tree fndecl = gimple_call_fndecl (stmt);
5605 tree parmt = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
5606 tree itype = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (parmt)));
5607 tree ctype = build_complex_type (itype);
5608 tree expected = TREE_OPERAND (gimple_call_arg (stmt, 1), 0);
5609 bool throws = false;
5610 edge e = NULL;
5611 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
5612 expected);
5613 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5614 gimple_stmt_iterator gsiret = gsi_for_stmt (g);
5615 if (!useless_type_conversion_p (itype, TREE_TYPE (expected)))
5616 {
5617 g = gimple_build_assign (make_ssa_name (itype), VIEW_CONVERT_EXPR,
5618 build1 (VIEW_CONVERT_EXPR, itype,
5619 gimple_assign_lhs (g)));
5620 gsi_insert_before (gsi, g, GSI_SAME_STMT);
5621 }
5622 int flag = (integer_onep (gimple_call_arg (stmt, 3)) ? 256 : 0)
5623 + int_size_in_bytes (itype);
5624 g = gimple_build_call_internal (IFN_ATOMIC_COMPARE_EXCHANGE, 6,
5625 gimple_call_arg (stmt, 0),
5626 gimple_assign_lhs (g),
5627 gimple_call_arg (stmt, 2),
5628 build_int_cst (integer_type_node, flag),
5629 gimple_call_arg (stmt, 4),
5630 gimple_call_arg (stmt, 5));
5631 tree lhs = make_ssa_name (ctype);
5632 gimple_call_set_lhs (g, lhs);
5633 gimple_move_vops (g, stmt);
5634 tree oldlhs = gimple_call_lhs (stmt);
5635 if (stmt_can_throw_internal (cfun, stmt))
5636 {
5637 throws = true;
5638 e = find_fallthru_edge (gsi_bb (*gsi)->succs);
5639 }
5640 gimple_call_set_nothrow (as_a <gcall *> (g),
5641 gimple_call_nothrow_p (as_a <gcall *> (stmt)));
5642 gimple_call_set_lhs (stmt, NULL_TREE);
5643 gsi_replace (gsi, g, true);
5644 if (oldlhs)
5645 {
5646 g = gimple_build_assign (make_ssa_name (itype), IMAGPART_EXPR,
5647 build1 (IMAGPART_EXPR, itype, lhs));
5648 if (throws)
5649 {
5650 gsi_insert_on_edge_immediate (e, g);
5651 *gsi = gsi_for_stmt (g);
5652 }
5653 else
5654 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5655 g = gimple_build_assign (oldlhs, NOP_EXPR, gimple_assign_lhs (g));
5656 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5657 }
5658 g = gimple_build_assign (make_ssa_name (itype), REALPART_EXPR,
5659 build1 (REALPART_EXPR, itype, lhs));
5660 if (throws && oldlhs == NULL_TREE)
5661 {
5662 gsi_insert_on_edge_immediate (e, g);
5663 *gsi = gsi_for_stmt (g);
5664 }
5665 else
5666 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5667 if (!useless_type_conversion_p (TREE_TYPE (expected), itype))
5668 {
5669 g = gimple_build_assign (make_ssa_name (TREE_TYPE (expected)),
5670 VIEW_CONVERT_EXPR,
5671 build1 (VIEW_CONVERT_EXPR, TREE_TYPE (expected),
5672 gimple_assign_lhs (g)));
5673 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5674 }
5675 g = gimple_build_assign (expected, SSA_NAME, gimple_assign_lhs (g));
5676 gsi_insert_after (gsi, g, GSI_NEW_STMT);
5677 *gsi = gsiret;
5678 }
5679
5680 /* Return true if ARG0 CODE ARG1 in infinite signed precision operation
5681 doesn't fit into TYPE. The test for overflow should be regardless of
5682 -fwrapv, and even for unsigned types. */
5683
5684 bool
5685 arith_overflowed_p (enum tree_code code, const_tree type,
5686 const_tree arg0, const_tree arg1)
5687 {
5688 widest2_int warg0 = widest2_int_cst (arg0);
5689 widest2_int warg1 = widest2_int_cst (arg1);
5690 widest2_int wres;
5691 switch (code)
5692 {
5693 case PLUS_EXPR: wres = wi::add (warg0, warg1); break;
5694 case MINUS_EXPR: wres = wi::sub (warg0, warg1); break;
5695 case MULT_EXPR: wres = wi::mul (warg0, warg1); break;
5696 default: gcc_unreachable ();
5697 }
5698 signop sign = TYPE_SIGN (type);
5699 if (sign == UNSIGNED && wi::neg_p (wres))
5700 return true;
5701 return wi::min_precision (wres, sign) > TYPE_PRECISION (type);
5702 }
5703
5704 /* If IFN_{MASK,LEN,MASK_LEN}_LOAD/STORE call CALL is unconditional,
5705 return a MEM_REF for the memory it references, otherwise return null.
5706 VECTYPE is the type of the memory vector. MASK_P indicates it's for
5707 MASK if true, otherwise it's for LEN. */
5708
5709 static tree
5710 gimple_fold_partial_load_store_mem_ref (gcall *call, tree vectype, bool mask_p)
5711 {
5712 tree ptr = gimple_call_arg (call, 0);
5713 tree alias_align = gimple_call_arg (call, 1);
5714 if (!tree_fits_uhwi_p (alias_align))
5715 return NULL_TREE;
5716
5717 if (mask_p)
5718 {
5719 tree mask = gimple_call_arg (call, 2);
5720 if (!integer_all_onesp (mask))
5721 return NULL_TREE;
5722 }
5723 else
5724 {
5725 internal_fn ifn = gimple_call_internal_fn (call);
5726 int len_index = internal_fn_len_index (ifn);
5727 tree basic_len = gimple_call_arg (call, len_index);
5728 if (!poly_int_tree_p (basic_len))
5729 return NULL_TREE;
5730 tree bias = gimple_call_arg (call, len_index + 1);
5731 gcc_assert (TREE_CODE (bias) == INTEGER_CST);
5732 /* For LEN_LOAD/LEN_STORE/MASK_LEN_LOAD/MASK_LEN_STORE,
5733 we don't fold when (bias + len) != VF. */
5734 if (maybe_ne (wi::to_poly_widest (basic_len) + wi::to_widest (bias),
5735 GET_MODE_NUNITS (TYPE_MODE (vectype))))
5736 return NULL_TREE;
5737
5738 /* For MASK_LEN_{LOAD,STORE}, we should also check whether
5739 the mask is all ones mask. */
5740 if (ifn == IFN_MASK_LEN_LOAD || ifn == IFN_MASK_LEN_STORE)
5741 {
5742 tree mask = gimple_call_arg (call, internal_fn_mask_index (ifn));
5743 if (!integer_all_onesp (mask))
5744 return NULL_TREE;
5745 }
5746 }
5747
5748 unsigned HOST_WIDE_INT align = tree_to_uhwi (alias_align);
5749 if (TYPE_ALIGN (vectype) != align)
5750 vectype = build_aligned_type (vectype, align);
5751 tree offset = build_zero_cst (TREE_TYPE (alias_align));
5752 return fold_build2 (MEM_REF, vectype, ptr, offset);
5753 }
5754
5755 /* Try to fold IFN_{MASK,LEN}_LOAD call CALL. Return true on success.
5756 MASK_P indicates it's for MASK if true, otherwise it's for LEN. */
5757
5758 static bool
5759 gimple_fold_partial_load (gimple_stmt_iterator *gsi, gcall *call, bool mask_p)
5760 {
5761 tree lhs = gimple_call_lhs (call);
5762 if (!lhs)
5763 return false;
5764
5765 if (tree rhs
5766 = gimple_fold_partial_load_store_mem_ref (call, TREE_TYPE (lhs), mask_p))
5767 {
5768 gassign *new_stmt = gimple_build_assign (lhs, rhs);
5769 gimple_set_location (new_stmt, gimple_location (call));
5770 gimple_move_vops (new_stmt, call);
5771 gsi_replace (gsi, new_stmt, false);
5772 return true;
5773 }
5774 return false;
5775 }
5776
5777 /* Try to fold IFN_{MASK,LEN}_STORE call CALL. Return true on success.
5778 MASK_P indicates it's for MASK if true, otherwise it's for LEN. */
5779
5780 static bool
5781 gimple_fold_partial_store (gimple_stmt_iterator *gsi, gcall *call,
5782 bool mask_p)
5783 {
5784 internal_fn ifn = gimple_call_internal_fn (call);
5785 tree rhs = gimple_call_arg (call, internal_fn_stored_value_index (ifn));
5786 if (tree lhs
5787 = gimple_fold_partial_load_store_mem_ref (call, TREE_TYPE (rhs), mask_p))
5788 {
5789 gassign *new_stmt = gimple_build_assign (lhs, rhs);
5790 gimple_set_location (new_stmt, gimple_location (call));
5791 gimple_move_vops (new_stmt, call);
5792 gsi_replace (gsi, new_stmt, false);
5793 return true;
5794 }
5795 return false;
5796 }
5797
5798 /* Attempt to fold a call statement referenced by the statement iterator GSI.
5799 The statement may be replaced by another statement, e.g., if the call
5800 simplifies to a constant value. Return true if any changes were made.
5801 It is assumed that the operands have been previously folded. */
5802
5803 static bool
5804 gimple_fold_call (gimple_stmt_iterator *gsi, bool inplace)
5805 {
5806 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
5807 tree callee;
5808 bool changed = false;
5809
5810 /* Check for virtual calls that became direct calls. */
5811 callee = gimple_call_fn (stmt);
5812 if (callee && TREE_CODE (callee) == OBJ_TYPE_REF)
5813 {
5814 if (gimple_call_addr_fndecl (OBJ_TYPE_REF_EXPR (callee)) != NULL_TREE)
5815 {
5816 if (dump_file && virtual_method_call_p (callee)
5817 && !possible_polymorphic_call_target_p
5818 (callee, stmt, cgraph_node::get (gimple_call_addr_fndecl
5819 (OBJ_TYPE_REF_EXPR (callee)))))
5820 {
5821 fprintf (dump_file,
5822 "Type inheritance inconsistent devirtualization of ");
5823 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5824 fprintf (dump_file, " to ");
5825 print_generic_expr (dump_file, callee, TDF_SLIM);
5826 fprintf (dump_file, "\n");
5827 }
5828
5829 gimple_call_set_fn (stmt, OBJ_TYPE_REF_EXPR (callee));
5830 changed = true;
5831 }
5832 else if (flag_devirtualize && !inplace && virtual_method_call_p (callee))
5833 {
5834 bool final;
5835 vec <cgraph_node *>targets
5836 = possible_polymorphic_call_targets (callee, stmt, &final);
5837 if (final && targets.length () <= 1 && dbg_cnt (devirt))
5838 {
5839 tree lhs = gimple_call_lhs (stmt);
5840 if (dump_enabled_p ())
5841 {
5842 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
5843 "folding virtual function call to %s\n",
5844 targets.length () == 1
5845 ? targets[0]->name ()
5846 : "__builtin_unreachable");
5847 }
5848 if (targets.length () == 1)
5849 {
5850 tree fndecl = targets[0]->decl;
5851 gimple_call_set_fndecl (stmt, fndecl);
5852 changed = true;
5853 /* If changing the call to __cxa_pure_virtual
5854 or similar noreturn function, adjust gimple_call_fntype
5855 too. */
5856 if (gimple_call_noreturn_p (stmt)
5857 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fndecl)))
5858 && TYPE_ARG_TYPES (TREE_TYPE (fndecl))
5859 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)))
5860 == void_type_node))
5861 gimple_call_set_fntype (stmt, TREE_TYPE (fndecl));
5862 /* If the call becomes noreturn, remove the lhs. */
5863 if (lhs
5864 && gimple_call_noreturn_p (stmt)
5865 && (VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))
5866 || should_remove_lhs_p (lhs)))
5867 {
5868 if (TREE_CODE (lhs) == SSA_NAME)
5869 {
5870 tree var = create_tmp_var (TREE_TYPE (lhs));
5871 tree def = get_or_create_ssa_default_def (cfun, var);
5872 gimple *new_stmt = gimple_build_assign (lhs, def);
5873 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
5874 }
5875 gimple_call_set_lhs (stmt, NULL_TREE);
5876 }
5877 maybe_remove_unused_call_args (cfun, stmt);
5878 }
5879 else
5880 {
5881 location_t loc = gimple_location (stmt);
5882 gimple *new_stmt = gimple_build_builtin_unreachable (loc);
5883 gimple_call_set_ctrl_altering (new_stmt, false);
5884 /* If the call had a SSA name as lhs morph that into
5885 an uninitialized value. */
5886 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5887 {
5888 tree var = create_tmp_var (TREE_TYPE (lhs));
5889 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, var);
5890 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
5891 set_ssa_default_def (cfun, var, lhs);
5892 }
5893 gimple_move_vops (new_stmt, stmt);
5894 gsi_replace (gsi, new_stmt, false);
5895 return true;
5896 }
5897 }
5898 }
5899 }
5900
5901 /* Check for indirect calls that became direct calls, and then
5902 no longer require a static chain. */
5903 if (gimple_call_chain (stmt))
5904 {
5905 tree fn = gimple_call_fndecl (stmt);
5906 if (fn && !DECL_STATIC_CHAIN (fn))
5907 {
5908 gimple_call_set_chain (stmt, NULL);
5909 changed = true;
5910 }
5911 }
5912
5913 if (inplace)
5914 return changed;
5915
5916 /* Don't constant fold functions which can change the control. */
5917 if (gimple_call_ctrl_altering_p (stmt))
5918 return changed;
5919
5920 /* Check for builtins that CCP can handle using information not
5921 available in the generic fold routines. */
5922 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
5923 {
5924 if (gimple_fold_builtin (gsi))
5925 changed = true;
5926 }
5927 else if (gimple_call_builtin_p (stmt, BUILT_IN_MD))
5928 {
5929 changed |= targetm.gimple_fold_builtin (gsi);
5930 }
5931 else if (gimple_call_internal_p (stmt))
5932 {
5933 enum tree_code subcode = ERROR_MARK;
5934 tree result = NULL_TREE;
5935 bool cplx_result = false;
5936 bool uaddc_usubc = false;
5937 tree overflow = NULL_TREE;
5938 switch (gimple_call_internal_fn (stmt))
5939 {
5940 case IFN_BUILTIN_EXPECT:
5941 result = fold_builtin_expect (gimple_location (stmt),
5942 gimple_call_arg (stmt, 0),
5943 gimple_call_arg (stmt, 1),
5944 gimple_call_arg (stmt, 2),
5945 NULL_TREE);
5946 break;
5947 case IFN_UBSAN_OBJECT_SIZE:
5948 {
5949 tree offset = gimple_call_arg (stmt, 1);
5950 tree objsize = gimple_call_arg (stmt, 2);
5951 if (integer_all_onesp (objsize)
5952 || (TREE_CODE (offset) == INTEGER_CST
5953 && TREE_CODE (objsize) == INTEGER_CST
5954 && tree_int_cst_le (offset, objsize)))
5955 {
5956 replace_call_with_value (gsi, NULL_TREE);
5957 return true;
5958 }
5959 }
5960 break;
5961 case IFN_UBSAN_PTR:
5962 if (integer_zerop (gimple_call_arg (stmt, 1)))
5963 {
5964 replace_call_with_value (gsi, NULL_TREE);
5965 return true;
5966 }
5967 break;
5968 case IFN_UBSAN_BOUNDS:
5969 {
5970 tree index = gimple_call_arg (stmt, 1);
5971 tree bound = gimple_call_arg (stmt, 2);
5972 if (TREE_CODE (index) == INTEGER_CST
5973 && TREE_CODE (bound) == INTEGER_CST)
5974 {
5975 index = fold_convert (TREE_TYPE (bound), index);
5976 if (TREE_CODE (index) == INTEGER_CST
5977 && tree_int_cst_lt (index, bound))
5978 {
5979 replace_call_with_value (gsi, NULL_TREE);
5980 return true;
5981 }
5982 }
5983 }
5984 break;
5985 case IFN_GOACC_DIM_SIZE:
5986 case IFN_GOACC_DIM_POS:
5987 result = fold_internal_goacc_dim (stmt);
5988 break;
5989 case IFN_UBSAN_CHECK_ADD:
5990 subcode = PLUS_EXPR;
5991 break;
5992 case IFN_UBSAN_CHECK_SUB:
5993 subcode = MINUS_EXPR;
5994 break;
5995 case IFN_UBSAN_CHECK_MUL:
5996 subcode = MULT_EXPR;
5997 break;
5998 case IFN_ADD_OVERFLOW:
5999 subcode = PLUS_EXPR;
6000 cplx_result = true;
6001 break;
6002 case IFN_SUB_OVERFLOW:
6003 subcode = MINUS_EXPR;
6004 cplx_result = true;
6005 break;
6006 case IFN_MUL_OVERFLOW:
6007 subcode = MULT_EXPR;
6008 cplx_result = true;
6009 break;
6010 case IFN_UADDC:
6011 subcode = PLUS_EXPR;
6012 cplx_result = true;
6013 uaddc_usubc = true;
6014 break;
6015 case IFN_USUBC:
6016 subcode = MINUS_EXPR;
6017 cplx_result = true;
6018 uaddc_usubc = true;
6019 break;
6020 case IFN_MASK_LOAD:
6021 changed |= gimple_fold_partial_load (gsi, stmt, true);
6022 break;
6023 case IFN_MASK_STORE:
6024 changed |= gimple_fold_partial_store (gsi, stmt, true);
6025 break;
6026 case IFN_LEN_LOAD:
6027 case IFN_MASK_LEN_LOAD:
6028 changed |= gimple_fold_partial_load (gsi, stmt, false);
6029 break;
6030 case IFN_LEN_STORE:
6031 case IFN_MASK_LEN_STORE:
6032 changed |= gimple_fold_partial_store (gsi, stmt, false);
6033 break;
6034 default:
6035 break;
6036 }
6037 if (subcode != ERROR_MARK)
6038 {
6039 tree arg0 = gimple_call_arg (stmt, 0);
6040 tree arg1 = gimple_call_arg (stmt, 1);
6041 tree arg2 = NULL_TREE;
6042 tree type = TREE_TYPE (arg0);
6043 if (cplx_result)
6044 {
6045 tree lhs = gimple_call_lhs (stmt);
6046 if (lhs == NULL_TREE)
6047 type = NULL_TREE;
6048 else
6049 type = TREE_TYPE (TREE_TYPE (lhs));
6050 if (uaddc_usubc)
6051 arg2 = gimple_call_arg (stmt, 2);
6052 }
6053 if (type == NULL_TREE)
6054 ;
6055 else if (uaddc_usubc)
6056 {
6057 if (!integer_zerop (arg2))
6058 ;
6059 /* x = y + 0 + 0; x = y - 0 - 0; */
6060 else if (integer_zerop (arg1))
6061 result = arg0;
6062 /* x = 0 + y + 0; */
6063 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
6064 result = arg1;
6065 /* x = y - y - 0; */
6066 else if (subcode == MINUS_EXPR
6067 && operand_equal_p (arg0, arg1, 0))
6068 result = integer_zero_node;
6069 }
6070 /* x = y + 0; x = y - 0; x = y * 0; */
6071 else if (integer_zerop (arg1))
6072 result = subcode == MULT_EXPR ? integer_zero_node : arg0;
6073 /* x = 0 + y; x = 0 * y; */
6074 else if (subcode != MINUS_EXPR && integer_zerop (arg0))
6075 result = subcode == MULT_EXPR ? integer_zero_node : arg1;
6076 /* x = y - y; */
6077 else if (subcode == MINUS_EXPR && operand_equal_p (arg0, arg1, 0))
6078 result = integer_zero_node;
6079 /* x = y * 1; x = 1 * y; */
6080 else if (subcode == MULT_EXPR && integer_onep (arg1))
6081 result = arg0;
6082 else if (subcode == MULT_EXPR && integer_onep (arg0))
6083 result = arg1;
6084 if (result)
6085 {
6086 if (result == integer_zero_node)
6087 result = build_zero_cst (type);
6088 else if (cplx_result && TREE_TYPE (result) != type)
6089 {
6090 if (TREE_CODE (result) == INTEGER_CST)
6091 {
6092 if (arith_overflowed_p (PLUS_EXPR, type, result,
6093 integer_zero_node))
6094 overflow = build_one_cst (type);
6095 }
6096 else if ((!TYPE_UNSIGNED (TREE_TYPE (result))
6097 && TYPE_UNSIGNED (type))
6098 || (TYPE_PRECISION (type)
6099 < (TYPE_PRECISION (TREE_TYPE (result))
6100 + (TYPE_UNSIGNED (TREE_TYPE (result))
6101 && !TYPE_UNSIGNED (type)))))
6102 result = NULL_TREE;
6103 if (result)
6104 result = fold_convert (type, result);
6105 }
6106 }
6107 }
6108
6109 if (result)
6110 {
6111 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
6112 result = drop_tree_overflow (result);
6113 if (cplx_result)
6114 {
6115 if (overflow == NULL_TREE)
6116 overflow = build_zero_cst (TREE_TYPE (result));
6117 tree ctype = build_complex_type (TREE_TYPE (result));
6118 if (TREE_CODE (result) == INTEGER_CST
6119 && TREE_CODE (overflow) == INTEGER_CST)
6120 result = build_complex (ctype, result, overflow);
6121 else
6122 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
6123 ctype, result, overflow);
6124 }
6125 gimplify_and_update_call_from_tree (gsi, result);
6126 changed = true;
6127 }
6128 }
6129
6130 return changed;
6131 }
6132
6133
6134 /* Return true whether NAME has a use on STMT. Note this can return
6135 false even though there's a use on STMT if SSA operands are not
6136 up-to-date. */
6137
6138 static bool
6139 has_use_on_stmt (tree name, gimple *stmt)
6140 {
6141 ssa_op_iter iter;
6142 tree op;
6143 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
6144 if (op == name)
6145 return true;
6146 return false;
6147 }
6148
6149 /* Add the lhs of each statement of SEQ to DCE_WORKLIST. */
6150
6151 static void
6152 mark_lhs_in_seq_for_dce (bitmap dce_worklist, gimple_seq seq)
6153 {
6154 if (!dce_worklist)
6155 return;
6156
6157 for (gimple_stmt_iterator i = gsi_start (seq);
6158 !gsi_end_p (i); gsi_next (&i))
6159 {
6160 gimple *stmt = gsi_stmt (i);
6161 tree name = gimple_get_lhs (stmt);
6162 if (name && TREE_CODE (name) == SSA_NAME)
6163 bitmap_set_bit (dce_worklist, SSA_NAME_VERSION (name));
6164 }
6165 }
6166
6167 /* Worker for fold_stmt_1 dispatch to pattern based folding with
6168 gimple_simplify.
6169
6170 Replaces *GSI with the simplification result in RCODE and OPS
6171 and the associated statements in *SEQ. Does the replacement
6172 according to INPLACE and returns true if the operation succeeded. */
6173
6174 static bool
6175 replace_stmt_with_simplification (gimple_stmt_iterator *gsi,
6176 gimple_match_op *res_op,
6177 gimple_seq *seq, bool inplace,
6178 bitmap dce_worklist)
6179 {
6180 gimple *stmt = gsi_stmt (*gsi);
6181 tree *ops = res_op->ops;
6182 unsigned int num_ops = res_op->num_ops;
6183
6184 /* Play safe and do not allow abnormals to be mentioned in
6185 newly created statements. See also maybe_push_res_to_seq.
6186 As an exception allow such uses if there was a use of the
6187 same SSA name on the old stmt. */
6188 for (unsigned int i = 0; i < num_ops; ++i)
6189 if (TREE_CODE (ops[i]) == SSA_NAME
6190 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ops[i])
6191 && !has_use_on_stmt (ops[i], stmt))
6192 return false;
6193
6194 if (num_ops > 0 && COMPARISON_CLASS_P (ops[0]))
6195 for (unsigned int i = 0; i < 2; ++i)
6196 if (TREE_CODE (TREE_OPERAND (ops[0], i)) == SSA_NAME
6197 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (ops[0], i))
6198 && !has_use_on_stmt (TREE_OPERAND (ops[0], i), stmt))
6199 return false;
6200
6201 /* Don't insert new statements when INPLACE is true, even if we could
6202 reuse STMT for the final statement. */
6203 if (inplace && !gimple_seq_empty_p (*seq))
6204 return false;
6205
6206 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6207 {
6208 gcc_assert (res_op->code.is_tree_code ());
6209 auto code = tree_code (res_op->code);
6210 if (TREE_CODE_CLASS (code) == tcc_comparison
6211 /* GIMPLE_CONDs condition may not throw. */
6212 && (!flag_exceptions
6213 || !cfun->can_throw_non_call_exceptions
6214 || !operation_could_trap_p (code,
6215 FLOAT_TYPE_P (TREE_TYPE (ops[0])),
6216 false, NULL_TREE)))
6217 gimple_cond_set_condition (cond_stmt, code, ops[0], ops[1]);
6218 else if (code == SSA_NAME)
6219 gimple_cond_set_condition (cond_stmt, NE_EXPR, ops[0],
6220 build_zero_cst (TREE_TYPE (ops[0])));
6221 else if (code == INTEGER_CST)
6222 {
6223 if (integer_zerop (ops[0]))
6224 gimple_cond_make_false (cond_stmt);
6225 else
6226 gimple_cond_make_true (cond_stmt);
6227 }
6228 else if (!inplace)
6229 {
6230 tree res = maybe_push_res_to_seq (res_op, seq);
6231 if (!res)
6232 return false;
6233 gimple_cond_set_condition (cond_stmt, NE_EXPR, res,
6234 build_zero_cst (TREE_TYPE (res)));
6235 }
6236 else
6237 return false;
6238 if (dump_file && (dump_flags & TDF_DETAILS))
6239 {
6240 fprintf (dump_file, "gimple_simplified to ");
6241 if (!gimple_seq_empty_p (*seq))
6242 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
6243 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
6244 0, TDF_SLIM);
6245 }
6246 // Mark the lhs of the new statements maybe for dce
6247 mark_lhs_in_seq_for_dce (dce_worklist, *seq);
6248 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
6249 return true;
6250 }
6251 else if (is_gimple_assign (stmt)
6252 && res_op->code.is_tree_code ())
6253 {
6254 auto code = tree_code (res_op->code);
6255 if (!inplace
6256 || gimple_num_ops (stmt) > get_gimple_rhs_num_ops (code))
6257 {
6258 maybe_build_generic_op (res_op);
6259 gimple_assign_set_rhs_with_ops (gsi, code,
6260 res_op->op_or_null (0),
6261 res_op->op_or_null (1),
6262 res_op->op_or_null (2));
6263 if (dump_file && (dump_flags & TDF_DETAILS))
6264 {
6265 fprintf (dump_file, "gimple_simplified to ");
6266 if (!gimple_seq_empty_p (*seq))
6267 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
6268 print_gimple_stmt (dump_file, gsi_stmt (*gsi),
6269 0, TDF_SLIM);
6270 }
6271 // Mark the lhs of the new statements maybe for dce
6272 mark_lhs_in_seq_for_dce (dce_worklist, *seq);
6273 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
6274 return true;
6275 }
6276 }
6277 else if (res_op->code.is_fn_code ()
6278 && gimple_call_combined_fn (stmt) == combined_fn (res_op->code))
6279 {
6280 gcc_assert (num_ops == gimple_call_num_args (stmt));
6281 for (unsigned int i = 0; i < num_ops; ++i)
6282 gimple_call_set_arg (stmt, i, ops[i]);
6283 if (dump_file && (dump_flags & TDF_DETAILS))
6284 {
6285 fprintf (dump_file, "gimple_simplified to ");
6286 if (!gimple_seq_empty_p (*seq))
6287 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
6288 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_SLIM);
6289 }
6290 // Mark the lhs of the new statements maybe for dce
6291 mark_lhs_in_seq_for_dce (dce_worklist, *seq);
6292 gsi_insert_seq_before (gsi, *seq, GSI_SAME_STMT);
6293 return true;
6294 }
6295 else if (!inplace)
6296 {
6297 if (gimple_has_lhs (stmt))
6298 {
6299 tree lhs = gimple_get_lhs (stmt);
6300 if (!maybe_push_res_to_seq (res_op, seq, lhs))
6301 return false;
6302 if (dump_file && (dump_flags & TDF_DETAILS))
6303 {
6304 fprintf (dump_file, "gimple_simplified to ");
6305 print_gimple_seq (dump_file, *seq, 0, TDF_SLIM);
6306 }
6307 // Mark the lhs of the new statements maybe for dce
6308 mark_lhs_in_seq_for_dce (dce_worklist, *seq);
6309 gsi_replace_with_seq_vops (gsi, *seq);
6310 return true;
6311 }
6312 else
6313 gcc_unreachable ();
6314 }
6315
6316 return false;
6317 }
6318
6319 /* Canonicalize MEM_REFs invariant address operand after propagation. */
6320
6321 static bool
6322 maybe_canonicalize_mem_ref_addr (tree *t, bool is_debug = false)
6323 {
6324 bool res = false;
6325 tree *orig_t = t;
6326
6327 if (TREE_CODE (*t) == ADDR_EXPR)
6328 t = &TREE_OPERAND (*t, 0);
6329
6330 /* The C and C++ frontends use an ARRAY_REF for indexing with their
6331 generic vector extension. The actual vector referenced is
6332 view-converted to an array type for this purpose. If the index
6333 is constant the canonical representation in the middle-end is a
6334 BIT_FIELD_REF so re-write the former to the latter here. */
6335 if (TREE_CODE (*t) == ARRAY_REF
6336 && TREE_CODE (TREE_OPERAND (*t, 0)) == VIEW_CONVERT_EXPR
6337 && TREE_CODE (TREE_OPERAND (*t, 1)) == INTEGER_CST
6338 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0))))
6339 {
6340 tree vtype = TREE_TYPE (TREE_OPERAND (TREE_OPERAND (*t, 0), 0));
6341 if (VECTOR_TYPE_P (vtype))
6342 {
6343 tree low = array_ref_low_bound (*t);
6344 if (TREE_CODE (low) == INTEGER_CST)
6345 {
6346 if (tree_int_cst_le (low, TREE_OPERAND (*t, 1)))
6347 {
6348 widest_int idx = wi::sub (wi::to_widest (TREE_OPERAND (*t, 1)),
6349 wi::to_widest (low));
6350 idx = wi::mul (idx, wi::to_widest
6351 (TYPE_SIZE (TREE_TYPE (*t))));
6352 widest_int ext
6353 = wi::add (idx, wi::to_widest (TYPE_SIZE (TREE_TYPE (*t))));
6354 if (maybe_le (ext, wi::to_poly_widest (TYPE_SIZE (vtype))))
6355 {
6356 *t = build3_loc (EXPR_LOCATION (*t), BIT_FIELD_REF,
6357 TREE_TYPE (*t),
6358 TREE_OPERAND (TREE_OPERAND (*t, 0), 0),
6359 TYPE_SIZE (TREE_TYPE (*t)),
6360 wide_int_to_tree (bitsizetype, idx));
6361 res = true;
6362 }
6363 }
6364 }
6365 }
6366 }
6367
6368 while (handled_component_p (*t))
6369 t = &TREE_OPERAND (*t, 0);
6370
6371 /* Canonicalize MEM [&foo.bar, 0] which appears after propagating
6372 of invariant addresses into a SSA name MEM_REF address. */
6373 if (TREE_CODE (*t) == MEM_REF
6374 || TREE_CODE (*t) == TARGET_MEM_REF)
6375 {
6376 tree addr = TREE_OPERAND (*t, 0);
6377 if (TREE_CODE (addr) == ADDR_EXPR
6378 && (TREE_CODE (TREE_OPERAND (addr, 0)) == MEM_REF
6379 || handled_component_p (TREE_OPERAND (addr, 0))))
6380 {
6381 tree base;
6382 poly_int64 coffset;
6383 base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0),
6384 &coffset);
6385 if (!base)
6386 {
6387 if (is_debug)
6388 return false;
6389 gcc_unreachable ();
6390 }
6391
6392 TREE_OPERAND (*t, 0) = build_fold_addr_expr (base);
6393 TREE_OPERAND (*t, 1) = int_const_binop (PLUS_EXPR,
6394 TREE_OPERAND (*t, 1),
6395 size_int (coffset));
6396 res = true;
6397 }
6398 gcc_checking_assert (TREE_CODE (TREE_OPERAND (*t, 0)) == DEBUG_EXPR_DECL
6399 || is_gimple_mem_ref_addr (TREE_OPERAND (*t, 0)));
6400 }
6401
6402 /* Canonicalize back MEM_REFs to plain reference trees if the object
6403 accessed is a decl that has the same access semantics as the MEM_REF. */
6404 if (TREE_CODE (*t) == MEM_REF
6405 && TREE_CODE (TREE_OPERAND (*t, 0)) == ADDR_EXPR
6406 && integer_zerop (TREE_OPERAND (*t, 1))
6407 && MR_DEPENDENCE_CLIQUE (*t) == 0)
6408 {
6409 tree decl = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
6410 tree alias_type = TREE_TYPE (TREE_OPERAND (*t, 1));
6411 if (/* Same volatile qualification. */
6412 TREE_THIS_VOLATILE (*t) == TREE_THIS_VOLATILE (decl)
6413 /* Same TBAA behavior with -fstrict-aliasing. */
6414 && !TYPE_REF_CAN_ALIAS_ALL (alias_type)
6415 && (TYPE_MAIN_VARIANT (TREE_TYPE (decl))
6416 == TYPE_MAIN_VARIANT (TREE_TYPE (alias_type)))
6417 /* Same alignment. */
6418 && TYPE_ALIGN (TREE_TYPE (decl)) == TYPE_ALIGN (TREE_TYPE (*t))
6419 /* We have to look out here to not drop a required conversion
6420 from the rhs to the lhs if *t appears on the lhs or vice-versa
6421 if it appears on the rhs. Thus require strict type
6422 compatibility. */
6423 && types_compatible_p (TREE_TYPE (*t), TREE_TYPE (decl)))
6424 {
6425 *t = TREE_OPERAND (TREE_OPERAND (*t, 0), 0);
6426 res = true;
6427 }
6428 }
6429
6430 else if (TREE_CODE (*orig_t) == ADDR_EXPR
6431 && TREE_CODE (*t) == MEM_REF
6432 && TREE_CODE (TREE_OPERAND (*t, 0)) == INTEGER_CST)
6433 {
6434 tree base;
6435 poly_int64 coffset;
6436 base = get_addr_base_and_unit_offset (TREE_OPERAND (*orig_t, 0),
6437 &coffset);
6438 if (base)
6439 {
6440 gcc_assert (TREE_CODE (base) == MEM_REF);
6441 poly_int64 moffset;
6442 if (mem_ref_offset (base).to_shwi (&moffset))
6443 {
6444 coffset += moffset;
6445 if (wi::to_poly_wide (TREE_OPERAND (base, 0)).to_shwi (&moffset))
6446 {
6447 coffset += moffset;
6448 *orig_t = build_int_cst (TREE_TYPE (*orig_t), coffset);
6449 return true;
6450 }
6451 }
6452 }
6453 }
6454
6455 /* Canonicalize TARGET_MEM_REF in particular with respect to
6456 the indexes becoming constant. */
6457 else if (TREE_CODE (*t) == TARGET_MEM_REF)
6458 {
6459 tree tem = maybe_fold_tmr (*t);
6460 if (tem)
6461 {
6462 *t = tem;
6463 if (TREE_CODE (*orig_t) == ADDR_EXPR)
6464 recompute_tree_invariant_for_addr_expr (*orig_t);
6465 res = true;
6466 }
6467 }
6468
6469 return res;
6470 }
6471
6472 /* Worker for both fold_stmt and fold_stmt_inplace. The INPLACE argument
6473 distinguishes both cases. */
6474
6475 static bool
6476 fold_stmt_1 (gimple_stmt_iterator *gsi, bool inplace, tree (*valueize) (tree),
6477 bitmap dce_worklist = nullptr)
6478 {
6479 bool changed = false;
6480 gimple *stmt = gsi_stmt (*gsi);
6481 bool nowarning = warning_suppressed_p (stmt, OPT_Wstrict_overflow);
6482 unsigned i;
6483 fold_defer_overflow_warnings ();
6484
6485 /* First do required canonicalization of [TARGET_]MEM_REF addresses
6486 after propagation.
6487 ??? This shouldn't be done in generic folding but in the
6488 propagation helpers which also know whether an address was
6489 propagated.
6490 Also canonicalize operand order. */
6491 switch (gimple_code (stmt))
6492 {
6493 case GIMPLE_ASSIGN:
6494 if (gimple_assign_rhs_class (stmt) == GIMPLE_SINGLE_RHS)
6495 {
6496 tree *rhs = gimple_assign_rhs1_ptr (stmt);
6497 if ((REFERENCE_CLASS_P (*rhs)
6498 || TREE_CODE (*rhs) == ADDR_EXPR)
6499 && maybe_canonicalize_mem_ref_addr (rhs))
6500 changed = true;
6501 tree *lhs = gimple_assign_lhs_ptr (stmt);
6502 if (REFERENCE_CLASS_P (*lhs)
6503 && maybe_canonicalize_mem_ref_addr (lhs))
6504 changed = true;
6505 /* Canonicalize &MEM[ssa_n, CST] to ssa_n p+ CST.
6506 This cannot be done in maybe_canonicalize_mem_ref_addr
6507 as the gimple now has two operands rather than one.
6508 The same reason why this can't be done in
6509 maybe_canonicalize_mem_ref_addr is the same reason why
6510 this can't be done inplace. */
6511 if (!inplace && TREE_CODE (*rhs) == ADDR_EXPR)
6512 {
6513 tree inner = TREE_OPERAND (*rhs, 0);
6514 if (TREE_CODE (inner) == MEM_REF
6515 && TREE_CODE (TREE_OPERAND (inner, 0)) == SSA_NAME
6516 && TREE_CODE (TREE_OPERAND (inner, 1)) == INTEGER_CST)
6517 {
6518 tree ptr = TREE_OPERAND (inner, 0);
6519 tree addon = TREE_OPERAND (inner, 1);
6520 addon = fold_convert (sizetype, addon);
6521 gimple_assign_set_rhs_with_ops (gsi, POINTER_PLUS_EXPR,
6522 ptr, addon);
6523 changed = true;
6524 stmt = gsi_stmt (*gsi);
6525 }
6526 }
6527 }
6528 else
6529 {
6530 /* Canonicalize operand order. */
6531 enum tree_code code = gimple_assign_rhs_code (stmt);
6532 if (TREE_CODE_CLASS (code) == tcc_comparison
6533 || commutative_tree_code (code)
6534 || commutative_ternary_tree_code (code))
6535 {
6536 tree rhs1 = gimple_assign_rhs1 (stmt);
6537 tree rhs2 = gimple_assign_rhs2 (stmt);
6538 if (tree_swap_operands_p (rhs1, rhs2))
6539 {
6540 gimple_assign_set_rhs1 (stmt, rhs2);
6541 gimple_assign_set_rhs2 (stmt, rhs1);
6542 if (TREE_CODE_CLASS (code) == tcc_comparison)
6543 gimple_assign_set_rhs_code (stmt,
6544 swap_tree_comparison (code));
6545 changed = true;
6546 }
6547 }
6548 }
6549 break;
6550 case GIMPLE_CALL:
6551 {
6552 gcall *call = as_a<gcall *> (stmt);
6553 for (i = 0; i < gimple_call_num_args (call); ++i)
6554 {
6555 tree *arg = gimple_call_arg_ptr (call, i);
6556 if (REFERENCE_CLASS_P (*arg)
6557 && maybe_canonicalize_mem_ref_addr (arg))
6558 changed = true;
6559 }
6560 tree *lhs = gimple_call_lhs_ptr (call);
6561 if (*lhs
6562 && REFERENCE_CLASS_P (*lhs)
6563 && maybe_canonicalize_mem_ref_addr (lhs))
6564 changed = true;
6565 if (*lhs)
6566 {
6567 combined_fn cfn = gimple_call_combined_fn (call);
6568 internal_fn ifn = associated_internal_fn (cfn, TREE_TYPE (*lhs));
6569 int opno = first_commutative_argument (ifn);
6570 if (opno >= 0)
6571 {
6572 tree arg1 = gimple_call_arg (call, opno);
6573 tree arg2 = gimple_call_arg (call, opno + 1);
6574 if (tree_swap_operands_p (arg1, arg2))
6575 {
6576 gimple_call_set_arg (call, opno, arg2);
6577 gimple_call_set_arg (call, opno + 1, arg1);
6578 changed = true;
6579 }
6580 }
6581 }
6582 break;
6583 }
6584 case GIMPLE_ASM:
6585 {
6586 gasm *asm_stmt = as_a <gasm *> (stmt);
6587 for (i = 0; i < gimple_asm_noutputs (asm_stmt); ++i)
6588 {
6589 tree link = gimple_asm_output_op (asm_stmt, i);
6590 tree op = TREE_VALUE (link);
6591 if (REFERENCE_CLASS_P (op)
6592 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
6593 changed = true;
6594 }
6595 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
6596 {
6597 tree link = gimple_asm_input_op (asm_stmt, i);
6598 tree op = TREE_VALUE (link);
6599 if ((REFERENCE_CLASS_P (op)
6600 || TREE_CODE (op) == ADDR_EXPR)
6601 && maybe_canonicalize_mem_ref_addr (&TREE_VALUE (link)))
6602 changed = true;
6603 }
6604 }
6605 break;
6606 case GIMPLE_DEBUG:
6607 if (gimple_debug_bind_p (stmt))
6608 {
6609 tree *val = gimple_debug_bind_get_value_ptr (stmt);
6610 if (*val
6611 && (REFERENCE_CLASS_P (*val)
6612 || TREE_CODE (*val) == ADDR_EXPR)
6613 && maybe_canonicalize_mem_ref_addr (val, true))
6614 changed = true;
6615 }
6616 break;
6617 case GIMPLE_COND:
6618 {
6619 /* Canonicalize operand order. */
6620 tree lhs = gimple_cond_lhs (stmt);
6621 tree rhs = gimple_cond_rhs (stmt);
6622 if (tree_swap_operands_p (lhs, rhs))
6623 {
6624 gcond *gc = as_a <gcond *> (stmt);
6625 gimple_cond_set_lhs (gc, rhs);
6626 gimple_cond_set_rhs (gc, lhs);
6627 gimple_cond_set_code (gc,
6628 swap_tree_comparison (gimple_cond_code (gc)));
6629 changed = true;
6630 }
6631 }
6632 default:;
6633 }
6634
6635 /* Dispatch to pattern-based folding. */
6636 if (!inplace
6637 || is_gimple_assign (stmt)
6638 || gimple_code (stmt) == GIMPLE_COND)
6639 {
6640 gimple_seq seq = NULL;
6641 gimple_match_op res_op;
6642 if (gimple_simplify (stmt, &res_op, inplace ? NULL : &seq,
6643 valueize, valueize)
6644 && replace_stmt_with_simplification (gsi, &res_op, &seq, inplace,
6645 dce_worklist))
6646 changed = true;
6647 else
6648 gimple_seq_discard (seq);
6649 }
6650
6651 stmt = gsi_stmt (*gsi);
6652
6653 /* Fold the main computation performed by the statement. */
6654 switch (gimple_code (stmt))
6655 {
6656 case GIMPLE_ASSIGN:
6657 {
6658 if (gimple_assign_load_p (stmt) && gimple_store_p (stmt))
6659 {
6660 if (optimize_memcpy_to_memset (gsi, gimple_assign_lhs (stmt),
6661 gimple_assign_rhs1 (stmt),
6662 /* len = */NULL_TREE))
6663 {
6664 changed = true;
6665 break;
6666 }
6667 }
6668 /* Try to canonicalize for boolean-typed X the comparisons
6669 X == 0, X == 1, X != 0, and X != 1. */
6670 if (gimple_assign_rhs_code (stmt) == EQ_EXPR
6671 || gimple_assign_rhs_code (stmt) == NE_EXPR)
6672 {
6673 tree lhs = gimple_assign_lhs (stmt);
6674 tree op1 = gimple_assign_rhs1 (stmt);
6675 tree op2 = gimple_assign_rhs2 (stmt);
6676 tree type = TREE_TYPE (op1);
6677
6678 /* Check whether the comparison operands are of the same boolean
6679 type as the result type is.
6680 Check that second operand is an integer-constant with value
6681 one or zero. */
6682 if (TREE_CODE (op2) == INTEGER_CST
6683 && (integer_zerop (op2) || integer_onep (op2))
6684 && useless_type_conversion_p (TREE_TYPE (lhs), type))
6685 {
6686 enum tree_code cmp_code = gimple_assign_rhs_code (stmt);
6687 bool is_logical_not = false;
6688
6689 /* X == 0 and X != 1 is a logical-not.of X
6690 X == 1 and X != 0 is X */
6691 if ((cmp_code == EQ_EXPR && integer_zerop (op2))
6692 || (cmp_code == NE_EXPR && integer_onep (op2)))
6693 is_logical_not = true;
6694
6695 if (is_logical_not == false)
6696 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op1), op1);
6697 /* Only for one-bit precision typed X the transformation
6698 !X -> ~X is valied. */
6699 else if (TYPE_PRECISION (type) == 1)
6700 gimple_assign_set_rhs_with_ops (gsi, BIT_NOT_EXPR, op1);
6701 /* Otherwise we use !X -> X ^ 1. */
6702 else
6703 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op1,
6704 build_int_cst (type, 1));
6705 changed = true;
6706 break;
6707 }
6708 }
6709
6710 unsigned old_num_ops = gimple_num_ops (stmt);
6711 tree lhs = gimple_assign_lhs (stmt);
6712 tree new_rhs = fold_gimple_assign (gsi);
6713 if (new_rhs
6714 && !useless_type_conversion_p (TREE_TYPE (lhs),
6715 TREE_TYPE (new_rhs)))
6716 new_rhs = fold_convert (TREE_TYPE (lhs), new_rhs);
6717 if (new_rhs
6718 && (!inplace
6719 || get_gimple_rhs_num_ops (TREE_CODE (new_rhs)) < old_num_ops))
6720 {
6721 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
6722 changed = true;
6723 }
6724 break;
6725 }
6726
6727 case GIMPLE_CALL:
6728 changed |= gimple_fold_call (gsi, inplace);
6729 break;
6730
6731 case GIMPLE_DEBUG:
6732 if (gimple_debug_bind_p (stmt))
6733 {
6734 tree val = gimple_debug_bind_get_value (stmt);
6735 if (val && REFERENCE_CLASS_P (val))
6736 {
6737 tree tem = maybe_fold_reference (val);
6738 if (tem)
6739 {
6740 gimple_debug_bind_set_value (stmt, tem);
6741 changed = true;
6742 }
6743 }
6744 }
6745 break;
6746
6747 case GIMPLE_RETURN:
6748 {
6749 greturn *ret_stmt = as_a<greturn *> (stmt);
6750 tree ret = gimple_return_retval(ret_stmt);
6751
6752 if (ret && TREE_CODE (ret) == SSA_NAME && valueize)
6753 {
6754 tree val = valueize (ret);
6755 if (val && val != ret
6756 && may_propagate_copy (ret, val))
6757 {
6758 gimple_return_set_retval (ret_stmt, val);
6759 changed = true;
6760 }
6761 }
6762 }
6763 break;
6764
6765 default:;
6766 }
6767
6768 stmt = gsi_stmt (*gsi);
6769
6770 fold_undefer_overflow_warnings (changed && !nowarning, stmt, 0);
6771 return changed;
6772 }
6773
6774 /* Valueziation callback that ends up not following SSA edges. */
6775
6776 tree
6777 no_follow_ssa_edges (tree)
6778 {
6779 return NULL_TREE;
6780 }
6781
6782 /* Valueization callback that ends up following single-use SSA edges only. */
6783
6784 tree
6785 follow_single_use_edges (tree val)
6786 {
6787 if (TREE_CODE (val) == SSA_NAME
6788 && !has_single_use (val))
6789 return NULL_TREE;
6790 return val;
6791 }
6792
6793 /* Valueization callback that follows all SSA edges. */
6794
6795 tree
6796 follow_all_ssa_edges (tree val)
6797 {
6798 return val;
6799 }
6800
6801 /* Fold the statement pointed to by GSI. In some cases, this function may
6802 replace the whole statement with a new one. Returns true iff folding
6803 makes any changes.
6804 The statement pointed to by GSI should be in valid gimple form but may
6805 be in unfolded state as resulting from for example constant propagation
6806 which can produce *&x = 0. */
6807
6808 bool
6809 fold_stmt (gimple_stmt_iterator *gsi, bitmap dce_bitmap)
6810 {
6811 return fold_stmt_1 (gsi, false, no_follow_ssa_edges, dce_bitmap);
6812 }
6813
6814 bool
6815 fold_stmt (gimple_stmt_iterator *gsi, tree (*valueize) (tree), bitmap dce_bitmap)
6816 {
6817 return fold_stmt_1 (gsi, false, valueize, dce_bitmap);
6818 }
6819
6820 /* Perform the minimal folding on statement *GSI. Only operations like
6821 *&x created by constant propagation are handled. The statement cannot
6822 be replaced with a new one. Return true if the statement was
6823 changed, false otherwise.
6824 The statement *GSI should be in valid gimple form but may
6825 be in unfolded state as resulting from for example constant propagation
6826 which can produce *&x = 0. */
6827
6828 bool
6829 fold_stmt_inplace (gimple_stmt_iterator *gsi)
6830 {
6831 gimple *stmt = gsi_stmt (*gsi);
6832 bool changed = fold_stmt_1 (gsi, true, no_follow_ssa_edges);
6833 gcc_assert (gsi_stmt (*gsi) == stmt);
6834 return changed;
6835 }
6836
6837 /* Canonicalize and possibly invert the boolean EXPR; return NULL_TREE
6838 if EXPR is null or we don't know how.
6839 If non-null, the result always has boolean type. */
6840
6841 static tree
6842 canonicalize_bool (tree expr, bool invert)
6843 {
6844 if (!expr)
6845 return NULL_TREE;
6846 else if (invert)
6847 {
6848 if (integer_nonzerop (expr))
6849 return boolean_false_node;
6850 else if (integer_zerop (expr))
6851 return boolean_true_node;
6852 else if (TREE_CODE (expr) == SSA_NAME)
6853 return fold_build2 (EQ_EXPR, boolean_type_node, expr,
6854 build_int_cst (TREE_TYPE (expr), 0));
6855 else if (COMPARISON_CLASS_P (expr))
6856 return fold_build2 (invert_tree_comparison (TREE_CODE (expr), false),
6857 boolean_type_node,
6858 TREE_OPERAND (expr, 0),
6859 TREE_OPERAND (expr, 1));
6860 else
6861 return NULL_TREE;
6862 }
6863 else
6864 {
6865 if (TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
6866 return expr;
6867 if (integer_nonzerop (expr))
6868 return boolean_true_node;
6869 else if (integer_zerop (expr))
6870 return boolean_false_node;
6871 else if (TREE_CODE (expr) == SSA_NAME)
6872 return fold_build2 (NE_EXPR, boolean_type_node, expr,
6873 build_int_cst (TREE_TYPE (expr), 0));
6874 else if (COMPARISON_CLASS_P (expr))
6875 return fold_build2 (TREE_CODE (expr),
6876 boolean_type_node,
6877 TREE_OPERAND (expr, 0),
6878 TREE_OPERAND (expr, 1));
6879 else
6880 return NULL_TREE;
6881 }
6882 }
6883
6884 /* Check to see if a boolean expression EXPR is logically equivalent to the
6885 comparison (OP1 CODE OP2). Check for various identities involving
6886 SSA_NAMEs. */
6887
6888 static bool
6889 same_bool_comparison_p (const_tree expr, enum tree_code code,
6890 const_tree op1, const_tree op2)
6891 {
6892 gimple *s;
6893
6894 /* The obvious case. */
6895 if (TREE_CODE (expr) == code
6896 && operand_equal_p (TREE_OPERAND (expr, 0), op1, 0)
6897 && operand_equal_p (TREE_OPERAND (expr, 1), op2, 0))
6898 return true;
6899
6900 /* Check for comparing (name, name != 0) and the case where expr
6901 is an SSA_NAME with a definition matching the comparison. */
6902 if (TREE_CODE (expr) == SSA_NAME
6903 && TREE_CODE (TREE_TYPE (expr)) == BOOLEAN_TYPE)
6904 {
6905 if (operand_equal_p (expr, op1, 0))
6906 return ((code == NE_EXPR && integer_zerop (op2))
6907 || (code == EQ_EXPR && integer_nonzerop (op2)));
6908 s = SSA_NAME_DEF_STMT (expr);
6909 if (is_gimple_assign (s)
6910 && gimple_assign_rhs_code (s) == code
6911 && operand_equal_p (gimple_assign_rhs1 (s), op1, 0)
6912 && operand_equal_p (gimple_assign_rhs2 (s), op2, 0))
6913 return true;
6914 }
6915
6916 /* If op1 is of the form (name != 0) or (name == 0), and the definition
6917 of name is a comparison, recurse. */
6918 if (TREE_CODE (op1) == SSA_NAME
6919 && TREE_CODE (TREE_TYPE (op1)) == BOOLEAN_TYPE)
6920 {
6921 s = SSA_NAME_DEF_STMT (op1);
6922 if (is_gimple_assign (s)
6923 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
6924 {
6925 enum tree_code c = gimple_assign_rhs_code (s);
6926 if ((c == NE_EXPR && integer_zerop (op2))
6927 || (c == EQ_EXPR && integer_nonzerop (op2)))
6928 return same_bool_comparison_p (expr, c,
6929 gimple_assign_rhs1 (s),
6930 gimple_assign_rhs2 (s));
6931 if ((c == EQ_EXPR && integer_zerop (op2))
6932 || (c == NE_EXPR && integer_nonzerop (op2)))
6933 return same_bool_comparison_p (expr,
6934 invert_tree_comparison (c, false),
6935 gimple_assign_rhs1 (s),
6936 gimple_assign_rhs2 (s));
6937 }
6938 }
6939 return false;
6940 }
6941
6942 /* Check to see if two boolean expressions OP1 and OP2 are logically
6943 equivalent. */
6944
6945 static bool
6946 same_bool_result_p (const_tree op1, const_tree op2)
6947 {
6948 /* Simple cases first. */
6949 if (operand_equal_p (op1, op2, 0))
6950 return true;
6951
6952 /* Check the cases where at least one of the operands is a comparison.
6953 These are a bit smarter than operand_equal_p in that they apply some
6954 identifies on SSA_NAMEs. */
6955 if (COMPARISON_CLASS_P (op2)
6956 && same_bool_comparison_p (op1, TREE_CODE (op2),
6957 TREE_OPERAND (op2, 0),
6958 TREE_OPERAND (op2, 1)))
6959 return true;
6960 if (COMPARISON_CLASS_P (op1)
6961 && same_bool_comparison_p (op2, TREE_CODE (op1),
6962 TREE_OPERAND (op1, 0),
6963 TREE_OPERAND (op1, 1)))
6964 return true;
6965
6966 /* Default case. */
6967 return false;
6968 }
6969
6970 /* Forward declarations for some mutually recursive functions. */
6971
6972 static tree
6973 and_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
6974 enum tree_code code2, tree op2a, tree op2b, basic_block);
6975 static tree
6976 and_var_with_comparison (tree type, tree var, bool invert,
6977 enum tree_code code2, tree op2a, tree op2b,
6978 basic_block);
6979 static tree
6980 and_var_with_comparison_1 (tree type, gimple *stmt,
6981 enum tree_code code2, tree op2a, tree op2b,
6982 basic_block);
6983 static tree
6984 or_comparisons_1 (tree, enum tree_code code1, tree op1a, tree op1b,
6985 enum tree_code code2, tree op2a, tree op2b,
6986 basic_block);
6987 static tree
6988 or_var_with_comparison (tree, tree var, bool invert,
6989 enum tree_code code2, tree op2a, tree op2b,
6990 basic_block);
6991 static tree
6992 or_var_with_comparison_1 (tree, gimple *stmt,
6993 enum tree_code code2, tree op2a, tree op2b,
6994 basic_block);
6995
6996 /* Helper function for and_comparisons_1: try to simplify the AND of the
6997 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
6998 If INVERT is true, invert the value of the VAR before doing the AND.
6999 Return NULL_EXPR if we can't simplify this to a single expression. */
7000
7001 static tree
7002 and_var_with_comparison (tree type, tree var, bool invert,
7003 enum tree_code code2, tree op2a, tree op2b,
7004 basic_block outer_cond_bb)
7005 {
7006 tree t;
7007 gimple *stmt = SSA_NAME_DEF_STMT (var);
7008
7009 /* We can only deal with variables whose definitions are assignments. */
7010 if (!is_gimple_assign (stmt))
7011 return NULL_TREE;
7012
7013 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
7014 !var AND (op2a code2 op2b) => !(var OR !(op2a code2 op2b))
7015 Then we only have to consider the simpler non-inverted cases. */
7016 if (invert)
7017 t = or_var_with_comparison_1 (type, stmt,
7018 invert_tree_comparison (code2, false),
7019 op2a, op2b, outer_cond_bb);
7020 else
7021 t = and_var_with_comparison_1 (type, stmt, code2, op2a, op2b,
7022 outer_cond_bb);
7023 return canonicalize_bool (t, invert);
7024 }
7025
7026 /* Try to simplify the AND of the ssa variable defined by the assignment
7027 STMT with the comparison specified by (OP2A CODE2 OP2B).
7028 Return NULL_EXPR if we can't simplify this to a single expression. */
7029
7030 static tree
7031 and_var_with_comparison_1 (tree type, gimple *stmt,
7032 enum tree_code code2, tree op2a, tree op2b,
7033 basic_block outer_cond_bb)
7034 {
7035 tree var = gimple_assign_lhs (stmt);
7036 tree true_test_var = NULL_TREE;
7037 tree false_test_var = NULL_TREE;
7038 enum tree_code innercode = gimple_assign_rhs_code (stmt);
7039
7040 /* Check for identities like (var AND (var == 0)) => false. */
7041 if (TREE_CODE (op2a) == SSA_NAME
7042 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
7043 {
7044 if ((code2 == NE_EXPR && integer_zerop (op2b))
7045 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
7046 {
7047 true_test_var = op2a;
7048 if (var == true_test_var)
7049 return var;
7050 }
7051 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
7052 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
7053 {
7054 false_test_var = op2a;
7055 if (var == false_test_var)
7056 return boolean_false_node;
7057 }
7058 }
7059
7060 /* If the definition is a comparison, recurse on it. */
7061 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
7062 {
7063 tree t = and_comparisons_1 (type, innercode,
7064 gimple_assign_rhs1 (stmt),
7065 gimple_assign_rhs2 (stmt),
7066 code2,
7067 op2a,
7068 op2b, outer_cond_bb);
7069 if (t)
7070 return t;
7071 }
7072
7073 /* If the definition is an AND or OR expression, we may be able to
7074 simplify by reassociating. */
7075 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
7076 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
7077 {
7078 tree inner1 = gimple_assign_rhs1 (stmt);
7079 tree inner2 = gimple_assign_rhs2 (stmt);
7080 gimple *s;
7081 tree t;
7082 tree partial = NULL_TREE;
7083 bool is_and = (innercode == BIT_AND_EXPR);
7084
7085 /* Check for boolean identities that don't require recursive examination
7086 of inner1/inner2:
7087 inner1 AND (inner1 AND inner2) => inner1 AND inner2 => var
7088 inner1 AND (inner1 OR inner2) => inner1
7089 !inner1 AND (inner1 AND inner2) => false
7090 !inner1 AND (inner1 OR inner2) => !inner1 AND inner2
7091 Likewise for similar cases involving inner2. */
7092 if (inner1 == true_test_var)
7093 return (is_and ? var : inner1);
7094 else if (inner2 == true_test_var)
7095 return (is_and ? var : inner2);
7096 else if (inner1 == false_test_var)
7097 return (is_and
7098 ? boolean_false_node
7099 : and_var_with_comparison (type, inner2, false, code2, op2a,
7100 op2b, outer_cond_bb));
7101 else if (inner2 == false_test_var)
7102 return (is_and
7103 ? boolean_false_node
7104 : and_var_with_comparison (type, inner1, false, code2, op2a,
7105 op2b, outer_cond_bb));
7106
7107 /* Next, redistribute/reassociate the AND across the inner tests.
7108 Compute the first partial result, (inner1 AND (op2a code op2b)) */
7109 if (TREE_CODE (inner1) == SSA_NAME
7110 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
7111 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
7112 && (t = maybe_fold_and_comparisons (type, gimple_assign_rhs_code (s),
7113 gimple_assign_rhs1 (s),
7114 gimple_assign_rhs2 (s),
7115 code2, op2a, op2b,
7116 outer_cond_bb)))
7117 {
7118 /* Handle the AND case, where we are reassociating:
7119 (inner1 AND inner2) AND (op2a code2 op2b)
7120 => (t AND inner2)
7121 If the partial result t is a constant, we win. Otherwise
7122 continue on to try reassociating with the other inner test. */
7123 if (is_and)
7124 {
7125 if (integer_onep (t))
7126 return inner2;
7127 else if (integer_zerop (t))
7128 return boolean_false_node;
7129 }
7130
7131 /* Handle the OR case, where we are redistributing:
7132 (inner1 OR inner2) AND (op2a code2 op2b)
7133 => (t OR (inner2 AND (op2a code2 op2b))) */
7134 else if (integer_onep (t))
7135 return boolean_true_node;
7136
7137 /* Save partial result for later. */
7138 partial = t;
7139 }
7140
7141 /* Compute the second partial result, (inner2 AND (op2a code op2b)) */
7142 if (TREE_CODE (inner2) == SSA_NAME
7143 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
7144 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
7145 && (t = maybe_fold_and_comparisons (type, gimple_assign_rhs_code (s),
7146 gimple_assign_rhs1 (s),
7147 gimple_assign_rhs2 (s),
7148 code2, op2a, op2b,
7149 outer_cond_bb)))
7150 {
7151 /* Handle the AND case, where we are reassociating:
7152 (inner1 AND inner2) AND (op2a code2 op2b)
7153 => (inner1 AND t) */
7154 if (is_and)
7155 {
7156 if (integer_onep (t))
7157 return inner1;
7158 else if (integer_zerop (t))
7159 return boolean_false_node;
7160 /* If both are the same, we can apply the identity
7161 (x AND x) == x. */
7162 else if (partial && same_bool_result_p (t, partial))
7163 return t;
7164 }
7165
7166 /* Handle the OR case. where we are redistributing:
7167 (inner1 OR inner2) AND (op2a code2 op2b)
7168 => (t OR (inner1 AND (op2a code2 op2b)))
7169 => (t OR partial) */
7170 else
7171 {
7172 if (integer_onep (t))
7173 return boolean_true_node;
7174 else if (partial)
7175 {
7176 /* We already got a simplification for the other
7177 operand to the redistributed OR expression. The
7178 interesting case is when at least one is false.
7179 Or, if both are the same, we can apply the identity
7180 (x OR x) == x. */
7181 if (integer_zerop (partial))
7182 return t;
7183 else if (integer_zerop (t))
7184 return partial;
7185 else if (same_bool_result_p (t, partial))
7186 return t;
7187 }
7188 }
7189 }
7190 }
7191 return NULL_TREE;
7192 }
7193
7194 /* Try to simplify the AND of two comparisons defined by
7195 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
7196 If this can be done without constructing an intermediate value,
7197 return the resulting tree; otherwise NULL_TREE is returned.
7198 This function is deliberately asymmetric as it recurses on SSA_DEFs
7199 in the first comparison but not the second. */
7200
7201 static tree
7202 and_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
7203 enum tree_code code2, tree op2a, tree op2b,
7204 basic_block outer_cond_bb)
7205 {
7206 tree truth_type = truth_type_for (TREE_TYPE (op1a));
7207
7208 /* First check for ((x CODE1 y) AND (x CODE2 y)). */
7209 if (operand_equal_p (op1a, op2a, 0)
7210 && operand_equal_p (op1b, op2b, 0))
7211 {
7212 /* Result will be either NULL_TREE, or a combined comparison. */
7213 tree t = combine_comparisons (UNKNOWN_LOCATION,
7214 TRUTH_ANDIF_EXPR, code1, code2,
7215 truth_type, op1a, op1b);
7216 if (t)
7217 return t;
7218 }
7219
7220 /* Likewise the swapped case of the above. */
7221 if (operand_equal_p (op1a, op2b, 0)
7222 && operand_equal_p (op1b, op2a, 0))
7223 {
7224 /* Result will be either NULL_TREE, or a combined comparison. */
7225 tree t = combine_comparisons (UNKNOWN_LOCATION,
7226 TRUTH_ANDIF_EXPR, code1,
7227 swap_tree_comparison (code2),
7228 truth_type, op1a, op1b);
7229 if (t)
7230 return t;
7231 }
7232
7233 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
7234 NAME's definition is a truth value. See if there are any simplifications
7235 that can be done against the NAME's definition. */
7236 if (TREE_CODE (op1a) == SSA_NAME
7237 && (code1 == NE_EXPR || code1 == EQ_EXPR)
7238 && (integer_zerop (op1b) || integer_onep (op1b)))
7239 {
7240 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
7241 || (code1 == NE_EXPR && integer_onep (op1b)));
7242 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
7243 switch (gimple_code (stmt))
7244 {
7245 case GIMPLE_ASSIGN:
7246 /* Try to simplify by copy-propagating the definition. */
7247 return and_var_with_comparison (type, op1a, invert, code2, op2a,
7248 op2b, outer_cond_bb);
7249
7250 case GIMPLE_PHI:
7251 /* If every argument to the PHI produces the same result when
7252 ANDed with the second comparison, we win.
7253 Do not do this unless the type is bool since we need a bool
7254 result here anyway. */
7255 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
7256 {
7257 tree result = NULL_TREE;
7258 unsigned i;
7259 for (i = 0; i < gimple_phi_num_args (stmt); i++)
7260 {
7261 tree arg = gimple_phi_arg_def (stmt, i);
7262
7263 /* If this PHI has itself as an argument, ignore it.
7264 If all the other args produce the same result,
7265 we're still OK. */
7266 if (arg == gimple_phi_result (stmt))
7267 continue;
7268 else if (TREE_CODE (arg) == INTEGER_CST)
7269 {
7270 if (invert ? integer_nonzerop (arg) : integer_zerop (arg))
7271 {
7272 if (!result)
7273 result = boolean_false_node;
7274 else if (!integer_zerop (result))
7275 return NULL_TREE;
7276 }
7277 else if (!result)
7278 result = fold_build2 (code2, boolean_type_node,
7279 op2a, op2b);
7280 else if (!same_bool_comparison_p (result,
7281 code2, op2a, op2b))
7282 return NULL_TREE;
7283 }
7284 else if (TREE_CODE (arg) == SSA_NAME
7285 && !SSA_NAME_IS_DEFAULT_DEF (arg))
7286 {
7287 tree temp;
7288 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
7289 /* In simple cases we can look through PHI nodes,
7290 but we have to be careful with loops.
7291 See PR49073. */
7292 if (! dom_info_available_p (CDI_DOMINATORS)
7293 || gimple_bb (def_stmt) == gimple_bb (stmt)
7294 || dominated_by_p (CDI_DOMINATORS,
7295 gimple_bb (def_stmt),
7296 gimple_bb (stmt)))
7297 return NULL_TREE;
7298 temp = and_var_with_comparison (type, arg, invert, code2,
7299 op2a, op2b,
7300 outer_cond_bb);
7301 if (!temp)
7302 return NULL_TREE;
7303 else if (!result)
7304 result = temp;
7305 else if (!same_bool_result_p (result, temp))
7306 return NULL_TREE;
7307 }
7308 else
7309 return NULL_TREE;
7310 }
7311 return result;
7312 }
7313
7314 default:
7315 break;
7316 }
7317 }
7318 return NULL_TREE;
7319 }
7320
7321 static basic_block fosa_bb;
7322 static vec<std::pair<tree, flow_sensitive_info_storage> > *fosa_unwind;
7323 static tree
7324 follow_outer_ssa_edges (tree val)
7325 {
7326 if (TREE_CODE (val) == SSA_NAME
7327 && !SSA_NAME_IS_DEFAULT_DEF (val))
7328 {
7329 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (val));
7330 if (!def_bb
7331 || def_bb == fosa_bb
7332 || (dom_info_available_p (CDI_DOMINATORS)
7333 && (def_bb == fosa_bb
7334 || dominated_by_p (CDI_DOMINATORS, fosa_bb, def_bb))))
7335 return val;
7336 /* We cannot temporarily rewrite stmts with undefined overflow
7337 behavior, so avoid expanding them. */
7338 if ((ANY_INTEGRAL_TYPE_P (TREE_TYPE (val))
7339 || POINTER_TYPE_P (TREE_TYPE (val)))
7340 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (val)))
7341 return NULL_TREE;
7342 flow_sensitive_info_storage storage;
7343 storage.save_and_clear (val);
7344 /* If the definition does not dominate fosa_bb temporarily reset
7345 flow-sensitive info. */
7346 fosa_unwind->safe_push (std::make_pair (val, storage));
7347 return val;
7348 }
7349 return val;
7350 }
7351
7352 /* Helper function for maybe_fold_and_comparisons and maybe_fold_or_comparisons
7353 : try to simplify the AND/OR of the ssa variable VAR with the comparison
7354 specified by (OP2A CODE2 OP2B) from match.pd. Return NULL_EXPR if we can't
7355 simplify this to a single expression. As we are going to lower the cost
7356 of building SSA names / gimple stmts significantly, we need to allocate
7357 them ont the stack. This will cause the code to be a bit ugly. */
7358
7359 static tree
7360 maybe_fold_comparisons_from_match_pd (tree type, enum tree_code code,
7361 enum tree_code code1,
7362 tree op1a, tree op1b,
7363 enum tree_code code2, tree op2a,
7364 tree op2b,
7365 basic_block outer_cond_bb)
7366 {
7367 /* Allocate gimple stmt1 on the stack. */
7368 gassign *stmt1
7369 = (gassign *) XALLOCAVEC (char, gimple_size (GIMPLE_ASSIGN, 3));
7370 gimple_init (stmt1, GIMPLE_ASSIGN, 3);
7371 gimple_assign_set_rhs_code (stmt1, code1);
7372 gimple_assign_set_rhs1 (stmt1, op1a);
7373 gimple_assign_set_rhs2 (stmt1, op1b);
7374 gimple_set_bb (stmt1, NULL);
7375
7376 /* Allocate gimple stmt2 on the stack. */
7377 gassign *stmt2
7378 = (gassign *) XALLOCAVEC (char, gimple_size (GIMPLE_ASSIGN, 3));
7379 gimple_init (stmt2, GIMPLE_ASSIGN, 3);
7380 gimple_assign_set_rhs_code (stmt2, code2);
7381 gimple_assign_set_rhs1 (stmt2, op2a);
7382 gimple_assign_set_rhs2 (stmt2, op2b);
7383 gimple_set_bb (stmt2, NULL);
7384
7385 /* Allocate SSA names(lhs1) on the stack. */
7386 alignas (tree_node) unsigned char lhs1buf[sizeof (tree_ssa_name)];
7387 tree lhs1 = (tree) &lhs1buf[0];
7388 memset (lhs1, 0, sizeof (tree_ssa_name));
7389 TREE_SET_CODE (lhs1, SSA_NAME);
7390 TREE_TYPE (lhs1) = type;
7391 init_ssa_name_imm_use (lhs1);
7392
7393 /* Allocate SSA names(lhs2) on the stack. */
7394 alignas (tree_node) unsigned char lhs2buf[sizeof (tree_ssa_name)];
7395 tree lhs2 = (tree) &lhs2buf[0];
7396 memset (lhs2, 0, sizeof (tree_ssa_name));
7397 TREE_SET_CODE (lhs2, SSA_NAME);
7398 TREE_TYPE (lhs2) = type;
7399 init_ssa_name_imm_use (lhs2);
7400
7401 gimple_assign_set_lhs (stmt1, lhs1);
7402 gimple_assign_set_lhs (stmt2, lhs2);
7403
7404 gimple_match_op op (gimple_match_cond::UNCOND, code,
7405 type, gimple_assign_lhs (stmt1),
7406 gimple_assign_lhs (stmt2));
7407 fosa_bb = outer_cond_bb;
7408 auto_vec<std::pair<tree, flow_sensitive_info_storage>, 8> unwind_stack;
7409 fosa_unwind = &unwind_stack;
7410 if (op.resimplify (NULL, (!outer_cond_bb
7411 ? follow_all_ssa_edges : follow_outer_ssa_edges)))
7412 {
7413 fosa_unwind = NULL;
7414 for (auto p : unwind_stack)
7415 p.second.restore (p.first);
7416 if (gimple_simplified_result_is_gimple_val (&op))
7417 {
7418 tree res = op.ops[0];
7419 if (res == lhs1)
7420 return build2 (code1, type, op1a, op1b);
7421 else if (res == lhs2)
7422 return build2 (code2, type, op2a, op2b);
7423 else
7424 return res;
7425 }
7426 else if (op.code.is_tree_code ()
7427 && TREE_CODE_CLASS ((tree_code)op.code) == tcc_comparison)
7428 {
7429 tree op0 = op.ops[0];
7430 tree op1 = op.ops[1];
7431 if (op0 == lhs1 || op0 == lhs2 || op1 == lhs1 || op1 == lhs2)
7432 return NULL_TREE; /* not simple */
7433
7434 return build2 ((enum tree_code)op.code, op.type, op0, op1);
7435 }
7436 }
7437 fosa_unwind = NULL;
7438 for (auto p : unwind_stack)
7439 p.second.restore (p.first);
7440
7441 return NULL_TREE;
7442 }
7443
7444 /* Return TRUE and set op[0] if T, following all SSA edges, is a type
7445 conversion. Reject loads if LOAD is NULL, otherwise set *LOAD if a
7446 converting load is found. */
7447
7448 static bool
7449 gimple_convert_def_p (tree t, tree op[1], gimple **load = NULL)
7450 {
7451 bool ret = false;
7452
7453 if (TREE_CODE (t) == SSA_NAME
7454 && !SSA_NAME_IS_DEFAULT_DEF (t))
7455 if (gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (t)))
7456 {
7457 bool load_p = gimple_assign_load_p (def);
7458 if (load_p && !load)
7459 return false;
7460 switch (gimple_assign_rhs_code (def))
7461 {
7462 CASE_CONVERT:
7463 op[0] = gimple_assign_rhs1 (def);
7464 ret = true;
7465 break;
7466
7467 case VIEW_CONVERT_EXPR:
7468 op[0] = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
7469 ret = true;
7470 break;
7471
7472 default:
7473 break;
7474 }
7475
7476 if (ret && load_p)
7477 *load = def;
7478 }
7479
7480 return ret;
7481 }
7482
7483 /* Return TRUE and set op[*] if T, following all SSA edges, resolves to a
7484 binary expression with code CODE. */
7485
7486 static bool
7487 gimple_binop_def_p (enum tree_code code, tree t, tree op[2])
7488 {
7489 if (TREE_CODE (t) == SSA_NAME
7490 && !SSA_NAME_IS_DEFAULT_DEF (t))
7491 if (gimple *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (t)))
7492 if (gimple_assign_rhs_code (def) == code)
7493 {
7494 op[0] = gimple_assign_rhs1 (def);
7495 op[1] = gimple_assign_rhs2 (def);
7496 return true;
7497 }
7498 return false;
7499 }
7500 /* Subroutine for fold_truth_andor_1: decode a field reference.
7501
7502 If *PEXP is a comparison reference, we return the innermost reference.
7503
7504 *PBITSIZE is set to the number of bits in the reference, *PBITPOS is
7505 set to the starting bit number.
7506
7507 *PVOLATILEP is set to 1 if the any expression encountered is volatile;
7508 otherwise it is not changed.
7509
7510 *PUNSIGNEDP is set to the signedness of the field.
7511
7512 *PREVERSEP is set to the storage order of the field.
7513
7514 *PAND_MASK is set to the mask found in a BIT_AND_EXPR, if any. If
7515 *PAND_MASK is initially set to a mask with nonzero precision, that mask is
7516 combined with the found mask, or adjusted in precision to match.
7517
7518 *PSIGNBIT is set to TRUE if, before clipping to *PBITSIZE, the mask
7519 encompassed bits that corresponded to extensions of the sign bit.
7520
7521 *PXORP is to be FALSE if EXP might be a XOR used in a compare, in which
7522 case, if PXOR_CMP_OP is a zero constant, it will be overridden with *PEXP,
7523 *PXORP will be set to TRUE, *PXOR_AND_MASK will be copied from *PAND_MASK,
7524 and the left-hand operand of the XOR will be decoded. If *PXORP is TRUE,
7525 PXOR_CMP_OP and PXOR_AND_MASK are supposed to be NULL, and then the
7526 right-hand operand of the XOR will be decoded.
7527
7528 *LOAD is set to the load stmt of the innermost reference, if any,
7529 *and NULL otherwise.
7530
7531 LOC[0..3] are filled in as conversion, masking, shifting and loading
7532 operations are located.
7533
7534 Return 0 if this is not a component reference or is one that we can't
7535 do anything with. */
7536
7537 static tree
7538 decode_field_reference (tree *pexp, HOST_WIDE_INT *pbitsize,
7539 HOST_WIDE_INT *pbitpos,
7540 bool *punsignedp, bool *preversep, bool *pvolatilep,
7541 wide_int *pand_mask, bool *psignbit,
7542 bool *pxorp, tree *pxor_cmp_op, wide_int *pxor_and_mask,
7543 gimple **pload, location_t loc[4])
7544 {
7545 tree exp = *pexp;
7546 tree outer_type = 0;
7547 wide_int and_mask;
7548 tree inner, offset;
7549 int shiftrt = 0;
7550 tree res_ops[2];
7551 machine_mode mode;
7552 bool convert_before_shift = false;
7553 bool signbit = false;
7554 bool xorp = false;
7555 tree xor_cmp_op;
7556 wide_int xor_and_mask;
7557 gimple *load = NULL;
7558
7559 /* All the optimizations using this function assume integer fields.
7560 There are problems with FP fields since the type_for_size call
7561 below can fail for, e.g., XFmode. */
7562 if (! INTEGRAL_TYPE_P (TREE_TYPE (exp)))
7563 return NULL_TREE;
7564
7565 /* Drop casts, saving only the outermost type, effectively used in
7566 the compare. We can deal with at most one conversion, and it may
7567 appear at various points in the chain of recognized preparation
7568 statements. Earlier optimizers will often have already dropped
7569 unneeded extensions, but they may survive, as in PR118046. ???
7570 Can we do better and allow multiple conversions, perhaps taking
7571 note of the narrowest intermediate type, sign extensions and
7572 whatnot? */
7573 if (!outer_type && gimple_convert_def_p (exp, res_ops))
7574 {
7575 outer_type = TREE_TYPE (exp);
7576 loc[0] = gimple_location (SSA_NAME_DEF_STMT (exp));
7577 exp = res_ops[0];
7578 }
7579
7580 /* Recognize and save a masking operation. Combine it with an
7581 incoming mask. */
7582 if (gimple_binop_def_p (BIT_AND_EXPR, exp, res_ops)
7583 && TREE_CODE (res_ops[1]) == INTEGER_CST)
7584 {
7585 loc[1] = gimple_location (SSA_NAME_DEF_STMT (exp));
7586 exp = res_ops[0];
7587 and_mask = wi::to_wide (res_ops[1]);
7588 unsigned prec_in = pand_mask->get_precision ();
7589 if (prec_in)
7590 {
7591 unsigned prec_op = and_mask.get_precision ();
7592 if (prec_in >= prec_op)
7593 {
7594 if (prec_in > prec_op)
7595 and_mask = wide_int::from (and_mask, prec_in, UNSIGNED);
7596 and_mask &= *pand_mask;
7597 }
7598 else
7599 and_mask &= wide_int::from (*pand_mask, prec_op, UNSIGNED);
7600 }
7601 }
7602 else
7603 and_mask = *pand_mask;
7604
7605 /* Turn (a ^ b) [!]= 0 into a [!]= b. */
7606 if (pxorp && gimple_binop_def_p (BIT_XOR_EXPR, exp, res_ops))
7607 {
7608 /* No location recorded for this one, it's entirely subsumed by the
7609 compare. */
7610 if (*pxorp)
7611 {
7612 exp = res_ops[1];
7613 gcc_checking_assert (!pxor_cmp_op && !pxor_and_mask);
7614 }
7615 else if (!pxor_cmp_op)
7616 /* Not much we can do when xor appears in the right-hand compare
7617 operand. */
7618 return NULL_TREE;
7619 else if (integer_zerop (*pxor_cmp_op))
7620 {
7621 xorp = true;
7622 exp = res_ops[0];
7623 xor_cmp_op = *pexp;
7624 xor_and_mask = *pand_mask;
7625 }
7626 }
7627
7628 /* Another chance to drop conversions. */
7629 if (!outer_type && gimple_convert_def_p (exp, res_ops))
7630 {
7631 outer_type = TREE_TYPE (exp);
7632 loc[0] = gimple_location (SSA_NAME_DEF_STMT (exp));
7633 exp = res_ops[0];
7634 }
7635
7636 /* Take note of shifts. */
7637 if (gimple_binop_def_p (RSHIFT_EXPR, exp, res_ops)
7638 && TREE_CODE (res_ops[1]) == INTEGER_CST)
7639 {
7640 loc[2] = gimple_location (SSA_NAME_DEF_STMT (exp));
7641 exp = res_ops[0];
7642 if (!tree_fits_shwi_p (res_ops[1]))
7643 return NULL_TREE;
7644 shiftrt = tree_to_shwi (res_ops[1]);
7645 if (shiftrt <= 0)
7646 return NULL_TREE;
7647 }
7648
7649 /* Yet another chance to drop conversions. This one is allowed to
7650 match a converting load, subsuming the load identification block
7651 below. */
7652 if (!outer_type && gimple_convert_def_p (exp, res_ops, &load))
7653 {
7654 outer_type = TREE_TYPE (exp);
7655 loc[0] = gimple_location (SSA_NAME_DEF_STMT (exp));
7656 if (load)
7657 loc[3] = gimple_location (load);
7658 exp = res_ops[0];
7659 /* This looks backwards, but we're going back the def chain, so if we
7660 find the conversion here, after finding a shift, that's because the
7661 convert appears before the shift, and we should thus adjust the bit
7662 pos and size because of the shift after adjusting it due to type
7663 conversion. */
7664 convert_before_shift = true;
7665 }
7666
7667 /* Identify the load, if there is one. */
7668 if (!load && TREE_CODE (exp) == SSA_NAME && !SSA_NAME_IS_DEFAULT_DEF (exp))
7669 {
7670 gimple *def = SSA_NAME_DEF_STMT (exp);
7671 if (gimple_assign_load_p (def))
7672 {
7673 loc[3] = gimple_location (def);
7674 load = def;
7675 exp = gimple_assign_rhs1 (def);
7676 }
7677 }
7678
7679 /* Identify the relevant bits. */
7680 poly_int64 poly_bitsize, poly_bitpos;
7681 int unsignedp, reversep = *preversep, volatilep = *pvolatilep;
7682 inner = get_inner_reference (exp, &poly_bitsize, &poly_bitpos, &offset,
7683 &mode, &unsignedp, &reversep, &volatilep);
7684
7685 HOST_WIDE_INT bs, bp;
7686 if (!poly_bitsize.is_constant (&bs)
7687 || !poly_bitpos.is_constant (&bp)
7688 || bs <= shiftrt
7689 || offset != 0
7690 || TREE_CODE (inner) == PLACEHOLDER_EXPR
7691 /* Reject out-of-bound accesses (PR79731, PR118514). */
7692 || !access_in_bounds_of_type_p (TREE_TYPE (inner), bs, bp)
7693 || (INTEGRAL_TYPE_P (TREE_TYPE (inner))
7694 && !type_has_mode_precision_p (TREE_TYPE (inner))))
7695 return NULL_TREE;
7696
7697 /* Adjust shifts... */
7698 if (convert_before_shift
7699 && outer_type && bs > TYPE_PRECISION (outer_type))
7700 {
7701 HOST_WIDE_INT excess = bs - TYPE_PRECISION (outer_type);
7702 if (reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
7703 bp += excess;
7704 bs -= excess;
7705 }
7706
7707 if (shiftrt)
7708 {
7709 /* Punt if we're shifting by more than the loaded bitfield (after
7710 adjustment), or if there's a shift after a change of signedness, punt.
7711 When comparing this field with a constant, we'll check that the
7712 constant is a proper sign- or zero-extension (depending on signedness)
7713 of a value that would fit in the selected portion of the bitfield. A
7714 shift after a change of signedness would make the extension
7715 non-uniform, and we can't deal with that (yet ???). See
7716 gcc.dg/field-merge-22.c for a test that would go wrong. */
7717 if (bs <= shiftrt
7718 || (convert_before_shift
7719 && outer_type && unsignedp != TYPE_UNSIGNED (outer_type)))
7720 return NULL_TREE;
7721 if (!reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
7722 bp += shiftrt;
7723 bs -= shiftrt;
7724 }
7725
7726 /* ... and bit position. */
7727 if (!convert_before_shift
7728 && outer_type && bs > TYPE_PRECISION (outer_type))
7729 {
7730 HOST_WIDE_INT excess = bs - TYPE_PRECISION (outer_type);
7731 if (reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
7732 bp += excess;
7733 bs -= excess;
7734 }
7735
7736 /* If the number of bits in the reference is the same as the bitsize of
7737 the outer type, then the outer type gives the signedness. Otherwise
7738 (in case of a small bitfield) the signedness is unchanged. */
7739 if (outer_type && bs == TYPE_PRECISION (outer_type))
7740 unsignedp = TYPE_UNSIGNED (outer_type);
7741
7742 /* Make the mask the expected width. */
7743 if (and_mask.get_precision () != 0)
7744 {
7745 /* If the AND_MASK encompasses bits that would be extensions of
7746 the sign bit, set SIGNBIT. */
7747 if (!unsignedp
7748 && and_mask.get_precision () > bs
7749 && (and_mask & wi::mask (bs, true, and_mask.get_precision ())) != 0)
7750 signbit = true;
7751 and_mask = wide_int::from (and_mask, bs, UNSIGNED);
7752 }
7753
7754 *pexp = exp;
7755 *pload = load;
7756 *pbitsize = bs;
7757 *pbitpos = bp;
7758 *punsignedp = unsignedp;
7759 *preversep = reversep;
7760 *pvolatilep = volatilep;
7761 *psignbit = signbit;
7762 *pand_mask = and_mask;
7763 if (xorp)
7764 {
7765 *pxorp = xorp;
7766 *pxor_cmp_op = xor_cmp_op;
7767 *pxor_and_mask = xor_and_mask;
7768 }
7769
7770 return inner;
7771 }
7772
7773 /* Return the one bitpos within bit extents L or R that is at an
7774 ALIGN-bit alignment boundary, or -1 if there is more than one such
7775 boundary, if there isn't any, or if there is any such boundary
7776 between the extents. L and R are given by bitpos and bitsize. If
7777 it doesn't return -1, there are two consecutive ALIGN-bit words
7778 that contain both extents, and at least one of the extents
7779 straddles across the returned alignment boundary. */
7780
7781 static inline HOST_WIDE_INT
7782 compute_split_boundary_from_align (HOST_WIDE_INT align,
7783 HOST_WIDE_INT l_bitpos,
7784 HOST_WIDE_INT l_bitsize,
7785 HOST_WIDE_INT r_bitpos,
7786 HOST_WIDE_INT r_bitsize)
7787 {
7788 HOST_WIDE_INT amask = ~(align - 1);
7789
7790 HOST_WIDE_INT first_bit = MIN (l_bitpos, r_bitpos);
7791 HOST_WIDE_INT end_bit = MAX (l_bitpos + l_bitsize, r_bitpos + r_bitsize);
7792
7793 HOST_WIDE_INT boundary = (end_bit - 1) & amask;
7794
7795 /* Make sure we're crossing no more than one alignment boundary.
7796
7797 ??? We don't have logic to recombine loads of two adjacent
7798 fields that each crosses a different alignment boundary, so
7799 as to load the middle word only once, if other words can't be
7800 otherwise recombined. */
7801 if (boundary - first_bit > align)
7802 return -1;
7803
7804 HOST_WIDE_INT l_start_word = l_bitpos & amask;
7805 HOST_WIDE_INT l_end_word = (l_bitpos + l_bitsize - 1) & amask;
7806
7807 HOST_WIDE_INT r_start_word = r_bitpos & amask;
7808 HOST_WIDE_INT r_end_word = (r_bitpos + r_bitsize - 1) & amask;
7809
7810 /* If neither field straddles across an alignment boundary, it's no
7811 use to even try to merge them. */
7812 if (l_start_word == l_end_word && r_start_word == r_end_word)
7813 return -1;
7814
7815 return boundary;
7816 }
7817
7818 /* Make a bit_field_ref. If POINT is NULL, return the BIT_FIELD_REF.
7819 Otherwise, build and insert a load stmt before POINT, and return
7820 the SSA_NAME. ??? Rewrite LOAD in terms of the bitfield? */
7821
7822 static tree
7823 make_bit_field_load (location_t loc, tree inner, tree orig_inner, tree type,
7824 HOST_WIDE_INT bitsize, poly_int64 bitpos,
7825 bool unsignedp, bool reversep, gimple *point)
7826 {
7827 if (point && loc == UNKNOWN_LOCATION)
7828 loc = gimple_location (point);
7829
7830 tree ref = make_bit_field_ref (loc, unshare_expr (inner),
7831 unshare_expr (orig_inner),
7832 type, bitsize, bitpos,
7833 unsignedp, reversep);
7834 if (!point)
7835 return ref;
7836
7837 /* If we're remaking the same load, reuse the SSA NAME it is already loaded
7838 into. */
7839 if (gimple_assign_load_p (point)
7840 && operand_equal_p (ref, gimple_assign_rhs1 (point)))
7841 {
7842 gcc_checking_assert (TREE_CODE (gimple_assign_lhs (point)) == SSA_NAME);
7843 return gimple_assign_lhs (point);
7844 }
7845
7846 gimple_seq stmts = NULL;
7847 tree ret = force_gimple_operand (ref, &stmts, true, NULL_TREE);
7848
7849 /* We know the vuse is supposed to end up being the same as that at the
7850 original load at the insertion point, but if we don't set it, it will be a
7851 generic placeholder that only the global SSA update at the end of the pass
7852 would make equal, too late for us to use in further combinations. So go
7853 ahead and copy the vuse. */
7854
7855 tree reaching_vuse = gimple_vuse (point);
7856 for (gimple_stmt_iterator i = gsi_start (stmts);
7857 !gsi_end_p (i); gsi_next (&i))
7858 {
7859 gimple *new_stmt = gsi_stmt (i);
7860 if (gimple_has_mem_ops (new_stmt))
7861 gimple_set_vuse (new_stmt, reaching_vuse);
7862 }
7863
7864 gimple_stmt_iterator gsi = gsi_for_stmt (point);
7865 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
7866 return ret;
7867 }
7868
7869 /* Initialize ln_arg[0] and ln_arg[1] to a pair of newly-created (at
7870 LOC) loads from INNER (from ORIG_INNER), of modes MODE and MODE2,
7871 respectively, starting at BIT_POS, using reversed endianness if
7872 REVERSEP. Also initialize BITPOS (the starting position of each
7873 part into INNER), BITSIZ (the bit count starting at BITPOS),
7874 TOSHIFT[1] (the amount by which the part and its mask are to be
7875 shifted right to bring its least-significant bit to bit zero) and
7876 SHIFTED (the amount by which the part, by separate loading, has
7877 already been shifted right, but that the mask needs shifting to
7878 match). */
7879
7880 static inline void
7881 build_split_load (tree /* out */ ln_arg[2],
7882 HOST_WIDE_INT /* out */ bitpos[2],
7883 HOST_WIDE_INT /* out */ bitsiz[2],
7884 HOST_WIDE_INT /* in[0] out[0..1] */ toshift[2],
7885 HOST_WIDE_INT /* out */ shifted[2],
7886 location_t loc, tree inner, tree orig_inner,
7887 scalar_int_mode mode, scalar_int_mode mode2,
7888 HOST_WIDE_INT bit_pos, bool reversep,
7889 gimple *point[2])
7890 {
7891 scalar_int_mode modes[2] = { mode, mode2 };
7892 bitsiz[0] = GET_MODE_BITSIZE (mode);
7893 bitsiz[1] = GET_MODE_BITSIZE (mode2);
7894
7895 for (int i = 0; i < 2; i++)
7896 {
7897 tree type = lang_hooks.types.type_for_mode (modes[i], 1);
7898 if (!type)
7899 {
7900 type = build_nonstandard_integer_type (bitsiz[0], 1);
7901 gcc_assert (type);
7902 }
7903 bitpos[i] = bit_pos;
7904 ln_arg[i] = make_bit_field_load (loc, inner, orig_inner,
7905 type, bitsiz[i],
7906 bit_pos, 1, reversep, point[i]);
7907 bit_pos += bitsiz[i];
7908 }
7909
7910 toshift[1] = toshift[0];
7911 if (reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
7912 {
7913 shifted[0] = bitsiz[1];
7914 shifted[1] = 0;
7915 toshift[0] = 0;
7916 }
7917 else
7918 {
7919 shifted[1] = bitsiz[0];
7920 shifted[0] = 0;
7921 toshift[1] = 0;
7922 }
7923 }
7924
7925 /* Make arrangements to split at bit BOUNDARY a single loaded word
7926 (with REVERSEP bit order) LN_ARG[0], to be shifted right by
7927 TOSHIFT[0] to bring the field of interest to the least-significant
7928 bit. The expectation is that the same loaded word will be
7929 propagated from part 0 to part 1, with just different shifting and
7930 masking to extract both parts. MASK is not expected to do more
7931 than masking out the bits that belong to the other part. See
7932 build_split_load for more information on the other fields. */
7933
7934 static inline void
7935 reuse_split_load (tree /* in[0] out[1] */ ln_arg[2],
7936 HOST_WIDE_INT /* in[0] out[1] */ bitpos[2],
7937 HOST_WIDE_INT /* in[0] out[1] */ bitsiz[2],
7938 HOST_WIDE_INT /* in[0] out[0..1] */ toshift[2],
7939 HOST_WIDE_INT /* out */ shifted[2],
7940 wide_int /* out */ mask[2],
7941 HOST_WIDE_INT boundary, bool reversep)
7942 {
7943 unsigned prec = TYPE_PRECISION (TREE_TYPE (ln_arg[0]));
7944
7945 ln_arg[1] = ln_arg[0];
7946 bitpos[1] = bitpos[0];
7947 bitsiz[1] = bitsiz[0];
7948 shifted[1] = shifted[0] = 0;
7949
7950 if (reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
7951 {
7952 toshift[1] = toshift[0];
7953 toshift[0] = bitpos[0] + bitsiz[0] - boundary;
7954 mask[0] = wi::mask (toshift[0], true, prec);
7955 mask[1] = wi::mask (toshift[0], false, prec);
7956 }
7957 else
7958 {
7959 toshift[1] = boundary - bitpos[1];
7960 mask[1] = wi::mask (toshift[1], true, prec);
7961 mask[0] = wi::mask (toshift[1], false, prec);
7962 }
7963 }
7964
7965 /* Find ways of folding logical expressions of LHS and RHS:
7966
7967 Try to merge two comparisons to nearby fields.
7968
7969 For example, if we have p->a == 2 && p->b == 4 and we can load both A and B
7970 at once, we can do this with a comparison against the object ANDed with the
7971 a mask.
7972
7973 If we have p->a == q->a && p->b == q->b, we may be able to use bit masking
7974 operations to do this with one comparison, loading both fields from P at
7975 once, and likewise from Q.
7976
7977 Herein, loading at once means loading from within the same alignment
7978 boundary for the enclosing object. If (packed) fields cross such alignment
7979 boundaries, we may still recombine the compares, so that loads do not cross
7980 the boundaries.
7981
7982 CODE is the logical operation being done. It can be TRUTH_ANDIF_EXPR,
7983 TRUTH_AND_EXPR, TRUTH_ORIF_EXPR, or TRUTH_OR_EXPR.
7984
7985 TRUTH_TYPE is the type of the logical operand.
7986
7987 LHS is denoted as LL_ARG LCODE LR_ARG.
7988
7989 RHS is denoted as RL_ARG RCODE RR_ARG.
7990
7991 LHS is assumed to dominate RHS.
7992
7993 Combined loads are inserted next to preexisting loads, once we determine
7994 that the combination is viable, and the combined condition references new
7995 SSA_NAMEs that hold the loaded values. Since the original loads are
7996 verified to have the same gimple_vuse, the insertion point doesn't matter
7997 for correctness. ??? The loads may be a lot earlier than the compares, and
7998 it's conceivable that one or two loads for RHS appear before those for LHS.
7999 It could be advantageous to try to place the loads optimally, taking
8000 advantage of knowing whether RHS is accessed before LHS, or that both are
8001 accessed before both compares, but we don't do that (yet?).
8002
8003 SEPARATEP should be NULL if the combined condition must be returned as a
8004 single expression, even if it is a compound condition. This must only be
8005 done if LHS and RHS are adjacent, without intervening conditions, and the
8006 combined condition is to replace RHS, while LHS is dropped altogether.
8007
8008 Otherwise, SEPARATEP must be a non-NULL pointer to a NULL_TREE, that may be
8009 replaced by a part of the compound condition that could replace RHS, while
8010 the returned expression replaces LHS. This works whether or not LHS and RHS
8011 are adjacent, as long as there aren't VDEFs or other side effects between
8012 them.
8013
8014 If the "words" accessed by RHS are already accessed by LHS, this won't
8015 matter, but if RHS accesses "words" that LHS doesn't, then *SEPARATEP will
8016 be set to the compares that should take RHS's place. By "words" we mean
8017 contiguous bits that do not cross a an TYPE_ALIGN boundary of the accessed
8018 object's type.
8019
8020 We return the simplified tree or 0 if no optimization is possible. */
8021
8022 tree
8023 fold_truth_andor_for_ifcombine (enum tree_code code, tree truth_type,
8024 location_t lloc, enum tree_code lcode,
8025 tree ll_arg, tree lr_arg,
8026 location_t rloc, enum tree_code rcode,
8027 tree rl_arg, tree rr_arg,
8028 tree *separatep)
8029 {
8030 /* If this is the "or" of two comparisons, we can do something if
8031 the comparisons are NE_EXPR. If this is the "and", we can do something
8032 if the comparisons are EQ_EXPR. I.e.,
8033 (a->b == 2 && a->c == 4) can become (a->new == NEW).
8034
8035 WANTED_CODE is this operation code. For single bit fields, we can
8036 convert EQ_EXPR to NE_EXPR so we need not reject the "wrong"
8037 comparison for one-bit fields. */
8038
8039 enum tree_code orig_code = code;
8040 enum tree_code wanted_code;
8041 tree ll_inner, lr_inner, rl_inner, rr_inner;
8042 gimple *ll_load, *lr_load, *rl_load, *rr_load;
8043 HOST_WIDE_INT ll_bitsize, ll_bitpos, lr_bitsize, lr_bitpos;
8044 HOST_WIDE_INT rl_bitsize, rl_bitpos, rr_bitsize, rr_bitpos;
8045 HOST_WIDE_INT xll_bitpos, xlr_bitpos, xrl_bitpos, xrr_bitpos;
8046 HOST_WIDE_INT lnbitsize, lnbitpos, lnprec;
8047 HOST_WIDE_INT rnbitsize, rnbitpos, rnprec;
8048 bool ll_unsignedp, lr_unsignedp, rl_unsignedp, rr_unsignedp;
8049 bool ll_reversep, lr_reversep, rl_reversep, rr_reversep;
8050 bool ll_signbit, lr_signbit, rl_signbit, rr_signbit;
8051 scalar_int_mode lnmode, lnmode2, rnmode;
8052 wide_int ll_and_mask, lr_and_mask, rl_and_mask, rr_and_mask;
8053 wide_int l_const, r_const;
8054 tree lntype, rntype, result;
8055 HOST_WIDE_INT first_bit, end_bit;
8056 bool volatilep;
8057 bool l_split_load;
8058
8059 /* These are indexed by: conv, mask, shft, load. */
8060 location_t ll_loc[4] = { lloc, lloc, lloc, UNKNOWN_LOCATION };
8061 location_t lr_loc[4] = { lloc, lloc, lloc, UNKNOWN_LOCATION };
8062 location_t rl_loc[4] = { rloc, rloc, rloc, UNKNOWN_LOCATION };
8063 location_t rr_loc[4] = { rloc, rloc, rloc, UNKNOWN_LOCATION };
8064
8065 gcc_checking_assert (!separatep || !*separatep);
8066
8067 /* Start by getting the comparison codes. Fail if anything is volatile.
8068 If one operand is a BIT_AND_EXPR with the constant one, treat it as if
8069 it were surrounded with a NE_EXPR. */
8070
8071 if (TREE_CODE_CLASS (lcode) != tcc_comparison
8072 || TREE_CODE_CLASS (rcode) != tcc_comparison)
8073 return 0;
8074
8075 /* We don't normally find TRUTH_*IF_EXPR in gimple, but these codes may be
8076 given by our caller to denote conditions from different blocks. */
8077 switch (code)
8078 {
8079 case TRUTH_AND_EXPR:
8080 case TRUTH_ANDIF_EXPR:
8081 code = TRUTH_AND_EXPR;
8082 break;
8083
8084 case TRUTH_OR_EXPR:
8085 case TRUTH_ORIF_EXPR:
8086 code = TRUTH_OR_EXPR;
8087 break;
8088
8089 default:
8090 return 0;
8091 }
8092
8093 /* Prepare to turn compares of signed quantities with zero into sign-bit
8094 tests. We need not worry about *_reversep here for these compare
8095 rewrites: loads will have already been reversed before compares. Save the
8096 precision, because [lr]l_arg may change and we won't be able to tell how
8097 wide it was originally. */
8098 unsigned lsignbit = 0, rsignbit = 0;
8099 if ((lcode == LT_EXPR || lcode == GE_EXPR)
8100 && integer_zerop (lr_arg)
8101 && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg))
8102 && !TYPE_UNSIGNED (TREE_TYPE (ll_arg)))
8103 {
8104 lsignbit = TYPE_PRECISION (TREE_TYPE (ll_arg));
8105 lcode = (lcode == LT_EXPR ? NE_EXPR : EQ_EXPR);
8106 }
8107 /* Turn compares of unsigned quantities with powers of two into
8108 equality tests of masks. */
8109 else if ((lcode == LT_EXPR || lcode == GE_EXPR)
8110 && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg))
8111 && TYPE_UNSIGNED (TREE_TYPE (ll_arg))
8112 && TREE_CODE (lr_arg) == INTEGER_CST
8113 && wi::popcount (wi::to_wide (lr_arg)) == 1)
8114 {
8115 ll_and_mask = ~(wi::to_wide (lr_arg) - 1);
8116 lcode = (lcode == GE_EXPR ? NE_EXPR : EQ_EXPR);
8117 lr_arg = wide_int_to_tree (TREE_TYPE (ll_arg), ll_and_mask * 0);
8118 }
8119 /* Turn compares of unsigned quantities with powers of two minus one
8120 into equality tests of masks. */
8121 else if ((lcode == LE_EXPR || lcode == GT_EXPR)
8122 && INTEGRAL_TYPE_P (TREE_TYPE (ll_arg))
8123 && TYPE_UNSIGNED (TREE_TYPE (ll_arg))
8124 && TREE_CODE (lr_arg) == INTEGER_CST
8125 && wi::popcount (wi::to_wide (lr_arg) + 1) == 1)
8126 {
8127 ll_and_mask = ~wi::to_wide (lr_arg);
8128 lcode = (lcode == GT_EXPR ? NE_EXPR : EQ_EXPR);
8129 lr_arg = wide_int_to_tree (TREE_TYPE (ll_arg), ll_and_mask * 0);
8130 }
8131 /* Likewise for the second compare. */
8132 if ((rcode == LT_EXPR || rcode == GE_EXPR)
8133 && integer_zerop (rr_arg)
8134 && INTEGRAL_TYPE_P (TREE_TYPE (rl_arg))
8135 && !TYPE_UNSIGNED (TREE_TYPE (rl_arg)))
8136 {
8137 rsignbit = TYPE_PRECISION (TREE_TYPE (rl_arg));
8138 rcode = (rcode == LT_EXPR ? NE_EXPR : EQ_EXPR);
8139 }
8140 else if ((rcode == LT_EXPR || rcode == GE_EXPR)
8141 && INTEGRAL_TYPE_P (TREE_TYPE (rl_arg))
8142 && TYPE_UNSIGNED (TREE_TYPE (rl_arg))
8143 && TREE_CODE (rr_arg) == INTEGER_CST
8144 && wi::popcount (wi::to_wide (rr_arg)) == 1)
8145 {
8146 rl_and_mask = ~(wi::to_wide (rr_arg) - 1);
8147 rcode = (rcode == GE_EXPR ? NE_EXPR : EQ_EXPR);
8148 rr_arg = wide_int_to_tree (TREE_TYPE (rl_arg), rl_and_mask * 0);
8149 }
8150 else if ((rcode == LE_EXPR || rcode == GT_EXPR)
8151 && INTEGRAL_TYPE_P (TREE_TYPE (rl_arg))
8152 && TYPE_UNSIGNED (TREE_TYPE (rl_arg))
8153 && TREE_CODE (rr_arg) == INTEGER_CST
8154 && wi::popcount (wi::to_wide (rr_arg) + 1) == 1)
8155 {
8156 rl_and_mask = ~wi::to_wide (rr_arg);
8157 rcode = (rcode == GT_EXPR ? NE_EXPR : EQ_EXPR);
8158 rr_arg = wide_int_to_tree (TREE_TYPE (rl_arg), rl_and_mask * 0);
8159 }
8160
8161 /* See if the comparisons can be merged. Then get all the parameters for
8162 each side. */
8163
8164 if ((lcode != EQ_EXPR && lcode != NE_EXPR)
8165 || (rcode != EQ_EXPR && rcode != NE_EXPR))
8166 return 0;
8167
8168 ll_reversep = lr_reversep = rl_reversep = rr_reversep = 0;
8169 volatilep = 0;
8170 bool l_xor = false, r_xor = false;
8171 ll_inner = decode_field_reference (&ll_arg, &ll_bitsize, &ll_bitpos,
8172 &ll_unsignedp, &ll_reversep, &volatilep,
8173 &ll_and_mask, &ll_signbit,
8174 &l_xor, &lr_arg, &lr_and_mask,
8175 &ll_load, ll_loc);
8176 if (!ll_inner)
8177 return 0;
8178 lr_inner = decode_field_reference (&lr_arg, &lr_bitsize, &lr_bitpos,
8179 &lr_unsignedp, &lr_reversep, &volatilep,
8180 &lr_and_mask, &lr_signbit, &l_xor, 0, 0,
8181 &lr_load, lr_loc);
8182 if (!lr_inner)
8183 return 0;
8184 rl_inner = decode_field_reference (&rl_arg, &rl_bitsize, &rl_bitpos,
8185 &rl_unsignedp, &rl_reversep, &volatilep,
8186 &rl_and_mask, &rl_signbit,
8187 &r_xor, &rr_arg, &rr_and_mask,
8188 &rl_load, rl_loc);
8189 if (!rl_inner)
8190 return 0;
8191 rr_inner = decode_field_reference (&rr_arg, &rr_bitsize, &rr_bitpos,
8192 &rr_unsignedp, &rr_reversep, &volatilep,
8193 &rr_and_mask, &rr_signbit, &r_xor, 0, 0,
8194 &rr_load, rr_loc);
8195 if (!rr_inner)
8196 return 0;
8197
8198 /* It must be true that the inner operation on the lhs of each
8199 comparison must be the same if we are to be able to do anything.
8200 Then see if we have constants. If not, the same must be true for
8201 the rhs's. If one is a load and the other isn't, we have to be
8202 conservative and avoid the optimization, otherwise we could get
8203 SRAed fields wrong. */
8204 if (volatilep)
8205 return 0;
8206
8207 if (ll_reversep != rl_reversep
8208 || ! operand_equal_p (ll_inner, rl_inner, 0))
8209 {
8210 /* Try swapping the operands. */
8211 if (ll_reversep != rr_reversep || rsignbit
8212 || !operand_equal_p (ll_inner, rr_inner, 0))
8213 return 0;
8214
8215 rcode = swap_tree_comparison (rcode);
8216 std::swap (rl_arg, rr_arg);
8217 std::swap (rl_inner, rr_inner);
8218 std::swap (rl_bitsize, rr_bitsize);
8219 std::swap (rl_bitpos, rr_bitpos);
8220 std::swap (rl_unsignedp, rr_unsignedp);
8221 std::swap (rl_reversep, rr_reversep);
8222 std::swap (rl_and_mask, rr_and_mask);
8223 std::swap (rl_signbit, rr_signbit);
8224 std::swap (rl_load, rr_load);
8225 std::swap (rl_loc, rr_loc);
8226 }
8227
8228 if ((ll_load && rl_load)
8229 ? gimple_vuse (ll_load) != gimple_vuse (rl_load)
8230 : (!ll_load != !rl_load))
8231 return 0;
8232
8233 /* ??? Can we do anything with these? */
8234 if (lr_signbit || rr_signbit)
8235 return 0;
8236
8237 /* If the mask encompassed extensions of the sign bit before
8238 clipping, try to include the sign bit in the test. If we're not
8239 comparing with zero, don't even try to deal with it (for now?).
8240 If we've already commited to a sign test, the extended (before
8241 clipping) mask could already be messing with it. */
8242 if (ll_signbit)
8243 {
8244 if (!integer_zerop (lr_arg) || lsignbit)
8245 return 0;
8246 wide_int sign = wi::mask (ll_bitsize - 1, true, ll_bitsize);
8247 if (!ll_and_mask.get_precision ())
8248 ll_and_mask = sign;
8249 else
8250 ll_and_mask |= sign;
8251 }
8252
8253 if (rl_signbit)
8254 {
8255 if (!integer_zerop (rr_arg) || rsignbit)
8256 return 0;
8257 wide_int sign = wi::mask (rl_bitsize - 1, true, rl_bitsize);
8258 if (!rl_and_mask.get_precision ())
8259 rl_and_mask = sign;
8260 else
8261 rl_and_mask |= sign;
8262 }
8263
8264 if (TREE_CODE (lr_arg) == INTEGER_CST
8265 && TREE_CODE (rr_arg) == INTEGER_CST)
8266 {
8267 l_const = wi::to_wide (lr_arg);
8268 /* We don't expect masks on constants, but if there are any, apply
8269 them now. */
8270 if (lr_and_mask.get_precision ())
8271 l_const &= wide_int::from (lr_and_mask,
8272 l_const.get_precision (), UNSIGNED);
8273 r_const = wi::to_wide (rr_arg);
8274 if (rr_and_mask.get_precision ())
8275 r_const &= wide_int::from (rr_and_mask,
8276 r_const.get_precision (), UNSIGNED);
8277 lr_reversep = ll_reversep;
8278 }
8279 else if (lr_reversep != rr_reversep
8280 || ! operand_equal_p (lr_inner, rr_inner, 0)
8281 || ((lr_load && rr_load)
8282 ? gimple_vuse (lr_load) != gimple_vuse (rr_load)
8283 : (!lr_load != !rr_load)))
8284 return 0;
8285
8286 /* If we found sign tests, finish turning them into bit tests. */
8287
8288 if (lsignbit)
8289 {
8290 wide_int sign = wi::mask (ll_bitsize - 1, true, ll_bitsize);
8291 /* If ll_arg is zero-extended and we're testing the sign bit, we know
8292 what the result should be. Shifting the sign bit out of sign will get
8293 us to mask the entire field out, yielding zero, i.e., the sign bit of
8294 the zero-extended value. We know the masked value is being compared
8295 with zero, so the compare will get us the result we're looking
8296 for: TRUE if EQ_EXPR, FALSE if NE_EXPR. */
8297 if (lsignbit > ll_bitsize && ll_unsignedp)
8298 sign <<= 1;
8299 if (!ll_and_mask.get_precision ())
8300 ll_and_mask = sign;
8301 else
8302 ll_and_mask &= sign;
8303 if (l_xor)
8304 {
8305 if (ll_bitsize != lr_bitsize)
8306 return 0;
8307 if (!lr_and_mask.get_precision ())
8308 lr_and_mask = sign;
8309 else
8310 lr_and_mask &= sign;
8311 if (l_const.get_precision ())
8312 l_const &= wide_int::from (lr_and_mask,
8313 l_const.get_precision (), UNSIGNED);
8314 }
8315 }
8316
8317 if (rsignbit)
8318 {
8319 wide_int sign = wi::mask (rl_bitsize - 1, true, rl_bitsize);
8320 if (rsignbit > rl_bitsize && rl_unsignedp)
8321 sign <<= 1;
8322 if (!rl_and_mask.get_precision ())
8323 rl_and_mask = sign;
8324 else
8325 rl_and_mask &= sign;
8326 if (r_xor)
8327 {
8328 if (rl_bitsize != rr_bitsize)
8329 return 0;
8330 if (!rr_and_mask.get_precision ())
8331 rr_and_mask = sign;
8332 else
8333 rr_and_mask &= sign;
8334 if (r_const.get_precision ())
8335 r_const &= wide_int::from (rr_and_mask,
8336 r_const.get_precision (), UNSIGNED);
8337 }
8338 }
8339
8340 /* If either comparison code is not correct for our logical operation,
8341 fail. However, we can convert a one-bit comparison against zero into
8342 the opposite comparison against that bit being set in the field. */
8343
8344 wanted_code = (code == TRUTH_AND_EXPR ? EQ_EXPR : NE_EXPR);
8345 if (lcode != wanted_code)
8346 {
8347 if (l_const.get_precision ()
8348 && l_const == 0
8349 && ll_and_mask.get_precision ()
8350 && wi::popcount (ll_and_mask) == 1)
8351 {
8352 /* Make the left operand unsigned, since we are only interested
8353 in the value of one bit. Otherwise we are doing the wrong
8354 thing below. */
8355 ll_unsignedp = 1;
8356 l_const = ll_and_mask;
8357 }
8358 else
8359 return 0;
8360 }
8361
8362 /* This is analogous to the code for l_const above. */
8363 if (rcode != wanted_code)
8364 {
8365 if (r_const.get_precision ()
8366 && r_const == 0
8367 && rl_and_mask.get_precision ()
8368 && wi::popcount (rl_and_mask) == 1)
8369 {
8370 rl_unsignedp = 1;
8371 r_const = rl_and_mask;
8372 }
8373 else
8374 return 0;
8375 }
8376
8377 /* This will be bumped to 2 if any of the field pairs crosses an
8378 alignment boundary, so the merged compare has to be done in two
8379 parts. */
8380 int parts = 1;
8381 /* Set to true if the second combined compare should come first,
8382 e.g., because the second original compare accesses a word that
8383 the first one doesn't, and the combined compares access those in
8384 cmp[0]. */
8385 bool first1 = false;
8386 /* Set to true if the first original compare is not the one being
8387 split. */
8388 bool maybe_separate = false;
8389
8390 /* The following 2-dimensional arrays use the first index to
8391 identify left(0)- vs right(1)-hand compare operands, and the
8392 second one to identify merged compare parts. */
8393 /* The memory loads or constants to be compared. */
8394 tree ld_arg[2][2];
8395 /* The first bit of the corresponding inner object that the
8396 corresponding LD_ARG covers. */
8397 HOST_WIDE_INT bitpos[2][2];
8398 /* The bit count starting at BITPOS that the corresponding LD_ARG
8399 covers. */
8400 HOST_WIDE_INT bitsiz[2][2];
8401 /* The number of bits by which LD_ARG has already been shifted
8402 right, WRT mask. */
8403 HOST_WIDE_INT shifted[2][2];
8404 /* The number of bits by which both LD_ARG and MASK need shifting to
8405 bring its least-significant bit to bit zero. */
8406 HOST_WIDE_INT toshift[2][2];
8407 /* An additional mask to be applied to LD_ARG, to remove any bits
8408 that may have been loaded for use in another compare, but that
8409 don't belong in the corresponding compare. */
8410 wide_int xmask[2][2] = {};
8411
8412 /* The combined compare or compares. */
8413 tree cmp[2];
8414
8415 /* Consider we're comparing two non-contiguous fields of packed
8416 structs, both aligned at 32-bit boundaries:
8417
8418 ll_arg: an 8-bit field at offset 0
8419 lr_arg: a 16-bit field at offset 2
8420
8421 rl_arg: an 8-bit field at offset 1
8422 rr_arg: a 16-bit field at offset 3
8423
8424 We'll have r_split_load, because rr_arg straddles across an
8425 alignment boundary.
8426
8427 We'll want to have:
8428
8429 bitpos = { { 0, 0 }, { 0, 32 } }
8430 bitsiz = { { 32, 32 }, { 32, 8 } }
8431
8432 And, for little-endian:
8433
8434 shifted = { { 0, 0 }, { 0, 32 } }
8435 toshift = { { 0, 24 }, { 0, 0 } }
8436
8437 Or, for big-endian:
8438
8439 shifted = { { 0, 0 }, { 8, 0 } }
8440 toshift = { { 8, 0 }, { 0, 0 } }
8441 */
8442
8443 /* See if we can find a mode that contains both fields being compared on
8444 the left. If we can't, fail. Otherwise, update all constants and masks
8445 to be relative to a field of that size. */
8446 first_bit = MIN (ll_bitpos, rl_bitpos);
8447 end_bit = MAX (ll_bitpos + ll_bitsize, rl_bitpos + rl_bitsize);
8448 HOST_WIDE_INT ll_align = TYPE_ALIGN (TREE_TYPE (ll_inner));
8449 poly_uint64 ll_end_region = 0;
8450 if (TYPE_SIZE (TREE_TYPE (ll_inner))
8451 && tree_fits_poly_uint64_p (TYPE_SIZE (TREE_TYPE (ll_inner))))
8452 ll_end_region = tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (ll_inner)));
8453 if (get_best_mode (end_bit - first_bit, first_bit, 0, ll_end_region,
8454 ll_align, BITS_PER_WORD, volatilep, &lnmode))
8455 l_split_load = false;
8456 /* ??? If ll and rl share the same load, reuse that?
8457 See PR 118206 -> gcc.dg/field-merge-18.c */
8458 else
8459 {
8460 /* Consider the possibility of recombining loads if any of the
8461 fields straddles across an alignment boundary, so that either
8462 part can be loaded along with the other field. Since we
8463 limit access modes to BITS_PER_WORD, don't exceed that,
8464 otherwise on a 32-bit host and a 64-bit-aligned data
8465 structure, we'll fail the above for a field that straddles
8466 across two words, and would fail here for not even trying to
8467 split it at between 32-bit words. */
8468 HOST_WIDE_INT boundary = compute_split_boundary_from_align
8469 (MIN (ll_align, BITS_PER_WORD),
8470 ll_bitpos, ll_bitsize, rl_bitpos, rl_bitsize);
8471
8472 if (boundary < 0
8473 || !get_best_mode (boundary - first_bit, first_bit, 0, ll_end_region,
8474 ll_align, BITS_PER_WORD, volatilep, &lnmode)
8475 || !get_best_mode (end_bit - boundary, boundary, 0, ll_end_region,
8476 ll_align, BITS_PER_WORD, volatilep, &lnmode2))
8477 {
8478 if (ll_align <= BITS_PER_WORD)
8479 return 0;
8480
8481 /* As a last resort, try double-word access modes. This
8482 enables us to deal with misaligned double-word fields
8483 that straddle across 3 separate words. */
8484 boundary = compute_split_boundary_from_align
8485 (MIN (ll_align, 2 * BITS_PER_WORD),
8486 ll_bitpos, ll_bitsize, rl_bitpos, rl_bitsize);
8487 if (boundary < 0
8488 || !get_best_mode (boundary - first_bit, first_bit,
8489 0, ll_end_region, ll_align, 2 * BITS_PER_WORD,
8490 volatilep, &lnmode)
8491 || !get_best_mode (end_bit - boundary, boundary,
8492 0, ll_end_region, ll_align, 2 * BITS_PER_WORD,
8493 volatilep, &lnmode2))
8494 return 0;
8495 }
8496
8497 /* If we can't have a single load, but can with two, figure out whether
8498 the two compares can be separated, i.e., whether the entirety of the
8499 first original compare is encompassed by the entirety of the first
8500 combined compare. If the first original compare is past the alignment
8501 boundary, arrange to compare that range first, by setting first1
8502 (meaning make cmp[1] first, instead of cmp[0]). */
8503 l_split_load = true;
8504 parts = 2;
8505 if (ll_bitpos >= boundary)
8506 maybe_separate = first1 = true;
8507 else if (ll_bitpos + ll_bitsize <= boundary)
8508 maybe_separate = true;
8509 }
8510
8511 lnbitsize = GET_MODE_BITSIZE (lnmode);
8512 lnbitpos = first_bit & ~ (lnbitsize - 1);
8513 /* Avoid situations that the code below can't handle. */
8514 if (lnbitpos < 0)
8515 return 0;
8516
8517 /* Choose the type for the combined compare. Even if we're splitting loads,
8518 make it wide enough to hold both. */
8519 if (l_split_load)
8520 lnbitsize += GET_MODE_BITSIZE (lnmode2);
8521 lntype = build_nonstandard_integer_type (lnbitsize, 1);
8522 if (!lntype)
8523 return NULL_TREE;
8524 lnprec = TYPE_PRECISION (lntype);
8525 xll_bitpos = ll_bitpos - lnbitpos, xrl_bitpos = rl_bitpos - lnbitpos;
8526
8527 /* Adjust bit ranges for reverse endianness. */
8528 if (ll_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
8529 {
8530 xll_bitpos = lnbitsize - xll_bitpos - ll_bitsize;
8531 xrl_bitpos = lnbitsize - xrl_bitpos - rl_bitsize;
8532 }
8533
8534 /* Adjust masks to match the positions in the combined lntype. */
8535 wide_int ll_mask, rl_mask, r_mask;
8536 if (ll_and_mask.get_precision ())
8537 ll_mask = wi::lshift (wide_int::from (ll_and_mask, lnprec, UNSIGNED),
8538 xll_bitpos);
8539 else
8540 ll_mask = wi::shifted_mask (xll_bitpos, ll_bitsize, false, lnprec);
8541 if (rl_and_mask.get_precision ())
8542 rl_mask = wi::lshift (wide_int::from (rl_and_mask, lnprec, UNSIGNED),
8543 xrl_bitpos);
8544 else
8545 rl_mask = wi::shifted_mask (xrl_bitpos, rl_bitsize, false, lnprec);
8546
8547 /* When we set l_const, we also set r_const. */
8548 gcc_checking_assert (!l_const.get_precision () == !r_const.get_precision ());
8549
8550 /* Adjust right-hand constants in both original comparisons to match width
8551 and bit position. */
8552 if (l_const.get_precision ())
8553 {
8554 /* Before clipping upper bits of the right-hand operand of the compare,
8555 check that they're sign or zero extensions, depending on how the
8556 left-hand operand would be extended. If it is unsigned, or if there's
8557 a mask that zeroes out extension bits, whether because we've checked
8558 for upper bits in the mask and did not set ll_signbit, or because the
8559 sign bit itself is masked out, check that the right-hand operand is
8560 zero-extended. */
8561 bool l_non_ext_bits = false;
8562 if (ll_bitsize < lr_bitsize)
8563 {
8564 wide_int zext = wi::zext (l_const, ll_bitsize);
8565 if ((ll_unsignedp
8566 || (ll_and_mask.get_precision ()
8567 && (!ll_signbit
8568 || ((ll_and_mask & wi::mask (ll_bitsize - 1, true, ll_bitsize))
8569 == 0)))
8570 ? zext : wi::sext (l_const, ll_bitsize)) == l_const)
8571 l_const = zext;
8572 else
8573 l_non_ext_bits = true;
8574 }
8575 /* We're doing bitwise equality tests, so don't bother with sign
8576 extensions. */
8577 l_const = wide_int::from (l_const, lnprec, UNSIGNED);
8578 if (ll_and_mask.get_precision ())
8579 l_const &= wide_int::from (ll_and_mask, lnprec, UNSIGNED);
8580 l_const <<= xll_bitpos;
8581 if (l_non_ext_bits || (l_const & ~ll_mask) != 0)
8582 {
8583 warning_at (lloc, OPT_Wtautological_compare,
8584 "comparison is always %d", wanted_code == NE_EXPR);
8585
8586 return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
8587 }
8588
8589 /* Before clipping upper bits of the right-hand operand of the compare,
8590 check that they're sign or zero extensions, depending on how the
8591 left-hand operand would be extended. */
8592 bool r_non_ext_bits = false;
8593 if (rl_bitsize < rr_bitsize)
8594 {
8595 wide_int zext = wi::zext (r_const, rl_bitsize);
8596 if ((rl_unsignedp
8597 || (rl_and_mask.get_precision ()
8598 && (!rl_signbit
8599 || ((rl_and_mask & wi::mask (rl_bitsize - 1, true, rl_bitsize))
8600 == 0)))
8601 ? zext : wi::sext (r_const, rl_bitsize)) == r_const)
8602 r_const = zext;
8603 else
8604 r_non_ext_bits = true;
8605 }
8606 r_const = wide_int::from (r_const, lnprec, UNSIGNED);
8607 if (rl_and_mask.get_precision ())
8608 r_const &= wide_int::from (rl_and_mask, lnprec, UNSIGNED);
8609 r_const <<= xrl_bitpos;
8610 if (r_non_ext_bits || (r_const & ~rl_mask) != 0)
8611 {
8612 warning_at (rloc, OPT_Wtautological_compare,
8613 "comparison is always %d", wanted_code == NE_EXPR);
8614
8615 return constant_boolean_node (wanted_code == NE_EXPR, truth_type);
8616 }
8617
8618 /* If there is something in common between the masks, those bits of the
8619 constants must be the same. If not, the combined condition cannot be
8620 met, and the result is known. Test for this to avoid generating
8621 incorrect code below. */
8622 wide_int mask = ll_mask & rl_mask;
8623 if (mask != 0
8624 && (l_const & mask) != (r_const & mask))
8625 {
8626 if (wanted_code == NE_EXPR)
8627 return constant_boolean_node (true, truth_type);
8628 else
8629 return constant_boolean_node (false, truth_type);
8630 }
8631
8632 /* The constants are combined so as to line up with the loaded field, so
8633 tentatively use the same parameters for the second combined
8634 compare. */
8635 ld_arg[1][0] = wide_int_to_tree (lntype, l_const | r_const);
8636 toshift[1][0] = MIN (xll_bitpos, xrl_bitpos);
8637 shifted[1][0] = 0;
8638 bitpos[1][0] = lnbitpos;
8639 bitsiz[1][0] = lnbitsize;
8640
8641 if (parts > 1)
8642 reuse_split_load (ld_arg[1], bitpos[1], bitsiz[1], toshift[1],
8643 shifted[1], xmask[1],
8644 lnbitpos + GET_MODE_BITSIZE (lnmode),
8645 lr_reversep);
8646
8647 /* No masking needed, we know the full constants. */
8648 r_mask = wi::mask (0, true, lnprec);
8649
8650 /* If the compiler thinks this is used uninitialized below, it's
8651 because it can't realize that parts can only be 2 when
8652 comparing with constants if l_split_load is also true. This
8653 just silences the warning. */
8654 rnbitpos = 0;
8655 }
8656
8657 /* Likewise, if the right sides are not constant, align them for the combined
8658 compare. Also, disallow this optimization if a size, signedness or
8659 storage order mismatch occurs between the left and right sides. */
8660 else
8661 {
8662 if (ll_bitsize != lr_bitsize || rl_bitsize != rr_bitsize
8663 || ll_unsignedp != lr_unsignedp || rl_unsignedp != rr_unsignedp
8664 || ll_reversep != lr_reversep
8665 /* Make sure the two fields on the right
8666 correspond to the left without being swapped. */
8667 || ll_bitpos - rl_bitpos != lr_bitpos - rr_bitpos)
8668 return 0;
8669
8670 bool r_split_load;
8671 scalar_int_mode rnmode2;
8672
8673 /* Figure out how to load the bits for the right-hand size of the
8674 combined compare. As in the left-hand size, we may have to split it,
8675 and then we use two separate compares. */
8676 first_bit = MIN (lr_bitpos, rr_bitpos);
8677 end_bit = MAX (lr_bitpos + lr_bitsize, rr_bitpos + rr_bitsize);
8678 HOST_WIDE_INT lr_align = TYPE_ALIGN (TREE_TYPE (lr_inner));
8679 poly_uint64 lr_end_region = 0;
8680 if (TYPE_SIZE (TREE_TYPE (lr_inner))
8681 && tree_fits_poly_uint64_p (TYPE_SIZE (TREE_TYPE (lr_inner))))
8682 lr_end_region = tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (lr_inner)));
8683 if (!get_best_mode (end_bit - first_bit, first_bit, 0, lr_end_region,
8684 lr_align, BITS_PER_WORD, volatilep, &rnmode))
8685 {
8686 /* Consider the possibility of recombining loads if any of the
8687 fields straddles across an alignment boundary, so that either
8688 part can be loaded along with the other field. */
8689 HOST_WIDE_INT boundary = compute_split_boundary_from_align
8690 (lr_align, lr_bitpos, lr_bitsize, rr_bitpos, rr_bitsize);
8691
8692 if (boundary < 0
8693 /* If we're to split both, make sure the split point is
8694 the same. */
8695 || (l_split_load
8696 && (boundary - lr_bitpos
8697 != (lnbitpos + GET_MODE_BITSIZE (lnmode)) - ll_bitpos))
8698 || !get_best_mode (boundary - first_bit, first_bit,
8699 0, lr_end_region,
8700 lr_align, BITS_PER_WORD, volatilep, &rnmode)
8701 || !get_best_mode (end_bit - boundary, boundary, 0, lr_end_region,
8702 lr_align, BITS_PER_WORD, volatilep, &rnmode2))
8703 return 0;
8704
8705 r_split_load = true;
8706 parts = 2;
8707 if (lr_bitpos >= boundary)
8708 maybe_separate = first1 = true;
8709 else if (lr_bitpos + lr_bitsize <= boundary)
8710 maybe_separate = true;
8711 }
8712 else
8713 r_split_load = false;
8714
8715 /* Find a type that can hold the entire right-hand operand. */
8716 rnbitsize = GET_MODE_BITSIZE (rnmode);
8717 rnbitpos = first_bit & ~ (rnbitsize - 1);
8718 if (r_split_load)
8719 rnbitsize += GET_MODE_BITSIZE (rnmode2);
8720 rntype = build_nonstandard_integer_type (rnbitsize, 1);
8721 if (!rntype)
8722 return 0;
8723 rnprec = TYPE_PRECISION (rntype);
8724 xlr_bitpos = lr_bitpos - rnbitpos, xrr_bitpos = rr_bitpos - rnbitpos;
8725
8726 /* Adjust for reversed endianness. */
8727 if (lr_reversep ? !BYTES_BIG_ENDIAN : BYTES_BIG_ENDIAN)
8728 {
8729 xlr_bitpos = rnbitsize - xlr_bitpos - lr_bitsize;
8730 xrr_bitpos = rnbitsize - xrr_bitpos - rr_bitsize;
8731 }
8732
8733 /* Adjust the masks to match the combined type, and combine them. */
8734 wide_int lr_mask, rr_mask;
8735 if (lr_and_mask.get_precision ())
8736 lr_mask = wi::lshift (wide_int::from (lr_and_mask, rnprec, UNSIGNED),
8737 xlr_bitpos);
8738 else
8739 lr_mask = wi::shifted_mask (xlr_bitpos, lr_bitsize, false, rnprec);
8740 if (rr_and_mask.get_precision ())
8741 rr_mask = wi::lshift (wide_int::from (rr_and_mask, rnprec, UNSIGNED),
8742 xrr_bitpos);
8743 else
8744 rr_mask = wi::shifted_mask (xrr_bitpos, rr_bitsize, false, rnprec);
8745 r_mask = lr_mask | rr_mask;
8746
8747 /* Load the right-hand operand of the combined compare. */
8748 toshift[1][0] = MIN (xlr_bitpos, xrr_bitpos);
8749 shifted[1][0] = 0;
8750
8751 if (!r_split_load)
8752 {
8753 bitpos[1][0] = rnbitpos;
8754 bitsiz[1][0] = rnbitsize;
8755 ld_arg[1][0] = make_bit_field_load (ll_loc[3], lr_inner, lr_arg,
8756 rntype, rnbitsize, rnbitpos,
8757 lr_unsignedp || rr_unsignedp,
8758 lr_reversep, lr_load);
8759 }
8760
8761 /* ... and the second part of the right-hand operand if needed. */
8762 if (parts > 1)
8763 {
8764 if (r_split_load)
8765 {
8766 gimple *point[2];
8767 point[0] = lr_load;
8768 point[1] = rr_load;
8769 build_split_load (ld_arg[1], bitpos[1], bitsiz[1], toshift[1],
8770 shifted[1], rl_loc[3], lr_inner, lr_arg,
8771 rnmode, rnmode2, rnbitpos, lr_reversep, point);
8772 }
8773 else
8774 reuse_split_load (ld_arg[1], bitpos[1], bitsiz[1], toshift[1],
8775 shifted[1], xmask[1],
8776 lnbitpos + GET_MODE_BITSIZE (lnmode)
8777 - ll_bitpos + lr_bitpos, lr_reversep);
8778 }
8779 }
8780
8781 /* Now issue the loads for the left-hand combined operand/s. */
8782 wide_int l_mask = ll_mask | rl_mask;
8783 toshift[0][0] = MIN (xll_bitpos, xrl_bitpos);
8784 shifted[0][0] = 0;
8785
8786 if (!l_split_load)
8787 {
8788 bitpos[0][0] = lnbitpos;
8789 bitsiz[0][0] = lnbitsize;
8790 ld_arg[0][0] = make_bit_field_load (ll_loc[3], ll_inner, ll_arg,
8791 lntype, lnbitsize, lnbitpos,
8792 ll_unsignedp || rl_unsignedp,
8793 ll_reversep, ll_load);
8794 }
8795
8796 if (parts > 1)
8797 {
8798 if (l_split_load)
8799 {
8800 gimple *point[2];
8801 point[0] = ll_load;
8802 point[1] = rl_load;
8803 build_split_load (ld_arg[0], bitpos[0], bitsiz[0], toshift[0],
8804 shifted[0], rl_loc[3], ll_inner, ll_arg,
8805 lnmode, lnmode2, lnbitpos, ll_reversep, point);
8806 }
8807 else
8808 reuse_split_load (ld_arg[0], bitpos[0], bitsiz[0], toshift[0],
8809 shifted[0], xmask[0],
8810 rnbitpos + GET_MODE_BITSIZE (rnmode)
8811 - lr_bitpos + ll_bitpos, ll_reversep);
8812 }
8813
8814 /* Compute the compares. */
8815 for (int i = 0; i < parts; i++)
8816 {
8817 tree op[2] = { ld_arg[0][i], ld_arg[1][i] };
8818 wide_int mask[2] = { l_mask, r_mask };
8819 location_t *locs[2] = { i ? rl_loc : ll_loc, i ? rr_loc : lr_loc };
8820
8821 /* Figure out the masks, and unshare the original operands. */
8822 for (int j = 0; j < 2; j++)
8823 {
8824 unsigned prec = TYPE_PRECISION (TREE_TYPE (op[j]));
8825 op[j] = unshare_expr (op[j]);
8826
8827 /* Mask out the bits belonging to the other part. */
8828 if (xmask[j][i].get_precision ())
8829 mask[j] &= xmask[j][i];
8830
8831 if (shifted[j][i])
8832 {
8833 wide_int shift = wide_int::from (shifted[j][i], prec, UNSIGNED);
8834 mask[j] = wi::lrshift (mask[j], shift);
8835 }
8836 mask[j] = wide_int::from (mask[j], prec, UNSIGNED);
8837 }
8838
8839 /* Line up the operands for a compare. */
8840 HOST_WIDE_INT shift = (toshift[0][i] - toshift[1][i]);
8841
8842 if (shift)
8843 {
8844 int j;
8845 if (shift > 0)
8846 j = 0;
8847 else
8848 {
8849 j = 1;
8850 shift = -shift;
8851 }
8852
8853 tree shiftsz = bitsize_int (shift);
8854 op[j] = fold_build2_loc (locs[j][1], RSHIFT_EXPR, TREE_TYPE (op[j]),
8855 op[j], shiftsz);
8856 mask[j] = wi::lrshift (mask[j], shift);
8857 }
8858
8859 /* Convert to the smaller type before masking out unwanted
8860 bits. */
8861 tree type = TREE_TYPE (op[0]);
8862 if (type != TREE_TYPE (op[1]))
8863 {
8864 int j = (TYPE_PRECISION (type)
8865 < TYPE_PRECISION (TREE_TYPE (op[1])));
8866 if (!j)
8867 type = TREE_TYPE (op[1]);
8868 op[j] = fold_convert_loc (locs[j][0], type, op[j]);
8869 mask[j] = wide_int::from (mask[j], TYPE_PRECISION (type), UNSIGNED);
8870 }
8871
8872 /* Apply masks. */
8873 for (int j = 0; j < 2; j++)
8874 if (mask[j] != wi::mask (0, true, mask[j].get_precision ()))
8875 op[j] = fold_build2_loc (locs[j][2], BIT_AND_EXPR, type,
8876 op[j], wide_int_to_tree (type, mask[j]));
8877
8878 cmp[i] = fold_build2_loc (i ? rloc : lloc, wanted_code, truth_type,
8879 op[0], op[1]);
8880 }
8881
8882 /* Reorder the compares if needed. */
8883 if (first1)
8884 std::swap (cmp[0], cmp[1]);
8885
8886 /* Prepare to return the resulting compares. Combine two parts if
8887 needed. */
8888 if (parts == 1)
8889 result = cmp[0];
8890 else if (!separatep || !maybe_separate)
8891 {
8892 /* Only fold if any of the cmp is known, otherwise we may lose the
8893 sequence point, and that may prevent further optimizations. */
8894 if (TREE_CODE (cmp[0]) == INTEGER_CST
8895 || TREE_CODE (cmp[1]) == INTEGER_CST)
8896 result = fold_build2_loc (rloc, orig_code, truth_type, cmp[0], cmp[1]);
8897 else
8898 result = build2_loc (rloc, orig_code, truth_type, cmp[0], cmp[1]);
8899 }
8900 else
8901 {
8902 result = cmp[0];
8903 *separatep = cmp[1];
8904 }
8905
8906 return result;
8907 }
8908
8909 /* Try to simplify the AND of two comparisons, specified by
8910 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
8911 If this can be simplified to a single expression (without requiring
8912 introducing more SSA variables to hold intermediate values),
8913 return the resulting tree. Otherwise return NULL_TREE.
8914 If the result expression is non-null, it has boolean type. */
8915
8916 tree
8917 maybe_fold_and_comparisons (tree type,
8918 enum tree_code code1, tree op1a, tree op1b,
8919 enum tree_code code2, tree op2a, tree op2b,
8920 basic_block outer_cond_bb)
8921 {
8922 if (tree t = and_comparisons_1 (type, code1, op1a, op1b, code2, op2a, op2b,
8923 outer_cond_bb))
8924 return t;
8925
8926 if (tree t = and_comparisons_1 (type, code2, op2a, op2b, code1, op1a, op1b,
8927 outer_cond_bb))
8928 return t;
8929
8930 if (tree t = maybe_fold_comparisons_from_match_pd (type, BIT_AND_EXPR, code1,
8931 op1a, op1b, code2, op2a,
8932 op2b, outer_cond_bb))
8933 return t;
8934
8935 return NULL_TREE;
8936 }
8937
8938 /* Helper function for or_comparisons_1: try to simplify the OR of the
8939 ssa variable VAR with the comparison specified by (OP2A CODE2 OP2B).
8940 If INVERT is true, invert the value of VAR before doing the OR.
8941 Return NULL_EXPR if we can't simplify this to a single expression. */
8942
8943 static tree
8944 or_var_with_comparison (tree type, tree var, bool invert,
8945 enum tree_code code2, tree op2a, tree op2b,
8946 basic_block outer_cond_bb)
8947 {
8948 tree t;
8949 gimple *stmt = SSA_NAME_DEF_STMT (var);
8950
8951 /* We can only deal with variables whose definitions are assignments. */
8952 if (!is_gimple_assign (stmt))
8953 return NULL_TREE;
8954
8955 /* If we have an inverted comparison, apply DeMorgan's law and rewrite
8956 !var OR (op2a code2 op2b) => !(var AND !(op2a code2 op2b))
8957 Then we only have to consider the simpler non-inverted cases. */
8958 if (invert)
8959 t = and_var_with_comparison_1 (type, stmt,
8960 invert_tree_comparison (code2, false),
8961 op2a, op2b, outer_cond_bb);
8962 else
8963 t = or_var_with_comparison_1 (type, stmt, code2, op2a, op2b,
8964 outer_cond_bb);
8965 return canonicalize_bool (t, invert);
8966 }
8967
8968 /* Try to simplify the OR of the ssa variable defined by the assignment
8969 STMT with the comparison specified by (OP2A CODE2 OP2B).
8970 Return NULL_EXPR if we can't simplify this to a single expression. */
8971
8972 static tree
8973 or_var_with_comparison_1 (tree type, gimple *stmt,
8974 enum tree_code code2, tree op2a, tree op2b,
8975 basic_block outer_cond_bb)
8976 {
8977 tree var = gimple_assign_lhs (stmt);
8978 tree true_test_var = NULL_TREE;
8979 tree false_test_var = NULL_TREE;
8980 enum tree_code innercode = gimple_assign_rhs_code (stmt);
8981
8982 /* Check for identities like (var OR (var != 0)) => true . */
8983 if (TREE_CODE (op2a) == SSA_NAME
8984 && TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE)
8985 {
8986 if ((code2 == NE_EXPR && integer_zerop (op2b))
8987 || (code2 == EQ_EXPR && integer_nonzerop (op2b)))
8988 {
8989 true_test_var = op2a;
8990 if (var == true_test_var)
8991 return var;
8992 }
8993 else if ((code2 == EQ_EXPR && integer_zerop (op2b))
8994 || (code2 == NE_EXPR && integer_nonzerop (op2b)))
8995 {
8996 false_test_var = op2a;
8997 if (var == false_test_var)
8998 return boolean_true_node;
8999 }
9000 }
9001
9002 /* If the definition is a comparison, recurse on it. */
9003 if (TREE_CODE_CLASS (innercode) == tcc_comparison)
9004 {
9005 tree t = or_comparisons_1 (type, innercode,
9006 gimple_assign_rhs1 (stmt),
9007 gimple_assign_rhs2 (stmt),
9008 code2, op2a, op2b, outer_cond_bb);
9009 if (t)
9010 return t;
9011 }
9012
9013 /* If the definition is an AND or OR expression, we may be able to
9014 simplify by reassociating. */
9015 if (TREE_CODE (TREE_TYPE (var)) == BOOLEAN_TYPE
9016 && (innercode == BIT_AND_EXPR || innercode == BIT_IOR_EXPR))
9017 {
9018 tree inner1 = gimple_assign_rhs1 (stmt);
9019 tree inner2 = gimple_assign_rhs2 (stmt);
9020 gimple *s;
9021 tree t;
9022 tree partial = NULL_TREE;
9023 bool is_or = (innercode == BIT_IOR_EXPR);
9024
9025 /* Check for boolean identities that don't require recursive examination
9026 of inner1/inner2:
9027 inner1 OR (inner1 OR inner2) => inner1 OR inner2 => var
9028 inner1 OR (inner1 AND inner2) => inner1
9029 !inner1 OR (inner1 OR inner2) => true
9030 !inner1 OR (inner1 AND inner2) => !inner1 OR inner2
9031 */
9032 if (inner1 == true_test_var)
9033 return (is_or ? var : inner1);
9034 else if (inner2 == true_test_var)
9035 return (is_or ? var : inner2);
9036 else if (inner1 == false_test_var)
9037 return (is_or
9038 ? boolean_true_node
9039 : or_var_with_comparison (type, inner2, false, code2, op2a,
9040 op2b, outer_cond_bb));
9041 else if (inner2 == false_test_var)
9042 return (is_or
9043 ? boolean_true_node
9044 : or_var_with_comparison (type, inner1, false, code2, op2a,
9045 op2b, outer_cond_bb));
9046
9047 /* Next, redistribute/reassociate the OR across the inner tests.
9048 Compute the first partial result, (inner1 OR (op2a code op2b)) */
9049 if (TREE_CODE (inner1) == SSA_NAME
9050 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner1))
9051 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
9052 && (t = maybe_fold_or_comparisons (type, gimple_assign_rhs_code (s),
9053 gimple_assign_rhs1 (s),
9054 gimple_assign_rhs2 (s),
9055 code2, op2a, op2b,
9056 outer_cond_bb)))
9057 {
9058 /* Handle the OR case, where we are reassociating:
9059 (inner1 OR inner2) OR (op2a code2 op2b)
9060 => (t OR inner2)
9061 If the partial result t is a constant, we win. Otherwise
9062 continue on to try reassociating with the other inner test. */
9063 if (is_or)
9064 {
9065 if (integer_onep (t))
9066 return boolean_true_node;
9067 else if (integer_zerop (t))
9068 return inner2;
9069 }
9070
9071 /* Handle the AND case, where we are redistributing:
9072 (inner1 AND inner2) OR (op2a code2 op2b)
9073 => (t AND (inner2 OR (op2a code op2b))) */
9074 else if (integer_zerop (t))
9075 return boolean_false_node;
9076
9077 /* Save partial result for later. */
9078 partial = t;
9079 }
9080
9081 /* Compute the second partial result, (inner2 OR (op2a code op2b)) */
9082 if (TREE_CODE (inner2) == SSA_NAME
9083 && is_gimple_assign (s = SSA_NAME_DEF_STMT (inner2))
9084 && TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison
9085 && (t = maybe_fold_or_comparisons (type, gimple_assign_rhs_code (s),
9086 gimple_assign_rhs1 (s),
9087 gimple_assign_rhs2 (s),
9088 code2, op2a, op2b,
9089 outer_cond_bb)))
9090 {
9091 /* Handle the OR case, where we are reassociating:
9092 (inner1 OR inner2) OR (op2a code2 op2b)
9093 => (inner1 OR t)
9094 => (t OR partial) */
9095 if (is_or)
9096 {
9097 if (integer_zerop (t))
9098 return inner1;
9099 else if (integer_onep (t))
9100 return boolean_true_node;
9101 /* If both are the same, we can apply the identity
9102 (x OR x) == x. */
9103 else if (partial && same_bool_result_p (t, partial))
9104 return t;
9105 }
9106
9107 /* Handle the AND case, where we are redistributing:
9108 (inner1 AND inner2) OR (op2a code2 op2b)
9109 => (t AND (inner1 OR (op2a code2 op2b)))
9110 => (t AND partial) */
9111 else
9112 {
9113 if (integer_zerop (t))
9114 return boolean_false_node;
9115 else if (partial)
9116 {
9117 /* We already got a simplification for the other
9118 operand to the redistributed AND expression. The
9119 interesting case is when at least one is true.
9120 Or, if both are the same, we can apply the identity
9121 (x AND x) == x. */
9122 if (integer_onep (partial))
9123 return t;
9124 else if (integer_onep (t))
9125 return partial;
9126 else if (same_bool_result_p (t, partial))
9127 return t;
9128 }
9129 }
9130 }
9131 }
9132 return NULL_TREE;
9133 }
9134
9135 /* Try to simplify the OR of two comparisons defined by
9136 (OP1A CODE1 OP1B) and (OP2A CODE2 OP2B), respectively.
9137 If this can be done without constructing an intermediate value,
9138 return the resulting tree; otherwise NULL_TREE is returned.
9139 This function is deliberately asymmetric as it recurses on SSA_DEFs
9140 in the first comparison but not the second. */
9141
9142 static tree
9143 or_comparisons_1 (tree type, enum tree_code code1, tree op1a, tree op1b,
9144 enum tree_code code2, tree op2a, tree op2b,
9145 basic_block outer_cond_bb)
9146 {
9147 tree truth_type = truth_type_for (TREE_TYPE (op1a));
9148
9149 /* First check for ((x CODE1 y) OR (x CODE2 y)). */
9150 if (operand_equal_p (op1a, op2a, 0)
9151 && operand_equal_p (op1b, op2b, 0))
9152 {
9153 /* Result will be either NULL_TREE, or a combined comparison. */
9154 tree t = combine_comparisons (UNKNOWN_LOCATION,
9155 TRUTH_ORIF_EXPR, code1, code2,
9156 truth_type, op1a, op1b);
9157 if (t)
9158 return t;
9159 }
9160
9161 /* Likewise the swapped case of the above. */
9162 if (operand_equal_p (op1a, op2b, 0)
9163 && operand_equal_p (op1b, op2a, 0))
9164 {
9165 /* Result will be either NULL_TREE, or a combined comparison. */
9166 tree t = combine_comparisons (UNKNOWN_LOCATION,
9167 TRUTH_ORIF_EXPR, code1,
9168 swap_tree_comparison (code2),
9169 truth_type, op1a, op1b);
9170 if (t)
9171 return t;
9172 }
9173
9174 /* Perhaps the first comparison is (NAME != 0) or (NAME == 1) where
9175 NAME's definition is a truth value. See if there are any simplifications
9176 that can be done against the NAME's definition. */
9177 if (TREE_CODE (op1a) == SSA_NAME
9178 && (code1 == NE_EXPR || code1 == EQ_EXPR)
9179 && (integer_zerop (op1b) || integer_onep (op1b)))
9180 {
9181 bool invert = ((code1 == EQ_EXPR && integer_zerop (op1b))
9182 || (code1 == NE_EXPR && integer_onep (op1b)));
9183 gimple *stmt = SSA_NAME_DEF_STMT (op1a);
9184 switch (gimple_code (stmt))
9185 {
9186 case GIMPLE_ASSIGN:
9187 /* Try to simplify by copy-propagating the definition. */
9188 return or_var_with_comparison (type, op1a, invert, code2, op2a,
9189 op2b, outer_cond_bb);
9190
9191 case GIMPLE_PHI:
9192 /* If every argument to the PHI produces the same result when
9193 ORed with the second comparison, we win.
9194 Do not do this unless the type is bool since we need a bool
9195 result here anyway. */
9196 if (TREE_CODE (TREE_TYPE (op1a)) == BOOLEAN_TYPE)
9197 {
9198 tree result = NULL_TREE;
9199 unsigned i;
9200 for (i = 0; i < gimple_phi_num_args (stmt); i++)
9201 {
9202 tree arg = gimple_phi_arg_def (stmt, i);
9203
9204 /* If this PHI has itself as an argument, ignore it.
9205 If all the other args produce the same result,
9206 we're still OK. */
9207 if (arg == gimple_phi_result (stmt))
9208 continue;
9209 else if (TREE_CODE (arg) == INTEGER_CST)
9210 {
9211 if (invert ? integer_zerop (arg) : integer_nonzerop (arg))
9212 {
9213 if (!result)
9214 result = boolean_true_node;
9215 else if (!integer_onep (result))
9216 return NULL_TREE;
9217 }
9218 else if (!result)
9219 result = fold_build2 (code2, boolean_type_node,
9220 op2a, op2b);
9221 else if (!same_bool_comparison_p (result,
9222 code2, op2a, op2b))
9223 return NULL_TREE;
9224 }
9225 else if (TREE_CODE (arg) == SSA_NAME
9226 && !SSA_NAME_IS_DEFAULT_DEF (arg))
9227 {
9228 tree temp;
9229 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
9230 /* In simple cases we can look through PHI nodes,
9231 but we have to be careful with loops.
9232 See PR49073. */
9233 if (! dom_info_available_p (CDI_DOMINATORS)
9234 || gimple_bb (def_stmt) == gimple_bb (stmt)
9235 || dominated_by_p (CDI_DOMINATORS,
9236 gimple_bb (def_stmt),
9237 gimple_bb (stmt)))
9238 return NULL_TREE;
9239 temp = or_var_with_comparison (type, arg, invert, code2,
9240 op2a, op2b, outer_cond_bb);
9241 if (!temp)
9242 return NULL_TREE;
9243 else if (!result)
9244 result = temp;
9245 else if (!same_bool_result_p (result, temp))
9246 return NULL_TREE;
9247 }
9248 else
9249 return NULL_TREE;
9250 }
9251 return result;
9252 }
9253
9254 default:
9255 break;
9256 }
9257 }
9258 return NULL_TREE;
9259 }
9260
9261 /* Try to simplify the OR of two comparisons, specified by
9262 (OP1A CODE1 OP1B) and (OP2B CODE2 OP2B), respectively.
9263 If this can be simplified to a single expression (without requiring
9264 introducing more SSA variables to hold intermediate values),
9265 return the resulting tree. Otherwise return NULL_TREE.
9266 If the result expression is non-null, it has boolean type. */
9267
9268 tree
9269 maybe_fold_or_comparisons (tree type,
9270 enum tree_code code1, tree op1a, tree op1b,
9271 enum tree_code code2, tree op2a, tree op2b,
9272 basic_block outer_cond_bb)
9273 {
9274 if (tree t = or_comparisons_1 (type, code1, op1a, op1b, code2, op2a, op2b,
9275 outer_cond_bb))
9276 return t;
9277
9278 if (tree t = or_comparisons_1 (type, code2, op2a, op2b, code1, op1a, op1b,
9279 outer_cond_bb))
9280 return t;
9281
9282 if (tree t = maybe_fold_comparisons_from_match_pd (type, BIT_IOR_EXPR, code1,
9283 op1a, op1b, code2, op2a,
9284 op2b, outer_cond_bb))
9285 return t;
9286
9287 return NULL_TREE;
9288 }
9289
9290 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
9291
9292 Either NULL_TREE, a simplified but non-constant or a constant
9293 is returned.
9294
9295 ??? This should go into a gimple-fold-inline.h file to be eventually
9296 privatized with the single valueize function used in the various TUs
9297 to avoid the indirect function call overhead. */
9298
9299 tree
9300 gimple_fold_stmt_to_constant_1 (gimple *stmt, tree (*valueize) (tree),
9301 tree (*gvalueize) (tree))
9302 {
9303 gimple_match_op res_op;
9304 /* ??? The SSA propagators do not correctly deal with following SSA use-def
9305 edges if there are intermediate VARYING defs. For this reason
9306 do not follow SSA edges here even though SCCVN can technically
9307 just deal fine with that. */
9308 if (gimple_simplify (stmt, &res_op, NULL, gvalueize, valueize))
9309 {
9310 tree res = NULL_TREE;
9311 if (gimple_simplified_result_is_gimple_val (&res_op))
9312 res = res_op.ops[0];
9313 else if (mprts_hook)
9314 res = mprts_hook (&res_op);
9315 if (res)
9316 {
9317 if (dump_file && dump_flags & TDF_DETAILS)
9318 {
9319 fprintf (dump_file, "Match-and-simplified ");
9320 print_gimple_expr (dump_file, stmt, 0, TDF_SLIM);
9321 fprintf (dump_file, " to ");
9322 print_generic_expr (dump_file, res);
9323 fprintf (dump_file, "\n");
9324 }
9325 return res;
9326 }
9327 }
9328
9329 location_t loc = gimple_location (stmt);
9330 switch (gimple_code (stmt))
9331 {
9332 case GIMPLE_ASSIGN:
9333 {
9334 enum tree_code subcode = gimple_assign_rhs_code (stmt);
9335
9336 switch (get_gimple_rhs_class (subcode))
9337 {
9338 case GIMPLE_SINGLE_RHS:
9339 {
9340 tree rhs = gimple_assign_rhs1 (stmt);
9341 enum tree_code_class kind = TREE_CODE_CLASS (subcode);
9342
9343 if (TREE_CODE (rhs) == SSA_NAME)
9344 {
9345 /* If the RHS is an SSA_NAME, return its known constant value,
9346 if any. */
9347 return (*valueize) (rhs);
9348 }
9349 /* Handle propagating invariant addresses into address
9350 operations. */
9351 else if (TREE_CODE (rhs) == ADDR_EXPR
9352 && !is_gimple_min_invariant (rhs))
9353 {
9354 poly_int64 offset = 0;
9355 tree base;
9356 base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (rhs, 0),
9357 &offset,
9358 valueize);
9359 if (base
9360 && (CONSTANT_CLASS_P (base)
9361 || decl_address_invariant_p (base)))
9362 return build_invariant_address (TREE_TYPE (rhs),
9363 base, offset);
9364 }
9365 else if (TREE_CODE (rhs) == CONSTRUCTOR
9366 && TREE_CODE (TREE_TYPE (rhs)) == VECTOR_TYPE
9367 && known_eq (CONSTRUCTOR_NELTS (rhs),
9368 TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs))))
9369 {
9370 unsigned i, nelts;
9371 tree val;
9372
9373 nelts = CONSTRUCTOR_NELTS (rhs);
9374 tree_vector_builder vec (TREE_TYPE (rhs), nelts, 1);
9375 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), i, val)
9376 {
9377 val = (*valueize) (val);
9378 if (TREE_CODE (val) == INTEGER_CST
9379 || TREE_CODE (val) == REAL_CST
9380 || TREE_CODE (val) == FIXED_CST)
9381 vec.quick_push (val);
9382 else
9383 return NULL_TREE;
9384 }
9385
9386 return vec.build ();
9387 }
9388 if (subcode == OBJ_TYPE_REF)
9389 {
9390 tree val = (*valueize) (OBJ_TYPE_REF_EXPR (rhs));
9391 /* If callee is constant, we can fold away the wrapper. */
9392 if (is_gimple_min_invariant (val))
9393 return val;
9394 }
9395
9396 if (kind == tcc_reference)
9397 {
9398 if ((TREE_CODE (rhs) == VIEW_CONVERT_EXPR
9399 || TREE_CODE (rhs) == REALPART_EXPR
9400 || TREE_CODE (rhs) == IMAGPART_EXPR)
9401 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
9402 {
9403 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
9404 return fold_unary_loc (EXPR_LOCATION (rhs),
9405 TREE_CODE (rhs),
9406 TREE_TYPE (rhs), val);
9407 }
9408 else if (TREE_CODE (rhs) == BIT_FIELD_REF
9409 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
9410 {
9411 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
9412 return fold_ternary_loc (EXPR_LOCATION (rhs),
9413 TREE_CODE (rhs),
9414 TREE_TYPE (rhs), val,
9415 TREE_OPERAND (rhs, 1),
9416 TREE_OPERAND (rhs, 2));
9417 }
9418 else if (TREE_CODE (rhs) == MEM_REF
9419 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
9420 {
9421 tree val = (*valueize) (TREE_OPERAND (rhs, 0));
9422 if (TREE_CODE (val) == ADDR_EXPR
9423 && is_gimple_min_invariant (val))
9424 {
9425 tree tem = fold_build2 (MEM_REF, TREE_TYPE (rhs),
9426 unshare_expr (val),
9427 TREE_OPERAND (rhs, 1));
9428 if (tem)
9429 rhs = tem;
9430 }
9431 }
9432 return fold_const_aggregate_ref_1 (rhs, valueize);
9433 }
9434 else if (kind == tcc_declaration)
9435 return get_symbol_constant_value (rhs);
9436 return rhs;
9437 }
9438
9439 case GIMPLE_UNARY_RHS:
9440 return NULL_TREE;
9441
9442 case GIMPLE_BINARY_RHS:
9443 /* Translate &x + CST into an invariant form suitable for
9444 further propagation. */
9445 if (subcode == POINTER_PLUS_EXPR)
9446 {
9447 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
9448 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
9449 if (TREE_CODE (op0) == ADDR_EXPR
9450 && TREE_CODE (op1) == INTEGER_CST)
9451 {
9452 tree off = fold_convert (ptr_type_node, op1);
9453 return build1_loc
9454 (loc, ADDR_EXPR, TREE_TYPE (op0),
9455 fold_build2 (MEM_REF,
9456 TREE_TYPE (TREE_TYPE (op0)),
9457 unshare_expr (op0), off));
9458 }
9459 }
9460 /* Canonicalize bool != 0 and bool == 0 appearing after
9461 valueization. While gimple_simplify handles this
9462 it can get confused by the ~X == 1 -> X == 0 transform
9463 which we cant reduce to a SSA name or a constant
9464 (and we have no way to tell gimple_simplify to not
9465 consider those transforms in the first place). */
9466 else if (subcode == EQ_EXPR
9467 || subcode == NE_EXPR)
9468 {
9469 tree lhs = gimple_assign_lhs (stmt);
9470 tree op0 = gimple_assign_rhs1 (stmt);
9471 if (useless_type_conversion_p (TREE_TYPE (lhs),
9472 TREE_TYPE (op0)))
9473 {
9474 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
9475 op0 = (*valueize) (op0);
9476 if (TREE_CODE (op0) == INTEGER_CST)
9477 std::swap (op0, op1);
9478 if (TREE_CODE (op1) == INTEGER_CST
9479 && ((subcode == NE_EXPR && integer_zerop (op1))
9480 || (subcode == EQ_EXPR && integer_onep (op1))))
9481 return op0;
9482 }
9483 }
9484 return NULL_TREE;
9485
9486 case GIMPLE_TERNARY_RHS:
9487 {
9488 /* Handle ternary operators that can appear in GIMPLE form. */
9489 tree op0 = (*valueize) (gimple_assign_rhs1 (stmt));
9490 tree op1 = (*valueize) (gimple_assign_rhs2 (stmt));
9491 tree op2 = (*valueize) (gimple_assign_rhs3 (stmt));
9492 return fold_ternary_loc (loc, subcode,
9493 TREE_TYPE (gimple_assign_lhs (stmt)),
9494 op0, op1, op2);
9495 }
9496
9497 default:
9498 gcc_unreachable ();
9499 }
9500 }
9501
9502 case GIMPLE_CALL:
9503 {
9504 tree fn;
9505 gcall *call_stmt = as_a <gcall *> (stmt);
9506
9507 if (gimple_call_internal_p (stmt))
9508 {
9509 enum tree_code subcode = ERROR_MARK;
9510 switch (gimple_call_internal_fn (stmt))
9511 {
9512 case IFN_UBSAN_CHECK_ADD:
9513 subcode = PLUS_EXPR;
9514 break;
9515 case IFN_UBSAN_CHECK_SUB:
9516 subcode = MINUS_EXPR;
9517 break;
9518 case IFN_UBSAN_CHECK_MUL:
9519 subcode = MULT_EXPR;
9520 break;
9521 case IFN_BUILTIN_EXPECT:
9522 {
9523 tree arg0 = gimple_call_arg (stmt, 0);
9524 tree op0 = (*valueize) (arg0);
9525 if (TREE_CODE (op0) == INTEGER_CST)
9526 return op0;
9527 return NULL_TREE;
9528 }
9529 default:
9530 return NULL_TREE;
9531 }
9532 tree arg0 = gimple_call_arg (stmt, 0);
9533 tree arg1 = gimple_call_arg (stmt, 1);
9534 tree op0 = (*valueize) (arg0);
9535 tree op1 = (*valueize) (arg1);
9536
9537 if (TREE_CODE (op0) != INTEGER_CST
9538 || TREE_CODE (op1) != INTEGER_CST)
9539 {
9540 switch (subcode)
9541 {
9542 case MULT_EXPR:
9543 /* x * 0 = 0 * x = 0 without overflow. */
9544 if (integer_zerop (op0) || integer_zerop (op1))
9545 return build_zero_cst (TREE_TYPE (arg0));
9546 break;
9547 case MINUS_EXPR:
9548 /* y - y = 0 without overflow. */
9549 if (operand_equal_p (op0, op1, 0))
9550 return build_zero_cst (TREE_TYPE (arg0));
9551 break;
9552 default:
9553 break;
9554 }
9555 }
9556 tree res
9557 = fold_binary_loc (loc, subcode, TREE_TYPE (arg0), op0, op1);
9558 if (res
9559 && TREE_CODE (res) == INTEGER_CST
9560 && !TREE_OVERFLOW (res))
9561 return res;
9562 return NULL_TREE;
9563 }
9564
9565 fn = (*valueize) (gimple_call_fn (stmt));
9566 if (TREE_CODE (fn) == ADDR_EXPR
9567 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
9568 && fndecl_built_in_p (TREE_OPERAND (fn, 0))
9569 && gimple_builtin_call_types_compatible_p (stmt,
9570 TREE_OPERAND (fn, 0)))
9571 {
9572 tree *args = XALLOCAVEC (tree, gimple_call_num_args (stmt));
9573 tree retval;
9574 unsigned i;
9575 for (i = 0; i < gimple_call_num_args (stmt); ++i)
9576 args[i] = (*valueize) (gimple_call_arg (stmt, i));
9577 retval = fold_builtin_call_array (loc,
9578 gimple_call_return_type (call_stmt),
9579 fn, gimple_call_num_args (stmt), args);
9580 if (retval)
9581 {
9582 /* fold_call_expr wraps the result inside a NOP_EXPR. */
9583 STRIP_NOPS (retval);
9584 retval = fold_convert (gimple_call_return_type (call_stmt),
9585 retval);
9586 }
9587 return retval;
9588 }
9589 return NULL_TREE;
9590 }
9591
9592 default:
9593 return NULL_TREE;
9594 }
9595 }
9596
9597 /* Fold STMT to a constant using VALUEIZE to valueize SSA names.
9598 Returns NULL_TREE if folding to a constant is not possible, otherwise
9599 returns a constant according to is_gimple_min_invariant. */
9600
9601 tree
9602 gimple_fold_stmt_to_constant (gimple *stmt, tree (*valueize) (tree))
9603 {
9604 tree res = gimple_fold_stmt_to_constant_1 (stmt, valueize);
9605 if (res && is_gimple_min_invariant (res))
9606 return res;
9607 return NULL_TREE;
9608 }
9609
9610
9611 /* The following set of functions are supposed to fold references using
9612 their constant initializers. */
9613
9614 /* See if we can find constructor defining value of BASE.
9615 When we know the consructor with constant offset (such as
9616 base is array[40] and we do know constructor of array), then
9617 BIT_OFFSET is adjusted accordingly.
9618
9619 As a special case, return error_mark_node when constructor
9620 is not explicitly available, but it is known to be zero
9621 such as 'static const int a;'. */
9622 static tree
9623 get_base_constructor (tree base, poly_int64 *bit_offset,
9624 tree (*valueize)(tree))
9625 {
9626 poly_int64 bit_offset2, size, max_size;
9627 bool reverse;
9628
9629 if (TREE_CODE (base) == MEM_REF)
9630 {
9631 poly_offset_int boff = *bit_offset + mem_ref_offset (base) * BITS_PER_UNIT;
9632 if (!boff.to_shwi (bit_offset))
9633 return NULL_TREE;
9634
9635 if (valueize
9636 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
9637 base = valueize (TREE_OPERAND (base, 0));
9638 if (!base || TREE_CODE (base) != ADDR_EXPR)
9639 return NULL_TREE;
9640 base = TREE_OPERAND (base, 0);
9641 }
9642 else if (valueize
9643 && TREE_CODE (base) == SSA_NAME)
9644 base = valueize (base);
9645
9646 /* Get a CONSTRUCTOR. If BASE is a VAR_DECL, get its
9647 DECL_INITIAL. If BASE is a nested reference into another
9648 ARRAY_REF or COMPONENT_REF, make a recursive call to resolve
9649 the inner reference. */
9650 switch (TREE_CODE (base))
9651 {
9652 case VAR_DECL:
9653 case CONST_DECL:
9654 {
9655 tree init = ctor_for_folding (base);
9656
9657 /* Our semantic is exact opposite of ctor_for_folding;
9658 NULL means unknown, while error_mark_node is 0. */
9659 if (init == error_mark_node)
9660 return NULL_TREE;
9661 if (!init)
9662 return error_mark_node;
9663 return init;
9664 }
9665
9666 case VIEW_CONVERT_EXPR:
9667 return get_base_constructor (TREE_OPERAND (base, 0),
9668 bit_offset, valueize);
9669
9670 case ARRAY_REF:
9671 case COMPONENT_REF:
9672 base = get_ref_base_and_extent (base, &bit_offset2, &size, &max_size,
9673 &reverse);
9674 if (!known_size_p (max_size) || maybe_ne (size, max_size))
9675 return NULL_TREE;
9676 *bit_offset += bit_offset2;
9677 return get_base_constructor (base, bit_offset, valueize);
9678
9679 case CONSTRUCTOR:
9680 return base;
9681
9682 default:
9683 if (CONSTANT_CLASS_P (base))
9684 return base;
9685
9686 return NULL_TREE;
9687 }
9688 }
9689
9690 /* CTOR is a CONSTRUCTOR of an array or vector type. Fold a reference of SIZE
9691 bits to the memory at bit OFFSET. If non-null, TYPE is the expected type of
9692 the reference; otherwise the type of the referenced element is used instead.
9693 When SIZE is zero, attempt to fold a reference to the entire element OFFSET
9694 refers to. Increment *SUBOFF by the bit offset of the accessed element. */
9695
9696 static tree
9697 fold_array_ctor_reference (tree type, tree ctor,
9698 unsigned HOST_WIDE_INT offset,
9699 unsigned HOST_WIDE_INT size,
9700 tree from_decl,
9701 unsigned HOST_WIDE_INT *suboff)
9702 {
9703 offset_int low_bound;
9704 offset_int elt_size;
9705 offset_int access_index;
9706 tree domain_type = NULL_TREE;
9707 HOST_WIDE_INT inner_offset;
9708
9709 /* Compute low bound and elt size. */
9710 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE)
9711 domain_type = TYPE_DOMAIN (TREE_TYPE (ctor));
9712 if (domain_type && TYPE_MIN_VALUE (domain_type))
9713 {
9714 /* Static constructors for variably sized objects make no sense. */
9715 if (TREE_CODE (TYPE_MIN_VALUE (domain_type)) != INTEGER_CST)
9716 return NULL_TREE;
9717 low_bound = wi::to_offset (TYPE_MIN_VALUE (domain_type));
9718 }
9719 else
9720 low_bound = 0;
9721 /* Static constructors for variably sized objects make no sense. */
9722 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor)))) != INTEGER_CST)
9723 return NULL_TREE;
9724 elt_size = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ctor))));
9725
9726 /* When TYPE is non-null, verify that it specifies a constant-sized
9727 access of a multiple of the array element size. Avoid division
9728 by zero below when ELT_SIZE is zero, such as with the result of
9729 an initializer for a zero-length array or an empty struct. */
9730 if (elt_size == 0
9731 || (type
9732 && (!TYPE_SIZE_UNIT (type)
9733 || TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST)))
9734 return NULL_TREE;
9735
9736 /* Compute the array index we look for. */
9737 access_index = wi::udiv_trunc (offset_int (offset / BITS_PER_UNIT),
9738 elt_size);
9739 access_index += low_bound;
9740
9741 /* And offset within the access. */
9742 inner_offset = offset % (elt_size.to_uhwi () * BITS_PER_UNIT);
9743
9744 unsigned HOST_WIDE_INT elt_sz = elt_size.to_uhwi ();
9745 if (size > elt_sz * BITS_PER_UNIT)
9746 {
9747 /* native_encode_expr constraints. */
9748 if (size > MAX_BITSIZE_MODE_ANY_MODE
9749 || size % BITS_PER_UNIT != 0
9750 || inner_offset % BITS_PER_UNIT != 0
9751 || elt_sz > MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT)
9752 return NULL_TREE;
9753
9754 unsigned ctor_idx;
9755 tree val = get_array_ctor_element_at_index (ctor, access_index,
9756 &ctor_idx);
9757 if (!val && ctor_idx >= CONSTRUCTOR_NELTS (ctor))
9758 return build_zero_cst (type);
9759
9760 /* native-encode adjacent ctor elements. */
9761 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
9762 unsigned bufoff = 0;
9763 offset_int index = 0;
9764 offset_int max_index = access_index;
9765 constructor_elt *elt = CONSTRUCTOR_ELT (ctor, ctor_idx);
9766 if (!val)
9767 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
9768 else if (!CONSTANT_CLASS_P (val))
9769 return NULL_TREE;
9770 if (!elt->index)
9771 ;
9772 else if (TREE_CODE (elt->index) == RANGE_EXPR)
9773 {
9774 index = wi::to_offset (TREE_OPERAND (elt->index, 0));
9775 max_index = wi::to_offset (TREE_OPERAND (elt->index, 1));
9776 }
9777 else
9778 index = max_index = wi::to_offset (elt->index);
9779 index = wi::umax (index, access_index);
9780 do
9781 {
9782 if (bufoff + elt_sz > sizeof (buf))
9783 elt_sz = sizeof (buf) - bufoff;
9784 int len;
9785 if (TREE_CODE (val) == RAW_DATA_CST)
9786 {
9787 gcc_assert (inner_offset == 0);
9788 if (!elt->index || TREE_CODE (elt->index) != INTEGER_CST)
9789 return NULL_TREE;
9790 inner_offset = (access_index
9791 - wi::to_offset (elt->index)).to_uhwi ();
9792 len = MIN (sizeof (buf) - bufoff,
9793 (unsigned) (RAW_DATA_LENGTH (val) - inner_offset));
9794 memcpy (buf + bufoff, RAW_DATA_POINTER (val) + inner_offset,
9795 len);
9796 access_index += len - 1;
9797 }
9798 else
9799 {
9800 len = native_encode_expr (val, buf + bufoff, elt_sz,
9801 inner_offset / BITS_PER_UNIT);
9802 if (len != (int) elt_sz - inner_offset / BITS_PER_UNIT)
9803 return NULL_TREE;
9804 }
9805 inner_offset = 0;
9806 bufoff += len;
9807
9808 access_index += 1;
9809 if (wi::cmpu (access_index, index) == 0)
9810 val = elt->value;
9811 else if (wi::cmpu (access_index, max_index) > 0)
9812 {
9813 ctor_idx++;
9814 if (ctor_idx >= CONSTRUCTOR_NELTS (ctor))
9815 {
9816 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
9817 ++max_index;
9818 }
9819 else
9820 {
9821 elt = CONSTRUCTOR_ELT (ctor, ctor_idx);
9822 index = 0;
9823 max_index = access_index;
9824 if (!elt->index)
9825 ;
9826 else if (TREE_CODE (elt->index) == RANGE_EXPR)
9827 {
9828 index = wi::to_offset (TREE_OPERAND (elt->index, 0));
9829 max_index = wi::to_offset (TREE_OPERAND (elt->index, 1));
9830 }
9831 else
9832 index = max_index = wi::to_offset (elt->index);
9833 index = wi::umax (index, access_index);
9834 if (wi::cmpu (access_index, index) == 0)
9835 val = elt->value;
9836 else
9837 val = build_zero_cst (TREE_TYPE (TREE_TYPE (ctor)));
9838 }
9839 }
9840 }
9841 while (bufoff < size / BITS_PER_UNIT);
9842 *suboff += size;
9843 return native_interpret_expr (type, buf, size / BITS_PER_UNIT);
9844 }
9845
9846 unsigned ctor_idx;
9847 if (tree val = get_array_ctor_element_at_index (ctor, access_index,
9848 &ctor_idx))
9849 {
9850 if (TREE_CODE (val) == RAW_DATA_CST)
9851 {
9852 if (size != BITS_PER_UNIT || elt_sz != 1 || inner_offset != 0)
9853 return NULL_TREE;
9854 constructor_elt *elt = CONSTRUCTOR_ELT (ctor, ctor_idx);
9855 if (elt->index == NULL_TREE || TREE_CODE (elt->index) != INTEGER_CST)
9856 return NULL_TREE;
9857 unsigned o = (access_index - wi::to_offset (elt->index)).to_uhwi ();
9858 val = build_int_cst (TREE_TYPE (val), RAW_DATA_UCHAR_ELT (val, o));
9859 }
9860 if (!size && TREE_CODE (val) != CONSTRUCTOR)
9861 {
9862 /* For the final reference to the entire accessed element
9863 (SIZE is zero), reset INNER_OFFSET, disegard TYPE (which
9864 may be null) in favor of the type of the element, and set
9865 SIZE to the size of the accessed element. */
9866 inner_offset = 0;
9867 type = TREE_TYPE (val);
9868 size = elt_sz * BITS_PER_UNIT;
9869 }
9870 else if (size && access_index < CONSTRUCTOR_NELTS (ctor) - 1
9871 && TREE_CODE (val) == CONSTRUCTOR
9872 && (elt_sz * BITS_PER_UNIT - inner_offset) < size)
9873 /* If this isn't the last element in the CTOR and a CTOR itself
9874 and it does not cover the whole object we are requesting give up
9875 since we're not set up for combining from multiple CTORs. */
9876 return NULL_TREE;
9877
9878 *suboff += access_index.to_uhwi () * elt_sz * BITS_PER_UNIT;
9879 return fold_ctor_reference (type, val, inner_offset, size, from_decl,
9880 suboff);
9881 }
9882
9883 /* Memory not explicitly mentioned in constructor is 0 (or
9884 the reference is out of range). */
9885 return type ? build_zero_cst (type) : NULL_TREE;
9886 }
9887
9888 /* CTOR is a CONSTRUCTOR of a record or union type. Fold a reference of SIZE
9889 bits to the memory at bit OFFSET. If non-null, TYPE is the expected type of
9890 the reference; otherwise the type of the referenced member is used instead.
9891 When SIZE is zero, attempt to fold a reference to the entire member OFFSET
9892 refers to. Increment *SUBOFF by the bit offset of the accessed member. */
9893
9894 static tree
9895 fold_nonarray_ctor_reference (tree type, tree ctor,
9896 unsigned HOST_WIDE_INT offset,
9897 unsigned HOST_WIDE_INT size,
9898 tree from_decl,
9899 unsigned HOST_WIDE_INT *suboff)
9900 {
9901 unsigned HOST_WIDE_INT cnt;
9902 tree cfield, cval;
9903
9904 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), cnt, cfield, cval)
9905 {
9906 tree byte_offset = DECL_FIELD_OFFSET (cfield);
9907 tree field_offset = DECL_FIELD_BIT_OFFSET (cfield);
9908 tree field_size = DECL_SIZE (cfield);
9909
9910 if (!field_size)
9911 {
9912 /* Determine the size of the flexible array member from
9913 the size of the initializer provided for it. */
9914 field_size = TYPE_SIZE (TREE_TYPE (cval));
9915 }
9916
9917 /* Variable sized objects in static constructors makes no sense,
9918 but field_size can be NULL for flexible array members. */
9919 gcc_assert (TREE_CODE (field_offset) == INTEGER_CST
9920 && TREE_CODE (byte_offset) == INTEGER_CST
9921 && (field_size != NULL_TREE
9922 ? TREE_CODE (field_size) == INTEGER_CST
9923 : TREE_CODE (TREE_TYPE (cfield)) == ARRAY_TYPE));
9924
9925 /* Compute bit offset of the field. */
9926 offset_int bitoffset
9927 = (wi::to_offset (field_offset)
9928 + (wi::to_offset (byte_offset) << LOG2_BITS_PER_UNIT));
9929 /* Compute bit offset where the field ends. */
9930 offset_int bitoffset_end;
9931 if (field_size != NULL_TREE)
9932 bitoffset_end = bitoffset + wi::to_offset (field_size);
9933 else
9934 bitoffset_end = 0;
9935
9936 /* Compute the bit offset of the end of the desired access.
9937 As a special case, if the size of the desired access is
9938 zero, assume the access is to the entire field (and let
9939 the caller make any necessary adjustments by storing
9940 the actual bounds of the field in FIELDBOUNDS). */
9941 offset_int access_end = offset_int (offset);
9942 if (size)
9943 access_end += size;
9944 else
9945 access_end = bitoffset_end;
9946
9947 /* Is there any overlap between the desired access at
9948 [OFFSET, OFFSET+SIZE) and the offset of the field within
9949 the object at [BITOFFSET, BITOFFSET_END)? */
9950 if (wi::cmps (access_end, bitoffset) > 0
9951 && (field_size == NULL_TREE
9952 || wi::lts_p (offset, bitoffset_end)))
9953 {
9954 *suboff += bitoffset.to_uhwi ();
9955
9956 if (!size && TREE_CODE (cval) != CONSTRUCTOR)
9957 {
9958 /* For the final reference to the entire accessed member
9959 (SIZE is zero), reset OFFSET, disegard TYPE (which may
9960 be null) in favor of the type of the member, and set
9961 SIZE to the size of the accessed member. */
9962 offset = bitoffset.to_uhwi ();
9963 type = TREE_TYPE (cval);
9964 size = (bitoffset_end - bitoffset).to_uhwi ();
9965 }
9966
9967 /* We do have overlap. Now see if the field is large enough
9968 to cover the access. Give up for accesses that extend
9969 beyond the end of the object or that span multiple fields. */
9970 if (wi::cmps (access_end, bitoffset_end) > 0)
9971 return NULL_TREE;
9972 if (offset < bitoffset)
9973 return NULL_TREE;
9974
9975 offset_int inner_offset = offset_int (offset) - bitoffset;
9976
9977 /* Integral bit-fields are left-justified on big-endian targets, so
9978 we must arrange for native_encode_int to start at their MSB. */
9979 if (DECL_BIT_FIELD (cfield) && INTEGRAL_TYPE_P (TREE_TYPE (cfield)))
9980 {
9981 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
9982 return NULL_TREE;
9983 if (BYTES_BIG_ENDIAN)
9984 {
9985 tree ctype = TREE_TYPE (cfield);
9986 unsigned int encoding_size;
9987 if (TYPE_MODE (ctype) != BLKmode)
9988 encoding_size
9989 = GET_MODE_BITSIZE (SCALAR_INT_TYPE_MODE (ctype));
9990 else
9991 encoding_size = TREE_INT_CST_LOW (TYPE_SIZE (ctype));
9992 inner_offset += encoding_size - wi::to_offset (field_size);
9993 }
9994 }
9995
9996 return fold_ctor_reference (type, cval,
9997 inner_offset.to_uhwi (), size,
9998 from_decl, suboff);
9999 }
10000 }
10001
10002 if (!type)
10003 return NULL_TREE;
10004
10005 return build_zero_cst (type);
10006 }
10007
10008 /* CTOR is a value initializing memory. Fold a reference of TYPE and
10009 bit size POLY_SIZE to the memory at bit POLY_OFFSET. When POLY_SIZE
10010 is zero, attempt to fold a reference to the entire subobject
10011 which OFFSET refers to. This is used when folding accesses to
10012 string members of aggregates. When non-null, set *SUBOFF to
10013 the bit offset of the accessed subobject. */
10014
10015 tree
10016 fold_ctor_reference (tree type, tree ctor, const poly_uint64 &poly_offset,
10017 const poly_uint64 &poly_size, tree from_decl,
10018 unsigned HOST_WIDE_INT *suboff /* = NULL */)
10019 {
10020 tree ret;
10021
10022 /* We found the field with exact match. */
10023 if (type
10024 && useless_type_conversion_p (type, TREE_TYPE (ctor))
10025 && known_eq (poly_offset, 0U))
10026 return canonicalize_constructor_val (unshare_expr (ctor), from_decl);
10027
10028 /* The remaining optimizations need a constant size and offset. */
10029 unsigned HOST_WIDE_INT size, offset;
10030 if (!poly_size.is_constant (&size) || !poly_offset.is_constant (&offset))
10031 return NULL_TREE;
10032
10033 /* We are at the end of walk, see if we can view convert the
10034 result. */
10035 if (!AGGREGATE_TYPE_P (TREE_TYPE (ctor)) && !offset
10036 /* VIEW_CONVERT_EXPR is defined only for matching sizes. */
10037 && known_eq (wi::to_poly_widest (TYPE_SIZE (type)), size)
10038 && known_eq (wi::to_poly_widest (TYPE_SIZE (TREE_TYPE (ctor))), size))
10039 {
10040 ret = canonicalize_constructor_val (unshare_expr (ctor), from_decl);
10041 if (ret)
10042 {
10043 ret = fold_unary (VIEW_CONVERT_EXPR, type, ret);
10044 if (ret)
10045 STRIP_USELESS_TYPE_CONVERSION (ret);
10046 }
10047 return ret;
10048 }
10049
10050 /* For constants and byte-aligned/sized reads, try to go through
10051 native_encode/interpret. */
10052 if (CONSTANT_CLASS_P (ctor)
10053 && BITS_PER_UNIT == 8
10054 && offset % BITS_PER_UNIT == 0
10055 && offset / BITS_PER_UNIT <= INT_MAX
10056 && size % BITS_PER_UNIT == 0
10057 && size <= MAX_BITSIZE_MODE_ANY_MODE
10058 && can_native_interpret_type_p (type))
10059 {
10060 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
10061 int len = native_encode_expr (ctor, buf, size / BITS_PER_UNIT,
10062 offset / BITS_PER_UNIT);
10063 if (len > 0)
10064 return native_interpret_expr (type, buf, len);
10065 }
10066
10067 /* For constructors, try first a recursive local processing, but in any case
10068 this requires the native storage order. */
10069 if (TREE_CODE (ctor) == CONSTRUCTOR
10070 && !(AGGREGATE_TYPE_P (TREE_TYPE (ctor))
10071 && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (ctor))))
10072 {
10073 unsigned HOST_WIDE_INT dummy = 0;
10074 if (!suboff)
10075 suboff = &dummy;
10076
10077 tree ret;
10078 if (TREE_CODE (TREE_TYPE (ctor)) == ARRAY_TYPE
10079 || TREE_CODE (TREE_TYPE (ctor)) == VECTOR_TYPE)
10080 ret = fold_array_ctor_reference (type, ctor, offset, size,
10081 from_decl, suboff);
10082 else
10083 ret = fold_nonarray_ctor_reference (type, ctor, offset, size,
10084 from_decl, suboff);
10085
10086 /* Otherwise fall back to native_encode_initializer. This may be done
10087 only from the outermost fold_ctor_reference call (because it itself
10088 recurses into CONSTRUCTORs and doesn't update suboff). */
10089 if (ret == NULL_TREE
10090 && suboff == &dummy
10091 && BITS_PER_UNIT == 8
10092 && offset % BITS_PER_UNIT == 0
10093 && offset / BITS_PER_UNIT <= INT_MAX
10094 && size % BITS_PER_UNIT == 0
10095 && size <= MAX_BITSIZE_MODE_ANY_MODE
10096 && can_native_interpret_type_p (type))
10097 {
10098 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
10099 int len = native_encode_initializer (ctor, buf, size / BITS_PER_UNIT,
10100 offset / BITS_PER_UNIT);
10101 if (len > 0)
10102 return native_interpret_expr (type, buf, len);
10103 }
10104
10105 return ret;
10106 }
10107
10108 return NULL_TREE;
10109 }
10110
10111 /* Return the tree representing the element referenced by T if T is an
10112 ARRAY_REF or COMPONENT_REF into constant aggregates valuezing SSA
10113 names using VALUEIZE. Return NULL_TREE otherwise. */
10114
10115 tree
10116 fold_const_aggregate_ref_1 (tree t, tree (*valueize) (tree))
10117 {
10118 tree ctor, idx, base;
10119 poly_int64 offset, size, max_size;
10120 tree tem;
10121 bool reverse;
10122
10123 if (TREE_THIS_VOLATILE (t))
10124 return NULL_TREE;
10125
10126 if (DECL_P (t))
10127 return get_symbol_constant_value (t);
10128
10129 tem = fold_read_from_constant_string (t);
10130 if (tem)
10131 return tem;
10132
10133 switch (TREE_CODE (t))
10134 {
10135 case ARRAY_REF:
10136 case ARRAY_RANGE_REF:
10137 /* Constant indexes are handled well by get_base_constructor.
10138 Only special case variable offsets.
10139 FIXME: This code can't handle nested references with variable indexes
10140 (they will be handled only by iteration of ccp). Perhaps we can bring
10141 get_ref_base_and_extent here and make it use a valueize callback. */
10142 if (TREE_CODE (TREE_OPERAND (t, 1)) == SSA_NAME
10143 && valueize
10144 && (idx = (*valueize) (TREE_OPERAND (t, 1)))
10145 && poly_int_tree_p (idx))
10146 {
10147 tree low_bound, unit_size;
10148
10149 /* If the resulting bit-offset is constant, track it. */
10150 if ((low_bound = array_ref_low_bound (t),
10151 poly_int_tree_p (low_bound))
10152 && (unit_size = array_ref_element_size (t),
10153 tree_fits_uhwi_p (unit_size)))
10154 {
10155 poly_offset_int woffset
10156 = wi::sext (wi::to_poly_offset (idx)
10157 - wi::to_poly_offset (low_bound),
10158 TYPE_PRECISION (sizetype));
10159 woffset *= tree_to_uhwi (unit_size);
10160 woffset *= BITS_PER_UNIT;
10161 if (woffset.to_shwi (&offset))
10162 {
10163 base = TREE_OPERAND (t, 0);
10164 ctor = get_base_constructor (base, &offset, valueize);
10165 /* Empty constructor. Always fold to 0. */
10166 if (ctor == error_mark_node)
10167 return build_zero_cst (TREE_TYPE (t));
10168 /* Out of bound array access. Value is undefined,
10169 but don't fold. */
10170 if (maybe_lt (offset, 0))
10171 return NULL_TREE;
10172 /* We cannot determine ctor. */
10173 if (!ctor)
10174 return NULL_TREE;
10175 return fold_ctor_reference (TREE_TYPE (t), ctor, offset,
10176 tree_to_uhwi (unit_size)
10177 * BITS_PER_UNIT,
10178 base);
10179 }
10180 }
10181 }
10182 /* Fallthru. */
10183
10184 case COMPONENT_REF:
10185 case BIT_FIELD_REF:
10186 case TARGET_MEM_REF:
10187 case MEM_REF:
10188 base = get_ref_base_and_extent (t, &offset, &size, &max_size, &reverse);
10189 ctor = get_base_constructor (base, &offset, valueize);
10190
10191 /* We cannot determine ctor. */
10192 if (!ctor)
10193 return NULL_TREE;
10194 /* Empty constructor. Always fold to 0. */
10195 if (ctor == error_mark_node)
10196 return build_zero_cst (TREE_TYPE (t));
10197 /* We do not know precise access. */
10198 if (!known_size_p (max_size) || maybe_ne (max_size, size))
10199 return NULL_TREE;
10200 /* Out of bound array access. Value is undefined, but don't fold. */
10201 if (maybe_lt (offset, 0))
10202 return NULL_TREE;
10203 /* Access with reverse storage order. */
10204 if (reverse)
10205 return NULL_TREE;
10206
10207 tem = fold_ctor_reference (TREE_TYPE (t), ctor, offset, size, base);
10208 if (tem)
10209 return tem;
10210
10211 /* For bit field reads try to read the representative and
10212 adjust. */
10213 if (TREE_CODE (t) == COMPONENT_REF
10214 && DECL_BIT_FIELD (TREE_OPERAND (t, 1))
10215 && DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1)))
10216 {
10217 HOST_WIDE_INT csize, coffset;
10218 tree field = TREE_OPERAND (t, 1);
10219 tree repr = DECL_BIT_FIELD_REPRESENTATIVE (field);
10220 if (INTEGRAL_TYPE_P (TREE_TYPE (repr))
10221 && size.is_constant (&csize)
10222 && offset.is_constant (&coffset)
10223 && (coffset % BITS_PER_UNIT != 0
10224 || csize % BITS_PER_UNIT != 0)
10225 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN)
10226 {
10227 poly_int64 bitoffset;
10228 poly_uint64 field_offset, repr_offset;
10229 if (poly_int_tree_p (DECL_FIELD_OFFSET (field), &field_offset)
10230 && poly_int_tree_p (DECL_FIELD_OFFSET (repr), &repr_offset))
10231 bitoffset = (field_offset - repr_offset) * BITS_PER_UNIT;
10232 else
10233 bitoffset = 0;
10234 bitoffset += (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field))
10235 - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (repr)));
10236 HOST_WIDE_INT bitoff;
10237 int diff = (TYPE_PRECISION (TREE_TYPE (repr))
10238 - TYPE_PRECISION (TREE_TYPE (field)));
10239 if (bitoffset.is_constant (&bitoff)
10240 && bitoff >= 0
10241 && bitoff <= diff)
10242 {
10243 offset -= bitoff;
10244 size = tree_to_uhwi (DECL_SIZE (repr));
10245
10246 tem = fold_ctor_reference (TREE_TYPE (repr), ctor, offset,
10247 size, base);
10248 if (tem && TREE_CODE (tem) == INTEGER_CST)
10249 {
10250 if (!BYTES_BIG_ENDIAN)
10251 tem = wide_int_to_tree (TREE_TYPE (field),
10252 wi::lrshift (wi::to_wide (tem),
10253 bitoff));
10254 else
10255 tem = wide_int_to_tree (TREE_TYPE (field),
10256 wi::lrshift (wi::to_wide (tem),
10257 diff - bitoff));
10258 return tem;
10259 }
10260 }
10261 }
10262 }
10263 break;
10264
10265 case REALPART_EXPR:
10266 case IMAGPART_EXPR:
10267 {
10268 tree c = fold_const_aggregate_ref_1 (TREE_OPERAND (t, 0), valueize);
10269 if (c && TREE_CODE (c) == COMPLEX_CST)
10270 return fold_build1_loc (EXPR_LOCATION (t),
10271 TREE_CODE (t), TREE_TYPE (t), c);
10272 break;
10273 }
10274
10275 default:
10276 break;
10277 }
10278
10279 return NULL_TREE;
10280 }
10281
10282 tree
10283 fold_const_aggregate_ref (tree t)
10284 {
10285 return fold_const_aggregate_ref_1 (t, NULL);
10286 }
10287
10288 /* Lookup virtual method with index TOKEN in a virtual table V
10289 at OFFSET.
10290 Set CAN_REFER if non-NULL to false if method
10291 is not referable or if the virtual table is ill-formed (such as rewriten
10292 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
10293
10294 tree
10295 gimple_get_virt_method_for_vtable (HOST_WIDE_INT token,
10296 tree v,
10297 unsigned HOST_WIDE_INT offset,
10298 bool *can_refer)
10299 {
10300 tree vtable = v, init, fn;
10301 unsigned HOST_WIDE_INT size;
10302 unsigned HOST_WIDE_INT elt_size, access_index;
10303 tree domain_type;
10304
10305 if (can_refer)
10306 *can_refer = true;
10307
10308 /* First of all double check we have virtual table. */
10309 if (!VAR_P (v) || !DECL_VIRTUAL_P (v))
10310 {
10311 /* Pass down that we lost track of the target. */
10312 if (can_refer)
10313 *can_refer = false;
10314 return NULL_TREE;
10315 }
10316
10317 init = ctor_for_folding (v);
10318
10319 /* The virtual tables should always be born with constructors
10320 and we always should assume that they are avaialble for
10321 folding. At the moment we do not stream them in all cases,
10322 but it should never happen that ctor seem unreachable. */
10323 gcc_assert (init);
10324 if (init == error_mark_node)
10325 {
10326 /* Pass down that we lost track of the target. */
10327 if (can_refer)
10328 *can_refer = false;
10329 return NULL_TREE;
10330 }
10331 gcc_checking_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE);
10332 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (v))));
10333 offset *= BITS_PER_UNIT;
10334 offset += token * size;
10335
10336 /* Lookup the value in the constructor that is assumed to be array.
10337 This is equivalent to
10338 fn = fold_ctor_reference (TREE_TYPE (TREE_TYPE (v)), init,
10339 offset, size, NULL);
10340 but in a constant time. We expect that frontend produced a simple
10341 array without indexed initializers. */
10342
10343 gcc_checking_assert (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE);
10344 domain_type = TYPE_DOMAIN (TREE_TYPE (init));
10345 gcc_checking_assert (integer_zerop (TYPE_MIN_VALUE (domain_type)));
10346 elt_size = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (init))));
10347
10348 access_index = offset / BITS_PER_UNIT / elt_size;
10349 gcc_checking_assert (offset % (elt_size * BITS_PER_UNIT) == 0);
10350
10351 /* The C++ FE can now produce indexed fields, and we check if the indexes
10352 match. */
10353 if (access_index < CONSTRUCTOR_NELTS (init))
10354 {
10355 fn = CONSTRUCTOR_ELT (init, access_index)->value;
10356 tree idx = CONSTRUCTOR_ELT (init, access_index)->index;
10357 gcc_checking_assert (!idx || tree_to_uhwi (idx) == access_index);
10358 STRIP_NOPS (fn);
10359 }
10360 else
10361 fn = NULL;
10362
10363 /* For type inconsistent program we may end up looking up virtual method
10364 in virtual table that does not contain TOKEN entries. We may overrun
10365 the virtual table and pick up a constant or RTTI info pointer.
10366 In any case the call is undefined. */
10367 if (!fn
10368 || (TREE_CODE (fn) != ADDR_EXPR && TREE_CODE (fn) != FDESC_EXPR)
10369 || TREE_CODE (TREE_OPERAND (fn, 0)) != FUNCTION_DECL)
10370 fn = builtin_decl_unreachable ();
10371 else
10372 {
10373 fn = TREE_OPERAND (fn, 0);
10374
10375 /* When cgraph node is missing and function is not public, we cannot
10376 devirtualize. This can happen in WHOPR when the actual method
10377 ends up in other partition, because we found devirtualization
10378 possibility too late. */
10379 if (!can_refer_decl_in_current_unit_p (fn, vtable))
10380 {
10381 if (can_refer)
10382 {
10383 *can_refer = false;
10384 return fn;
10385 }
10386 return NULL_TREE;
10387 }
10388 }
10389
10390 /* Make sure we create a cgraph node for functions we'll reference.
10391 They can be non-existent if the reference comes from an entry
10392 of an external vtable for example. */
10393 cgraph_node::get_create (fn);
10394
10395 return fn;
10396 }
10397
10398 /* Return a declaration of a function which an OBJ_TYPE_REF references. TOKEN
10399 is integer form of OBJ_TYPE_REF_TOKEN of the reference expression.
10400 KNOWN_BINFO carries the binfo describing the true type of
10401 OBJ_TYPE_REF_OBJECT(REF).
10402 Set CAN_REFER if non-NULL to false if method
10403 is not referable or if the virtual table is ill-formed (such as rewriten
10404 by non-C++ produced symbol). Otherwise just return NULL in that calse. */
10405
10406 tree
10407 gimple_get_virt_method_for_binfo (HOST_WIDE_INT token, tree known_binfo,
10408 bool *can_refer)
10409 {
10410 unsigned HOST_WIDE_INT offset;
10411 tree v;
10412
10413 v = BINFO_VTABLE (known_binfo);
10414 /* If there is no virtual methods table, leave the OBJ_TYPE_REF alone. */
10415 if (!v)
10416 return NULL_TREE;
10417
10418 if (!vtable_pointer_value_to_vtable (v, &v, &offset))
10419 {
10420 if (can_refer)
10421 *can_refer = false;
10422 return NULL_TREE;
10423 }
10424 return gimple_get_virt_method_for_vtable (token, v, offset, can_refer);
10425 }
10426
10427 /* Given a pointer value T, return a simplified version of an
10428 indirection through T, or NULL_TREE if no simplification is
10429 possible. Note that the resulting type may be different from
10430 the type pointed to in the sense that it is still compatible
10431 from the langhooks point of view. */
10432
10433 tree
10434 gimple_fold_indirect_ref (tree t)
10435 {
10436 tree ptype = TREE_TYPE (t), type = TREE_TYPE (ptype);
10437 tree sub = t;
10438 tree subtype;
10439
10440 STRIP_NOPS (sub);
10441 subtype = TREE_TYPE (sub);
10442 if (!POINTER_TYPE_P (subtype)
10443 || TYPE_REF_CAN_ALIAS_ALL (ptype))
10444 return NULL_TREE;
10445
10446 if (TREE_CODE (sub) == ADDR_EXPR)
10447 {
10448 tree op = TREE_OPERAND (sub, 0);
10449 tree optype = TREE_TYPE (op);
10450 /* *&p => p */
10451 if (useless_type_conversion_p (type, optype))
10452 return op;
10453
10454 /* *(foo *)&fooarray => fooarray[0] */
10455 if (TREE_CODE (optype) == ARRAY_TYPE
10456 && TREE_CODE (TYPE_SIZE (TREE_TYPE (optype))) == INTEGER_CST
10457 && useless_type_conversion_p (type, TREE_TYPE (optype)))
10458 {
10459 tree type_domain = TYPE_DOMAIN (optype);
10460 tree min_val = size_zero_node;
10461 if (type_domain && TYPE_MIN_VALUE (type_domain))
10462 min_val = TYPE_MIN_VALUE (type_domain);
10463 if (TREE_CODE (min_val) == INTEGER_CST)
10464 return build4 (ARRAY_REF, type, op, min_val, NULL_TREE, NULL_TREE);
10465 }
10466 /* *(foo *)&complexfoo => __real__ complexfoo */
10467 else if (TREE_CODE (optype) == COMPLEX_TYPE
10468 && useless_type_conversion_p (type, TREE_TYPE (optype)))
10469 return fold_build1 (REALPART_EXPR, type, op);
10470 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
10471 else if (TREE_CODE (optype) == VECTOR_TYPE
10472 && useless_type_conversion_p (type, TREE_TYPE (optype)))
10473 {
10474 tree part_width = TYPE_SIZE (type);
10475 tree index = bitsize_int (0);
10476 return fold_build3 (BIT_FIELD_REF, type, op, part_width, index);
10477 }
10478 }
10479
10480 /* *(p + CST) -> ... */
10481 if (TREE_CODE (sub) == POINTER_PLUS_EXPR
10482 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
10483 {
10484 tree addr = TREE_OPERAND (sub, 0);
10485 tree off = TREE_OPERAND (sub, 1);
10486 tree addrtype;
10487
10488 STRIP_NOPS (addr);
10489 addrtype = TREE_TYPE (addr);
10490
10491 /* ((foo*)&vectorfoo)[1] -> BIT_FIELD_REF<vectorfoo,...> */
10492 if (TREE_CODE (addr) == ADDR_EXPR
10493 && TREE_CODE (TREE_TYPE (addrtype)) == VECTOR_TYPE
10494 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype)))
10495 && tree_fits_uhwi_p (off))
10496 {
10497 unsigned HOST_WIDE_INT offset = tree_to_uhwi (off);
10498 tree part_width = TYPE_SIZE (type);
10499 unsigned HOST_WIDE_INT part_widthi
10500 = tree_to_shwi (part_width) / BITS_PER_UNIT;
10501 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
10502 tree index = bitsize_int (indexi);
10503 if (known_lt (offset / part_widthi,
10504 TYPE_VECTOR_SUBPARTS (TREE_TYPE (addrtype))))
10505 return fold_build3 (BIT_FIELD_REF, type, TREE_OPERAND (addr, 0),
10506 part_width, index);
10507 }
10508
10509 /* ((foo*)&complexfoo)[1] -> __imag__ complexfoo */
10510 if (TREE_CODE (addr) == ADDR_EXPR
10511 && TREE_CODE (TREE_TYPE (addrtype)) == COMPLEX_TYPE
10512 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (addrtype))))
10513 {
10514 tree size = TYPE_SIZE_UNIT (type);
10515 if (tree_int_cst_equal (size, off))
10516 return fold_build1 (IMAGPART_EXPR, type, TREE_OPERAND (addr, 0));
10517 }
10518
10519 /* *(p + CST) -> MEM_REF <p, CST>. */
10520 if (TREE_CODE (addr) != ADDR_EXPR
10521 || DECL_P (TREE_OPERAND (addr, 0)))
10522 return fold_build2 (MEM_REF, type,
10523 addr,
10524 wide_int_to_tree (ptype, wi::to_wide (off)));
10525 }
10526
10527 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
10528 if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
10529 && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (subtype)))) == INTEGER_CST
10530 && useless_type_conversion_p (type, TREE_TYPE (TREE_TYPE (subtype))))
10531 {
10532 tree type_domain;
10533 tree min_val = size_zero_node;
10534 tree osub = sub;
10535 sub = gimple_fold_indirect_ref (sub);
10536 if (! sub)
10537 sub = build1 (INDIRECT_REF, TREE_TYPE (subtype), osub);
10538 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
10539 if (type_domain && TYPE_MIN_VALUE (type_domain))
10540 min_val = TYPE_MIN_VALUE (type_domain);
10541 if (TREE_CODE (min_val) == INTEGER_CST)
10542 return build4 (ARRAY_REF, type, sub, min_val, NULL_TREE, NULL_TREE);
10543 }
10544
10545 return NULL_TREE;
10546 }
10547
10548 /* Return true if CODE is an operation that when operating on signed
10549 integer types involves undefined behavior on overflow and the
10550 operation can be expressed with unsigned arithmetic. */
10551
10552 bool
10553 arith_code_with_undefined_signed_overflow (tree_code code)
10554 {
10555 switch (code)
10556 {
10557 case ABS_EXPR:
10558 case PLUS_EXPR:
10559 case MINUS_EXPR:
10560 case MULT_EXPR:
10561 case NEGATE_EXPR:
10562 case POINTER_PLUS_EXPR:
10563 return true;
10564 default:
10565 return false;
10566 }
10567 }
10568
10569 /* Rewrite STMT, an assignment with a signed integer or pointer arithmetic
10570 operation that can be transformed to unsigned arithmetic by converting
10571 its operand, carrying out the operation in the corresponding unsigned
10572 type and converting the result back to the original type.
10573
10574 If IN_PLACE is true, *GSI points to STMT, adjust the stmt in place and
10575 return NULL.
10576 Otherwise returns a sequence of statements that replace STMT and also
10577 contain a modified form of STMT itself. */
10578
10579 static gimple_seq
10580 rewrite_to_defined_overflow (gimple_stmt_iterator *gsi, gimple *stmt,
10581 bool in_place)
10582 {
10583 if (dump_file && (dump_flags & TDF_DETAILS))
10584 {
10585 fprintf (dump_file, "rewriting stmt with undefined signed "
10586 "overflow ");
10587 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
10588 }
10589
10590 tree lhs = gimple_assign_lhs (stmt);
10591 tree type = unsigned_type_for (TREE_TYPE (lhs));
10592 gimple_seq stmts = NULL;
10593 if (gimple_assign_rhs_code (stmt) == ABS_EXPR)
10594 gimple_assign_set_rhs_code (stmt, ABSU_EXPR);
10595 else
10596 for (unsigned i = 1; i < gimple_num_ops (stmt); ++i)
10597 {
10598 tree op = gimple_op (stmt, i);
10599 op = gimple_convert (&stmts, type, op);
10600 gimple_set_op (stmt, i, op);
10601 }
10602 gimple_assign_set_lhs (stmt, make_ssa_name (type, stmt));
10603 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
10604 gimple_assign_set_rhs_code (stmt, PLUS_EXPR);
10605 gimple_set_modified (stmt, true);
10606 if (in_place)
10607 {
10608 if (stmts)
10609 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
10610 stmts = NULL;
10611 }
10612 else
10613 gimple_seq_add_stmt (&stmts, stmt);
10614 gimple *cvt = gimple_build_assign (lhs, NOP_EXPR, gimple_assign_lhs (stmt));
10615 if (in_place)
10616 {
10617 gsi_insert_after (gsi, cvt, GSI_SAME_STMT);
10618 update_stmt (stmt);
10619 }
10620 else
10621 gimple_seq_add_stmt (&stmts, cvt);
10622
10623 return stmts;
10624 }
10625
10626 void
10627 rewrite_to_defined_overflow (gimple_stmt_iterator *gsi)
10628 {
10629 rewrite_to_defined_overflow (gsi, gsi_stmt (*gsi), true);
10630 }
10631
10632 gimple_seq
10633 rewrite_to_defined_overflow (gimple *stmt)
10634 {
10635 return rewrite_to_defined_overflow (nullptr, stmt, false);
10636 }
10637
10638 /* The valueization hook we use for the gimple_build API simplification.
10639 This makes us match fold_buildN behavior by only combining with
10640 statements in the sequence(s) we are currently building. */
10641
10642 static tree
10643 gimple_build_valueize (tree op)
10644 {
10645 if (gimple_bb (SSA_NAME_DEF_STMT (op)) == NULL)
10646 return op;
10647 return NULL_TREE;
10648 }
10649
10650 /* Helper for gimple_build to perform the final insertion of stmts on SEQ. */
10651
10652 static inline void
10653 gimple_build_insert_seq (gimple_stmt_iterator *gsi,
10654 bool before, gsi_iterator_update update,
10655 gimple_seq seq)
10656 {
10657 if (before)
10658 {
10659 if (gsi->bb)
10660 gsi_insert_seq_before (gsi, seq, update);
10661 else
10662 gsi_insert_seq_before_without_update (gsi, seq, update);
10663 }
10664 else
10665 {
10666 if (gsi->bb)
10667 gsi_insert_seq_after (gsi, seq, update);
10668 else
10669 gsi_insert_seq_after_without_update (gsi, seq, update);
10670 }
10671 }
10672
10673 /* Build the expression CODE OP0 of type TYPE with location LOC,
10674 simplifying it first if possible. Returns the built
10675 expression value and inserts statements possibly defining it
10676 before GSI if BEFORE is true or after GSI if false and advance
10677 the iterator accordingly.
10678 If gsi refers to a basic block simplifying is allowed to look
10679 at all SSA defs while when it does not it is restricted to
10680 SSA defs that are not associated with a basic block yet,
10681 indicating they belong to the currently building sequence. */
10682
10683 tree
10684 gimple_build (gimple_stmt_iterator *gsi,
10685 bool before, gsi_iterator_update update,
10686 location_t loc, enum tree_code code, tree type, tree op0)
10687 {
10688 gimple_seq seq = NULL;
10689 tree res
10690 = gimple_simplify (code, type, op0, &seq,
10691 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
10692 if (!res)
10693 {
10694 res = create_tmp_reg_or_ssa_name (type);
10695 gimple *stmt;
10696 if (code == REALPART_EXPR
10697 || code == IMAGPART_EXPR
10698 || code == VIEW_CONVERT_EXPR)
10699 stmt = gimple_build_assign (res, code, build1 (code, type, op0));
10700 else
10701 stmt = gimple_build_assign (res, code, op0);
10702 gimple_set_location (stmt, loc);
10703 gimple_seq_add_stmt_without_update (&seq, stmt);
10704 }
10705 gimple_build_insert_seq (gsi, before, update, seq);
10706 return res;
10707 }
10708
10709 /* Build the expression OP0 CODE OP1 of type TYPE with location LOC,
10710 simplifying it first if possible. Returns the built
10711 expression value inserting any new statements at GSI honoring BEFORE
10712 and UPDATE. */
10713
10714 tree
10715 gimple_build (gimple_stmt_iterator *gsi,
10716 bool before, gsi_iterator_update update,
10717 location_t loc, enum tree_code code, tree type,
10718 tree op0, tree op1)
10719 {
10720 gimple_seq seq = NULL;
10721 tree res
10722 = gimple_simplify (code, type, op0, op1, &seq,
10723 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
10724 if (!res)
10725 {
10726 res = create_tmp_reg_or_ssa_name (type);
10727 gimple *stmt = gimple_build_assign (res, code, op0, op1);
10728 gimple_set_location (stmt, loc);
10729 gimple_seq_add_stmt_without_update (&seq, stmt);
10730 }
10731 gimple_build_insert_seq (gsi, before, update, seq);
10732 return res;
10733 }
10734
10735 /* Build the expression (CODE OP0 OP1 OP2) of type TYPE with location LOC,
10736 simplifying it first if possible. Returns the built
10737 expression value inserting any new statements at GSI honoring BEFORE
10738 and UPDATE. */
10739
10740 tree
10741 gimple_build (gimple_stmt_iterator *gsi,
10742 bool before, gsi_iterator_update update,
10743 location_t loc, enum tree_code code, tree type,
10744 tree op0, tree op1, tree op2)
10745 {
10746
10747 gimple_seq seq = NULL;
10748 tree res
10749 = gimple_simplify (code, type, op0, op1, op2, &seq,
10750 gsi->bb ? follow_all_ssa_edges : gimple_build_valueize);
10751 if (!res)
10752 {
10753 res = create_tmp_reg_or_ssa_name (type);
10754 gimple *stmt;
10755 if (code == BIT_FIELD_REF)
10756 stmt = gimple_build_assign (res, code,
10757 build3 (code, type, op0, op1, op2));
10758 else
10759 stmt = gimple_build_assign (res, code, op0, op1, op2);
10760 gimple_set_location (stmt, loc);
10761 gimple_seq_add_stmt_without_update (&seq, stmt);
10762 }
10763 gimple_build_insert_seq (gsi, before, update, seq);
10764 return res;
10765 }
10766
10767 /* Build the call FN () with a result of type TYPE (or no result if TYPE is
10768 void) with a location LOC. Returns the built expression value (or NULL_TREE
10769 if TYPE is void) inserting any new statements at GSI honoring BEFORE
10770 and UPDATE. */
10771
10772 tree
10773 gimple_build (gimple_stmt_iterator *gsi,
10774 bool before, gsi_iterator_update update,
10775 location_t loc, combined_fn fn, tree type)
10776 {
10777 tree res = NULL_TREE;
10778 gimple_seq seq = NULL;
10779 gcall *stmt;
10780 if (internal_fn_p (fn))
10781 stmt = gimple_build_call_internal (as_internal_fn (fn), 0);
10782 else
10783 {
10784 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
10785 stmt = gimple_build_call (decl, 0);
10786 }
10787 if (!VOID_TYPE_P (type))
10788 {
10789 res = create_tmp_reg_or_ssa_name (type);
10790 gimple_call_set_lhs (stmt, res);
10791 }
10792 gimple_set_location (stmt, loc);
10793 gimple_seq_add_stmt_without_update (&seq, stmt);
10794 gimple_build_insert_seq (gsi, before, update, seq);
10795 return res;
10796 }
10797
10798 /* Build the call FN (ARG0) with a result of type TYPE
10799 (or no result if TYPE is void) with location LOC,
10800 simplifying it first if possible. Returns the built
10801 expression value (or NULL_TREE if TYPE is void) inserting any new
10802 statements at GSI honoring BEFORE and UPDATE. */
10803
10804 tree
10805 gimple_build (gimple_stmt_iterator *gsi,
10806 bool before, gsi_iterator_update update,
10807 location_t loc, combined_fn fn,
10808 tree type, tree arg0)
10809 {
10810 gimple_seq seq = NULL;
10811 tree res = gimple_simplify (fn, type, arg0, &seq, gimple_build_valueize);
10812 if (!res)
10813 {
10814 gcall *stmt;
10815 if (internal_fn_p (fn))
10816 stmt = gimple_build_call_internal (as_internal_fn (fn), 1, arg0);
10817 else
10818 {
10819 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
10820 stmt = gimple_build_call (decl, 1, arg0);
10821 }
10822 if (!VOID_TYPE_P (type))
10823 {
10824 res = create_tmp_reg_or_ssa_name (type);
10825 gimple_call_set_lhs (stmt, res);
10826 }
10827 gimple_set_location (stmt, loc);
10828 gimple_seq_add_stmt_without_update (&seq, stmt);
10829 }
10830 gimple_build_insert_seq (gsi, before, update, seq);
10831 return res;
10832 }
10833
10834 /* Build the call FN (ARG0, ARG1) with a result of type TYPE
10835 (or no result if TYPE is void) with location LOC,
10836 simplifying it first if possible. Returns the built
10837 expression value (or NULL_TREE if TYPE is void) inserting any new
10838 statements at GSI honoring BEFORE and UPDATE. */
10839
10840 tree
10841 gimple_build (gimple_stmt_iterator *gsi,
10842 bool before, gsi_iterator_update update,
10843 location_t loc, combined_fn fn,
10844 tree type, tree arg0, tree arg1)
10845 {
10846 gimple_seq seq = NULL;
10847 tree res = gimple_simplify (fn, type, arg0, arg1, &seq,
10848 gimple_build_valueize);
10849 if (!res)
10850 {
10851 gcall *stmt;
10852 if (internal_fn_p (fn))
10853 stmt = gimple_build_call_internal (as_internal_fn (fn), 2, arg0, arg1);
10854 else
10855 {
10856 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
10857 stmt = gimple_build_call (decl, 2, arg0, arg1);
10858 }
10859 if (!VOID_TYPE_P (type))
10860 {
10861 res = create_tmp_reg_or_ssa_name (type);
10862 gimple_call_set_lhs (stmt, res);
10863 }
10864 gimple_set_location (stmt, loc);
10865 gimple_seq_add_stmt_without_update (&seq, stmt);
10866 }
10867 gimple_build_insert_seq (gsi, before, update, seq);
10868 return res;
10869 }
10870
10871 /* Build the call FN (ARG0, ARG1, ARG2) with a result of type TYPE
10872 (or no result if TYPE is void) with location LOC,
10873 simplifying it first if possible. Returns the built
10874 expression value (or NULL_TREE if TYPE is void) inserting any new
10875 statements at GSI honoring BEFORE and UPDATE. */
10876
10877 tree
10878 gimple_build (gimple_stmt_iterator *gsi,
10879 bool before, gsi_iterator_update update,
10880 location_t loc, combined_fn fn,
10881 tree type, tree arg0, tree arg1, tree arg2)
10882 {
10883 gimple_seq seq = NULL;
10884 tree res = gimple_simplify (fn, type, arg0, arg1, arg2,
10885 &seq, gimple_build_valueize);
10886 if (!res)
10887 {
10888 gcall *stmt;
10889 if (internal_fn_p (fn))
10890 stmt = gimple_build_call_internal (as_internal_fn (fn),
10891 3, arg0, arg1, arg2);
10892 else
10893 {
10894 tree decl = builtin_decl_implicit (as_builtin_fn (fn));
10895 stmt = gimple_build_call (decl, 3, arg0, arg1, arg2);
10896 }
10897 if (!VOID_TYPE_P (type))
10898 {
10899 res = create_tmp_reg_or_ssa_name (type);
10900 gimple_call_set_lhs (stmt, res);
10901 }
10902 gimple_set_location (stmt, loc);
10903 gimple_seq_add_stmt_without_update (&seq, stmt);
10904 }
10905 gimple_build_insert_seq (gsi, before, update, seq);
10906 return res;
10907 }
10908
10909 /* Build CODE (OP0) with a result of type TYPE (or no result if TYPE is
10910 void) with location LOC, simplifying it first if possible. Returns the
10911 built expression value (or NULL_TREE if TYPE is void) inserting any new
10912 statements at GSI honoring BEFORE and UPDATE. */
10913
10914 tree
10915 gimple_build (gimple_stmt_iterator *gsi,
10916 bool before, gsi_iterator_update update,
10917 location_t loc, code_helper code, tree type, tree op0)
10918 {
10919 if (code.is_tree_code ())
10920 return gimple_build (gsi, before, update, loc, tree_code (code), type, op0);
10921 return gimple_build (gsi, before, update, loc, combined_fn (code), type, op0);
10922 }
10923
10924 /* Build CODE (OP0, OP1) with a result of type TYPE (or no result if TYPE is
10925 void) with location LOC, simplifying it first if possible. Returns the
10926 built expression value (or NULL_TREE if TYPE is void) inserting any new
10927 statements at GSI honoring BEFORE and UPDATE. */
10928
10929 tree
10930 gimple_build (gimple_stmt_iterator *gsi,
10931 bool before, gsi_iterator_update update,
10932 location_t loc, code_helper code, tree type, tree op0, tree op1)
10933 {
10934 if (code.is_tree_code ())
10935 return gimple_build (gsi, before, update,
10936 loc, tree_code (code), type, op0, op1);
10937 return gimple_build (gsi, before, update,
10938 loc, combined_fn (code), type, op0, op1);
10939 }
10940
10941 /* Build CODE (OP0, OP1, OP2) with a result of type TYPE (or no result if TYPE
10942 is void) with location LOC, simplifying it first if possible. Returns the
10943 built expression value (or NULL_TREE if TYPE is void) inserting any new
10944 statements at GSI honoring BEFORE and UPDATE. */
10945
10946 tree
10947 gimple_build (gimple_stmt_iterator *gsi,
10948 bool before, gsi_iterator_update update,
10949 location_t loc, code_helper code,
10950 tree type, tree op0, tree op1, tree op2)
10951 {
10952 if (code.is_tree_code ())
10953 return gimple_build (gsi, before, update,
10954 loc, tree_code (code), type, op0, op1, op2);
10955 return gimple_build (gsi, before, update,
10956 loc, combined_fn (code), type, op0, op1, op2);
10957 }
10958
10959 /* Build the conversion (TYPE) OP with a result of type TYPE
10960 with location LOC if such conversion is neccesary in GIMPLE,
10961 simplifying it first.
10962 Returns the built expression inserting any new statements
10963 at GSI honoring BEFORE and UPDATE. */
10964
10965 tree
10966 gimple_convert (gimple_stmt_iterator *gsi,
10967 bool before, gsi_iterator_update update,
10968 location_t loc, tree type, tree op)
10969 {
10970 if (useless_type_conversion_p (type, TREE_TYPE (op)))
10971 return op;
10972 return gimple_build (gsi, before, update, loc, NOP_EXPR, type, op);
10973 }
10974
10975 /* Build the conversion (ptrofftype) OP with a result of a type
10976 compatible with ptrofftype with location LOC if such conversion
10977 is neccesary in GIMPLE, simplifying it first.
10978 Returns the built expression value inserting any new statements
10979 at GSI honoring BEFORE and UPDATE. */
10980
10981 tree
10982 gimple_convert_to_ptrofftype (gimple_stmt_iterator *gsi,
10983 bool before, gsi_iterator_update update,
10984 location_t loc, tree op)
10985 {
10986 if (ptrofftype_p (TREE_TYPE (op)))
10987 return op;
10988 return gimple_convert (gsi, before, update, loc, sizetype, op);
10989 }
10990
10991 /* Build a vector of type TYPE in which each element has the value OP.
10992 Return a gimple value for the result, inserting any new statements
10993 at GSI honoring BEFORE and UPDATE. */
10994
10995 tree
10996 gimple_build_vector_from_val (gimple_stmt_iterator *gsi,
10997 bool before, gsi_iterator_update update,
10998 location_t loc, tree type, tree op)
10999 {
11000 if (!TYPE_VECTOR_SUBPARTS (type).is_constant ()
11001 && !CONSTANT_CLASS_P (op))
11002 return gimple_build (gsi, before, update,
11003 loc, VEC_DUPLICATE_EXPR, type, op);
11004
11005 tree res, vec = build_vector_from_val (type, op);
11006 if (is_gimple_val (vec))
11007 return vec;
11008 if (gimple_in_ssa_p (cfun))
11009 res = make_ssa_name (type);
11010 else
11011 res = create_tmp_reg (type);
11012 gimple_seq seq = NULL;
11013 gimple *stmt = gimple_build_assign (res, vec);
11014 gimple_set_location (stmt, loc);
11015 gimple_seq_add_stmt_without_update (&seq, stmt);
11016 gimple_build_insert_seq (gsi, before, update, seq);
11017 return res;
11018 }
11019
11020 /* Build a vector from BUILDER, handling the case in which some elements
11021 are non-constant. Return a gimple value for the result, inserting
11022 any new instructions to GSI honoring BEFORE and UPDATE.
11023
11024 BUILDER must not have a stepped encoding on entry. This is because
11025 the function is not geared up to handle the arithmetic that would
11026 be needed in the variable case, and any code building a vector that
11027 is known to be constant should use BUILDER->build () directly. */
11028
11029 tree
11030 gimple_build_vector (gimple_stmt_iterator *gsi,
11031 bool before, gsi_iterator_update update,
11032 location_t loc, tree_vector_builder *builder)
11033 {
11034 gcc_assert (builder->nelts_per_pattern () <= 2);
11035 unsigned int encoded_nelts = builder->encoded_nelts ();
11036 for (unsigned int i = 0; i < encoded_nelts; ++i)
11037 if (!CONSTANT_CLASS_P ((*builder)[i]))
11038 {
11039 gimple_seq seq = NULL;
11040 tree type = builder->type ();
11041 unsigned int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
11042 vec<constructor_elt, va_gc> *v;
11043 vec_alloc (v, nelts);
11044 for (i = 0; i < nelts; ++i)
11045 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, builder->elt (i));
11046
11047 tree res;
11048 if (gimple_in_ssa_p (cfun))
11049 res = make_ssa_name (type);
11050 else
11051 res = create_tmp_reg (type);
11052 gimple *stmt = gimple_build_assign (res, build_constructor (type, v));
11053 gimple_set_location (stmt, loc);
11054 gimple_seq_add_stmt_without_update (&seq, stmt);
11055 gimple_build_insert_seq (gsi, before, update, seq);
11056 return res;
11057 }
11058 return builder->build ();
11059 }
11060
11061 /* Emit gimple statements into &stmts that take a value given in OLD_SIZE
11062 and generate a value guaranteed to be rounded upwards to ALIGN.
11063
11064 Return the tree node representing this size, it is of TREE_TYPE TYPE. */
11065
11066 tree
11067 gimple_build_round_up (gimple_stmt_iterator *gsi,
11068 bool before, gsi_iterator_update update,
11069 location_t loc, tree type,
11070 tree old_size, unsigned HOST_WIDE_INT align)
11071 {
11072 unsigned HOST_WIDE_INT tg_mask = align - 1;
11073 /* tree new_size = (old_size + tg_mask) & ~tg_mask; */
11074 gcc_assert (INTEGRAL_TYPE_P (type));
11075 tree tree_mask = build_int_cst (type, tg_mask);
11076 tree oversize = gimple_build (gsi, before, update,
11077 loc, PLUS_EXPR, type, old_size, tree_mask);
11078
11079 tree mask = build_int_cst (type, -align);
11080 return gimple_build (gsi, before, update,
11081 loc, BIT_AND_EXPR, type, oversize, mask);
11082 }
11083
11084 /* Return true if the result of assignment STMT is known to be non-negative.
11085 If the return value is based on the assumption that signed overflow is
11086 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
11087 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
11088
11089 static bool
11090 gimple_assign_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
11091 int depth)
11092 {
11093 enum tree_code code = gimple_assign_rhs_code (stmt);
11094 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
11095 switch (get_gimple_rhs_class (code))
11096 {
11097 case GIMPLE_UNARY_RHS:
11098 return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
11099 type,
11100 gimple_assign_rhs1 (stmt),
11101 strict_overflow_p, depth);
11102 case GIMPLE_BINARY_RHS:
11103 return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
11104 type,
11105 gimple_assign_rhs1 (stmt),
11106 gimple_assign_rhs2 (stmt),
11107 strict_overflow_p, depth);
11108 case GIMPLE_TERNARY_RHS:
11109 return false;
11110 case GIMPLE_SINGLE_RHS:
11111 return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
11112 strict_overflow_p, depth);
11113 case GIMPLE_INVALID_RHS:
11114 break;
11115 }
11116 gcc_unreachable ();
11117 }
11118
11119 /* Return true if return value of call STMT is known to be non-negative.
11120 If the return value is based on the assumption that signed overflow is
11121 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
11122 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
11123
11124 static bool
11125 gimple_call_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
11126 int depth)
11127 {
11128 tree arg0
11129 = gimple_call_num_args (stmt) > 0 ? gimple_call_arg (stmt, 0) : NULL_TREE;
11130 tree arg1
11131 = gimple_call_num_args (stmt) > 1 ? gimple_call_arg (stmt, 1) : NULL_TREE;
11132 tree lhs = gimple_call_lhs (stmt);
11133 return (lhs
11134 && tree_call_nonnegative_warnv_p (TREE_TYPE (lhs),
11135 gimple_call_combined_fn (stmt),
11136 arg0, arg1,
11137 strict_overflow_p, depth));
11138 }
11139
11140 /* Return true if return value of call STMT is known to be non-negative.
11141 If the return value is based on the assumption that signed overflow is
11142 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
11143 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
11144
11145 static bool
11146 gimple_phi_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
11147 int depth)
11148 {
11149 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
11150 {
11151 tree arg = gimple_phi_arg_def (stmt, i);
11152 if (!tree_single_nonnegative_warnv_p (arg, strict_overflow_p, depth + 1))
11153 return false;
11154 }
11155 return true;
11156 }
11157
11158 /* Return true if STMT is known to compute a non-negative value.
11159 If the return value is based on the assumption that signed overflow is
11160 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
11161 *STRICT_OVERFLOW_P. DEPTH is the current nesting depth of the query. */
11162
11163 bool
11164 gimple_stmt_nonnegative_warnv_p (gimple *stmt, bool *strict_overflow_p,
11165 int depth)
11166 {
11167 tree type = gimple_range_type (stmt);
11168 if (type && frange::supports_p (type))
11169 {
11170 frange r;
11171 bool sign;
11172 if (get_global_range_query ()->range_of_stmt (r, stmt)
11173 && r.signbit_p (sign))
11174 return !sign;
11175 }
11176 switch (gimple_code (stmt))
11177 {
11178 case GIMPLE_ASSIGN:
11179 return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p,
11180 depth);
11181 case GIMPLE_CALL:
11182 return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p,
11183 depth);
11184 case GIMPLE_PHI:
11185 return gimple_phi_nonnegative_warnv_p (stmt, strict_overflow_p,
11186 depth);
11187 default:
11188 return false;
11189 }
11190 }
11191
11192 /* Return true if the floating-point value computed by assignment STMT
11193 is known to have an integer value. We also allow +Inf, -Inf and NaN
11194 to be considered integer values. Return false for signaling NaN.
11195
11196 DEPTH is the current nesting depth of the query. */
11197
11198 static bool
11199 gimple_assign_integer_valued_real_p (gimple *stmt, int depth)
11200 {
11201 enum tree_code code = gimple_assign_rhs_code (stmt);
11202 switch (get_gimple_rhs_class (code))
11203 {
11204 case GIMPLE_UNARY_RHS:
11205 return integer_valued_real_unary_p (gimple_assign_rhs_code (stmt),
11206 gimple_assign_rhs1 (stmt), depth);
11207 case GIMPLE_BINARY_RHS:
11208 return integer_valued_real_binary_p (gimple_assign_rhs_code (stmt),
11209 gimple_assign_rhs1 (stmt),
11210 gimple_assign_rhs2 (stmt), depth);
11211 case GIMPLE_TERNARY_RHS:
11212 return false;
11213 case GIMPLE_SINGLE_RHS:
11214 return integer_valued_real_single_p (gimple_assign_rhs1 (stmt), depth);
11215 case GIMPLE_INVALID_RHS:
11216 break;
11217 }
11218 gcc_unreachable ();
11219 }
11220
11221 /* Return true if the floating-point value computed by call STMT is known
11222 to have an integer value. We also allow +Inf, -Inf and NaN to be
11223 considered integer values. Return false for signaling NaN.
11224
11225 DEPTH is the current nesting depth of the query. */
11226
11227 static bool
11228 gimple_call_integer_valued_real_p (gimple *stmt, int depth)
11229 {
11230 tree arg0 = (gimple_call_num_args (stmt) > 0
11231 ? gimple_call_arg (stmt, 0)
11232 : NULL_TREE);
11233 tree arg1 = (gimple_call_num_args (stmt) > 1
11234 ? gimple_call_arg (stmt, 1)
11235 : NULL_TREE);
11236 return integer_valued_real_call_p (gimple_call_combined_fn (stmt),
11237 arg0, arg1, depth);
11238 }
11239
11240 /* Return true if the floating-point result of phi STMT is known to have
11241 an integer value. We also allow +Inf, -Inf and NaN to be considered
11242 integer values. Return false for signaling NaN.
11243
11244 DEPTH is the current nesting depth of the query. */
11245
11246 static bool
11247 gimple_phi_integer_valued_real_p (gimple *stmt, int depth)
11248 {
11249 for (unsigned i = 0; i < gimple_phi_num_args (stmt); ++i)
11250 {
11251 tree arg = gimple_phi_arg_def (stmt, i);
11252 if (!integer_valued_real_single_p (arg, depth + 1))
11253 return false;
11254 }
11255 return true;
11256 }
11257
11258 /* Return true if the floating-point value computed by STMT is known
11259 to have an integer value. We also allow +Inf, -Inf and NaN to be
11260 considered integer values. Return false for signaling NaN.
11261
11262 DEPTH is the current nesting depth of the query. */
11263
11264 bool
11265 gimple_stmt_integer_valued_real_p (gimple *stmt, int depth)
11266 {
11267 switch (gimple_code (stmt))
11268 {
11269 case GIMPLE_ASSIGN:
11270 return gimple_assign_integer_valued_real_p (stmt, depth);
11271 case GIMPLE_CALL:
11272 return gimple_call_integer_valued_real_p (stmt, depth);
11273 case GIMPLE_PHI:
11274 return gimple_phi_integer_valued_real_p (stmt, depth);
11275 default:
11276 return false;
11277 }
11278 }