c++: 'this' adjustment for devirtualized call
[official-gcc.git] / gcc / tree-ssa-uninit.c
blobdcfdec96881889f0e2e48bc6505826c702f7007d
1 /* Predicate aware uninitialized variable warning.
2 Copyright (C) 2001-2021 Free Software Foundation, Inc.
3 Contributed by Xinliang David Li <davidxl@google.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #define INCLUDE_STRING
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "gimple-pretty-print.h"
31 #include "diagnostic-core.h"
32 #include "fold-const.h"
33 #include "gimple-iterator.h"
34 #include "tree-ssa.h"
35 #include "tree-cfg.h"
36 #include "cfghooks.h"
37 #include "attribs.h"
38 #include "builtins.h"
39 #include "calls.h"
40 #include "gimple-range.h"
42 /* This implements the pass that does predicate aware warning on uses of
43 possibly uninitialized variables. The pass first collects the set of
44 possibly uninitialized SSA names. For each such name, it walks through
45 all its immediate uses. For each immediate use, it rebuilds the condition
46 expression (the predicate) that guards the use. The predicate is then
47 examined to see if the variable is always defined under that same condition.
48 This is done either by pruning the unrealizable paths that lead to the
49 default definitions or by checking if the predicate set that guards the
50 defining paths is a superset of the use predicate. */
52 /* Max PHI args we can handle in pass. */
53 const unsigned max_phi_args = 32;
55 /* Pointer set of potentially undefined ssa names, i.e.,
56 ssa names that are defined by phi with operands that
57 are not defined or potentially undefined. */
58 static hash_set<tree> *possibly_undefined_names = 0;
60 /* Bit mask handling macros. */
61 #define MASK_SET_BIT(mask, pos) mask |= (1 << pos)
62 #define MASK_TEST_BIT(mask, pos) (mask & (1 << pos))
63 #define MASK_EMPTY(mask) (mask == 0)
65 /* Returns the first bit position (starting from LSB)
66 in mask that is non zero. Returns -1 if the mask is empty. */
67 static int
68 get_mask_first_set_bit (unsigned mask)
70 int pos = 0;
71 if (mask == 0)
72 return -1;
74 while ((mask & (1 << pos)) == 0)
75 pos++;
77 return pos;
79 #define MASK_FIRST_SET_BIT(mask) get_mask_first_set_bit (mask)
81 /* Return true if T, an SSA_NAME, has an undefined value. */
82 static bool
83 has_undefined_value_p (tree t)
85 return (ssa_undefined_value_p (t)
86 || (possibly_undefined_names
87 && possibly_undefined_names->contains (t)));
90 /* Like has_undefined_value_p, but don't return true if TREE_NO_WARNING
91 is set on SSA_NAME_VAR. */
93 static inline bool
94 uninit_undefined_value_p (tree t)
96 if (!has_undefined_value_p (t))
97 return false;
98 if (SSA_NAME_VAR (t) && TREE_NO_WARNING (SSA_NAME_VAR (t)))
99 return false;
100 return true;
103 /* Emit warnings for uninitialized variables. This is done in two passes.
105 The first pass notices real uses of SSA names with undefined values.
106 Such uses are unconditionally uninitialized, and we can be certain that
107 such a use is a mistake. This pass is run before most optimizations,
108 so that we catch as many as we can.
110 The second pass follows PHI nodes to find uses that are potentially
111 uninitialized. In this case we can't necessarily prove that the use
112 is really uninitialized. This pass is run after most optimizations,
113 so that we thread as many jumps and possible, and delete as much dead
114 code as possible, in order to reduce false positives. We also look
115 again for plain uninitialized variables, since optimization may have
116 changed conditionally uninitialized to unconditionally uninitialized. */
118 /* Emit a warning for EXPR based on variable VAR at the point in the
119 program T, an SSA_NAME, is used being uninitialized. The exact
120 warning text is in MSGID and DATA is the gimple stmt with info about
121 the location in source code. When DATA is a GIMPLE_PHI, PHIARG_IDX
122 gives which argument of the phi node to take the location from. WC
123 is the warning code. */
125 static void
126 warn_uninit (enum opt_code wc, tree t, tree expr, tree var,
127 const char *gmsgid, void *data, location_t phiarg_loc)
129 gimple *context = (gimple *) data;
130 location_t location, cfun_loc;
131 expanded_location xloc, floc;
133 /* Ignore COMPLEX_EXPR as initializing only a part of a complex
134 turns in a COMPLEX_EXPR with the not initialized part being
135 set to its previous (undefined) value. */
136 if (is_gimple_assign (context)
137 && gimple_assign_rhs_code (context) == COMPLEX_EXPR)
138 return;
139 if (!has_undefined_value_p (t))
140 return;
142 /* Anonymous SSA_NAMEs shouldn't be uninitialized, but ssa_undefined_value_p
143 can return true if the def stmt of anonymous SSA_NAME is COMPLEX_EXPR
144 created for conversion from scalar to complex. Use the underlying var of
145 the COMPLEX_EXPRs real part in that case. See PR71581. */
146 if (expr == NULL_TREE
147 && var == NULL_TREE
148 && SSA_NAME_VAR (t) == NULL_TREE
149 && is_gimple_assign (SSA_NAME_DEF_STMT (t))
150 && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (t)) == COMPLEX_EXPR)
152 tree v = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (t));
153 if (TREE_CODE (v) == SSA_NAME
154 && has_undefined_value_p (v)
155 && zerop (gimple_assign_rhs2 (SSA_NAME_DEF_STMT (t))))
157 expr = SSA_NAME_VAR (v);
158 var = expr;
162 if (expr == NULL_TREE)
163 return;
165 /* TREE_NO_WARNING either means we already warned, or the front end
166 wishes to suppress the warning. */
167 if ((context
168 && (gimple_no_warning_p (context)
169 || (gimple_assign_single_p (context)
170 && TREE_NO_WARNING (gimple_assign_rhs1 (context)))))
171 || TREE_NO_WARNING (expr))
172 return;
174 if (context != NULL && gimple_has_location (context))
175 location = gimple_location (context);
176 else if (phiarg_loc != UNKNOWN_LOCATION)
177 location = phiarg_loc;
178 else
179 location = DECL_SOURCE_LOCATION (var);
180 location = linemap_resolve_location (line_table, location,
181 LRK_SPELLING_LOCATION, NULL);
182 cfun_loc = DECL_SOURCE_LOCATION (cfun->decl);
183 xloc = expand_location (location);
184 floc = expand_location (cfun_loc);
185 auto_diagnostic_group d;
186 if (warning_at (location, wc, gmsgid, expr))
188 TREE_NO_WARNING (expr) = 1;
190 if (location == DECL_SOURCE_LOCATION (var))
191 return;
192 if (xloc.file != floc.file
193 || linemap_location_before_p (line_table, location, cfun_loc)
194 || linemap_location_before_p (line_table, cfun->function_end_locus,
195 location))
196 inform (DECL_SOURCE_LOCATION (var), "%qD was declared here", var);
200 struct check_defs_data
202 /* If we found any may-defs besides must-def clobbers. */
203 bool found_may_defs;
206 /* Callback for walk_aliased_vdefs. */
208 static bool
209 check_defs (ao_ref *ref, tree vdef, void *data_)
211 check_defs_data *data = (check_defs_data *)data_;
212 gimple *def_stmt = SSA_NAME_DEF_STMT (vdef);
214 /* The ASAN_MARK intrinsic doesn't modify the variable. */
215 if (is_gimple_call (def_stmt)
216 && gimple_call_internal_p (def_stmt, IFN_ASAN_MARK))
217 return false;
219 /* End of VLA scope is not a kill. */
220 if (gimple_call_builtin_p (def_stmt, BUILT_IN_STACK_RESTORE))
221 return false;
223 /* If this is a clobber then if it is not a kill walk past it. */
224 if (gimple_clobber_p (def_stmt))
226 if (stmt_kills_ref_p (def_stmt, ref))
227 return true;
228 return false;
231 /* Found a may-def on this path. */
232 data->found_may_defs = true;
233 return true;
236 /* Counters and limits controlling the the depth of analysis and
237 strictness of the warning. */
238 struct wlimits
240 /* Number of VDEFs encountered. */
241 unsigned int vdef_cnt;
242 /* Number of statements examined by walk_aliased_vdefs. */
243 unsigned int oracle_cnt;
244 /* Limit on the number of statements visited by walk_aliased_vdefs. */
245 unsigned limit;
246 /* Set when basic block with statement is executed unconditionally. */
247 bool always_executed;
248 /* Set to issue -Wmaybe-uninitialized. */
249 bool wmaybe_uninit;
252 /* Determine if REF references an uninitialized operand and diagnose
253 it if so. */
255 static tree
256 maybe_warn_operand (ao_ref &ref, gimple *stmt, tree lhs, tree rhs,
257 wlimits &wlims)
259 bool has_bit_insert = false;
260 use_operand_p luse_p;
261 imm_use_iterator liter;
263 if (TREE_NO_WARNING (rhs))
264 return NULL_TREE;
266 /* Do not warn if the base was marked so or this is a
267 hard register var. */
268 tree base = ao_ref_base (&ref);
269 if ((VAR_P (base)
270 && DECL_HARD_REGISTER (base))
271 || TREE_NO_WARNING (base))
272 return NULL_TREE;
274 /* Do not warn if the access is fully outside of the variable. */
275 poly_int64 decl_size;
276 if (DECL_P (base)
277 && ((known_size_p (ref.size)
278 && known_eq (ref.max_size, ref.size)
279 && known_le (ref.offset + ref.size, 0))
280 || (known_ge (ref.offset, 0)
281 && DECL_SIZE (base)
282 && poly_int_tree_p (DECL_SIZE (base), &decl_size)
283 && known_le (decl_size, ref.offset))))
284 return NULL_TREE;
286 /* Do not warn if the result of the access is then used for
287 a BIT_INSERT_EXPR. */
288 if (lhs && TREE_CODE (lhs) == SSA_NAME)
289 FOR_EACH_IMM_USE_FAST (luse_p, liter, lhs)
291 gimple *use_stmt = USE_STMT (luse_p);
292 /* BIT_INSERT_EXPR first operand should not be considered
293 a use for the purpose of uninit warnings. */
294 if (gassign *ass = dyn_cast <gassign *> (use_stmt))
296 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
297 && luse_p->use == gimple_assign_rhs1_ptr (ass))
299 has_bit_insert = true;
300 break;
305 if (has_bit_insert)
306 return NULL_TREE;
308 /* Limit the walking to a constant number of stmts after
309 we overcommit quadratic behavior for small functions
310 and O(n) behavior. */
311 if (wlims.oracle_cnt > 128 * 128
312 && wlims.oracle_cnt > wlims.vdef_cnt * 2)
313 wlims.limit = 32;
315 check_defs_data data;
316 bool fentry_reached = false;
317 data.found_may_defs = false;
318 tree use = gimple_vuse (stmt);
319 if (!use)
320 return NULL_TREE;
321 int res = walk_aliased_vdefs (&ref, use,
322 check_defs, &data, NULL,
323 &fentry_reached, wlims.limit);
324 if (res == -1)
326 wlims.oracle_cnt += wlims.limit;
327 return NULL_TREE;
330 wlims.oracle_cnt += res;
331 if (data.found_may_defs)
332 return NULL_TREE;
334 bool found_alloc = false;
336 if (fentry_reached)
338 if (TREE_CODE (base) == MEM_REF)
339 base = TREE_OPERAND (base, 0);
341 /* Follow the chain of SSA_NAME assignments looking for an alloca
342 call (or VLA) or malloc/realloc, or for decls. If any is found
343 (and in the latter case, the operand is a local variable) issue
344 a warning. */
345 while (TREE_CODE (base) == SSA_NAME)
347 gimple *def_stmt = SSA_NAME_DEF_STMT (base);
349 if (is_gimple_call (def_stmt)
350 && gimple_call_builtin_p (def_stmt))
352 /* Detect uses of uninitialized alloca/VLAs. */
353 tree fndecl = gimple_call_fndecl (def_stmt);
354 const built_in_function fncode = DECL_FUNCTION_CODE (fndecl);
355 if (fncode == BUILT_IN_ALLOCA
356 || fncode == BUILT_IN_ALLOCA_WITH_ALIGN
357 || fncode == BUILT_IN_MALLOC)
358 found_alloc = true;
359 break;
362 if (!is_gimple_assign (def_stmt))
363 break;
365 tree_code code = gimple_assign_rhs_code (def_stmt);
366 if (code != ADDR_EXPR && code != POINTER_PLUS_EXPR)
367 break;
369 base = gimple_assign_rhs1 (def_stmt);
370 if (TREE_CODE (base) == ADDR_EXPR)
371 base = TREE_OPERAND (base, 0);
373 if (DECL_P (base)
374 || TREE_CODE (base) == COMPONENT_REF)
375 rhs = base;
377 if (TREE_CODE (base) == MEM_REF)
378 base = TREE_OPERAND (base, 0);
380 if (tree ba = get_base_address (base))
381 base = ba;
384 /* Replace the RHS expression with BASE so that it
385 refers to it in the diagnostic (instead of to
386 '<unknown>'). */
387 if (DECL_P (base)
388 && EXPR_P (rhs)
389 && TREE_CODE (rhs) != COMPONENT_REF)
390 rhs = base;
393 /* Do not warn if it can be initialized outside this function.
394 If we did not reach function entry then we found killing
395 clobbers on all paths to entry. */
396 if (!found_alloc
397 && fentry_reached
398 /* ??? We'd like to use ref_may_alias_global_p but that
399 excludes global readonly memory and thus we get bogus
400 warnings from p = cond ? "a" : "b" for example. */
401 && (!VAR_P (base)
402 || is_global_var (base)))
403 return NULL_TREE;
405 /* Strip the address-of expression from arrays passed to functions. */
406 if (TREE_CODE (rhs) == ADDR_EXPR)
407 rhs = TREE_OPERAND (rhs, 0);
409 /* Check again since RHS may have changed above. */
410 if (TREE_NO_WARNING (rhs))
411 return NULL_TREE;
413 /* Avoid warning about empty types such as structs with no members.
414 The first_field() test is important for C++ where the predicate
415 alone isn't always sufficient. */
416 tree rhstype = TREE_TYPE (rhs);
417 if (POINTER_TYPE_P (rhstype))
418 rhstype = TREE_TYPE (rhstype);
419 if (is_empty_type (rhstype))
420 return NULL_TREE;
422 bool warned = false;
423 /* We didn't find any may-defs so on all paths either
424 reached function entry or a killing clobber. */
425 location_t location
426 = linemap_resolve_location (line_table, gimple_location (stmt),
427 LRK_SPELLING_LOCATION, NULL);
428 if (wlims.always_executed)
430 if (warning_at (location, OPT_Wuninitialized,
431 "%G%qE is used uninitialized", stmt, rhs))
433 /* ??? This is only effective for decls as in
434 gcc.dg/uninit-B-O0.c. Avoid doing this for maybe-uninit
435 uses or accesses by functions as it may hide important
436 locations. */
437 if (lhs)
438 TREE_NO_WARNING (rhs) = 1;
439 warned = true;
442 else if (wlims.wmaybe_uninit)
443 warned = warning_at (location, OPT_Wmaybe_uninitialized,
444 "%G%qE may be used uninitialized", stmt, rhs);
446 return warned ? base : NULL_TREE;
450 /* Diagnose passing addresses of uninitialized objects to either const
451 pointer arguments to functions, or to functions declared with attribute
452 access implying read access to those objects. */
454 static void
455 maybe_warn_pass_by_reference (gcall *stmt, wlimits &wlims)
457 if (!wlims.wmaybe_uninit)
458 return;
460 unsigned nargs = gimple_call_num_args (stmt);
461 if (!nargs)
462 return;
464 tree fndecl = gimple_call_fndecl (stmt);
465 tree fntype = gimple_call_fntype (stmt);
466 if (!fntype)
467 return;
469 /* Const function do not read their arguments. */
470 if (gimple_call_flags (stmt) & ECF_CONST)
471 return;
473 const built_in_function fncode
474 = (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
475 ? DECL_FUNCTION_CODE (fndecl) : (built_in_function)BUILT_IN_LAST);
477 if (fncode == BUILT_IN_MEMCPY || fncode == BUILT_IN_MEMMOVE)
478 /* Avoid diagnosing calls to raw memory functions (this is overly
479 permissive; consider tightening it up). */
480 return;
482 /* Save the current warning setting and replace it either a "maybe"
483 when passing addresses of uninitialized variables to const-qualified
484 pointers or arguments declared with attribute read_write, or with
485 a "certain" when passing them to arguments declared with attribute
486 read_only. */
487 const bool save_always_executed = wlims.always_executed;
489 /* Initialize a map of attribute access specifications for arguments
490 to the function function call. */
491 rdwr_map rdwr_idx;
492 init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
494 tree argtype;
495 unsigned argno = 0;
496 function_args_iterator it;
498 FOREACH_FUNCTION_ARGS (fntype, argtype, it)
500 ++argno;
502 if (!POINTER_TYPE_P (argtype))
503 continue;
505 tree access_size = NULL_TREE;
506 const attr_access* access = rdwr_idx.get (argno - 1);
507 if (access)
509 if (access->mode == access_none
510 || access->mode == access_write_only)
511 continue;
513 if (access->mode == access_deferred
514 && !TYPE_READONLY (TREE_TYPE (argtype)))
515 continue;
517 if (save_always_executed && access->mode == access_read_only)
518 /* Attribute read_only arguments imply read access. */
519 wlims.always_executed = true;
520 else
521 /* Attribute read_write arguments are documented as requiring
522 initialized objects but it's expected that aggregates may
523 be only partially initialized regardless. */
524 wlims.always_executed = false;
526 if (access->sizarg < nargs)
527 access_size = gimple_call_arg (stmt, access->sizarg);
529 else if (!TYPE_READONLY (TREE_TYPE (argtype)))
530 continue;
531 else if (save_always_executed && fncode != BUILT_IN_LAST)
532 /* Const-qualified arguments to built-ins imply read access. */
533 wlims.always_executed = true;
534 else
535 /* Const-qualified arguments to ordinary functions imply a likely
536 (but not definitive) read access. */
537 wlims.always_executed = false;
539 /* Ignore args we are not going to read from. */
540 if (gimple_call_arg_flags (stmt, argno - 1) & EAF_UNUSED)
541 continue;
543 tree arg = gimple_call_arg (stmt, argno - 1);
545 ao_ref ref;
546 ao_ref_init_from_ptr_and_size (&ref, arg, access_size);
547 tree argbase = maybe_warn_operand (ref, stmt, NULL_TREE, arg, wlims);
548 if (!argbase)
549 continue;
551 if (access && access->mode != access_deferred)
553 const char* const access_str =
554 TREE_STRING_POINTER (access->to_external_string ());
556 if (fndecl)
558 location_t loc = DECL_SOURCE_LOCATION (fndecl);
559 inform (loc, "in a call to %qD declared with "
560 "attribute %<%s%> here", fndecl, access_str);
562 else
564 /* Handle calls through function pointers. */
565 location_t loc = gimple_location (stmt);
566 inform (loc, "in a call to %qT declared with "
567 "attribute %<%s%>", fntype, access_str);
570 else
572 /* For a declaration with no relevant attribute access create
573 a dummy object and use the formatting function to avoid
574 having to complicate things here. */
575 attr_access ptr_access = { };
576 if (!access)
577 access = &ptr_access;
578 const std::string argtypestr = access->array_as_string (argtype);
579 if (fndecl)
581 location_t loc (DECL_SOURCE_LOCATION (fndecl));
582 inform (loc, "by argument %u of type %s to %qD "
583 "declared here",
584 argno, argtypestr.c_str (), fndecl);
586 else
588 /* Handle calls through function pointers. */
589 location_t loc (gimple_location (stmt));
590 inform (loc, "by argument %u of type %s to %qT",
591 argno, argtypestr.c_str (), fntype);
595 if (DECL_P (argbase))
597 location_t loc = DECL_SOURCE_LOCATION (argbase);
598 inform (loc, "%qD declared here", argbase);
602 wlims.always_executed = save_always_executed;
606 static unsigned int
607 warn_uninitialized_vars (bool wmaybe_uninit)
609 /* Counters and limits controlling the the depth of the warning. */
610 wlimits wlims = { };
611 wlims.wmaybe_uninit = wmaybe_uninit;
613 gimple_stmt_iterator gsi;
614 basic_block bb;
615 FOR_EACH_BB_FN (bb, cfun)
617 basic_block succ = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
618 wlims.always_executed = dominated_by_p (CDI_POST_DOMINATORS, succ, bb);
619 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
621 gimple *stmt = gsi_stmt (gsi);
622 use_operand_p use_p;
623 ssa_op_iter op_iter;
624 tree use;
626 if (is_gimple_debug (stmt))
627 continue;
629 /* We only do data flow with SSA_NAMEs, so that's all we
630 can warn about. */
631 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, op_iter, SSA_OP_USE)
633 /* BIT_INSERT_EXPR first operand should not be considered
634 a use for the purpose of uninit warnings. */
635 if (gassign *ass = dyn_cast <gassign *> (stmt))
637 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
638 && use_p->use == gimple_assign_rhs1_ptr (ass))
639 continue;
641 use = USE_FROM_PTR (use_p);
642 if (wlims.always_executed)
643 warn_uninit (OPT_Wuninitialized, use, SSA_NAME_VAR (use),
644 SSA_NAME_VAR (use),
645 "%qD is used uninitialized", stmt,
646 UNKNOWN_LOCATION);
647 else if (wmaybe_uninit)
648 warn_uninit (OPT_Wmaybe_uninitialized, use, SSA_NAME_VAR (use),
649 SSA_NAME_VAR (use),
650 "%qD may be used uninitialized",
651 stmt, UNKNOWN_LOCATION);
654 /* For limiting the alias walk below we count all
655 vdefs in the function. */
656 if (gimple_vdef (stmt))
657 wlims.vdef_cnt++;
659 if (gcall *call = dyn_cast <gcall *> (stmt))
660 maybe_warn_pass_by_reference (call, wlims);
661 else if (gimple_assign_load_p (stmt)
662 && gimple_has_location (stmt))
664 tree rhs = gimple_assign_rhs1 (stmt);
665 tree lhs = gimple_assign_lhs (stmt);
667 ao_ref ref;
668 ao_ref_init (&ref, rhs);
669 tree var = maybe_warn_operand (ref, stmt, lhs, rhs, wlims);
670 if (!var)
671 continue;
673 if (DECL_P (var))
675 location_t loc = DECL_SOURCE_LOCATION (var);
676 inform (loc, "%qD declared here", var);
682 return 0;
685 /* Checks if the operand OPND of PHI is defined by
686 another phi with one operand defined by this PHI,
687 but the rest operands are all defined. If yes,
688 returns true to skip this operand as being
689 redundant. Can be enhanced to be more general. */
691 static bool
692 can_skip_redundant_opnd (tree opnd, gimple *phi)
694 gimple *op_def;
695 tree phi_def;
696 int i, n;
698 phi_def = gimple_phi_result (phi);
699 op_def = SSA_NAME_DEF_STMT (opnd);
700 if (gimple_code (op_def) != GIMPLE_PHI)
701 return false;
702 n = gimple_phi_num_args (op_def);
703 for (i = 0; i < n; ++i)
705 tree op = gimple_phi_arg_def (op_def, i);
706 if (TREE_CODE (op) != SSA_NAME)
707 continue;
708 if (op != phi_def && uninit_undefined_value_p (op))
709 return false;
712 return true;
715 /* Returns a bit mask holding the positions of arguments in PHI
716 that have empty (or possibly empty) definitions. */
718 static unsigned
719 compute_uninit_opnds_pos (gphi *phi)
721 size_t i, n;
722 unsigned uninit_opnds = 0;
724 n = gimple_phi_num_args (phi);
725 /* Bail out for phi with too many args. */
726 if (n > max_phi_args)
727 return 0;
729 for (i = 0; i < n; ++i)
731 tree op = gimple_phi_arg_def (phi, i);
732 if (TREE_CODE (op) == SSA_NAME
733 && uninit_undefined_value_p (op)
734 && !can_skip_redundant_opnd (op, phi))
736 if (cfun->has_nonlocal_label || cfun->calls_setjmp)
738 /* Ignore SSA_NAMEs that appear on abnormal edges
739 somewhere. */
740 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
741 continue;
743 MASK_SET_BIT (uninit_opnds, i);
746 return uninit_opnds;
749 /* Find the immediate postdominator PDOM of the specified
750 basic block BLOCK. */
752 static inline basic_block
753 find_pdom (basic_block block)
755 if (block == EXIT_BLOCK_PTR_FOR_FN (cfun))
756 return EXIT_BLOCK_PTR_FOR_FN (cfun);
757 else
759 basic_block bb = get_immediate_dominator (CDI_POST_DOMINATORS, block);
760 if (!bb)
761 return EXIT_BLOCK_PTR_FOR_FN (cfun);
762 return bb;
766 /* Find the immediate DOM of the specified basic block BLOCK. */
768 static inline basic_block
769 find_dom (basic_block block)
771 if (block == ENTRY_BLOCK_PTR_FOR_FN (cfun))
772 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
773 else
775 basic_block bb = get_immediate_dominator (CDI_DOMINATORS, block);
776 if (!bb)
777 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
778 return bb;
782 /* Returns true if BB1 is postdominating BB2 and BB1 is
783 not a loop exit bb. The loop exit bb check is simple and does
784 not cover all cases. */
786 static bool
787 is_non_loop_exit_postdominating (basic_block bb1, basic_block bb2)
789 if (!dominated_by_p (CDI_POST_DOMINATORS, bb2, bb1))
790 return false;
792 if (single_pred_p (bb1) && !single_succ_p (bb2))
793 return false;
795 return true;
798 /* Find the closest postdominator of a specified BB, which is control
799 equivalent to BB. */
801 static inline basic_block
802 find_control_equiv_block (basic_block bb)
804 basic_block pdom;
806 pdom = find_pdom (bb);
808 /* Skip the postdominating bb that is also loop exit. */
809 if (!is_non_loop_exit_postdominating (pdom, bb))
810 return NULL;
812 if (dominated_by_p (CDI_DOMINATORS, pdom, bb))
813 return pdom;
815 return NULL;
818 #define MAX_NUM_CHAINS 8
819 #define MAX_CHAIN_LEN 5
820 #define MAX_POSTDOM_CHECK 8
821 #define MAX_SWITCH_CASES 40
823 /* Computes the control dependence chains (paths of edges)
824 for DEP_BB up to the dominating basic block BB (the head node of a
825 chain should be dominated by it). CD_CHAINS is pointer to an
826 array holding the result chains. CUR_CD_CHAIN is the current
827 chain being computed. *NUM_CHAINS is total number of chains. The
828 function returns true if the information is successfully computed,
829 return false if there is no control dependence or not computed. */
831 static bool
832 compute_control_dep_chain (basic_block bb, basic_block dep_bb,
833 vec<edge> *cd_chains,
834 size_t *num_chains,
835 vec<edge> *cur_cd_chain,
836 int *num_calls)
838 edge_iterator ei;
839 edge e;
840 size_t i;
841 bool found_cd_chain = false;
842 size_t cur_chain_len = 0;
844 if (*num_calls > param_uninit_control_dep_attempts)
845 return false;
846 ++*num_calls;
848 /* Could use a set instead. */
849 cur_chain_len = cur_cd_chain->length ();
850 if (cur_chain_len > MAX_CHAIN_LEN)
851 return false;
853 for (i = 0; i < cur_chain_len; i++)
855 edge e = (*cur_cd_chain)[i];
856 /* Cycle detected. */
857 if (e->src == bb)
858 return false;
861 FOR_EACH_EDGE (e, ei, bb->succs)
863 basic_block cd_bb;
864 int post_dom_check = 0;
865 if (e->flags & (EDGE_FAKE | EDGE_ABNORMAL))
866 continue;
868 cd_bb = e->dest;
869 cur_cd_chain->safe_push (e);
870 while (!is_non_loop_exit_postdominating (cd_bb, bb))
872 if (cd_bb == dep_bb)
874 /* Found a direct control dependence. */
875 if (*num_chains < MAX_NUM_CHAINS)
877 cd_chains[*num_chains] = cur_cd_chain->copy ();
878 (*num_chains)++;
880 found_cd_chain = true;
881 /* Check path from next edge. */
882 break;
885 /* Now check if DEP_BB is indirectly control dependent on BB. */
886 if (compute_control_dep_chain (cd_bb, dep_bb, cd_chains, num_chains,
887 cur_cd_chain, num_calls))
889 found_cd_chain = true;
890 break;
893 cd_bb = find_pdom (cd_bb);
894 post_dom_check++;
895 if (cd_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
896 || post_dom_check > MAX_POSTDOM_CHECK)
897 break;
899 cur_cd_chain->pop ();
900 gcc_assert (cur_cd_chain->length () == cur_chain_len);
902 gcc_assert (cur_cd_chain->length () == cur_chain_len);
904 return found_cd_chain;
907 /* The type to represent a simple predicate. */
909 struct pred_info
911 tree pred_lhs;
912 tree pred_rhs;
913 enum tree_code cond_code;
914 bool invert;
917 /* The type to represent a sequence of predicates grouped
918 with .AND. operation. */
920 typedef vec<pred_info, va_heap, vl_ptr> pred_chain;
922 /* The type to represent a sequence of pred_chains grouped
923 with .OR. operation. */
925 typedef vec<pred_chain, va_heap, vl_ptr> pred_chain_union;
927 /* Converts the chains of control dependence edges into a set of
928 predicates. A control dependence chain is represented by a vector
929 edges. DEP_CHAINS points to an array of dependence chains.
930 NUM_CHAINS is the size of the chain array. One edge in a dependence
931 chain is mapped to predicate expression represented by pred_info
932 type. One dependence chain is converted to a composite predicate that
933 is the result of AND operation of pred_info mapped to each edge.
934 A composite predicate is presented by a vector of pred_info. On
935 return, *PREDS points to the resulting array of composite predicates.
936 *NUM_PREDS is the number of composite predictes. */
938 static bool
939 convert_control_dep_chain_into_preds (vec<edge> *dep_chains,
940 size_t num_chains,
941 pred_chain_union *preds)
943 bool has_valid_pred = false;
944 size_t i, j;
945 if (num_chains == 0 || num_chains >= MAX_NUM_CHAINS)
946 return false;
948 /* Now convert the control dep chain into a set
949 of predicates. */
950 preds->reserve (num_chains);
952 for (i = 0; i < num_chains; i++)
954 vec<edge> one_cd_chain = dep_chains[i];
956 has_valid_pred = false;
957 pred_chain t_chain = vNULL;
958 for (j = 0; j < one_cd_chain.length (); j++)
960 gimple *cond_stmt;
961 gimple_stmt_iterator gsi;
962 basic_block guard_bb;
963 pred_info one_pred;
964 edge e;
966 e = one_cd_chain[j];
967 guard_bb = e->src;
968 gsi = gsi_last_bb (guard_bb);
969 /* Ignore empty forwarder blocks. */
970 if (empty_block_p (guard_bb) && single_succ_p (guard_bb))
971 continue;
972 /* An empty basic block here is likely a PHI, and is not one
973 of the cases we handle below. */
974 if (gsi_end_p (gsi))
976 has_valid_pred = false;
977 break;
979 cond_stmt = gsi_stmt (gsi);
980 if (is_gimple_call (cond_stmt) && EDGE_COUNT (e->src->succs) >= 2)
981 /* Ignore EH edge. Can add assertion on the other edge's flag. */
982 continue;
983 /* Skip if there is essentially one succesor. */
984 if (EDGE_COUNT (e->src->succs) == 2)
986 edge e1;
987 edge_iterator ei1;
988 bool skip = false;
990 FOR_EACH_EDGE (e1, ei1, e->src->succs)
992 if (EDGE_COUNT (e1->dest->succs) == 0)
994 skip = true;
995 break;
998 if (skip)
999 continue;
1001 if (gimple_code (cond_stmt) == GIMPLE_COND)
1003 one_pred.pred_lhs = gimple_cond_lhs (cond_stmt);
1004 one_pred.pred_rhs = gimple_cond_rhs (cond_stmt);
1005 one_pred.cond_code = gimple_cond_code (cond_stmt);
1006 one_pred.invert = !!(e->flags & EDGE_FALSE_VALUE);
1007 t_chain.safe_push (one_pred);
1008 has_valid_pred = true;
1010 else if (gswitch *gs = dyn_cast<gswitch *> (cond_stmt))
1012 /* Avoid quadratic behavior. */
1013 if (gimple_switch_num_labels (gs) > MAX_SWITCH_CASES)
1015 has_valid_pred = false;
1016 break;
1018 /* Find the case label. */
1019 tree l = NULL_TREE;
1020 unsigned idx;
1021 for (idx = 0; idx < gimple_switch_num_labels (gs); ++idx)
1023 tree tl = gimple_switch_label (gs, idx);
1024 if (e->dest == label_to_block (cfun, CASE_LABEL (tl)))
1026 if (!l)
1027 l = tl;
1028 else
1030 l = NULL_TREE;
1031 break;
1035 /* If more than one label reaches this block or the case
1036 label doesn't have a single value (like the default one)
1037 fail. */
1038 if (!l
1039 || !CASE_LOW (l)
1040 || (CASE_HIGH (l)
1041 && !operand_equal_p (CASE_LOW (l), CASE_HIGH (l), 0)))
1043 has_valid_pred = false;
1044 break;
1046 one_pred.pred_lhs = gimple_switch_index (gs);
1047 one_pred.pred_rhs = CASE_LOW (l);
1048 one_pred.cond_code = EQ_EXPR;
1049 one_pred.invert = false;
1050 t_chain.safe_push (one_pred);
1051 has_valid_pred = true;
1053 else
1055 has_valid_pred = false;
1056 break;
1060 if (!has_valid_pred)
1061 break;
1062 else
1063 preds->safe_push (t_chain);
1065 return has_valid_pred;
1068 /* Computes all control dependence chains for USE_BB. The control
1069 dependence chains are then converted to an array of composite
1070 predicates pointed to by PREDS. PHI_BB is the basic block of
1071 the phi whose result is used in USE_BB. */
1073 static bool
1074 find_predicates (pred_chain_union *preds,
1075 basic_block phi_bb,
1076 basic_block use_bb)
1078 size_t num_chains = 0, i;
1079 int num_calls = 0;
1080 vec<edge> dep_chains[MAX_NUM_CHAINS];
1081 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
1082 bool has_valid_pred = false;
1083 basic_block cd_root = 0;
1085 /* First find the closest bb that is control equivalent to PHI_BB
1086 that also dominates USE_BB. */
1087 cd_root = phi_bb;
1088 while (dominated_by_p (CDI_DOMINATORS, use_bb, cd_root))
1090 basic_block ctrl_eq_bb = find_control_equiv_block (cd_root);
1091 if (ctrl_eq_bb && dominated_by_p (CDI_DOMINATORS, use_bb, ctrl_eq_bb))
1092 cd_root = ctrl_eq_bb;
1093 else
1094 break;
1097 compute_control_dep_chain (cd_root, use_bb, dep_chains, &num_chains,
1098 &cur_chain, &num_calls);
1100 has_valid_pred
1101 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
1102 for (i = 0; i < num_chains; i++)
1103 dep_chains[i].release ();
1104 return has_valid_pred;
1107 /* Computes the set of incoming edges of PHI that have non empty
1108 definitions of a phi chain. The collection will be done
1109 recursively on operands that are defined by phis. CD_ROOT
1110 is the control dependence root. *EDGES holds the result, and
1111 VISITED_PHIS is a pointer set for detecting cycles. */
1113 static void
1114 collect_phi_def_edges (gphi *phi, basic_block cd_root,
1115 auto_vec<edge> *edges,
1116 hash_set<gimple *> *visited_phis)
1118 size_t i, n;
1119 edge opnd_edge;
1120 tree opnd;
1122 if (visited_phis->add (phi))
1123 return;
1125 n = gimple_phi_num_args (phi);
1126 for (i = 0; i < n; i++)
1128 opnd_edge = gimple_phi_arg_edge (phi, i);
1129 opnd = gimple_phi_arg_def (phi, i);
1131 if (TREE_CODE (opnd) != SSA_NAME)
1133 if (dump_file && (dump_flags & TDF_DETAILS))
1135 fprintf (dump_file, "\n[CHECK] Found def edge %d in ", (int) i);
1136 print_gimple_stmt (dump_file, phi, 0);
1138 edges->safe_push (opnd_edge);
1140 else
1142 gimple *def = SSA_NAME_DEF_STMT (opnd);
1144 if (gimple_code (def) == GIMPLE_PHI
1145 && dominated_by_p (CDI_DOMINATORS, gimple_bb (def), cd_root))
1146 collect_phi_def_edges (as_a<gphi *> (def), cd_root, edges,
1147 visited_phis);
1148 else if (!uninit_undefined_value_p (opnd))
1150 if (dump_file && (dump_flags & TDF_DETAILS))
1152 fprintf (dump_file, "\n[CHECK] Found def edge %d in ",
1153 (int) i);
1154 print_gimple_stmt (dump_file, phi, 0);
1156 edges->safe_push (opnd_edge);
1162 /* For each use edge of PHI, computes all control dependence chains.
1163 The control dependence chains are then converted to an array of
1164 composite predicates pointed to by PREDS. */
1166 static bool
1167 find_def_preds (pred_chain_union *preds, gphi *phi)
1169 size_t num_chains = 0, i, n;
1170 vec<edge> dep_chains[MAX_NUM_CHAINS];
1171 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
1172 auto_vec<edge> def_edges;
1173 bool has_valid_pred = false;
1174 basic_block phi_bb, cd_root = 0;
1176 phi_bb = gimple_bb (phi);
1177 /* First find the closest dominating bb to be
1178 the control dependence root. */
1179 cd_root = find_dom (phi_bb);
1180 if (!cd_root)
1181 return false;
1183 hash_set<gimple *> visited_phis;
1184 collect_phi_def_edges (phi, cd_root, &def_edges, &visited_phis);
1186 n = def_edges.length ();
1187 if (n == 0)
1188 return false;
1190 for (i = 0; i < n; i++)
1192 size_t prev_nc, j;
1193 int num_calls = 0;
1194 edge opnd_edge;
1196 opnd_edge = def_edges[i];
1197 prev_nc = num_chains;
1198 compute_control_dep_chain (cd_root, opnd_edge->src, dep_chains,
1199 &num_chains, &cur_chain, &num_calls);
1201 /* Now update the newly added chains with
1202 the phi operand edge: */
1203 if (EDGE_COUNT (opnd_edge->src->succs) > 1)
1205 if (prev_nc == num_chains && num_chains < MAX_NUM_CHAINS)
1206 dep_chains[num_chains++] = vNULL;
1207 for (j = prev_nc; j < num_chains; j++)
1208 dep_chains[j].safe_push (opnd_edge);
1212 has_valid_pred
1213 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
1214 for (i = 0; i < num_chains; i++)
1215 dep_chains[i].release ();
1216 return has_valid_pred;
1219 /* Dump a pred_info. */
1221 static void
1222 dump_pred_info (pred_info one_pred)
1224 if (one_pred.invert)
1225 fprintf (dump_file, " (.NOT.) ");
1226 print_generic_expr (dump_file, one_pred.pred_lhs);
1227 fprintf (dump_file, " %s ", op_symbol_code (one_pred.cond_code));
1228 print_generic_expr (dump_file, one_pred.pred_rhs);
1231 /* Dump a pred_chain. */
1233 static void
1234 dump_pred_chain (pred_chain one_pred_chain)
1236 size_t np = one_pred_chain.length ();
1237 for (size_t j = 0; j < np; j++)
1239 dump_pred_info (one_pred_chain[j]);
1240 if (j < np - 1)
1241 fprintf (dump_file, " (.AND.) ");
1242 else
1243 fprintf (dump_file, "\n");
1247 /* Dumps the predicates (PREDS) for USESTMT. */
1249 static void
1250 dump_predicates (gimple *usestmt, pred_chain_union preds, const char *msg)
1252 fprintf (dump_file, "%s", msg);
1253 if (usestmt)
1255 print_gimple_stmt (dump_file, usestmt, 0);
1256 fprintf (dump_file, "is guarded by :\n\n");
1258 size_t num_preds = preds.length ();
1259 for (size_t i = 0; i < num_preds; i++)
1261 dump_pred_chain (preds[i]);
1262 if (i < num_preds - 1)
1263 fprintf (dump_file, "(.OR.)\n");
1264 else
1265 fprintf (dump_file, "\n\n");
1269 /* Destroys the predicate set *PREDS. */
1271 static void
1272 destroy_predicate_vecs (pred_chain_union *preds)
1274 size_t i;
1276 size_t n = preds->length ();
1277 for (i = 0; i < n; i++)
1278 (*preds)[i].release ();
1279 preds->release ();
1282 /* Computes the 'normalized' conditional code with operand
1283 swapping and condition inversion. */
1285 static enum tree_code
1286 get_cmp_code (enum tree_code orig_cmp_code, bool swap_cond, bool invert)
1288 enum tree_code tc = orig_cmp_code;
1290 if (swap_cond)
1291 tc = swap_tree_comparison (orig_cmp_code);
1292 if (invert)
1293 tc = invert_tree_comparison (tc, false);
1295 switch (tc)
1297 case LT_EXPR:
1298 case LE_EXPR:
1299 case GT_EXPR:
1300 case GE_EXPR:
1301 case EQ_EXPR:
1302 case NE_EXPR:
1303 break;
1304 default:
1305 return ERROR_MARK;
1307 return tc;
1310 /* Returns whether VAL CMPC BOUNDARY is true. */
1312 static bool
1313 is_value_included_in (tree val, tree boundary, enum tree_code cmpc)
1315 bool inverted = false;
1316 bool result;
1318 /* Only handle integer constant here. */
1319 if (TREE_CODE (val) != INTEGER_CST || TREE_CODE (boundary) != INTEGER_CST)
1320 return true;
1322 if (cmpc == GE_EXPR || cmpc == GT_EXPR || cmpc == NE_EXPR)
1324 cmpc = invert_tree_comparison (cmpc, false);
1325 inverted = true;
1328 if (cmpc == EQ_EXPR)
1329 result = tree_int_cst_equal (val, boundary);
1330 else if (cmpc == LT_EXPR)
1331 result = tree_int_cst_lt (val, boundary);
1332 else
1334 gcc_assert (cmpc == LE_EXPR);
1335 result = tree_int_cst_le (val, boundary);
1338 if (inverted)
1339 result ^= 1;
1341 return result;
1344 /* Returns whether VAL satisfies (x CMPC BOUNDARY) predicate. CMPC can be
1345 either one of the range comparison codes ({GE,LT,EQ,NE}_EXPR and the like),
1346 or BIT_AND_EXPR. EXACT_P is only meaningful for the latter. It modifies the
1347 question from whether VAL & BOUNDARY != 0 to whether VAL & BOUNDARY == VAL.
1348 For other values of CMPC, EXACT_P is ignored. */
1350 static bool
1351 value_sat_pred_p (tree val, tree boundary, enum tree_code cmpc,
1352 bool exact_p = false)
1354 if (cmpc != BIT_AND_EXPR)
1355 return is_value_included_in (val, boundary, cmpc);
1357 wide_int andw = wi::to_wide (val) & wi::to_wide (boundary);
1358 if (exact_p)
1359 return andw == wi::to_wide (val);
1360 else
1361 return andw.to_uhwi ();
1364 /* Returns true if PRED is common among all the predicate
1365 chains (PREDS) (and therefore can be factored out). */
1367 static bool
1368 find_matching_predicate_in_rest_chains (pred_info pred, pred_chain_union preds)
1370 size_t i, j, n;
1372 /* Trival case. */
1373 if (preds.length () == 1)
1374 return true;
1376 for (i = 1; i < preds.length (); i++)
1378 bool found = false;
1379 pred_chain one_chain = preds[i];
1380 n = one_chain.length ();
1381 for (j = 0; j < n; j++)
1383 pred_info pred2 = one_chain[j];
1384 /* Can relax the condition comparison to not
1385 use address comparison. However, the most common
1386 case is that multiple control dependent paths share
1387 a common path prefix, so address comparison should
1388 be ok. */
1390 if (operand_equal_p (pred2.pred_lhs, pred.pred_lhs, 0)
1391 && operand_equal_p (pred2.pred_rhs, pred.pred_rhs, 0)
1392 && pred2.invert == pred.invert)
1394 found = true;
1395 break;
1398 if (!found)
1399 return false;
1401 return true;
1404 /* Forward declaration. */
1405 static bool is_use_properly_guarded (gimple *use_stmt,
1406 basic_block use_bb,
1407 gphi *phi,
1408 unsigned uninit_opnds,
1409 pred_chain_union *def_preds,
1410 hash_set<gphi *> *visited_phis);
1412 /* Returns true if all uninitialized opnds are pruned. Returns false
1413 otherwise. PHI is the phi node with uninitialized operands,
1414 UNINIT_OPNDS is the bitmap of the uninitialize operand positions,
1415 FLAG_DEF is the statement defining the flag guarding the use of the
1416 PHI output, BOUNDARY_CST is the const value used in the predicate
1417 associated with the flag, CMP_CODE is the comparison code used in
1418 the predicate, VISITED_PHIS is the pointer set of phis visited, and
1419 VISITED_FLAG_PHIS is the pointer to the pointer set of flag definitions
1420 that are also phis.
1422 Example scenario:
1424 BB1:
1425 flag_1 = phi <0, 1> // (1)
1426 var_1 = phi <undef, some_val>
1429 BB2:
1430 flag_2 = phi <0, flag_1, flag_1> // (2)
1431 var_2 = phi <undef, var_1, var_1>
1432 if (flag_2 == 1)
1433 goto BB3;
1435 BB3:
1436 use of var_2 // (3)
1438 Because some flag arg in (1) is not constant, if we do not look into the
1439 flag phis recursively, it is conservatively treated as unknown and var_1
1440 is thought to be flowed into use at (3). Since var_1 is potentially
1441 uninitialized a false warning will be emitted.
1442 Checking recursively into (1), the compiler can find out that only some_val
1443 (which is defined) can flow into (3) which is OK. */
1445 static bool
1446 prune_uninit_phi_opnds (gphi *phi, unsigned uninit_opnds, gphi *flag_def,
1447 tree boundary_cst, enum tree_code cmp_code,
1448 hash_set<gphi *> *visited_phis,
1449 bitmap *visited_flag_phis)
1451 unsigned i;
1453 for (i = 0; i < MIN (max_phi_args, gimple_phi_num_args (flag_def)); i++)
1455 tree flag_arg;
1457 if (!MASK_TEST_BIT (uninit_opnds, i))
1458 continue;
1460 flag_arg = gimple_phi_arg_def (flag_def, i);
1461 if (!is_gimple_constant (flag_arg))
1463 gphi *flag_arg_def, *phi_arg_def;
1464 tree phi_arg;
1465 unsigned uninit_opnds_arg_phi;
1467 if (TREE_CODE (flag_arg) != SSA_NAME)
1468 return false;
1469 flag_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (flag_arg));
1470 if (!flag_arg_def)
1471 return false;
1473 phi_arg = gimple_phi_arg_def (phi, i);
1474 if (TREE_CODE (phi_arg) != SSA_NAME)
1475 return false;
1477 phi_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (phi_arg));
1478 if (!phi_arg_def)
1479 return false;
1481 if (gimple_bb (phi_arg_def) != gimple_bb (flag_arg_def))
1482 return false;
1484 if (!*visited_flag_phis)
1485 *visited_flag_phis = BITMAP_ALLOC (NULL);
1487 tree phi_result = gimple_phi_result (flag_arg_def);
1488 if (bitmap_bit_p (*visited_flag_phis, SSA_NAME_VERSION (phi_result)))
1489 return false;
1491 bitmap_set_bit (*visited_flag_phis,
1492 SSA_NAME_VERSION (gimple_phi_result (flag_arg_def)));
1494 /* Now recursively prune the uninitialized phi args. */
1495 uninit_opnds_arg_phi = compute_uninit_opnds_pos (phi_arg_def);
1496 if (!prune_uninit_phi_opnds
1497 (phi_arg_def, uninit_opnds_arg_phi, flag_arg_def, boundary_cst,
1498 cmp_code, visited_phis, visited_flag_phis))
1499 return false;
1501 phi_result = gimple_phi_result (flag_arg_def);
1502 bitmap_clear_bit (*visited_flag_phis, SSA_NAME_VERSION (phi_result));
1503 continue;
1506 /* Now check if the constant is in the guarded range. */
1507 if (is_value_included_in (flag_arg, boundary_cst, cmp_code))
1509 tree opnd;
1510 gimple *opnd_def;
1512 /* Now that we know that this undefined edge is not
1513 pruned. If the operand is defined by another phi,
1514 we can further prune the incoming edges of that
1515 phi by checking the predicates of this operands. */
1517 opnd = gimple_phi_arg_def (phi, i);
1518 opnd_def = SSA_NAME_DEF_STMT (opnd);
1519 if (gphi *opnd_def_phi = dyn_cast <gphi *> (opnd_def))
1521 edge opnd_edge;
1522 unsigned uninit_opnds2 = compute_uninit_opnds_pos (opnd_def_phi);
1523 if (!MASK_EMPTY (uninit_opnds2))
1525 pred_chain_union def_preds = vNULL;
1526 bool ok;
1527 opnd_edge = gimple_phi_arg_edge (phi, i);
1528 ok = is_use_properly_guarded (phi,
1529 opnd_edge->src,
1530 opnd_def_phi,
1531 uninit_opnds2,
1532 &def_preds,
1533 visited_phis);
1534 destroy_predicate_vecs (&def_preds);
1535 if (!ok)
1536 return false;
1539 else
1540 return false;
1544 return true;
1547 /* A helper function finds predicate which will be examined against uninit
1548 paths. If there is no "flag_var cmp const" form predicate, the function
1549 tries to find predicate of form like "flag_var cmp flag_var" with value
1550 range info. PHI is the phi node whose incoming (undefined) paths need to
1551 be examined. On success, the function returns the comparsion code, sets
1552 defintion gimple of the flag_var to FLAG_DEF, sets boundary_cst to
1553 BOUNDARY_CST. On fail, the function returns ERROR_MARK. */
1555 static enum tree_code
1556 find_var_cmp_const (pred_chain_union preds, gphi *phi, gimple **flag_def,
1557 tree *boundary_cst)
1559 enum tree_code vrinfo_code = ERROR_MARK, code;
1560 gimple *vrinfo_def = NULL;
1561 tree vrinfo_cst = NULL, cond_lhs, cond_rhs;
1563 gcc_assert (preds.length () > 0);
1564 pred_chain the_pred_chain = preds[0];
1565 for (unsigned i = 0; i < the_pred_chain.length (); i++)
1567 bool use_vrinfo_p = false;
1568 pred_info the_pred = the_pred_chain[i];
1569 cond_lhs = the_pred.pred_lhs;
1570 cond_rhs = the_pred.pred_rhs;
1571 if (cond_lhs == NULL_TREE || cond_rhs == NULL_TREE)
1572 continue;
1574 code = get_cmp_code (the_pred.cond_code, false, the_pred.invert);
1575 if (code == ERROR_MARK)
1576 continue;
1578 if (TREE_CODE (cond_lhs) == SSA_NAME && is_gimple_constant (cond_rhs))
1580 else if (TREE_CODE (cond_rhs) == SSA_NAME
1581 && is_gimple_constant (cond_lhs))
1583 std::swap (cond_lhs, cond_rhs);
1584 if ((code = get_cmp_code (code, true, false)) == ERROR_MARK)
1585 continue;
1587 /* Check if we can take advantage of "flag_var comp flag_var" predicate
1588 with value range info. Note only first of such case is handled. */
1589 else if (vrinfo_code == ERROR_MARK
1590 && TREE_CODE (cond_lhs) == SSA_NAME
1591 && TREE_CODE (cond_rhs) == SSA_NAME)
1593 gimple* lhs_def = SSA_NAME_DEF_STMT (cond_lhs);
1594 if (!lhs_def || gimple_code (lhs_def) != GIMPLE_PHI
1595 || gimple_bb (lhs_def) != gimple_bb (phi))
1597 std::swap (cond_lhs, cond_rhs);
1598 if ((code = get_cmp_code (code, true, false)) == ERROR_MARK)
1599 continue;
1602 /* Check value range info of rhs, do following transforms:
1603 flag_var < [min, max] -> flag_var < max
1604 flag_var > [min, max] -> flag_var > min
1606 We can also transform LE_EXPR/GE_EXPR to LT_EXPR/GT_EXPR:
1607 flag_var <= [min, max] -> flag_var < [min, max+1]
1608 flag_var >= [min, max] -> flag_var > [min-1, max]
1609 if no overflow/wrap. */
1610 tree type = TREE_TYPE (cond_lhs);
1611 value_range r;
1612 if (!INTEGRAL_TYPE_P (type)
1613 || !get_range_query (cfun)->range_of_expr (r, cond_rhs)
1614 || r.kind () != VR_RANGE)
1615 continue;
1616 wide_int min = r.lower_bound ();
1617 wide_int max = r.upper_bound ();
1618 if (code == LE_EXPR
1619 && max != wi::max_value (TYPE_PRECISION (type), TYPE_SIGN (type)))
1621 code = LT_EXPR;
1622 max = max + 1;
1624 if (code == GE_EXPR
1625 && min != wi::min_value (TYPE_PRECISION (type), TYPE_SIGN (type)))
1627 code = GT_EXPR;
1628 min = min - 1;
1630 if (code == LT_EXPR)
1631 cond_rhs = wide_int_to_tree (type, max);
1632 else if (code == GT_EXPR)
1633 cond_rhs = wide_int_to_tree (type, min);
1634 else
1635 continue;
1637 use_vrinfo_p = true;
1639 else
1640 continue;
1642 if ((*flag_def = SSA_NAME_DEF_STMT (cond_lhs)) == NULL)
1643 continue;
1645 if (gimple_code (*flag_def) != GIMPLE_PHI
1646 || gimple_bb (*flag_def) != gimple_bb (phi)
1647 || !find_matching_predicate_in_rest_chains (the_pred, preds))
1648 continue;
1650 /* Return if any "flag_var comp const" predicate is found. */
1651 if (!use_vrinfo_p)
1653 *boundary_cst = cond_rhs;
1654 return code;
1656 /* Record if any "flag_var comp flag_var[vinfo]" predicate is found. */
1657 else if (vrinfo_code == ERROR_MARK)
1659 vrinfo_code = code;
1660 vrinfo_def = *flag_def;
1661 vrinfo_cst = cond_rhs;
1664 /* Return the "flag_var cmp flag_var[vinfo]" predicate we found. */
1665 if (vrinfo_code != ERROR_MARK)
1667 *flag_def = vrinfo_def;
1668 *boundary_cst = vrinfo_cst;
1670 return vrinfo_code;
1673 /* A helper function that determines if the predicate set
1674 of the use is not overlapping with that of the uninit paths.
1675 The most common senario of guarded use is in Example 1:
1676 Example 1:
1677 if (some_cond)
1679 x = ...;
1680 flag = true;
1683 ... some code ...
1685 if (flag)
1686 use (x);
1688 The real world examples are usually more complicated, but similar
1689 and usually result from inlining:
1691 bool init_func (int * x)
1693 if (some_cond)
1694 return false;
1695 *x = ..
1696 return true;
1699 void foo (..)
1701 int x;
1703 if (!init_func (&x))
1704 return;
1706 .. some_code ...
1707 use (x);
1710 Another possible use scenario is in the following trivial example:
1712 Example 2:
1713 if (n > 0)
1714 x = 1;
1716 if (n > 0)
1718 if (m < 2)
1719 .. = x;
1722 Predicate analysis needs to compute the composite predicate:
1724 1) 'x' use predicate: (n > 0) .AND. (m < 2)
1725 2) 'x' default value (non-def) predicate: .NOT. (n > 0)
1726 (the predicate chain for phi operand defs can be computed
1727 starting from a bb that is control equivalent to the phi's
1728 bb and is dominating the operand def.)
1730 and check overlapping:
1731 (n > 0) .AND. (m < 2) .AND. (.NOT. (n > 0))
1732 <==> false
1734 This implementation provides framework that can handle
1735 scenarios. (Note that many simple cases are handled properly
1736 without the predicate analysis -- this is due to jump threading
1737 transformation which eliminates the merge point thus makes
1738 path sensitive analysis unnecessary.)
1740 PHI is the phi node whose incoming (undefined) paths need to be
1741 pruned, and UNINIT_OPNDS is the bitmap holding uninit operand
1742 positions. VISITED_PHIS is the pointer set of phi stmts being
1743 checked. */
1745 static bool
1746 use_pred_not_overlap_with_undef_path_pred (pred_chain_union preds,
1747 gphi *phi, unsigned uninit_opnds,
1748 hash_set<gphi *> *visited_phis)
1750 gimple *flag_def = 0;
1751 tree boundary_cst = 0;
1752 enum tree_code cmp_code;
1753 bitmap visited_flag_phis = NULL;
1754 bool all_pruned = false;
1756 /* Find within the common prefix of multiple predicate chains
1757 a predicate that is a comparison of a flag variable against
1758 a constant. */
1759 cmp_code = find_var_cmp_const (preds, phi, &flag_def, &boundary_cst);
1760 if (cmp_code == ERROR_MARK)
1761 return false;
1763 /* Now check all the uninit incoming edge has a constant flag value
1764 that is in conflict with the use guard/predicate. */
1765 all_pruned = prune_uninit_phi_opnds
1766 (phi, uninit_opnds, as_a<gphi *> (flag_def), boundary_cst, cmp_code,
1767 visited_phis, &visited_flag_phis);
1769 if (visited_flag_phis)
1770 BITMAP_FREE (visited_flag_phis);
1772 return all_pruned;
1775 /* The helper function returns true if two predicates X1 and X2
1776 are equivalent. It assumes the expressions have already
1777 properly re-associated. */
1779 static inline bool
1780 pred_equal_p (pred_info x1, pred_info x2)
1782 enum tree_code c1, c2;
1783 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1784 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1785 return false;
1787 c1 = x1.cond_code;
1788 if (x1.invert != x2.invert
1789 && TREE_CODE_CLASS (x2.cond_code) == tcc_comparison)
1790 c2 = invert_tree_comparison (x2.cond_code, false);
1791 else
1792 c2 = x2.cond_code;
1794 return c1 == c2;
1797 /* Returns true if the predication is testing !=. */
1799 static inline bool
1800 is_neq_relop_p (pred_info pred)
1803 return ((pred.cond_code == NE_EXPR && !pred.invert)
1804 || (pred.cond_code == EQ_EXPR && pred.invert));
1807 /* Returns true if pred is of the form X != 0. */
1809 static inline bool
1810 is_neq_zero_form_p (pred_info pred)
1812 if (!is_neq_relop_p (pred) || !integer_zerop (pred.pred_rhs)
1813 || TREE_CODE (pred.pred_lhs) != SSA_NAME)
1814 return false;
1815 return true;
1818 /* The helper function returns true if two predicates X1
1819 is equivalent to X2 != 0. */
1821 static inline bool
1822 pred_expr_equal_p (pred_info x1, tree x2)
1824 if (!is_neq_zero_form_p (x1))
1825 return false;
1827 return operand_equal_p (x1.pred_lhs, x2, 0);
1830 /* Returns true of the domain of single predicate expression
1831 EXPR1 is a subset of that of EXPR2. Returns false if it
1832 cannot be proved. */
1834 static bool
1835 is_pred_expr_subset_of (pred_info expr1, pred_info expr2)
1837 enum tree_code code1, code2;
1839 if (pred_equal_p (expr1, expr2))
1840 return true;
1842 if ((TREE_CODE (expr1.pred_rhs) != INTEGER_CST)
1843 || (TREE_CODE (expr2.pred_rhs) != INTEGER_CST))
1844 return false;
1846 if (!operand_equal_p (expr1.pred_lhs, expr2.pred_lhs, 0))
1847 return false;
1849 code1 = expr1.cond_code;
1850 if (expr1.invert)
1851 code1 = invert_tree_comparison (code1, false);
1852 code2 = expr2.cond_code;
1853 if (expr2.invert)
1854 code2 = invert_tree_comparison (code2, false);
1856 if (code2 == NE_EXPR && code1 == NE_EXPR)
1857 return false;
1859 if (code2 == NE_EXPR)
1860 return !value_sat_pred_p (expr2.pred_rhs, expr1.pred_rhs, code1);
1862 if (code1 == EQ_EXPR)
1863 return value_sat_pred_p (expr1.pred_rhs, expr2.pred_rhs, code2);
1865 if (code1 == code2)
1866 return value_sat_pred_p (expr1.pred_rhs, expr2.pred_rhs, code2,
1867 code1 == BIT_AND_EXPR);
1869 return false;
1872 /* Returns true if the domain of PRED1 is a subset
1873 of that of PRED2. Returns false if it cannot be proved so. */
1875 static bool
1876 is_pred_chain_subset_of (pred_chain pred1, pred_chain pred2)
1878 size_t np1, np2, i1, i2;
1880 np1 = pred1.length ();
1881 np2 = pred2.length ();
1883 for (i2 = 0; i2 < np2; i2++)
1885 bool found = false;
1886 pred_info info2 = pred2[i2];
1887 for (i1 = 0; i1 < np1; i1++)
1889 pred_info info1 = pred1[i1];
1890 if (is_pred_expr_subset_of (info1, info2))
1892 found = true;
1893 break;
1896 if (!found)
1897 return false;
1899 return true;
1902 /* Returns true if the domain defined by
1903 one pred chain ONE_PRED is a subset of the domain
1904 of *PREDS. It returns false if ONE_PRED's domain is
1905 not a subset of any of the sub-domains of PREDS
1906 (corresponding to each individual chains in it), even
1907 though it may be still be a subset of whole domain
1908 of PREDS which is the union (ORed) of all its subdomains.
1909 In other words, the result is conservative. */
1911 static bool
1912 is_included_in (pred_chain one_pred, pred_chain_union preds)
1914 size_t i;
1915 size_t n = preds.length ();
1917 for (i = 0; i < n; i++)
1919 if (is_pred_chain_subset_of (one_pred, preds[i]))
1920 return true;
1923 return false;
1926 /* Compares two predicate sets PREDS1 and PREDS2 and returns
1927 true if the domain defined by PREDS1 is a superset
1928 of PREDS2's domain. N1 and N2 are array sizes of PREDS1 and
1929 PREDS2 respectively. The implementation chooses not to build
1930 generic trees (and relying on the folding capability of the
1931 compiler), but instead performs brute force comparison of
1932 individual predicate chains (won't be a compile time problem
1933 as the chains are pretty short). When the function returns
1934 false, it does not necessarily mean *PREDS1 is not a superset
1935 of *PREDS2, but mean it may not be so since the analysis cannot
1936 prove it. In such cases, false warnings may still be
1937 emitted. */
1939 static bool
1940 is_superset_of (pred_chain_union preds1, pred_chain_union preds2)
1942 size_t i, n2;
1943 pred_chain one_pred_chain = vNULL;
1945 n2 = preds2.length ();
1947 for (i = 0; i < n2; i++)
1949 one_pred_chain = preds2[i];
1950 if (!is_included_in (one_pred_chain, preds1))
1951 return false;
1954 return true;
1957 /* Returns true if X1 is the negate of X2. */
1959 static inline bool
1960 pred_neg_p (pred_info x1, pred_info x2)
1962 enum tree_code c1, c2;
1963 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1964 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1965 return false;
1967 c1 = x1.cond_code;
1968 if (x1.invert == x2.invert)
1969 c2 = invert_tree_comparison (x2.cond_code, false);
1970 else
1971 c2 = x2.cond_code;
1973 return c1 == c2;
1976 /* 1) ((x IOR y) != 0) AND (x != 0) is equivalent to (x != 0);
1977 2) (X AND Y) OR (!X AND Y) is equivalent to Y;
1978 3) X OR (!X AND Y) is equivalent to (X OR Y);
1979 4) ((x IAND y) != 0) || (x != 0 AND y != 0)) is equivalent to
1980 (x != 0 AND y != 0)
1981 5) (X AND Y) OR (!X AND Z) OR (!Y AND Z) is equivalent to
1982 (X AND Y) OR Z
1984 PREDS is the predicate chains, and N is the number of chains. */
1986 /* Helper function to implement rule 1 above. ONE_CHAIN is
1987 the AND predication to be simplified. */
1989 static void
1990 simplify_pred (pred_chain *one_chain)
1992 size_t i, j, n;
1993 bool simplified = false;
1994 pred_chain s_chain = vNULL;
1996 n = one_chain->length ();
1998 for (i = 0; i < n; i++)
2000 pred_info *a_pred = &(*one_chain)[i];
2002 if (!a_pred->pred_lhs)
2003 continue;
2004 if (!is_neq_zero_form_p (*a_pred))
2005 continue;
2007 gimple *def_stmt = SSA_NAME_DEF_STMT (a_pred->pred_lhs);
2008 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2009 continue;
2010 if (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
2012 for (j = 0; j < n; j++)
2014 pred_info *b_pred = &(*one_chain)[j];
2016 if (!b_pred->pred_lhs)
2017 continue;
2018 if (!is_neq_zero_form_p (*b_pred))
2019 continue;
2021 if (pred_expr_equal_p (*b_pred, gimple_assign_rhs1 (def_stmt))
2022 || pred_expr_equal_p (*b_pred, gimple_assign_rhs2 (def_stmt)))
2024 /* Mark a_pred for removal. */
2025 a_pred->pred_lhs = NULL;
2026 a_pred->pred_rhs = NULL;
2027 simplified = true;
2028 break;
2034 if (!simplified)
2035 return;
2037 for (i = 0; i < n; i++)
2039 pred_info *a_pred = &(*one_chain)[i];
2040 if (!a_pred->pred_lhs)
2041 continue;
2042 s_chain.safe_push (*a_pred);
2045 one_chain->release ();
2046 *one_chain = s_chain;
2049 /* The helper function implements the rule 2 for the
2050 OR predicate PREDS.
2052 2) (X AND Y) OR (!X AND Y) is equivalent to Y. */
2054 static bool
2055 simplify_preds_2 (pred_chain_union *preds)
2057 size_t i, j, n;
2058 bool simplified = false;
2059 pred_chain_union s_preds = vNULL;
2061 /* (X AND Y) OR (!X AND Y) is equivalent to Y.
2062 (X AND Y) OR (X AND !Y) is equivalent to X. */
2064 n = preds->length ();
2065 for (i = 0; i < n; i++)
2067 pred_info x, y;
2068 pred_chain *a_chain = &(*preds)[i];
2070 if (a_chain->length () != 2)
2071 continue;
2073 x = (*a_chain)[0];
2074 y = (*a_chain)[1];
2076 for (j = 0; j < n; j++)
2078 pred_chain *b_chain;
2079 pred_info x2, y2;
2081 if (j == i)
2082 continue;
2084 b_chain = &(*preds)[j];
2085 if (b_chain->length () != 2)
2086 continue;
2088 x2 = (*b_chain)[0];
2089 y2 = (*b_chain)[1];
2091 if (pred_equal_p (x, x2) && pred_neg_p (y, y2))
2093 /* Kill a_chain. */
2094 a_chain->release ();
2095 b_chain->release ();
2096 b_chain->safe_push (x);
2097 simplified = true;
2098 break;
2100 if (pred_neg_p (x, x2) && pred_equal_p (y, y2))
2102 /* Kill a_chain. */
2103 a_chain->release ();
2104 b_chain->release ();
2105 b_chain->safe_push (y);
2106 simplified = true;
2107 break;
2111 /* Now clean up the chain. */
2112 if (simplified)
2114 for (i = 0; i < n; i++)
2116 if ((*preds)[i].is_empty ())
2117 continue;
2118 s_preds.safe_push ((*preds)[i]);
2120 preds->release ();
2121 (*preds) = s_preds;
2122 s_preds = vNULL;
2125 return simplified;
2128 /* The helper function implements the rule 2 for the
2129 OR predicate PREDS.
2131 3) x OR (!x AND y) is equivalent to x OR y. */
2133 static bool
2134 simplify_preds_3 (pred_chain_union *preds)
2136 size_t i, j, n;
2137 bool simplified = false;
2139 /* Now iteratively simplify X OR (!X AND Z ..)
2140 into X OR (Z ...). */
2142 n = preds->length ();
2143 if (n < 2)
2144 return false;
2146 for (i = 0; i < n; i++)
2148 pred_info x;
2149 pred_chain *a_chain = &(*preds)[i];
2151 if (a_chain->length () != 1)
2152 continue;
2154 x = (*a_chain)[0];
2156 for (j = 0; j < n; j++)
2158 pred_chain *b_chain;
2159 pred_info x2;
2160 size_t k;
2162 if (j == i)
2163 continue;
2165 b_chain = &(*preds)[j];
2166 if (b_chain->length () < 2)
2167 continue;
2169 for (k = 0; k < b_chain->length (); k++)
2171 x2 = (*b_chain)[k];
2172 if (pred_neg_p (x, x2))
2174 b_chain->unordered_remove (k);
2175 simplified = true;
2176 break;
2181 return simplified;
2184 /* The helper function implements the rule 4 for the
2185 OR predicate PREDS.
2187 2) ((x AND y) != 0) OR (x != 0 AND y != 0) is equivalent to
2188 (x != 0 ANd y != 0). */
2190 static bool
2191 simplify_preds_4 (pred_chain_union *preds)
2193 size_t i, j, n;
2194 bool simplified = false;
2195 pred_chain_union s_preds = vNULL;
2196 gimple *def_stmt;
2198 n = preds->length ();
2199 for (i = 0; i < n; i++)
2201 pred_info z;
2202 pred_chain *a_chain = &(*preds)[i];
2204 if (a_chain->length () != 1)
2205 continue;
2207 z = (*a_chain)[0];
2209 if (!is_neq_zero_form_p (z))
2210 continue;
2212 def_stmt = SSA_NAME_DEF_STMT (z.pred_lhs);
2213 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2214 continue;
2216 if (gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2217 continue;
2219 for (j = 0; j < n; j++)
2221 pred_chain *b_chain;
2222 pred_info x2, y2;
2224 if (j == i)
2225 continue;
2227 b_chain = &(*preds)[j];
2228 if (b_chain->length () != 2)
2229 continue;
2231 x2 = (*b_chain)[0];
2232 y2 = (*b_chain)[1];
2233 if (!is_neq_zero_form_p (x2) || !is_neq_zero_form_p (y2))
2234 continue;
2236 if ((pred_expr_equal_p (x2, gimple_assign_rhs1 (def_stmt))
2237 && pred_expr_equal_p (y2, gimple_assign_rhs2 (def_stmt)))
2238 || (pred_expr_equal_p (x2, gimple_assign_rhs2 (def_stmt))
2239 && pred_expr_equal_p (y2, gimple_assign_rhs1 (def_stmt))))
2241 /* Kill a_chain. */
2242 a_chain->release ();
2243 simplified = true;
2244 break;
2248 /* Now clean up the chain. */
2249 if (simplified)
2251 for (i = 0; i < n; i++)
2253 if ((*preds)[i].is_empty ())
2254 continue;
2255 s_preds.safe_push ((*preds)[i]);
2258 preds->release ();
2259 (*preds) = s_preds;
2260 s_preds = vNULL;
2263 return simplified;
2266 /* This function simplifies predicates in PREDS. */
2268 static void
2269 simplify_preds (pred_chain_union *preds, gimple *use_or_def, bool is_use)
2271 size_t i, n;
2272 bool changed = false;
2274 if (dump_file && dump_flags & TDF_DETAILS)
2276 fprintf (dump_file, "[BEFORE SIMPLICATION -- ");
2277 dump_predicates (use_or_def, *preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2280 for (i = 0; i < preds->length (); i++)
2281 simplify_pred (&(*preds)[i]);
2283 n = preds->length ();
2284 if (n < 2)
2285 return;
2289 changed = false;
2290 if (simplify_preds_2 (preds))
2291 changed = true;
2293 /* Now iteratively simplify X OR (!X AND Z ..)
2294 into X OR (Z ...). */
2295 if (simplify_preds_3 (preds))
2296 changed = true;
2298 if (simplify_preds_4 (preds))
2299 changed = true;
2301 while (changed);
2303 return;
2306 /* This is a helper function which attempts to normalize predicate chains
2307 by following UD chains. It basically builds up a big tree of either IOR
2308 operations or AND operations, and convert the IOR tree into a
2309 pred_chain_union or BIT_AND tree into a pred_chain.
2310 Example:
2312 _3 = _2 RELOP1 _1;
2313 _6 = _5 RELOP2 _4;
2314 _9 = _8 RELOP3 _7;
2315 _10 = _3 | _6;
2316 _12 = _9 | _0;
2317 _t = _10 | _12;
2319 then _t != 0 will be normalized into a pred_chain_union
2321 (_2 RELOP1 _1) OR (_5 RELOP2 _4) OR (_8 RELOP3 _7) OR (_0 != 0)
2323 Similarly given,
2325 _3 = _2 RELOP1 _1;
2326 _6 = _5 RELOP2 _4;
2327 _9 = _8 RELOP3 _7;
2328 _10 = _3 & _6;
2329 _12 = _9 & _0;
2331 then _t != 0 will be normalized into a pred_chain:
2332 (_2 RELOP1 _1) AND (_5 RELOP2 _4) AND (_8 RELOP3 _7) AND (_0 != 0)
2336 /* This is a helper function that stores a PRED into NORM_PREDS. */
2338 inline static void
2339 push_pred (pred_chain_union *norm_preds, pred_info pred)
2341 pred_chain pred_chain = vNULL;
2342 pred_chain.safe_push (pred);
2343 norm_preds->safe_push (pred_chain);
2346 /* A helper function that creates a predicate of the form
2347 OP != 0 and push it WORK_LIST. */
2349 inline static void
2350 push_to_worklist (tree op, vec<pred_info, va_heap, vl_ptr> *work_list,
2351 hash_set<tree> *mark_set)
2353 if (mark_set->contains (op))
2354 return;
2355 mark_set->add (op);
2357 pred_info arg_pred;
2358 arg_pred.pred_lhs = op;
2359 arg_pred.pred_rhs = integer_zero_node;
2360 arg_pred.cond_code = NE_EXPR;
2361 arg_pred.invert = false;
2362 work_list->safe_push (arg_pred);
2365 /* A helper that generates a pred_info from a gimple assignment
2366 CMP_ASSIGN with comparison rhs. */
2368 static pred_info
2369 get_pred_info_from_cmp (gimple *cmp_assign)
2371 pred_info n_pred;
2372 n_pred.pred_lhs = gimple_assign_rhs1 (cmp_assign);
2373 n_pred.pred_rhs = gimple_assign_rhs2 (cmp_assign);
2374 n_pred.cond_code = gimple_assign_rhs_code (cmp_assign);
2375 n_pred.invert = false;
2376 return n_pred;
2379 /* Returns true if the PHI is a degenerated phi with
2380 all args with the same value (relop). In that case, *PRED
2381 will be updated to that value. */
2383 static bool
2384 is_degenerated_phi (gimple *phi, pred_info *pred_p)
2386 int i, n;
2387 tree op0;
2388 gimple *def0;
2389 pred_info pred0;
2391 n = gimple_phi_num_args (phi);
2392 op0 = gimple_phi_arg_def (phi, 0);
2394 if (TREE_CODE (op0) != SSA_NAME)
2395 return false;
2397 def0 = SSA_NAME_DEF_STMT (op0);
2398 if (gimple_code (def0) != GIMPLE_ASSIGN)
2399 return false;
2400 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def0)) != tcc_comparison)
2401 return false;
2402 pred0 = get_pred_info_from_cmp (def0);
2404 for (i = 1; i < n; ++i)
2406 gimple *def;
2407 pred_info pred;
2408 tree op = gimple_phi_arg_def (phi, i);
2410 if (TREE_CODE (op) != SSA_NAME)
2411 return false;
2413 def = SSA_NAME_DEF_STMT (op);
2414 if (gimple_code (def) != GIMPLE_ASSIGN)
2415 return false;
2416 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def)) != tcc_comparison)
2417 return false;
2418 pred = get_pred_info_from_cmp (def);
2419 if (!pred_equal_p (pred, pred0))
2420 return false;
2423 *pred_p = pred0;
2424 return true;
2427 /* Normalize one predicate PRED
2428 1) if PRED can no longer be normlized, put it into NORM_PREDS.
2429 2) otherwise if PRED is of the form x != 0, follow x's definition
2430 and put normalized predicates into WORK_LIST. */
2432 static void
2433 normalize_one_pred_1 (pred_chain_union *norm_preds,
2434 pred_chain *norm_chain,
2435 pred_info pred,
2436 enum tree_code and_or_code,
2437 vec<pred_info, va_heap, vl_ptr> *work_list,
2438 hash_set<tree> *mark_set)
2440 if (!is_neq_zero_form_p (pred))
2442 if (and_or_code == BIT_IOR_EXPR)
2443 push_pred (norm_preds, pred);
2444 else
2445 norm_chain->safe_push (pred);
2446 return;
2449 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2451 if (gimple_code (def_stmt) == GIMPLE_PHI
2452 && is_degenerated_phi (def_stmt, &pred))
2453 work_list->safe_push (pred);
2454 else if (gimple_code (def_stmt) == GIMPLE_PHI && and_or_code == BIT_IOR_EXPR)
2456 int i, n;
2457 n = gimple_phi_num_args (def_stmt);
2459 /* If we see non zero constant, we should punt. The predicate
2460 * should be one guarding the phi edge. */
2461 for (i = 0; i < n; ++i)
2463 tree op = gimple_phi_arg_def (def_stmt, i);
2464 if (TREE_CODE (op) == INTEGER_CST && !integer_zerop (op))
2466 push_pred (norm_preds, pred);
2467 return;
2471 for (i = 0; i < n; ++i)
2473 tree op = gimple_phi_arg_def (def_stmt, i);
2474 if (integer_zerop (op))
2475 continue;
2477 push_to_worklist (op, work_list, mark_set);
2480 else if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2482 if (and_or_code == BIT_IOR_EXPR)
2483 push_pred (norm_preds, pred);
2484 else
2485 norm_chain->safe_push (pred);
2487 else if (gimple_assign_rhs_code (def_stmt) == and_or_code)
2489 /* Avoid splitting up bit manipulations like x & 3 or y | 1. */
2490 if (is_gimple_min_invariant (gimple_assign_rhs2 (def_stmt)))
2492 /* But treat x & 3 as condition. */
2493 if (and_or_code == BIT_AND_EXPR)
2495 pred_info n_pred;
2496 n_pred.pred_lhs = gimple_assign_rhs1 (def_stmt);
2497 n_pred.pred_rhs = gimple_assign_rhs2 (def_stmt);
2498 n_pred.cond_code = and_or_code;
2499 n_pred.invert = false;
2500 norm_chain->safe_push (n_pred);
2503 else
2505 push_to_worklist (gimple_assign_rhs1 (def_stmt), work_list, mark_set);
2506 push_to_worklist (gimple_assign_rhs2 (def_stmt), work_list, mark_set);
2509 else if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2510 == tcc_comparison)
2512 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2513 if (and_or_code == BIT_IOR_EXPR)
2514 push_pred (norm_preds, n_pred);
2515 else
2516 norm_chain->safe_push (n_pred);
2518 else
2520 if (and_or_code == BIT_IOR_EXPR)
2521 push_pred (norm_preds, pred);
2522 else
2523 norm_chain->safe_push (pred);
2527 /* Normalize PRED and store the normalized predicates into NORM_PREDS. */
2529 static void
2530 normalize_one_pred (pred_chain_union *norm_preds, pred_info pred)
2532 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2533 enum tree_code and_or_code = ERROR_MARK;
2534 pred_chain norm_chain = vNULL;
2536 if (!is_neq_zero_form_p (pred))
2538 push_pred (norm_preds, pred);
2539 return;
2542 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2543 if (gimple_code (def_stmt) == GIMPLE_ASSIGN)
2544 and_or_code = gimple_assign_rhs_code (def_stmt);
2545 if (and_or_code != BIT_IOR_EXPR && and_or_code != BIT_AND_EXPR)
2547 if (TREE_CODE_CLASS (and_or_code) == tcc_comparison)
2549 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2550 push_pred (norm_preds, n_pred);
2552 else
2553 push_pred (norm_preds, pred);
2554 return;
2557 work_list.safe_push (pred);
2558 hash_set<tree> mark_set;
2560 while (!work_list.is_empty ())
2562 pred_info a_pred = work_list.pop ();
2563 normalize_one_pred_1 (norm_preds, &norm_chain, a_pred, and_or_code,
2564 &work_list, &mark_set);
2566 if (and_or_code == BIT_AND_EXPR)
2567 norm_preds->safe_push (norm_chain);
2569 work_list.release ();
2572 static void
2573 normalize_one_pred_chain (pred_chain_union *norm_preds, pred_chain one_chain)
2575 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2576 hash_set<tree> mark_set;
2577 pred_chain norm_chain = vNULL;
2578 size_t i;
2580 for (i = 0; i < one_chain.length (); i++)
2582 work_list.safe_push (one_chain[i]);
2583 mark_set.add (one_chain[i].pred_lhs);
2586 while (!work_list.is_empty ())
2588 pred_info a_pred = work_list.pop ();
2589 normalize_one_pred_1 (0, &norm_chain, a_pred, BIT_AND_EXPR, &work_list,
2590 &mark_set);
2593 norm_preds->safe_push (norm_chain);
2594 work_list.release ();
2597 /* Normalize predicate chains PREDS and returns the normalized one. */
2599 static pred_chain_union
2600 normalize_preds (pred_chain_union preds, gimple *use_or_def, bool is_use)
2602 pred_chain_union norm_preds = vNULL;
2603 size_t n = preds.length ();
2604 size_t i;
2606 if (dump_file && dump_flags & TDF_DETAILS)
2608 fprintf (dump_file, "[BEFORE NORMALIZATION --");
2609 dump_predicates (use_or_def, preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2612 for (i = 0; i < n; i++)
2614 if (preds[i].length () != 1)
2615 normalize_one_pred_chain (&norm_preds, preds[i]);
2616 else
2618 normalize_one_pred (&norm_preds, preds[i][0]);
2619 preds[i].release ();
2623 if (dump_file)
2625 fprintf (dump_file, "[AFTER NORMALIZATION -- ");
2626 dump_predicates (use_or_def, norm_preds,
2627 is_use ? "[USE]:\n" : "[DEF]:\n");
2630 destroy_predicate_vecs (&preds);
2631 return norm_preds;
2634 /* Return TRUE if PREDICATE can be invalidated by any individual
2635 predicate in USE_GUARD. */
2637 static bool
2638 can_one_predicate_be_invalidated_p (pred_info predicate,
2639 pred_chain use_guard)
2641 if (dump_file && dump_flags & TDF_DETAILS)
2643 fprintf (dump_file, "Testing if this predicate: ");
2644 dump_pred_info (predicate);
2645 fprintf (dump_file, "\n...can be invalidated by a USE guard of: ");
2646 dump_pred_chain (use_guard);
2648 for (size_t i = 0; i < use_guard.length (); ++i)
2650 /* NOTE: This is a very simple check, and only understands an
2651 exact opposite. So, [i == 0] is currently only invalidated
2652 by [.NOT. i == 0] or [i != 0]. Ideally we should also
2653 invalidate with say [i > 5] or [i == 8]. There is certainly
2654 room for improvement here. */
2655 if (pred_neg_p (predicate, use_guard[i]))
2657 if (dump_file && dump_flags & TDF_DETAILS)
2659 fprintf (dump_file, " Predicate was invalidated by: ");
2660 dump_pred_info (use_guard[i]);
2661 fputc ('\n', dump_file);
2663 return true;
2666 return false;
2669 /* Return TRUE if all predicates in UNINIT_PRED are invalidated by
2670 USE_GUARD being true. */
2672 static bool
2673 can_chain_union_be_invalidated_p (pred_chain_union uninit_pred,
2674 pred_chain use_guard)
2676 if (uninit_pred.is_empty ())
2677 return false;
2678 if (dump_file && dump_flags & TDF_DETAILS)
2679 dump_predicates (NULL, uninit_pred,
2680 "Testing if anything here can be invalidated: ");
2681 for (size_t i = 0; i < uninit_pred.length (); ++i)
2683 pred_chain c = uninit_pred[i];
2684 size_t j;
2685 for (j = 0; j < c.length (); ++j)
2686 if (can_one_predicate_be_invalidated_p (c[j], use_guard))
2687 break;
2689 /* If we were unable to invalidate any predicate in C, then there
2690 is a viable path from entry to the PHI where the PHI takes
2691 an uninitialized value and continues to a use of the PHI. */
2692 if (j == c.length ())
2693 return false;
2695 return true;
2698 /* Return TRUE if none of the uninitialized operands in UNINT_OPNDS
2699 can actually happen if we arrived at a use for PHI.
2701 PHI_USE_GUARDS are the guard conditions for the use of the PHI. */
2703 static bool
2704 uninit_uses_cannot_happen (gphi *phi, unsigned uninit_opnds,
2705 pred_chain_union phi_use_guards)
2707 unsigned phi_args = gimple_phi_num_args (phi);
2708 if (phi_args > max_phi_args)
2709 return false;
2711 /* PHI_USE_GUARDS are OR'ed together. If we have more than one
2712 possible guard, there's no way of knowing which guard was true.
2713 Since we need to be absolutely sure that the uninitialized
2714 operands will be invalidated, bail. */
2715 if (phi_use_guards.length () != 1)
2716 return false;
2718 /* Look for the control dependencies of all the uninitialized
2719 operands and build guard predicates describing them. */
2720 pred_chain_union uninit_preds;
2721 bool ret = true;
2722 for (unsigned i = 0; i < phi_args; ++i)
2724 if (!MASK_TEST_BIT (uninit_opnds, i))
2725 continue;
2727 edge e = gimple_phi_arg_edge (phi, i);
2728 vec<edge> dep_chains[MAX_NUM_CHAINS];
2729 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
2730 size_t num_chains = 0;
2731 int num_calls = 0;
2733 /* Build the control dependency chain for uninit operand `i'... */
2734 uninit_preds = vNULL;
2735 if (!compute_control_dep_chain (ENTRY_BLOCK_PTR_FOR_FN (cfun),
2736 e->src, dep_chains, &num_chains,
2737 &cur_chain, &num_calls))
2739 ret = false;
2740 break;
2742 /* ...and convert it into a set of predicates. */
2743 bool has_valid_preds
2744 = convert_control_dep_chain_into_preds (dep_chains, num_chains,
2745 &uninit_preds);
2746 for (size_t j = 0; j < num_chains; ++j)
2747 dep_chains[j].release ();
2748 if (!has_valid_preds)
2750 ret = false;
2751 break;
2753 simplify_preds (&uninit_preds, NULL, false);
2754 uninit_preds = normalize_preds (uninit_preds, NULL, false);
2756 /* Can the guard for this uninitialized operand be invalidated
2757 by the PHI use? */
2758 if (!can_chain_union_be_invalidated_p (uninit_preds, phi_use_guards[0]))
2760 ret = false;
2761 break;
2764 destroy_predicate_vecs (&uninit_preds);
2765 return ret;
2768 /* Computes the predicates that guard the use and checks
2769 if the incoming paths that have empty (or possibly
2770 empty) definition can be pruned/filtered. The function returns
2771 true if it can be determined that the use of PHI's def in
2772 USE_STMT is guarded with a predicate set not overlapping with
2773 predicate sets of all runtime paths that do not have a definition.
2775 Returns false if it is not or it cannot be determined. USE_BB is
2776 the bb of the use (for phi operand use, the bb is not the bb of
2777 the phi stmt, but the src bb of the operand edge).
2779 UNINIT_OPNDS is a bit vector. If an operand of PHI is uninitialized, the
2780 corresponding bit in the vector is 1. VISITED_PHIS is a pointer
2781 set of phis being visited.
2783 *DEF_PREDS contains the (memoized) defining predicate chains of PHI.
2784 If *DEF_PREDS is the empty vector, the defining predicate chains of
2785 PHI will be computed and stored into *DEF_PREDS as needed.
2787 VISITED_PHIS is a pointer set of phis being visited. */
2789 static bool
2790 is_use_properly_guarded (gimple *use_stmt,
2791 basic_block use_bb,
2792 gphi *phi,
2793 unsigned uninit_opnds,
2794 pred_chain_union *def_preds,
2795 hash_set<gphi *> *visited_phis)
2797 basic_block phi_bb;
2798 pred_chain_union preds = vNULL;
2799 bool has_valid_preds = false;
2800 bool is_properly_guarded = false;
2802 if (visited_phis->add (phi))
2803 return false;
2805 phi_bb = gimple_bb (phi);
2807 if (is_non_loop_exit_postdominating (use_bb, phi_bb))
2808 return false;
2810 has_valid_preds = find_predicates (&preds, phi_bb, use_bb);
2812 if (!has_valid_preds)
2814 destroy_predicate_vecs (&preds);
2815 return false;
2818 /* Try to prune the dead incoming phi edges. */
2819 is_properly_guarded
2820 = use_pred_not_overlap_with_undef_path_pred (preds, phi, uninit_opnds,
2821 visited_phis);
2823 /* We might be able to prove that if the control dependencies
2824 for UNINIT_OPNDS are true, that the control dependencies for
2825 USE_STMT can never be true. */
2826 if (!is_properly_guarded)
2827 is_properly_guarded |= uninit_uses_cannot_happen (phi, uninit_opnds,
2828 preds);
2830 if (is_properly_guarded)
2832 destroy_predicate_vecs (&preds);
2833 return true;
2836 if (def_preds->is_empty ())
2838 has_valid_preds = find_def_preds (def_preds, phi);
2840 if (!has_valid_preds)
2842 destroy_predicate_vecs (&preds);
2843 return false;
2846 simplify_preds (def_preds, phi, false);
2847 *def_preds = normalize_preds (*def_preds, phi, false);
2850 simplify_preds (&preds, use_stmt, true);
2851 preds = normalize_preds (preds, use_stmt, true);
2853 is_properly_guarded = is_superset_of (*def_preds, preds);
2855 destroy_predicate_vecs (&preds);
2856 return is_properly_guarded;
2859 /* Searches through all uses of a potentially
2860 uninitialized variable defined by PHI and returns a use
2861 statement if the use is not properly guarded. It returns
2862 NULL if all uses are guarded. UNINIT_OPNDS is a bitvector
2863 holding the position(s) of uninit PHI operands. WORKLIST
2864 is the vector of candidate phis that may be updated by this
2865 function. ADDED_TO_WORKLIST is the pointer set tracking
2866 if the new phi is already in the worklist. */
2868 static gimple *
2869 find_uninit_use (gphi *phi, unsigned uninit_opnds,
2870 vec<gphi *> *worklist,
2871 hash_set<gphi *> *added_to_worklist)
2873 tree phi_result;
2874 use_operand_p use_p;
2875 gimple *use_stmt;
2876 imm_use_iterator iter;
2877 pred_chain_union def_preds = vNULL;
2878 gimple *ret = NULL;
2880 phi_result = gimple_phi_result (phi);
2882 FOR_EACH_IMM_USE_FAST (use_p, iter, phi_result)
2884 basic_block use_bb;
2886 use_stmt = USE_STMT (use_p);
2887 if (is_gimple_debug (use_stmt))
2888 continue;
2890 if (gphi *use_phi = dyn_cast<gphi *> (use_stmt))
2891 use_bb = gimple_phi_arg_edge (use_phi,
2892 PHI_ARG_INDEX_FROM_USE (use_p))->src;
2893 else
2894 use_bb = gimple_bb (use_stmt);
2896 hash_set<gphi *> visited_phis;
2897 if (is_use_properly_guarded (use_stmt, use_bb, phi, uninit_opnds,
2898 &def_preds, &visited_phis))
2899 continue;
2901 if (dump_file && (dump_flags & TDF_DETAILS))
2903 fprintf (dump_file, "[CHECK]: Found unguarded use: ");
2904 print_gimple_stmt (dump_file, use_stmt, 0);
2906 /* Found one real use, return. */
2907 if (gimple_code (use_stmt) != GIMPLE_PHI)
2909 ret = use_stmt;
2910 break;
2913 /* Found a phi use that is not guarded,
2914 add the phi to the worklist. */
2915 if (!added_to_worklist->add (as_a<gphi *> (use_stmt)))
2917 if (dump_file && (dump_flags & TDF_DETAILS))
2919 fprintf (dump_file, "[WORKLIST]: Update worklist with phi: ");
2920 print_gimple_stmt (dump_file, use_stmt, 0);
2923 worklist->safe_push (as_a<gphi *> (use_stmt));
2924 possibly_undefined_names->add (phi_result);
2928 destroy_predicate_vecs (&def_preds);
2929 return ret;
2932 /* Look for inputs to PHI that are SSA_NAMEs that have empty definitions
2933 and gives warning if there exists a runtime path from the entry to a
2934 use of the PHI def that does not contain a definition. In other words,
2935 the warning is on the real use. The more dead paths that can be pruned
2936 by the compiler, the fewer false positives the warning is. WORKLIST
2937 is a vector of candidate phis to be examined. ADDED_TO_WORKLIST is
2938 a pointer set tracking if the new phi is added to the worklist or not. */
2940 static void
2941 warn_uninitialized_phi (gphi *phi, vec<gphi *> *worklist,
2942 hash_set<gphi *> *added_to_worklist)
2944 unsigned uninit_opnds;
2945 gimple *uninit_use_stmt = 0;
2946 tree uninit_op;
2947 int phiarg_index;
2948 location_t loc;
2950 /* Don't look at virtual operands. */
2951 if (virtual_operand_p (gimple_phi_result (phi)))
2952 return;
2954 uninit_opnds = compute_uninit_opnds_pos (phi);
2956 if (MASK_EMPTY (uninit_opnds))
2957 return;
2959 if (dump_file && (dump_flags & TDF_DETAILS))
2961 fprintf (dump_file, "[CHECK]: examining phi: ");
2962 print_gimple_stmt (dump_file, phi, 0);
2965 /* Now check if we have any use of the value without proper guard. */
2966 uninit_use_stmt = find_uninit_use (phi, uninit_opnds,
2967 worklist, added_to_worklist);
2969 /* All uses are properly guarded. */
2970 if (!uninit_use_stmt)
2971 return;
2973 phiarg_index = MASK_FIRST_SET_BIT (uninit_opnds);
2974 uninit_op = gimple_phi_arg_def (phi, phiarg_index);
2975 if (SSA_NAME_VAR (uninit_op) == NULL_TREE)
2976 return;
2977 if (gimple_phi_arg_has_location (phi, phiarg_index))
2978 loc = gimple_phi_arg_location (phi, phiarg_index);
2979 else
2980 loc = UNKNOWN_LOCATION;
2981 warn_uninit (OPT_Wmaybe_uninitialized, uninit_op, SSA_NAME_VAR (uninit_op),
2982 SSA_NAME_VAR (uninit_op),
2983 "%qD may be used uninitialized in this function",
2984 uninit_use_stmt, loc);
2987 static bool
2988 gate_warn_uninitialized (void)
2990 return warn_uninitialized || warn_maybe_uninitialized;
2993 namespace {
2995 const pass_data pass_data_late_warn_uninitialized =
2997 GIMPLE_PASS, /* type */
2998 "uninit", /* name */
2999 OPTGROUP_NONE, /* optinfo_flags */
3000 TV_NONE, /* tv_id */
3001 PROP_ssa, /* properties_required */
3002 0, /* properties_provided */
3003 0, /* properties_destroyed */
3004 0, /* todo_flags_start */
3005 0, /* todo_flags_finish */
3008 class pass_late_warn_uninitialized : public gimple_opt_pass
3010 public:
3011 pass_late_warn_uninitialized (gcc::context *ctxt)
3012 : gimple_opt_pass (pass_data_late_warn_uninitialized, ctxt)
3015 /* opt_pass methods: */
3016 opt_pass *clone () { return new pass_late_warn_uninitialized (m_ctxt); }
3017 virtual bool gate (function *) { return gate_warn_uninitialized (); }
3018 virtual unsigned int execute (function *);
3020 }; // class pass_late_warn_uninitialized
3022 unsigned int
3023 pass_late_warn_uninitialized::execute (function *fun)
3025 basic_block bb;
3026 gphi_iterator gsi;
3027 vec<gphi *> worklist = vNULL;
3029 calculate_dominance_info (CDI_DOMINATORS);
3030 calculate_dominance_info (CDI_POST_DOMINATORS);
3031 /* Re-do the plain uninitialized variable check, as optimization may have
3032 straightened control flow. Do this first so that we don't accidentally
3033 get a "may be" warning when we'd have seen an "is" warning later. */
3034 warn_uninitialized_vars (/*warn_maybe_uninitialized=*/1);
3036 timevar_push (TV_TREE_UNINIT);
3038 possibly_undefined_names = new hash_set<tree>;
3039 hash_set<gphi *> added_to_worklist;
3041 /* Initialize worklist */
3042 FOR_EACH_BB_FN (bb, fun)
3043 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3045 gphi *phi = gsi.phi ();
3046 size_t n, i;
3048 n = gimple_phi_num_args (phi);
3050 /* Don't look at virtual operands. */
3051 if (virtual_operand_p (gimple_phi_result (phi)))
3052 continue;
3054 for (i = 0; i < n; ++i)
3056 tree op = gimple_phi_arg_def (phi, i);
3057 if (TREE_CODE (op) == SSA_NAME && uninit_undefined_value_p (op))
3059 worklist.safe_push (phi);
3060 added_to_worklist.add (phi);
3061 if (dump_file && (dump_flags & TDF_DETAILS))
3063 fprintf (dump_file, "[WORKLIST]: add to initial list: ");
3064 print_gimple_stmt (dump_file, phi, 0);
3066 break;
3071 while (worklist.length () != 0)
3073 gphi *cur_phi = 0;
3074 cur_phi = worklist.pop ();
3075 warn_uninitialized_phi (cur_phi, &worklist, &added_to_worklist);
3078 worklist.release ();
3079 delete possibly_undefined_names;
3080 possibly_undefined_names = NULL;
3081 free_dominance_info (CDI_POST_DOMINATORS);
3082 timevar_pop (TV_TREE_UNINIT);
3083 return 0;
3086 } // anon namespace
3088 gimple_opt_pass *
3089 make_pass_late_warn_uninitialized (gcc::context *ctxt)
3091 return new pass_late_warn_uninitialized (ctxt);
3094 static unsigned int
3095 execute_early_warn_uninitialized (void)
3097 /* Currently, this pass runs always but
3098 execute_late_warn_uninitialized only runs with optimization. With
3099 optimization we want to warn about possible uninitialized as late
3100 as possible, thus don't do it here. However, without
3101 optimization we need to warn here about "may be uninitialized". */
3102 calculate_dominance_info (CDI_POST_DOMINATORS);
3104 warn_uninitialized_vars (/*warn_maybe_uninitialized=*/!optimize);
3106 /* Post-dominator information cannot be reliably updated. Free it
3107 after the use. */
3109 free_dominance_info (CDI_POST_DOMINATORS);
3110 return 0;
3113 namespace {
3115 const pass_data pass_data_early_warn_uninitialized =
3117 GIMPLE_PASS, /* type */
3118 "*early_warn_uninitialized", /* name */
3119 OPTGROUP_NONE, /* optinfo_flags */
3120 TV_TREE_UNINIT, /* tv_id */
3121 PROP_ssa, /* properties_required */
3122 0, /* properties_provided */
3123 0, /* properties_destroyed */
3124 0, /* todo_flags_start */
3125 0, /* todo_flags_finish */
3128 class pass_early_warn_uninitialized : public gimple_opt_pass
3130 public:
3131 pass_early_warn_uninitialized (gcc::context *ctxt)
3132 : gimple_opt_pass (pass_data_early_warn_uninitialized, ctxt)
3135 /* opt_pass methods: */
3136 virtual bool gate (function *) { return gate_warn_uninitialized (); }
3137 virtual unsigned int execute (function *)
3139 return execute_early_warn_uninitialized ();
3142 }; // class pass_early_warn_uninitialized
3144 } // anon namespace
3146 gimple_opt_pass *
3147 make_pass_early_warn_uninitialized (gcc::context *ctxt)
3149 return new pass_early_warn_uninitialized (ctxt);