gcc/ChangeLog:
[official-gcc.git] / gcc / tree-ssa-uninit.c
blobb587599f8f87acf70d21e6cbcfc445a88f5c5a29
1 /* Predicate aware uninitialized variable warning.
2 Copyright (C) 2001-2017 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 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "tree-ssa.h"
34 #include "params.h"
35 #include "tree-cfg.h"
37 /* This implements the pass that does predicate aware warning on uses of
38 possibly uninitialized variables. The pass first collects the set of
39 possibly uninitialized SSA names. For each such name, it walks through
40 all its immediate uses. For each immediate use, it rebuilds the condition
41 expression (the predicate) that guards the use. The predicate is then
42 examined to see if the variable is always defined under that same condition.
43 This is done either by pruning the unrealizable paths that lead to the
44 default definitions or by checking if the predicate set that guards the
45 defining paths is a superset of the use predicate. */
47 /* Max PHI args we can handle in pass. */
48 const unsigned max_phi_args = 32;
50 /* Pointer set of potentially undefined ssa names, i.e.,
51 ssa names that are defined by phi with operands that
52 are not defined or potentially undefined. */
53 static hash_set<tree> *possibly_undefined_names = 0;
55 /* Bit mask handling macros. */
56 #define MASK_SET_BIT(mask, pos) mask |= (1 << pos)
57 #define MASK_TEST_BIT(mask, pos) (mask & (1 << pos))
58 #define MASK_EMPTY(mask) (mask == 0)
60 /* Returns the first bit position (starting from LSB)
61 in mask that is non zero. Returns -1 if the mask is empty. */
62 static int
63 get_mask_first_set_bit (unsigned mask)
65 int pos = 0;
66 if (mask == 0)
67 return -1;
69 while ((mask & (1 << pos)) == 0)
70 pos++;
72 return pos;
74 #define MASK_FIRST_SET_BIT(mask) get_mask_first_set_bit (mask)
76 /* Return true if T, an SSA_NAME, has an undefined value. */
77 static bool
78 has_undefined_value_p (tree t)
80 return (ssa_undefined_value_p (t)
81 || (possibly_undefined_names
82 && possibly_undefined_names->contains (t)));
85 /* Like has_undefined_value_p, but don't return true if TREE_NO_WARNING
86 is set on SSA_NAME_VAR. */
88 static inline bool
89 uninit_undefined_value_p (tree t)
91 if (!has_undefined_value_p (t))
92 return false;
93 if (SSA_NAME_VAR (t) && TREE_NO_WARNING (SSA_NAME_VAR (t)))
94 return false;
95 return true;
98 /* Emit warnings for uninitialized variables. This is done in two passes.
100 The first pass notices real uses of SSA names with undefined values.
101 Such uses are unconditionally uninitialized, and we can be certain that
102 such a use is a mistake. This pass is run before most optimizations,
103 so that we catch as many as we can.
105 The second pass follows PHI nodes to find uses that are potentially
106 uninitialized. In this case we can't necessarily prove that the use
107 is really uninitialized. This pass is run after most optimizations,
108 so that we thread as many jumps and possible, and delete as much dead
109 code as possible, in order to reduce false positives. We also look
110 again for plain uninitialized variables, since optimization may have
111 changed conditionally uninitialized to unconditionally uninitialized. */
113 /* Emit a warning for EXPR based on variable VAR at the point in the
114 program T, an SSA_NAME, is used being uninitialized. The exact
115 warning text is in MSGID and DATA is the gimple stmt with info about
116 the location in source code. When DATA is a GIMPLE_PHI, PHIARG_IDX
117 gives which argument of the phi node to take the location from. WC
118 is the warning code. */
120 static void
121 warn_uninit (enum opt_code wc, tree t, tree expr, tree var,
122 const char *gmsgid, void *data, location_t phiarg_loc)
124 gimple *context = (gimple *) data;
125 location_t location, cfun_loc;
126 expanded_location xloc, floc;
128 /* Ignore COMPLEX_EXPR as initializing only a part of a complex
129 turns in a COMPLEX_EXPR with the not initialized part being
130 set to its previous (undefined) value. */
131 if (is_gimple_assign (context)
132 && gimple_assign_rhs_code (context) == COMPLEX_EXPR)
133 return;
134 if (!has_undefined_value_p (t))
135 return;
137 /* Anonymous SSA_NAMEs shouldn't be uninitialized, but ssa_undefined_value_p
138 can return true if the def stmt of anonymous SSA_NAME is COMPLEX_EXPR
139 created for conversion from scalar to complex. Use the underlying var of
140 the COMPLEX_EXPRs real part in that case. See PR71581. */
141 if (expr == NULL_TREE
142 && var == NULL_TREE
143 && SSA_NAME_VAR (t) == NULL_TREE
144 && is_gimple_assign (SSA_NAME_DEF_STMT (t))
145 && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (t)) == COMPLEX_EXPR)
147 tree v = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (t));
148 if (TREE_CODE (v) == SSA_NAME
149 && has_undefined_value_p (v)
150 && zerop (gimple_assign_rhs2 (SSA_NAME_DEF_STMT (t))))
152 expr = SSA_NAME_VAR (v);
153 var = expr;
157 if (expr == NULL_TREE)
158 return;
160 /* TREE_NO_WARNING either means we already warned, or the front end
161 wishes to suppress the warning. */
162 if ((context
163 && (gimple_no_warning_p (context)
164 || (gimple_assign_single_p (context)
165 && TREE_NO_WARNING (gimple_assign_rhs1 (context)))))
166 || TREE_NO_WARNING (expr))
167 return;
169 if (context != NULL && gimple_has_location (context))
170 location = gimple_location (context);
171 else if (phiarg_loc != UNKNOWN_LOCATION)
172 location = phiarg_loc;
173 else
174 location = DECL_SOURCE_LOCATION (var);
175 location = linemap_resolve_location (line_table, location,
176 LRK_SPELLING_LOCATION, NULL);
177 cfun_loc = DECL_SOURCE_LOCATION (cfun->decl);
178 xloc = expand_location (location);
179 floc = expand_location (cfun_loc);
180 if (warning_at (location, wc, gmsgid, expr))
182 TREE_NO_WARNING (expr) = 1;
184 if (location == DECL_SOURCE_LOCATION (var))
185 return;
186 if (xloc.file != floc.file
187 || linemap_location_before_p (line_table, location, cfun_loc)
188 || linemap_location_before_p (line_table, cfun->function_end_locus,
189 location))
190 inform (DECL_SOURCE_LOCATION (var), "%qD was declared here", var);
194 struct check_defs_data
196 /* If we found any may-defs besides must-def clobbers. */
197 bool found_may_defs;
200 /* Callback for walk_aliased_vdefs. */
202 static bool
203 check_defs (ao_ref *ref, tree vdef, void *data_)
205 check_defs_data *data = (check_defs_data *)data_;
206 gimple *def_stmt = SSA_NAME_DEF_STMT (vdef);
207 /* If this is a clobber then if it is not a kill walk past it. */
208 if (gimple_clobber_p (def_stmt))
210 if (stmt_kills_ref_p (def_stmt, ref))
211 return true;
212 return false;
214 /* Found a may-def on this path. */
215 data->found_may_defs = true;
216 return true;
219 static unsigned int
220 warn_uninitialized_vars (bool warn_possibly_uninitialized)
222 gimple_stmt_iterator gsi;
223 basic_block bb;
224 unsigned int vdef_cnt = 0;
225 unsigned int oracle_cnt = 0;
226 unsigned limit = 0;
228 FOR_EACH_BB_FN (bb, cfun)
230 basic_block succ = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
231 bool always_executed = dominated_by_p (CDI_POST_DOMINATORS, succ, bb);
232 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
234 gimple *stmt = gsi_stmt (gsi);
235 use_operand_p use_p;
236 ssa_op_iter op_iter;
237 tree use;
239 if (is_gimple_debug (stmt))
240 continue;
242 /* We only do data flow with SSA_NAMEs, so that's all we
243 can warn about. */
244 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, op_iter, SSA_OP_USE)
246 /* BIT_INSERT_EXPR first operand should not be considered
247 a use for the purpose of uninit warnings. */
248 if (gassign *ass = dyn_cast <gassign *> (stmt))
250 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
251 && use_p->use == gimple_assign_rhs1_ptr (ass))
252 continue;
254 use = USE_FROM_PTR (use_p);
255 if (always_executed)
256 warn_uninit (OPT_Wuninitialized, use, SSA_NAME_VAR (use),
257 SSA_NAME_VAR (use),
258 "%qD is used uninitialized in this function", stmt,
259 UNKNOWN_LOCATION);
260 else if (warn_possibly_uninitialized)
261 warn_uninit (OPT_Wmaybe_uninitialized, use, SSA_NAME_VAR (use),
262 SSA_NAME_VAR (use),
263 "%qD may be used uninitialized in this function",
264 stmt, UNKNOWN_LOCATION);
267 /* For limiting the alias walk below we count all
268 vdefs in the function. */
269 if (gimple_vdef (stmt))
270 vdef_cnt++;
272 if (gimple_assign_load_p (stmt)
273 && gimple_has_location (stmt))
275 tree rhs = gimple_assign_rhs1 (stmt);
276 if (TREE_NO_WARNING (rhs))
277 continue;
279 ao_ref ref;
280 ao_ref_init (&ref, rhs);
282 /* Do not warn if the base was marked so or this is a
283 hard register var. */
284 tree base = ao_ref_base (&ref);
285 if ((VAR_P (base)
286 && DECL_HARD_REGISTER (base))
287 || TREE_NO_WARNING (base))
288 continue;
290 /* Do not warn if the access is fully outside of the
291 variable. */
292 if (DECL_P (base)
293 && ref.size != -1
294 && ref.max_size == ref.size
295 && (ref.offset + ref.size <= 0
296 || (ref.offset >= 0
297 && DECL_SIZE (base)
298 && TREE_CODE (DECL_SIZE (base)) == INTEGER_CST
299 && compare_tree_int (DECL_SIZE (base),
300 ref.offset) <= 0)))
301 continue;
303 /* Limit the walking to a constant number of stmts after
304 we overcommit quadratic behavior for small functions
305 and O(n) behavior. */
306 if (oracle_cnt > 128 * 128
307 && oracle_cnt > vdef_cnt * 2)
308 limit = 32;
309 check_defs_data data;
310 bool fentry_reached = false;
311 data.found_may_defs = false;
312 use = gimple_vuse (stmt);
313 int res = walk_aliased_vdefs (&ref, use,
314 check_defs, &data, NULL,
315 &fentry_reached, limit);
316 if (res == -1)
318 oracle_cnt += limit;
319 continue;
321 oracle_cnt += res;
322 if (data.found_may_defs)
323 continue;
324 /* Do not warn if it can be initialized outside this function.
325 If we did not reach function entry then we found killing
326 clobbers on all paths to entry. */
327 if (fentry_reached
328 /* ??? We'd like to use ref_may_alias_global_p but that
329 excludes global readonly memory and thus we get bougs
330 warnings from p = cond ? "a" : "b" for example. */
331 && (!VAR_P (base)
332 || is_global_var (base)))
333 continue;
335 /* We didn't find any may-defs so on all paths either
336 reached function entry or a killing clobber. */
337 location_t location
338 = linemap_resolve_location (line_table, gimple_location (stmt),
339 LRK_SPELLING_LOCATION, NULL);
340 if (always_executed)
342 if (warning_at (location, OPT_Wuninitialized,
343 "%qE is used uninitialized in this function",
344 rhs))
345 /* ??? This is only effective for decls as in
346 gcc.dg/uninit-B-O0.c. Avoid doing this for
347 maybe-uninit uses as it may hide important
348 locations. */
349 TREE_NO_WARNING (rhs) = 1;
351 else if (warn_possibly_uninitialized)
352 warning_at (location, OPT_Wmaybe_uninitialized,
353 "%qE may be used uninitialized in this function",
354 rhs);
359 return 0;
362 /* Checks if the operand OPND of PHI is defined by
363 another phi with one operand defined by this PHI,
364 but the rest operands are all defined. If yes,
365 returns true to skip this operand as being
366 redundant. Can be enhanced to be more general. */
368 static bool
369 can_skip_redundant_opnd (tree opnd, gimple *phi)
371 gimple *op_def;
372 tree phi_def;
373 int i, n;
375 phi_def = gimple_phi_result (phi);
376 op_def = SSA_NAME_DEF_STMT (opnd);
377 if (gimple_code (op_def) != GIMPLE_PHI)
378 return false;
379 n = gimple_phi_num_args (op_def);
380 for (i = 0; i < n; ++i)
382 tree op = gimple_phi_arg_def (op_def, i);
383 if (TREE_CODE (op) != SSA_NAME)
384 continue;
385 if (op != phi_def && uninit_undefined_value_p (op))
386 return false;
389 return true;
392 /* Returns a bit mask holding the positions of arguments in PHI
393 that have empty (or possibly empty) definitions. */
395 static unsigned
396 compute_uninit_opnds_pos (gphi *phi)
398 size_t i, n;
399 unsigned uninit_opnds = 0;
401 n = gimple_phi_num_args (phi);
402 /* Bail out for phi with too many args. */
403 if (n > max_phi_args)
404 return 0;
406 for (i = 0; i < n; ++i)
408 tree op = gimple_phi_arg_def (phi, i);
409 if (TREE_CODE (op) == SSA_NAME
410 && uninit_undefined_value_p (op)
411 && !can_skip_redundant_opnd (op, phi))
413 if (cfun->has_nonlocal_label || cfun->calls_setjmp)
415 /* Ignore SSA_NAMEs that appear on abnormal edges
416 somewhere. */
417 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
418 continue;
420 MASK_SET_BIT (uninit_opnds, i);
423 return uninit_opnds;
426 /* Find the immediate postdominator PDOM of the specified
427 basic block BLOCK. */
429 static inline basic_block
430 find_pdom (basic_block block)
432 if (block == EXIT_BLOCK_PTR_FOR_FN (cfun))
433 return EXIT_BLOCK_PTR_FOR_FN (cfun);
434 else
436 basic_block bb = get_immediate_dominator (CDI_POST_DOMINATORS, block);
437 if (!bb)
438 return EXIT_BLOCK_PTR_FOR_FN (cfun);
439 return bb;
443 /* Find the immediate DOM of the specified basic block BLOCK. */
445 static inline basic_block
446 find_dom (basic_block block)
448 if (block == ENTRY_BLOCK_PTR_FOR_FN (cfun))
449 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
450 else
452 basic_block bb = get_immediate_dominator (CDI_DOMINATORS, block);
453 if (!bb)
454 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
455 return bb;
459 /* Returns true if BB1 is postdominating BB2 and BB1 is
460 not a loop exit bb. The loop exit bb check is simple and does
461 not cover all cases. */
463 static bool
464 is_non_loop_exit_postdominating (basic_block bb1, basic_block bb2)
466 if (!dominated_by_p (CDI_POST_DOMINATORS, bb2, bb1))
467 return false;
469 if (single_pred_p (bb1) && !single_succ_p (bb2))
470 return false;
472 return true;
475 /* Find the closest postdominator of a specified BB, which is control
476 equivalent to BB. */
478 static inline basic_block
479 find_control_equiv_block (basic_block bb)
481 basic_block pdom;
483 pdom = find_pdom (bb);
485 /* Skip the postdominating bb that is also loop exit. */
486 if (!is_non_loop_exit_postdominating (pdom, bb))
487 return NULL;
489 if (dominated_by_p (CDI_DOMINATORS, pdom, bb))
490 return pdom;
492 return NULL;
495 #define MAX_NUM_CHAINS 8
496 #define MAX_CHAIN_LEN 5
497 #define MAX_POSTDOM_CHECK 8
498 #define MAX_SWITCH_CASES 40
500 /* Computes the control dependence chains (paths of edges)
501 for DEP_BB up to the dominating basic block BB (the head node of a
502 chain should be dominated by it). CD_CHAINS is pointer to an
503 array holding the result chains. CUR_CD_CHAIN is the current
504 chain being computed. *NUM_CHAINS is total number of chains. The
505 function returns true if the information is successfully computed,
506 return false if there is no control dependence or not computed. */
508 static bool
509 compute_control_dep_chain (basic_block bb, basic_block dep_bb,
510 vec<edge> *cd_chains,
511 size_t *num_chains,
512 vec<edge> *cur_cd_chain,
513 int *num_calls)
515 edge_iterator ei;
516 edge e;
517 size_t i;
518 bool found_cd_chain = false;
519 size_t cur_chain_len = 0;
521 if (EDGE_COUNT (bb->succs) < 2)
522 return false;
524 if (*num_calls > PARAM_VALUE (PARAM_UNINIT_CONTROL_DEP_ATTEMPTS))
525 return false;
526 ++*num_calls;
528 /* Could use a set instead. */
529 cur_chain_len = cur_cd_chain->length ();
530 if (cur_chain_len > MAX_CHAIN_LEN)
531 return false;
533 for (i = 0; i < cur_chain_len; i++)
535 edge e = (*cur_cd_chain)[i];
536 /* Cycle detected. */
537 if (e->src == bb)
538 return false;
541 FOR_EACH_EDGE (e, ei, bb->succs)
543 basic_block cd_bb;
544 int post_dom_check = 0;
545 if (e->flags & (EDGE_FAKE | EDGE_ABNORMAL))
546 continue;
548 cd_bb = e->dest;
549 cur_cd_chain->safe_push (e);
550 while (!is_non_loop_exit_postdominating (cd_bb, bb))
552 if (cd_bb == dep_bb)
554 /* Found a direct control dependence. */
555 if (*num_chains < MAX_NUM_CHAINS)
557 cd_chains[*num_chains] = cur_cd_chain->copy ();
558 (*num_chains)++;
560 found_cd_chain = true;
561 /* Check path from next edge. */
562 break;
565 /* Now check if DEP_BB is indirectly control dependent on BB. */
566 if (compute_control_dep_chain (cd_bb, dep_bb, cd_chains, num_chains,
567 cur_cd_chain, num_calls))
569 found_cd_chain = true;
570 break;
573 cd_bb = find_pdom (cd_bb);
574 post_dom_check++;
575 if (cd_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
576 || post_dom_check > MAX_POSTDOM_CHECK)
577 break;
579 cur_cd_chain->pop ();
580 gcc_assert (cur_cd_chain->length () == cur_chain_len);
582 gcc_assert (cur_cd_chain->length () == cur_chain_len);
584 return found_cd_chain;
587 /* The type to represent a simple predicate. */
589 struct pred_info
591 tree pred_lhs;
592 tree pred_rhs;
593 enum tree_code cond_code;
594 bool invert;
597 /* The type to represent a sequence of predicates grouped
598 with .AND. operation. */
600 typedef vec<pred_info, va_heap, vl_ptr> pred_chain;
602 /* The type to represent a sequence of pred_chains grouped
603 with .OR. operation. */
605 typedef vec<pred_chain, va_heap, vl_ptr> pred_chain_union;
607 /* Converts the chains of control dependence edges into a set of
608 predicates. A control dependence chain is represented by a vector
609 edges. DEP_CHAINS points to an array of dependence chains.
610 NUM_CHAINS is the size of the chain array. One edge in a dependence
611 chain is mapped to predicate expression represented by pred_info
612 type. One dependence chain is converted to a composite predicate that
613 is the result of AND operation of pred_info mapped to each edge.
614 A composite predicate is presented by a vector of pred_info. On
615 return, *PREDS points to the resulting array of composite predicates.
616 *NUM_PREDS is the number of composite predictes. */
618 static bool
619 convert_control_dep_chain_into_preds (vec<edge> *dep_chains,
620 size_t num_chains,
621 pred_chain_union *preds)
623 bool has_valid_pred = false;
624 size_t i, j;
625 if (num_chains == 0 || num_chains >= MAX_NUM_CHAINS)
626 return false;
628 /* Now convert the control dep chain into a set
629 of predicates. */
630 preds->reserve (num_chains);
632 for (i = 0; i < num_chains; i++)
634 vec<edge> one_cd_chain = dep_chains[i];
636 has_valid_pred = false;
637 pred_chain t_chain = vNULL;
638 for (j = 0; j < one_cd_chain.length (); j++)
640 gimple *cond_stmt;
641 gimple_stmt_iterator gsi;
642 basic_block guard_bb;
643 pred_info one_pred;
644 edge e;
646 e = one_cd_chain[j];
647 guard_bb = e->src;
648 gsi = gsi_last_bb (guard_bb);
649 if (gsi_end_p (gsi))
651 has_valid_pred = false;
652 break;
654 cond_stmt = gsi_stmt (gsi);
655 if (is_gimple_call (cond_stmt) && EDGE_COUNT (e->src->succs) >= 2)
656 /* Ignore EH edge. Can add assertion on the other edge's flag. */
657 continue;
658 /* Skip if there is essentially one succesor. */
659 if (EDGE_COUNT (e->src->succs) == 2)
661 edge e1;
662 edge_iterator ei1;
663 bool skip = false;
665 FOR_EACH_EDGE (e1, ei1, e->src->succs)
667 if (EDGE_COUNT (e1->dest->succs) == 0)
669 skip = true;
670 break;
673 if (skip)
674 continue;
676 if (gimple_code (cond_stmt) == GIMPLE_COND)
678 one_pred.pred_lhs = gimple_cond_lhs (cond_stmt);
679 one_pred.pred_rhs = gimple_cond_rhs (cond_stmt);
680 one_pred.cond_code = gimple_cond_code (cond_stmt);
681 one_pred.invert = !!(e->flags & EDGE_FALSE_VALUE);
682 t_chain.safe_push (one_pred);
683 has_valid_pred = true;
685 else if (gswitch *gs = dyn_cast<gswitch *> (cond_stmt))
687 /* Avoid quadratic behavior. */
688 if (gimple_switch_num_labels (gs) > MAX_SWITCH_CASES)
690 has_valid_pred = false;
691 break;
693 /* Find the case label. */
694 tree l = NULL_TREE;
695 unsigned idx;
696 for (idx = 0; idx < gimple_switch_num_labels (gs); ++idx)
698 tree tl = gimple_switch_label (gs, idx);
699 if (e->dest == label_to_block (CASE_LABEL (tl)))
701 if (!l)
702 l = tl;
703 else
705 l = NULL_TREE;
706 break;
710 /* If more than one label reaches this block or the case
711 label doesn't have a single value (like the default one)
712 fail. */
713 if (!l
714 || !CASE_LOW (l)
715 || (CASE_HIGH (l)
716 && !operand_equal_p (CASE_LOW (l), CASE_HIGH (l), 0)))
718 has_valid_pred = false;
719 break;
721 one_pred.pred_lhs = gimple_switch_index (gs);
722 one_pred.pred_rhs = CASE_LOW (l);
723 one_pred.cond_code = EQ_EXPR;
724 one_pred.invert = false;
725 t_chain.safe_push (one_pred);
726 has_valid_pred = true;
728 else
730 has_valid_pred = false;
731 break;
735 if (!has_valid_pred)
736 break;
737 else
738 preds->safe_push (t_chain);
740 return has_valid_pred;
743 /* Computes all control dependence chains for USE_BB. The control
744 dependence chains are then converted to an array of composite
745 predicates pointed to by PREDS. PHI_BB is the basic block of
746 the phi whose result is used in USE_BB. */
748 static bool
749 find_predicates (pred_chain_union *preds,
750 basic_block phi_bb,
751 basic_block use_bb)
753 size_t num_chains = 0, i;
754 int num_calls = 0;
755 vec<edge> dep_chains[MAX_NUM_CHAINS];
756 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
757 bool has_valid_pred = false;
758 basic_block cd_root = 0;
760 /* First find the closest bb that is control equivalent to PHI_BB
761 that also dominates USE_BB. */
762 cd_root = phi_bb;
763 while (dominated_by_p (CDI_DOMINATORS, use_bb, cd_root))
765 basic_block ctrl_eq_bb = find_control_equiv_block (cd_root);
766 if (ctrl_eq_bb && dominated_by_p (CDI_DOMINATORS, use_bb, ctrl_eq_bb))
767 cd_root = ctrl_eq_bb;
768 else
769 break;
772 compute_control_dep_chain (cd_root, use_bb, dep_chains, &num_chains,
773 &cur_chain, &num_calls);
775 has_valid_pred
776 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
777 for (i = 0; i < num_chains; i++)
778 dep_chains[i].release ();
779 return has_valid_pred;
782 /* Computes the set of incoming edges of PHI that have non empty
783 definitions of a phi chain. The collection will be done
784 recursively on operands that are defined by phis. CD_ROOT
785 is the control dependence root. *EDGES holds the result, and
786 VISITED_PHIS is a pointer set for detecting cycles. */
788 static void
789 collect_phi_def_edges (gphi *phi, basic_block cd_root,
790 auto_vec<edge> *edges,
791 hash_set<gimple *> *visited_phis)
793 size_t i, n;
794 edge opnd_edge;
795 tree opnd;
797 if (visited_phis->add (phi))
798 return;
800 n = gimple_phi_num_args (phi);
801 for (i = 0; i < n; i++)
803 opnd_edge = gimple_phi_arg_edge (phi, i);
804 opnd = gimple_phi_arg_def (phi, i);
806 if (TREE_CODE (opnd) != SSA_NAME)
808 if (dump_file && (dump_flags & TDF_DETAILS))
810 fprintf (dump_file, "\n[CHECK] Found def edge %d in ", (int) i);
811 print_gimple_stmt (dump_file, phi, 0);
813 edges->safe_push (opnd_edge);
815 else
817 gimple *def = SSA_NAME_DEF_STMT (opnd);
819 if (gimple_code (def) == GIMPLE_PHI
820 && dominated_by_p (CDI_DOMINATORS, gimple_bb (def), cd_root))
821 collect_phi_def_edges (as_a<gphi *> (def), cd_root, edges,
822 visited_phis);
823 else if (!uninit_undefined_value_p (opnd))
825 if (dump_file && (dump_flags & TDF_DETAILS))
827 fprintf (dump_file, "\n[CHECK] Found def edge %d in ",
828 (int) i);
829 print_gimple_stmt (dump_file, phi, 0);
831 edges->safe_push (opnd_edge);
837 /* For each use edge of PHI, computes all control dependence chains.
838 The control dependence chains are then converted to an array of
839 composite predicates pointed to by PREDS. */
841 static bool
842 find_def_preds (pred_chain_union *preds, gphi *phi)
844 size_t num_chains = 0, i, n;
845 vec<edge> dep_chains[MAX_NUM_CHAINS];
846 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
847 auto_vec<edge> def_edges;
848 bool has_valid_pred = false;
849 basic_block phi_bb, cd_root = 0;
851 phi_bb = gimple_bb (phi);
852 /* First find the closest dominating bb to be
853 the control dependence root. */
854 cd_root = find_dom (phi_bb);
855 if (!cd_root)
856 return false;
858 hash_set<gimple *> visited_phis;
859 collect_phi_def_edges (phi, cd_root, &def_edges, &visited_phis);
861 n = def_edges.length ();
862 if (n == 0)
863 return false;
865 for (i = 0; i < n; i++)
867 size_t prev_nc, j;
868 int num_calls = 0;
869 edge opnd_edge;
871 opnd_edge = def_edges[i];
872 prev_nc = num_chains;
873 compute_control_dep_chain (cd_root, opnd_edge->src, dep_chains,
874 &num_chains, &cur_chain, &num_calls);
876 /* Now update the newly added chains with
877 the phi operand edge: */
878 if (EDGE_COUNT (opnd_edge->src->succs) > 1)
880 if (prev_nc == num_chains && num_chains < MAX_NUM_CHAINS)
881 dep_chains[num_chains++] = vNULL;
882 for (j = prev_nc; j < num_chains; j++)
883 dep_chains[j].safe_push (opnd_edge);
887 has_valid_pred
888 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
889 for (i = 0; i < num_chains; i++)
890 dep_chains[i].release ();
891 return has_valid_pred;
894 /* Dumps the predicates (PREDS) for USESTMT. */
896 static void
897 dump_predicates (gimple *usestmt, pred_chain_union preds, const char *msg)
899 size_t i, j;
900 pred_chain one_pred_chain = vNULL;
901 fprintf (dump_file, "%s", msg);
902 print_gimple_stmt (dump_file, usestmt, 0);
903 fprintf (dump_file, "is guarded by :\n\n");
904 size_t num_preds = preds.length ();
905 /* Do some dumping here: */
906 for (i = 0; i < num_preds; i++)
908 size_t np;
910 one_pred_chain = preds[i];
911 np = one_pred_chain.length ();
913 for (j = 0; j < np; j++)
915 pred_info one_pred = one_pred_chain[j];
916 if (one_pred.invert)
917 fprintf (dump_file, " (.NOT.) ");
918 print_generic_expr (dump_file, one_pred.pred_lhs);
919 fprintf (dump_file, " %s ", op_symbol_code (one_pred.cond_code));
920 print_generic_expr (dump_file, one_pred.pred_rhs);
921 if (j < np - 1)
922 fprintf (dump_file, " (.AND.) ");
923 else
924 fprintf (dump_file, "\n");
926 if (i < num_preds - 1)
927 fprintf (dump_file, "(.OR.)\n");
928 else
929 fprintf (dump_file, "\n\n");
933 /* Destroys the predicate set *PREDS. */
935 static void
936 destroy_predicate_vecs (pred_chain_union *preds)
938 size_t i;
940 size_t n = preds->length ();
941 for (i = 0; i < n; i++)
942 (*preds)[i].release ();
943 preds->release ();
946 /* Computes the 'normalized' conditional code with operand
947 swapping and condition inversion. */
949 static enum tree_code
950 get_cmp_code (enum tree_code orig_cmp_code, bool swap_cond, bool invert)
952 enum tree_code tc = orig_cmp_code;
954 if (swap_cond)
955 tc = swap_tree_comparison (orig_cmp_code);
956 if (invert)
957 tc = invert_tree_comparison (tc, false);
959 switch (tc)
961 case LT_EXPR:
962 case LE_EXPR:
963 case GT_EXPR:
964 case GE_EXPR:
965 case EQ_EXPR:
966 case NE_EXPR:
967 break;
968 default:
969 return ERROR_MARK;
971 return tc;
974 /* Returns true if VAL falls in the range defined by BOUNDARY and CMPC, i.e.
975 all values in the range satisfies (x CMPC BOUNDARY) == true. */
977 static bool
978 is_value_included_in (tree val, tree boundary, enum tree_code cmpc)
980 bool inverted = false;
981 bool is_unsigned;
982 bool result;
984 /* Only handle integer constant here. */
985 if (TREE_CODE (val) != INTEGER_CST || TREE_CODE (boundary) != INTEGER_CST)
986 return true;
988 is_unsigned = TYPE_UNSIGNED (TREE_TYPE (val));
990 if (cmpc == GE_EXPR || cmpc == GT_EXPR || cmpc == NE_EXPR)
992 cmpc = invert_tree_comparison (cmpc, false);
993 inverted = true;
996 if (is_unsigned)
998 if (cmpc == EQ_EXPR)
999 result = tree_int_cst_equal (val, boundary);
1000 else if (cmpc == LT_EXPR)
1001 result = tree_int_cst_lt (val, boundary);
1002 else
1004 gcc_assert (cmpc == LE_EXPR);
1005 result = tree_int_cst_le (val, boundary);
1008 else
1010 if (cmpc == EQ_EXPR)
1011 result = tree_int_cst_equal (val, boundary);
1012 else if (cmpc == LT_EXPR)
1013 result = tree_int_cst_lt (val, boundary);
1014 else
1016 gcc_assert (cmpc == LE_EXPR);
1017 result = (tree_int_cst_equal (val, boundary)
1018 || tree_int_cst_lt (val, boundary));
1022 if (inverted)
1023 result ^= 1;
1025 return result;
1028 /* Returns true if PRED is common among all the predicate
1029 chains (PREDS) (and therefore can be factored out).
1030 NUM_PRED_CHAIN is the size of array PREDS. */
1032 static bool
1033 find_matching_predicate_in_rest_chains (pred_info pred,
1034 pred_chain_union preds,
1035 size_t num_pred_chains)
1037 size_t i, j, n;
1039 /* Trival case. */
1040 if (num_pred_chains == 1)
1041 return true;
1043 for (i = 1; i < num_pred_chains; i++)
1045 bool found = false;
1046 pred_chain one_chain = preds[i];
1047 n = one_chain.length ();
1048 for (j = 0; j < n; j++)
1050 pred_info pred2 = one_chain[j];
1051 /* Can relax the condition comparison to not
1052 use address comparison. However, the most common
1053 case is that multiple control dependent paths share
1054 a common path prefix, so address comparison should
1055 be ok. */
1057 if (operand_equal_p (pred2.pred_lhs, pred.pred_lhs, 0)
1058 && operand_equal_p (pred2.pred_rhs, pred.pred_rhs, 0)
1059 && pred2.invert == pred.invert)
1061 found = true;
1062 break;
1065 if (!found)
1066 return false;
1068 return true;
1071 /* Forward declaration. */
1072 static bool is_use_properly_guarded (gimple *use_stmt,
1073 basic_block use_bb,
1074 gphi *phi,
1075 unsigned uninit_opnds,
1076 pred_chain_union *def_preds,
1077 hash_set<gphi *> *visited_phis);
1079 /* Returns true if all uninitialized opnds are pruned. Returns false
1080 otherwise. PHI is the phi node with uninitialized operands,
1081 UNINIT_OPNDS is the bitmap of the uninitialize operand positions,
1082 FLAG_DEF is the statement defining the flag guarding the use of the
1083 PHI output, BOUNDARY_CST is the const value used in the predicate
1084 associated with the flag, CMP_CODE is the comparison code used in
1085 the predicate, VISITED_PHIS is the pointer set of phis visited, and
1086 VISITED_FLAG_PHIS is the pointer to the pointer set of flag definitions
1087 that are also phis.
1089 Example scenario:
1091 BB1:
1092 flag_1 = phi <0, 1> // (1)
1093 var_1 = phi <undef, some_val>
1096 BB2:
1097 flag_2 = phi <0, flag_1, flag_1> // (2)
1098 var_2 = phi <undef, var_1, var_1>
1099 if (flag_2 == 1)
1100 goto BB3;
1102 BB3:
1103 use of var_2 // (3)
1105 Because some flag arg in (1) is not constant, if we do not look into the
1106 flag phis recursively, it is conservatively treated as unknown and var_1
1107 is thought to be flowed into use at (3). Since var_1 is potentially
1108 uninitialized a false warning will be emitted.
1109 Checking recursively into (1), the compiler can find out that only some_val
1110 (which is defined) can flow into (3) which is OK. */
1112 static bool
1113 prune_uninit_phi_opnds (gphi *phi, unsigned uninit_opnds, gphi *flag_def,
1114 tree boundary_cst, enum tree_code cmp_code,
1115 hash_set<gphi *> *visited_phis,
1116 bitmap *visited_flag_phis)
1118 unsigned i;
1120 for (i = 0; i < MIN (max_phi_args, gimple_phi_num_args (flag_def)); i++)
1122 tree flag_arg;
1124 if (!MASK_TEST_BIT (uninit_opnds, i))
1125 continue;
1127 flag_arg = gimple_phi_arg_def (flag_def, i);
1128 if (!is_gimple_constant (flag_arg))
1130 gphi *flag_arg_def, *phi_arg_def;
1131 tree phi_arg;
1132 unsigned uninit_opnds_arg_phi;
1134 if (TREE_CODE (flag_arg) != SSA_NAME)
1135 return false;
1136 flag_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (flag_arg));
1137 if (!flag_arg_def)
1138 return false;
1140 phi_arg = gimple_phi_arg_def (phi, i);
1141 if (TREE_CODE (phi_arg) != SSA_NAME)
1142 return false;
1144 phi_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (phi_arg));
1145 if (!phi_arg_def)
1146 return false;
1148 if (gimple_bb (phi_arg_def) != gimple_bb (flag_arg_def))
1149 return false;
1151 if (!*visited_flag_phis)
1152 *visited_flag_phis = BITMAP_ALLOC (NULL);
1154 tree phi_result = gimple_phi_result (flag_arg_def);
1155 if (bitmap_bit_p (*visited_flag_phis, SSA_NAME_VERSION (phi_result)))
1156 return false;
1158 bitmap_set_bit (*visited_flag_phis,
1159 SSA_NAME_VERSION (gimple_phi_result (flag_arg_def)));
1161 /* Now recursively prune the uninitialized phi args. */
1162 uninit_opnds_arg_phi = compute_uninit_opnds_pos (phi_arg_def);
1163 if (!prune_uninit_phi_opnds
1164 (phi_arg_def, uninit_opnds_arg_phi, flag_arg_def, boundary_cst,
1165 cmp_code, visited_phis, visited_flag_phis))
1166 return false;
1168 phi_result = gimple_phi_result (flag_arg_def);
1169 bitmap_clear_bit (*visited_flag_phis, SSA_NAME_VERSION (phi_result));
1170 continue;
1173 /* Now check if the constant is in the guarded range. */
1174 if (is_value_included_in (flag_arg, boundary_cst, cmp_code))
1176 tree opnd;
1177 gimple *opnd_def;
1179 /* Now that we know that this undefined edge is not
1180 pruned. If the operand is defined by another phi,
1181 we can further prune the incoming edges of that
1182 phi by checking the predicates of this operands. */
1184 opnd = gimple_phi_arg_def (phi, i);
1185 opnd_def = SSA_NAME_DEF_STMT (opnd);
1186 if (gphi *opnd_def_phi = dyn_cast <gphi *> (opnd_def))
1188 edge opnd_edge;
1189 unsigned uninit_opnds2 = compute_uninit_opnds_pos (opnd_def_phi);
1190 if (!MASK_EMPTY (uninit_opnds2))
1192 pred_chain_union def_preds = vNULL;
1193 bool ok;
1194 opnd_edge = gimple_phi_arg_edge (phi, i);
1195 ok = is_use_properly_guarded (phi,
1196 opnd_edge->src,
1197 opnd_def_phi,
1198 uninit_opnds2,
1199 &def_preds,
1200 visited_phis);
1201 destroy_predicate_vecs (&def_preds);
1202 if (!ok)
1203 return false;
1206 else
1207 return false;
1211 return true;
1214 /* A helper function that determines if the predicate set
1215 of the use is not overlapping with that of the uninit paths.
1216 The most common senario of guarded use is in Example 1:
1217 Example 1:
1218 if (some_cond)
1220 x = ...;
1221 flag = true;
1224 ... some code ...
1226 if (flag)
1227 use (x);
1229 The real world examples are usually more complicated, but similar
1230 and usually result from inlining:
1232 bool init_func (int * x)
1234 if (some_cond)
1235 return false;
1236 *x = ..
1237 return true;
1240 void foo (..)
1242 int x;
1244 if (!init_func (&x))
1245 return;
1247 .. some_code ...
1248 use (x);
1251 Another possible use scenario is in the following trivial example:
1253 Example 2:
1254 if (n > 0)
1255 x = 1;
1257 if (n > 0)
1259 if (m < 2)
1260 .. = x;
1263 Predicate analysis needs to compute the composite predicate:
1265 1) 'x' use predicate: (n > 0) .AND. (m < 2)
1266 2) 'x' default value (non-def) predicate: .NOT. (n > 0)
1267 (the predicate chain for phi operand defs can be computed
1268 starting from a bb that is control equivalent to the phi's
1269 bb and is dominating the operand def.)
1271 and check overlapping:
1272 (n > 0) .AND. (m < 2) .AND. (.NOT. (n > 0))
1273 <==> false
1275 This implementation provides framework that can handle
1276 scenarios. (Note that many simple cases are handled properly
1277 without the predicate analysis -- this is due to jump threading
1278 transformation which eliminates the merge point thus makes
1279 path sensitive analysis unnecessary.)
1281 PHI is the phi node whose incoming (undefined) paths need to be
1282 pruned, and UNINIT_OPNDS is the bitmap holding uninit operand
1283 positions. VISITED_PHIS is the pointer set of phi stmts being
1284 checked. */
1286 static bool
1287 use_pred_not_overlap_with_undef_path_pred (pred_chain_union preds,
1288 gphi *phi, unsigned uninit_opnds,
1289 hash_set<gphi *> *visited_phis)
1291 unsigned int i, n;
1292 gimple *flag_def = 0;
1293 tree boundary_cst = 0;
1294 enum tree_code cmp_code;
1295 bool swap_cond = false;
1296 bool invert = false;
1297 pred_chain the_pred_chain = vNULL;
1298 bitmap visited_flag_phis = NULL;
1299 bool all_pruned = false;
1300 size_t num_preds = preds.length ();
1302 gcc_assert (num_preds > 0);
1303 /* Find within the common prefix of multiple predicate chains
1304 a predicate that is a comparison of a flag variable against
1305 a constant. */
1306 the_pred_chain = preds[0];
1307 n = the_pred_chain.length ();
1308 for (i = 0; i < n; i++)
1310 tree cond_lhs, cond_rhs, flag = 0;
1312 pred_info the_pred = the_pred_chain[i];
1314 invert = the_pred.invert;
1315 cond_lhs = the_pred.pred_lhs;
1316 cond_rhs = the_pred.pred_rhs;
1317 cmp_code = the_pred.cond_code;
1319 if (cond_lhs != NULL_TREE && TREE_CODE (cond_lhs) == SSA_NAME
1320 && cond_rhs != NULL_TREE && is_gimple_constant (cond_rhs))
1322 boundary_cst = cond_rhs;
1323 flag = cond_lhs;
1325 else if (cond_rhs != NULL_TREE && TREE_CODE (cond_rhs) == SSA_NAME
1326 && cond_lhs != NULL_TREE && is_gimple_constant (cond_lhs))
1328 boundary_cst = cond_lhs;
1329 flag = cond_rhs;
1330 swap_cond = true;
1333 if (!flag)
1334 continue;
1336 flag_def = SSA_NAME_DEF_STMT (flag);
1338 if (!flag_def)
1339 continue;
1341 if ((gimple_code (flag_def) == GIMPLE_PHI)
1342 && (gimple_bb (flag_def) == gimple_bb (phi))
1343 && find_matching_predicate_in_rest_chains (the_pred, preds,
1344 num_preds))
1345 break;
1347 flag_def = 0;
1350 if (!flag_def)
1351 return false;
1353 /* Now check all the uninit incoming edge has a constant flag value
1354 that is in conflict with the use guard/predicate. */
1355 cmp_code = get_cmp_code (cmp_code, swap_cond, invert);
1357 if (cmp_code == ERROR_MARK)
1358 return false;
1360 all_pruned = prune_uninit_phi_opnds
1361 (phi, uninit_opnds, as_a<gphi *> (flag_def), boundary_cst, cmp_code,
1362 visited_phis, &visited_flag_phis);
1364 if (visited_flag_phis)
1365 BITMAP_FREE (visited_flag_phis);
1367 return all_pruned;
1370 /* The helper function returns true if two predicates X1 and X2
1371 are equivalent. It assumes the expressions have already
1372 properly re-associated. */
1374 static inline bool
1375 pred_equal_p (pred_info x1, pred_info x2)
1377 enum tree_code c1, c2;
1378 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1379 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1380 return false;
1382 c1 = x1.cond_code;
1383 if (x1.invert != x2.invert
1384 && TREE_CODE_CLASS (x2.cond_code) == tcc_comparison)
1385 c2 = invert_tree_comparison (x2.cond_code, false);
1386 else
1387 c2 = x2.cond_code;
1389 return c1 == c2;
1392 /* Returns true if the predication is testing !=. */
1394 static inline bool
1395 is_neq_relop_p (pred_info pred)
1398 return ((pred.cond_code == NE_EXPR && !pred.invert)
1399 || (pred.cond_code == EQ_EXPR && pred.invert));
1402 /* Returns true if pred is of the form X != 0. */
1404 static inline bool
1405 is_neq_zero_form_p (pred_info pred)
1407 if (!is_neq_relop_p (pred) || !integer_zerop (pred.pred_rhs)
1408 || TREE_CODE (pred.pred_lhs) != SSA_NAME)
1409 return false;
1410 return true;
1413 /* The helper function returns true if two predicates X1
1414 is equivalent to X2 != 0. */
1416 static inline bool
1417 pred_expr_equal_p (pred_info x1, tree x2)
1419 if (!is_neq_zero_form_p (x1))
1420 return false;
1422 return operand_equal_p (x1.pred_lhs, x2, 0);
1425 /* Returns true of the domain of single predicate expression
1426 EXPR1 is a subset of that of EXPR2. Returns false if it
1427 can not be proved. */
1429 static bool
1430 is_pred_expr_subset_of (pred_info expr1, pred_info expr2)
1432 enum tree_code code1, code2;
1434 if (pred_equal_p (expr1, expr2))
1435 return true;
1437 if ((TREE_CODE (expr1.pred_rhs) != INTEGER_CST)
1438 || (TREE_CODE (expr2.pred_rhs) != INTEGER_CST))
1439 return false;
1441 if (!operand_equal_p (expr1.pred_lhs, expr2.pred_lhs, 0))
1442 return false;
1444 code1 = expr1.cond_code;
1445 if (expr1.invert)
1446 code1 = invert_tree_comparison (code1, false);
1447 code2 = expr2.cond_code;
1448 if (expr2.invert)
1449 code2 = invert_tree_comparison (code2, false);
1451 if ((code1 == EQ_EXPR || code1 == BIT_AND_EXPR) && code2 == BIT_AND_EXPR)
1452 return wi::eq_p (expr1.pred_rhs,
1453 wi::bit_and (expr1.pred_rhs, expr2.pred_rhs));
1455 if (code1 != code2 && code2 != NE_EXPR)
1456 return false;
1458 if (is_value_included_in (expr1.pred_rhs, expr2.pred_rhs, code2))
1459 return true;
1461 return false;
1464 /* Returns true if the domain of PRED1 is a subset
1465 of that of PRED2. Returns false if it can not be proved so. */
1467 static bool
1468 is_pred_chain_subset_of (pred_chain pred1, pred_chain pred2)
1470 size_t np1, np2, i1, i2;
1472 np1 = pred1.length ();
1473 np2 = pred2.length ();
1475 for (i2 = 0; i2 < np2; i2++)
1477 bool found = false;
1478 pred_info info2 = pred2[i2];
1479 for (i1 = 0; i1 < np1; i1++)
1481 pred_info info1 = pred1[i1];
1482 if (is_pred_expr_subset_of (info1, info2))
1484 found = true;
1485 break;
1488 if (!found)
1489 return false;
1491 return true;
1494 /* Returns true if the domain defined by
1495 one pred chain ONE_PRED is a subset of the domain
1496 of *PREDS. It returns false if ONE_PRED's domain is
1497 not a subset of any of the sub-domains of PREDS
1498 (corresponding to each individual chains in it), even
1499 though it may be still be a subset of whole domain
1500 of PREDS which is the union (ORed) of all its subdomains.
1501 In other words, the result is conservative. */
1503 static bool
1504 is_included_in (pred_chain one_pred, pred_chain_union preds)
1506 size_t i;
1507 size_t n = preds.length ();
1509 for (i = 0; i < n; i++)
1511 if (is_pred_chain_subset_of (one_pred, preds[i]))
1512 return true;
1515 return false;
1518 /* Compares two predicate sets PREDS1 and PREDS2 and returns
1519 true if the domain defined by PREDS1 is a superset
1520 of PREDS2's domain. N1 and N2 are array sizes of PREDS1 and
1521 PREDS2 respectively. The implementation chooses not to build
1522 generic trees (and relying on the folding capability of the
1523 compiler), but instead performs brute force comparison of
1524 individual predicate chains (won't be a compile time problem
1525 as the chains are pretty short). When the function returns
1526 false, it does not necessarily mean *PREDS1 is not a superset
1527 of *PREDS2, but mean it may not be so since the analysis can
1528 not prove it. In such cases, false warnings may still be
1529 emitted. */
1531 static bool
1532 is_superset_of (pred_chain_union preds1, pred_chain_union preds2)
1534 size_t i, n2;
1535 pred_chain one_pred_chain = vNULL;
1537 n2 = preds2.length ();
1539 for (i = 0; i < n2; i++)
1541 one_pred_chain = preds2[i];
1542 if (!is_included_in (one_pred_chain, preds1))
1543 return false;
1546 return true;
1549 /* Returns true if TC is AND or OR. */
1551 static inline bool
1552 is_and_or_or_p (enum tree_code tc, tree type)
1554 return (tc == BIT_IOR_EXPR
1555 || (tc == BIT_AND_EXPR
1556 && (type == 0 || TREE_CODE (type) == BOOLEAN_TYPE)));
1559 /* Returns true if X1 is the negate of X2. */
1561 static inline bool
1562 pred_neg_p (pred_info x1, pred_info x2)
1564 enum tree_code c1, c2;
1565 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1566 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1567 return false;
1569 c1 = x1.cond_code;
1570 if (x1.invert == x2.invert)
1571 c2 = invert_tree_comparison (x2.cond_code, false);
1572 else
1573 c2 = x2.cond_code;
1575 return c1 == c2;
1578 /* 1) ((x IOR y) != 0) AND (x != 0) is equivalent to (x != 0);
1579 2) (X AND Y) OR (!X AND Y) is equivalent to Y;
1580 3) X OR (!X AND Y) is equivalent to (X OR Y);
1581 4) ((x IAND y) != 0) || (x != 0 AND y != 0)) is equivalent to
1582 (x != 0 AND y != 0)
1583 5) (X AND Y) OR (!X AND Z) OR (!Y AND Z) is equivalent to
1584 (X AND Y) OR Z
1586 PREDS is the predicate chains, and N is the number of chains. */
1588 /* Helper function to implement rule 1 above. ONE_CHAIN is
1589 the AND predication to be simplified. */
1591 static void
1592 simplify_pred (pred_chain *one_chain)
1594 size_t i, j, n;
1595 bool simplified = false;
1596 pred_chain s_chain = vNULL;
1598 n = one_chain->length ();
1600 for (i = 0; i < n; i++)
1602 pred_info *a_pred = &(*one_chain)[i];
1604 if (!a_pred->pred_lhs)
1605 continue;
1606 if (!is_neq_zero_form_p (*a_pred))
1607 continue;
1609 gimple *def_stmt = SSA_NAME_DEF_STMT (a_pred->pred_lhs);
1610 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
1611 continue;
1612 if (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
1614 for (j = 0; j < n; j++)
1616 pred_info *b_pred = &(*one_chain)[j];
1618 if (!b_pred->pred_lhs)
1619 continue;
1620 if (!is_neq_zero_form_p (*b_pred))
1621 continue;
1623 if (pred_expr_equal_p (*b_pred, gimple_assign_rhs1 (def_stmt))
1624 || pred_expr_equal_p (*b_pred, gimple_assign_rhs2 (def_stmt)))
1626 /* Mark a_pred for removal. */
1627 a_pred->pred_lhs = NULL;
1628 a_pred->pred_rhs = NULL;
1629 simplified = true;
1630 break;
1636 if (!simplified)
1637 return;
1639 for (i = 0; i < n; i++)
1641 pred_info *a_pred = &(*one_chain)[i];
1642 if (!a_pred->pred_lhs)
1643 continue;
1644 s_chain.safe_push (*a_pred);
1647 one_chain->release ();
1648 *one_chain = s_chain;
1651 /* The helper function implements the rule 2 for the
1652 OR predicate PREDS.
1654 2) (X AND Y) OR (!X AND Y) is equivalent to Y. */
1656 static bool
1657 simplify_preds_2 (pred_chain_union *preds)
1659 size_t i, j, n;
1660 bool simplified = false;
1661 pred_chain_union s_preds = vNULL;
1663 /* (X AND Y) OR (!X AND Y) is equivalent to Y.
1664 (X AND Y) OR (X AND !Y) is equivalent to X. */
1666 n = preds->length ();
1667 for (i = 0; i < n; i++)
1669 pred_info x, y;
1670 pred_chain *a_chain = &(*preds)[i];
1672 if (a_chain->length () != 2)
1673 continue;
1675 x = (*a_chain)[0];
1676 y = (*a_chain)[1];
1678 for (j = 0; j < n; j++)
1680 pred_chain *b_chain;
1681 pred_info x2, y2;
1683 if (j == i)
1684 continue;
1686 b_chain = &(*preds)[j];
1687 if (b_chain->length () != 2)
1688 continue;
1690 x2 = (*b_chain)[0];
1691 y2 = (*b_chain)[1];
1693 if (pred_equal_p (x, x2) && pred_neg_p (y, y2))
1695 /* Kill a_chain. */
1696 a_chain->release ();
1697 b_chain->release ();
1698 b_chain->safe_push (x);
1699 simplified = true;
1700 break;
1702 if (pred_neg_p (x, x2) && pred_equal_p (y, y2))
1704 /* Kill a_chain. */
1705 a_chain->release ();
1706 b_chain->release ();
1707 b_chain->safe_push (y);
1708 simplified = true;
1709 break;
1713 /* Now clean up the chain. */
1714 if (simplified)
1716 for (i = 0; i < n; i++)
1718 if ((*preds)[i].is_empty ())
1719 continue;
1720 s_preds.safe_push ((*preds)[i]);
1722 preds->release ();
1723 (*preds) = s_preds;
1724 s_preds = vNULL;
1727 return simplified;
1730 /* The helper function implements the rule 2 for the
1731 OR predicate PREDS.
1733 3) x OR (!x AND y) is equivalent to x OR y. */
1735 static bool
1736 simplify_preds_3 (pred_chain_union *preds)
1738 size_t i, j, n;
1739 bool simplified = false;
1741 /* Now iteratively simplify X OR (!X AND Z ..)
1742 into X OR (Z ...). */
1744 n = preds->length ();
1745 if (n < 2)
1746 return false;
1748 for (i = 0; i < n; i++)
1750 pred_info x;
1751 pred_chain *a_chain = &(*preds)[i];
1753 if (a_chain->length () != 1)
1754 continue;
1756 x = (*a_chain)[0];
1758 for (j = 0; j < n; j++)
1760 pred_chain *b_chain;
1761 pred_info x2;
1762 size_t k;
1764 if (j == i)
1765 continue;
1767 b_chain = &(*preds)[j];
1768 if (b_chain->length () < 2)
1769 continue;
1771 for (k = 0; k < b_chain->length (); k++)
1773 x2 = (*b_chain)[k];
1774 if (pred_neg_p (x, x2))
1776 b_chain->unordered_remove (k);
1777 simplified = true;
1778 break;
1783 return simplified;
1786 /* The helper function implements the rule 4 for the
1787 OR predicate PREDS.
1789 2) ((x AND y) != 0) OR (x != 0 AND y != 0) is equivalent to
1790 (x != 0 ANd y != 0). */
1792 static bool
1793 simplify_preds_4 (pred_chain_union *preds)
1795 size_t i, j, n;
1796 bool simplified = false;
1797 pred_chain_union s_preds = vNULL;
1798 gimple *def_stmt;
1800 n = preds->length ();
1801 for (i = 0; i < n; i++)
1803 pred_info z;
1804 pred_chain *a_chain = &(*preds)[i];
1806 if (a_chain->length () != 1)
1807 continue;
1809 z = (*a_chain)[0];
1811 if (!is_neq_zero_form_p (z))
1812 continue;
1814 def_stmt = SSA_NAME_DEF_STMT (z.pred_lhs);
1815 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
1816 continue;
1818 if (gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
1819 continue;
1821 for (j = 0; j < n; j++)
1823 pred_chain *b_chain;
1824 pred_info x2, y2;
1826 if (j == i)
1827 continue;
1829 b_chain = &(*preds)[j];
1830 if (b_chain->length () != 2)
1831 continue;
1833 x2 = (*b_chain)[0];
1834 y2 = (*b_chain)[1];
1835 if (!is_neq_zero_form_p (x2) || !is_neq_zero_form_p (y2))
1836 continue;
1838 if ((pred_expr_equal_p (x2, gimple_assign_rhs1 (def_stmt))
1839 && pred_expr_equal_p (y2, gimple_assign_rhs2 (def_stmt)))
1840 || (pred_expr_equal_p (x2, gimple_assign_rhs2 (def_stmt))
1841 && pred_expr_equal_p (y2, gimple_assign_rhs1 (def_stmt))))
1843 /* Kill a_chain. */
1844 a_chain->release ();
1845 simplified = true;
1846 break;
1850 /* Now clean up the chain. */
1851 if (simplified)
1853 for (i = 0; i < n; i++)
1855 if ((*preds)[i].is_empty ())
1856 continue;
1857 s_preds.safe_push ((*preds)[i]);
1860 preds->release ();
1861 (*preds) = s_preds;
1862 s_preds = vNULL;
1865 return simplified;
1868 /* This function simplifies predicates in PREDS. */
1870 static void
1871 simplify_preds (pred_chain_union *preds, gimple *use_or_def, bool is_use)
1873 size_t i, n;
1874 bool changed = false;
1876 if (dump_file && dump_flags & TDF_DETAILS)
1878 fprintf (dump_file, "[BEFORE SIMPLICATION -- ");
1879 dump_predicates (use_or_def, *preds, is_use ? "[USE]:\n" : "[DEF]:\n");
1882 for (i = 0; i < preds->length (); i++)
1883 simplify_pred (&(*preds)[i]);
1885 n = preds->length ();
1886 if (n < 2)
1887 return;
1891 changed = false;
1892 if (simplify_preds_2 (preds))
1893 changed = true;
1895 /* Now iteratively simplify X OR (!X AND Z ..)
1896 into X OR (Z ...). */
1897 if (simplify_preds_3 (preds))
1898 changed = true;
1900 if (simplify_preds_4 (preds))
1901 changed = true;
1903 while (changed);
1905 return;
1908 /* This is a helper function which attempts to normalize predicate chains
1909 by following UD chains. It basically builds up a big tree of either IOR
1910 operations or AND operations, and convert the IOR tree into a
1911 pred_chain_union or BIT_AND tree into a pred_chain.
1912 Example:
1914 _3 = _2 RELOP1 _1;
1915 _6 = _5 RELOP2 _4;
1916 _9 = _8 RELOP3 _7;
1917 _10 = _3 | _6;
1918 _12 = _9 | _0;
1919 _t = _10 | _12;
1921 then _t != 0 will be normalized into a pred_chain_union
1923 (_2 RELOP1 _1) OR (_5 RELOP2 _4) OR (_8 RELOP3 _7) OR (_0 != 0)
1925 Similarly given,
1927 _3 = _2 RELOP1 _1;
1928 _6 = _5 RELOP2 _4;
1929 _9 = _8 RELOP3 _7;
1930 _10 = _3 & _6;
1931 _12 = _9 & _0;
1933 then _t != 0 will be normalized into a pred_chain:
1934 (_2 RELOP1 _1) AND (_5 RELOP2 _4) AND (_8 RELOP3 _7) AND (_0 != 0)
1938 /* This is a helper function that stores a PRED into NORM_PREDS. */
1940 inline static void
1941 push_pred (pred_chain_union *norm_preds, pred_info pred)
1943 pred_chain pred_chain = vNULL;
1944 pred_chain.safe_push (pred);
1945 norm_preds->safe_push (pred_chain);
1948 /* A helper function that creates a predicate of the form
1949 OP != 0 and push it WORK_LIST. */
1951 inline static void
1952 push_to_worklist (tree op, vec<pred_info, va_heap, vl_ptr> *work_list,
1953 hash_set<tree> *mark_set)
1955 if (mark_set->contains (op))
1956 return;
1957 mark_set->add (op);
1959 pred_info arg_pred;
1960 arg_pred.pred_lhs = op;
1961 arg_pred.pred_rhs = integer_zero_node;
1962 arg_pred.cond_code = NE_EXPR;
1963 arg_pred.invert = false;
1964 work_list->safe_push (arg_pred);
1967 /* A helper that generates a pred_info from a gimple assignment
1968 CMP_ASSIGN with comparison rhs. */
1970 static pred_info
1971 get_pred_info_from_cmp (gimple *cmp_assign)
1973 pred_info n_pred;
1974 n_pred.pred_lhs = gimple_assign_rhs1 (cmp_assign);
1975 n_pred.pred_rhs = gimple_assign_rhs2 (cmp_assign);
1976 n_pred.cond_code = gimple_assign_rhs_code (cmp_assign);
1977 n_pred.invert = false;
1978 return n_pred;
1981 /* Returns true if the PHI is a degenerated phi with
1982 all args with the same value (relop). In that case, *PRED
1983 will be updated to that value. */
1985 static bool
1986 is_degenerated_phi (gimple *phi, pred_info *pred_p)
1988 int i, n;
1989 tree op0;
1990 gimple *def0;
1991 pred_info pred0;
1993 n = gimple_phi_num_args (phi);
1994 op0 = gimple_phi_arg_def (phi, 0);
1996 if (TREE_CODE (op0) != SSA_NAME)
1997 return false;
1999 def0 = SSA_NAME_DEF_STMT (op0);
2000 if (gimple_code (def0) != GIMPLE_ASSIGN)
2001 return false;
2002 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def0)) != tcc_comparison)
2003 return false;
2004 pred0 = get_pred_info_from_cmp (def0);
2006 for (i = 1; i < n; ++i)
2008 gimple *def;
2009 pred_info pred;
2010 tree op = gimple_phi_arg_def (phi, i);
2012 if (TREE_CODE (op) != SSA_NAME)
2013 return false;
2015 def = SSA_NAME_DEF_STMT (op);
2016 if (gimple_code (def) != GIMPLE_ASSIGN)
2017 return false;
2018 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def)) != tcc_comparison)
2019 return false;
2020 pred = get_pred_info_from_cmp (def);
2021 if (!pred_equal_p (pred, pred0))
2022 return false;
2025 *pred_p = pred0;
2026 return true;
2029 /* Normalize one predicate PRED
2030 1) if PRED can no longer be normlized, put it into NORM_PREDS.
2031 2) otherwise if PRED is of the form x != 0, follow x's definition
2032 and put normalized predicates into WORK_LIST. */
2034 static void
2035 normalize_one_pred_1 (pred_chain_union *norm_preds,
2036 pred_chain *norm_chain,
2037 pred_info pred,
2038 enum tree_code and_or_code,
2039 vec<pred_info, va_heap, vl_ptr> *work_list,
2040 hash_set<tree> *mark_set)
2042 if (!is_neq_zero_form_p (pred))
2044 if (and_or_code == BIT_IOR_EXPR)
2045 push_pred (norm_preds, pred);
2046 else
2047 norm_chain->safe_push (pred);
2048 return;
2051 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2053 if (gimple_code (def_stmt) == GIMPLE_PHI
2054 && is_degenerated_phi (def_stmt, &pred))
2055 work_list->safe_push (pred);
2056 else if (gimple_code (def_stmt) == GIMPLE_PHI && and_or_code == BIT_IOR_EXPR)
2058 int i, n;
2059 n = gimple_phi_num_args (def_stmt);
2061 /* If we see non zero constant, we should punt. The predicate
2062 * should be one guarding the phi edge. */
2063 for (i = 0; i < n; ++i)
2065 tree op = gimple_phi_arg_def (def_stmt, i);
2066 if (TREE_CODE (op) == INTEGER_CST && !integer_zerop (op))
2068 push_pred (norm_preds, pred);
2069 return;
2073 for (i = 0; i < n; ++i)
2075 tree op = gimple_phi_arg_def (def_stmt, i);
2076 if (integer_zerop (op))
2077 continue;
2079 push_to_worklist (op, work_list, mark_set);
2082 else if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2084 if (and_or_code == BIT_IOR_EXPR)
2085 push_pred (norm_preds, pred);
2086 else
2087 norm_chain->safe_push (pred);
2089 else if (gimple_assign_rhs_code (def_stmt) == and_or_code)
2091 /* Avoid splitting up bit manipulations like x & 3 or y | 1. */
2092 if (is_gimple_min_invariant (gimple_assign_rhs2 (def_stmt)))
2094 /* But treat x & 3 as condition. */
2095 if (and_or_code == BIT_AND_EXPR)
2097 pred_info n_pred;
2098 n_pred.pred_lhs = gimple_assign_rhs1 (def_stmt);
2099 n_pred.pred_rhs = gimple_assign_rhs2 (def_stmt);
2100 n_pred.cond_code = and_or_code;
2101 n_pred.invert = false;
2102 norm_chain->safe_push (n_pred);
2105 else
2107 push_to_worklist (gimple_assign_rhs1 (def_stmt), work_list, mark_set);
2108 push_to_worklist (gimple_assign_rhs2 (def_stmt), work_list, mark_set);
2111 else if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2112 == tcc_comparison)
2114 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2115 if (and_or_code == BIT_IOR_EXPR)
2116 push_pred (norm_preds, n_pred);
2117 else
2118 norm_chain->safe_push (n_pred);
2120 else
2122 if (and_or_code == BIT_IOR_EXPR)
2123 push_pred (norm_preds, pred);
2124 else
2125 norm_chain->safe_push (pred);
2129 /* Normalize PRED and store the normalized predicates into NORM_PREDS. */
2131 static void
2132 normalize_one_pred (pred_chain_union *norm_preds, pred_info pred)
2134 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2135 enum tree_code and_or_code = ERROR_MARK;
2136 pred_chain norm_chain = vNULL;
2138 if (!is_neq_zero_form_p (pred))
2140 push_pred (norm_preds, pred);
2141 return;
2144 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2145 if (gimple_code (def_stmt) == GIMPLE_ASSIGN)
2146 and_or_code = gimple_assign_rhs_code (def_stmt);
2147 if (and_or_code != BIT_IOR_EXPR && and_or_code != BIT_AND_EXPR)
2149 if (TREE_CODE_CLASS (and_or_code) == tcc_comparison)
2151 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2152 push_pred (norm_preds, n_pred);
2154 else
2155 push_pred (norm_preds, pred);
2156 return;
2159 work_list.safe_push (pred);
2160 hash_set<tree> mark_set;
2162 while (!work_list.is_empty ())
2164 pred_info a_pred = work_list.pop ();
2165 normalize_one_pred_1 (norm_preds, &norm_chain, a_pred, and_or_code,
2166 &work_list, &mark_set);
2168 if (and_or_code == BIT_AND_EXPR)
2169 norm_preds->safe_push (norm_chain);
2171 work_list.release ();
2174 static void
2175 normalize_one_pred_chain (pred_chain_union *norm_preds, pred_chain one_chain)
2177 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2178 hash_set<tree> mark_set;
2179 pred_chain norm_chain = vNULL;
2180 size_t i;
2182 for (i = 0; i < one_chain.length (); i++)
2184 work_list.safe_push (one_chain[i]);
2185 mark_set.add (one_chain[i].pred_lhs);
2188 while (!work_list.is_empty ())
2190 pred_info a_pred = work_list.pop ();
2191 normalize_one_pred_1 (0, &norm_chain, a_pred, BIT_AND_EXPR, &work_list,
2192 &mark_set);
2195 norm_preds->safe_push (norm_chain);
2196 work_list.release ();
2199 /* Normalize predicate chains PREDS and returns the normalized one. */
2201 static pred_chain_union
2202 normalize_preds (pred_chain_union preds, gimple *use_or_def, bool is_use)
2204 pred_chain_union norm_preds = vNULL;
2205 size_t n = preds.length ();
2206 size_t i;
2208 if (dump_file && dump_flags & TDF_DETAILS)
2210 fprintf (dump_file, "[BEFORE NORMALIZATION --");
2211 dump_predicates (use_or_def, preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2214 for (i = 0; i < n; i++)
2216 if (preds[i].length () != 1)
2217 normalize_one_pred_chain (&norm_preds, preds[i]);
2218 else
2220 normalize_one_pred (&norm_preds, preds[i][0]);
2221 preds[i].release ();
2225 if (dump_file)
2227 fprintf (dump_file, "[AFTER NORMALIZATION -- ");
2228 dump_predicates (use_or_def, norm_preds,
2229 is_use ? "[USE]:\n" : "[DEF]:\n");
2232 destroy_predicate_vecs (&preds);
2233 return norm_preds;
2236 /* Return TRUE if PREDICATE can be invalidated by any individual
2237 predicate in WORKLIST. */
2239 static bool
2240 can_one_predicate_be_invalidated_p (pred_info predicate,
2241 pred_chain use_guard)
2243 for (size_t i = 0; i < use_guard.length (); ++i)
2245 /* NOTE: This is a very simple check, and only understands an
2246 exact opposite. So, [i == 0] is currently only invalidated
2247 by [.NOT. i == 0] or [i != 0]. Ideally we should also
2248 invalidate with say [i > 5] or [i == 8]. There is certainly
2249 room for improvement here. */
2250 if (pred_neg_p (predicate, use_guard[i]))
2251 return true;
2253 return false;
2256 /* Return TRUE if all predicates in UNINIT_PRED are invalidated by
2257 USE_GUARD being true. */
2259 static bool
2260 can_chain_union_be_invalidated_p (pred_chain_union uninit_pred,
2261 pred_chain use_guard)
2263 if (uninit_pred.is_empty ())
2264 return false;
2265 for (size_t i = 0; i < uninit_pred.length (); ++i)
2267 pred_chain c = uninit_pred[i];
2268 for (size_t j = 0; j < c.length (); ++j)
2269 if (!can_one_predicate_be_invalidated_p (c[j], use_guard))
2270 return false;
2272 return true;
2275 /* Return TRUE if none of the uninitialized operands in UNINT_OPNDS
2276 can actually happen if we arrived at a use for PHI.
2278 PHI_USE_GUARDS are the guard conditions for the use of the PHI. */
2280 static bool
2281 uninit_uses_cannot_happen (gphi *phi, unsigned uninit_opnds,
2282 pred_chain_union phi_use_guards)
2284 unsigned phi_args = gimple_phi_num_args (phi);
2285 if (phi_args > max_phi_args)
2286 return false;
2288 /* PHI_USE_GUARDS are OR'ed together. If we have more than one
2289 possible guard, there's no way of knowing which guard was true.
2290 Since we need to be absolutely sure that the uninitialized
2291 operands will be invalidated, bail. */
2292 if (phi_use_guards.length () != 1)
2293 return false;
2295 /* Look for the control dependencies of all the uninitialized
2296 operands and build guard predicates describing them. */
2297 pred_chain_union uninit_preds;
2298 bool ret = true;
2299 for (unsigned i = 0; i < phi_args; ++i)
2301 if (!MASK_TEST_BIT (uninit_opnds, i))
2302 continue;
2304 edge e = gimple_phi_arg_edge (phi, i);
2305 vec<edge> dep_chains[MAX_NUM_CHAINS];
2306 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
2307 size_t num_chains = 0;
2308 int num_calls = 0;
2310 /* Build the control dependency chain for uninit operand `i'... */
2311 uninit_preds = vNULL;
2312 if (!compute_control_dep_chain (find_dom (e->src),
2313 e->src, dep_chains, &num_chains,
2314 &cur_chain, &num_calls))
2316 ret = false;
2317 break;
2319 /* ...and convert it into a set of predicates. */
2320 convert_control_dep_chain_into_preds (dep_chains, num_chains,
2321 &uninit_preds);
2322 for (size_t j = 0; j < num_chains; ++j)
2323 dep_chains[j].release ();
2324 simplify_preds (&uninit_preds, NULL, false);
2325 uninit_preds = normalize_preds (uninit_preds, NULL, false);
2327 /* Can the guard for this uninitialized operand be invalidated
2328 by the PHI use? */
2329 if (!can_chain_union_be_invalidated_p (uninit_preds, phi_use_guards[0]))
2331 ret = false;
2332 break;
2335 destroy_predicate_vecs (&uninit_preds);
2336 return ret;
2339 /* Computes the predicates that guard the use and checks
2340 if the incoming paths that have empty (or possibly
2341 empty) definition can be pruned/filtered. The function returns
2342 true if it can be determined that the use of PHI's def in
2343 USE_STMT is guarded with a predicate set not overlapping with
2344 predicate sets of all runtime paths that do not have a definition.
2346 Returns false if it is not or it can not be determined. USE_BB is
2347 the bb of the use (for phi operand use, the bb is not the bb of
2348 the phi stmt, but the src bb of the operand edge).
2350 UNINIT_OPNDS is a bit vector. If an operand of PHI is uninitialized, the
2351 corresponding bit in the vector is 1. VISITED_PHIS is a pointer
2352 set of phis being visited.
2354 *DEF_PREDS contains the (memoized) defining predicate chains of PHI.
2355 If *DEF_PREDS is the empty vector, the defining predicate chains of
2356 PHI will be computed and stored into *DEF_PREDS as needed.
2358 VISITED_PHIS is a pointer set of phis being visited. */
2360 static bool
2361 is_use_properly_guarded (gimple *use_stmt,
2362 basic_block use_bb,
2363 gphi *phi,
2364 unsigned uninit_opnds,
2365 pred_chain_union *def_preds,
2366 hash_set<gphi *> *visited_phis)
2368 basic_block phi_bb;
2369 pred_chain_union preds = vNULL;
2370 bool has_valid_preds = false;
2371 bool is_properly_guarded = false;
2373 if (visited_phis->add (phi))
2374 return false;
2376 phi_bb = gimple_bb (phi);
2378 if (is_non_loop_exit_postdominating (use_bb, phi_bb))
2379 return false;
2381 has_valid_preds = find_predicates (&preds, phi_bb, use_bb);
2383 if (!has_valid_preds)
2385 destroy_predicate_vecs (&preds);
2386 return false;
2389 /* Try to prune the dead incoming phi edges. */
2390 is_properly_guarded
2391 = use_pred_not_overlap_with_undef_path_pred (preds, phi, uninit_opnds,
2392 visited_phis);
2394 /* We might be able to prove that if the control dependencies
2395 for UNINIT_OPNDS are true, that the control dependencies for
2396 USE_STMT can never be true. */
2397 if (!is_properly_guarded)
2398 is_properly_guarded |= uninit_uses_cannot_happen (phi, uninit_opnds,
2399 preds);
2401 if (is_properly_guarded)
2403 destroy_predicate_vecs (&preds);
2404 return true;
2407 if (def_preds->is_empty ())
2409 has_valid_preds = find_def_preds (def_preds, phi);
2411 if (!has_valid_preds)
2413 destroy_predicate_vecs (&preds);
2414 return false;
2417 simplify_preds (def_preds, phi, false);
2418 *def_preds = normalize_preds (*def_preds, phi, false);
2421 simplify_preds (&preds, use_stmt, true);
2422 preds = normalize_preds (preds, use_stmt, true);
2424 is_properly_guarded = is_superset_of (*def_preds, preds);
2426 destroy_predicate_vecs (&preds);
2427 return is_properly_guarded;
2430 /* Searches through all uses of a potentially
2431 uninitialized variable defined by PHI and returns a use
2432 statement if the use is not properly guarded. It returns
2433 NULL if all uses are guarded. UNINIT_OPNDS is a bitvector
2434 holding the position(s) of uninit PHI operands. WORKLIST
2435 is the vector of candidate phis that may be updated by this
2436 function. ADDED_TO_WORKLIST is the pointer set tracking
2437 if the new phi is already in the worklist. */
2439 static gimple *
2440 find_uninit_use (gphi *phi, unsigned uninit_opnds,
2441 vec<gphi *> *worklist,
2442 hash_set<gphi *> *added_to_worklist)
2444 tree phi_result;
2445 use_operand_p use_p;
2446 gimple *use_stmt;
2447 imm_use_iterator iter;
2448 pred_chain_union def_preds = vNULL;
2449 gimple *ret = NULL;
2451 phi_result = gimple_phi_result (phi);
2453 FOR_EACH_IMM_USE_FAST (use_p, iter, phi_result)
2455 basic_block use_bb;
2457 use_stmt = USE_STMT (use_p);
2458 if (is_gimple_debug (use_stmt))
2459 continue;
2461 if (gphi *use_phi = dyn_cast<gphi *> (use_stmt))
2462 use_bb = gimple_phi_arg_edge (use_phi,
2463 PHI_ARG_INDEX_FROM_USE (use_p))->src;
2464 else
2465 use_bb = gimple_bb (use_stmt);
2467 hash_set<gphi *> visited_phis;
2468 if (is_use_properly_guarded (use_stmt, use_bb, phi, uninit_opnds,
2469 &def_preds, &visited_phis))
2470 continue;
2472 if (dump_file && (dump_flags & TDF_DETAILS))
2474 fprintf (dump_file, "[CHECK]: Found unguarded use: ");
2475 print_gimple_stmt (dump_file, use_stmt, 0);
2477 /* Found one real use, return. */
2478 if (gimple_code (use_stmt) != GIMPLE_PHI)
2480 ret = use_stmt;
2481 break;
2484 /* Found a phi use that is not guarded,
2485 add the phi to the worklist. */
2486 if (!added_to_worklist->add (as_a<gphi *> (use_stmt)))
2488 if (dump_file && (dump_flags & TDF_DETAILS))
2490 fprintf (dump_file, "[WORKLIST]: Update worklist with phi: ");
2491 print_gimple_stmt (dump_file, use_stmt, 0);
2494 worklist->safe_push (as_a<gphi *> (use_stmt));
2495 possibly_undefined_names->add (phi_result);
2499 destroy_predicate_vecs (&def_preds);
2500 return ret;
2503 /* Look for inputs to PHI that are SSA_NAMEs that have empty definitions
2504 and gives warning if there exists a runtime path from the entry to a
2505 use of the PHI def that does not contain a definition. In other words,
2506 the warning is on the real use. The more dead paths that can be pruned
2507 by the compiler, the fewer false positives the warning is. WORKLIST
2508 is a vector of candidate phis to be examined. ADDED_TO_WORKLIST is
2509 a pointer set tracking if the new phi is added to the worklist or not. */
2511 static void
2512 warn_uninitialized_phi (gphi *phi, vec<gphi *> *worklist,
2513 hash_set<gphi *> *added_to_worklist)
2515 unsigned uninit_opnds;
2516 gimple *uninit_use_stmt = 0;
2517 tree uninit_op;
2518 int phiarg_index;
2519 location_t loc;
2521 /* Don't look at virtual operands. */
2522 if (virtual_operand_p (gimple_phi_result (phi)))
2523 return;
2525 uninit_opnds = compute_uninit_opnds_pos (phi);
2527 if (MASK_EMPTY (uninit_opnds))
2528 return;
2530 if (dump_file && (dump_flags & TDF_DETAILS))
2532 fprintf (dump_file, "[CHECK]: examining phi: ");
2533 print_gimple_stmt (dump_file, phi, 0);
2536 /* Now check if we have any use of the value without proper guard. */
2537 uninit_use_stmt = find_uninit_use (phi, uninit_opnds,
2538 worklist, added_to_worklist);
2540 /* All uses are properly guarded. */
2541 if (!uninit_use_stmt)
2542 return;
2544 phiarg_index = MASK_FIRST_SET_BIT (uninit_opnds);
2545 uninit_op = gimple_phi_arg_def (phi, phiarg_index);
2546 if (SSA_NAME_VAR (uninit_op) == NULL_TREE)
2547 return;
2548 if (gimple_phi_arg_has_location (phi, phiarg_index))
2549 loc = gimple_phi_arg_location (phi, phiarg_index);
2550 else
2551 loc = UNKNOWN_LOCATION;
2552 warn_uninit (OPT_Wmaybe_uninitialized, uninit_op, SSA_NAME_VAR (uninit_op),
2553 SSA_NAME_VAR (uninit_op),
2554 "%qD may be used uninitialized in this function",
2555 uninit_use_stmt, loc);
2558 static bool
2559 gate_warn_uninitialized (void)
2561 return warn_uninitialized || warn_maybe_uninitialized;
2564 namespace {
2566 const pass_data pass_data_late_warn_uninitialized =
2568 GIMPLE_PASS, /* type */
2569 "uninit", /* name */
2570 OPTGROUP_NONE, /* optinfo_flags */
2571 TV_NONE, /* tv_id */
2572 PROP_ssa, /* properties_required */
2573 0, /* properties_provided */
2574 0, /* properties_destroyed */
2575 0, /* todo_flags_start */
2576 0, /* todo_flags_finish */
2579 class pass_late_warn_uninitialized : public gimple_opt_pass
2581 public:
2582 pass_late_warn_uninitialized (gcc::context *ctxt)
2583 : gimple_opt_pass (pass_data_late_warn_uninitialized, ctxt)
2586 /* opt_pass methods: */
2587 opt_pass *clone () { return new pass_late_warn_uninitialized (m_ctxt); }
2588 virtual bool gate (function *) { return gate_warn_uninitialized (); }
2589 virtual unsigned int execute (function *);
2591 }; // class pass_late_warn_uninitialized
2593 unsigned int
2594 pass_late_warn_uninitialized::execute (function *fun)
2596 basic_block bb;
2597 gphi_iterator gsi;
2598 vec<gphi *> worklist = vNULL;
2600 calculate_dominance_info (CDI_DOMINATORS);
2601 calculate_dominance_info (CDI_POST_DOMINATORS);
2602 /* Re-do the plain uninitialized variable check, as optimization may have
2603 straightened control flow. Do this first so that we don't accidentally
2604 get a "may be" warning when we'd have seen an "is" warning later. */
2605 warn_uninitialized_vars (/*warn_possibly_uninitialized=*/1);
2607 timevar_push (TV_TREE_UNINIT);
2609 possibly_undefined_names = new hash_set<tree>;
2610 hash_set<gphi *> added_to_worklist;
2612 /* Initialize worklist */
2613 FOR_EACH_BB_FN (bb, fun)
2614 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2616 gphi *phi = gsi.phi ();
2617 size_t n, i;
2619 n = gimple_phi_num_args (phi);
2621 /* Don't look at virtual operands. */
2622 if (virtual_operand_p (gimple_phi_result (phi)))
2623 continue;
2625 for (i = 0; i < n; ++i)
2627 tree op = gimple_phi_arg_def (phi, i);
2628 if (TREE_CODE (op) == SSA_NAME && uninit_undefined_value_p (op))
2630 worklist.safe_push (phi);
2631 added_to_worklist.add (phi);
2632 if (dump_file && (dump_flags & TDF_DETAILS))
2634 fprintf (dump_file, "[WORKLIST]: add to initial list: ");
2635 print_gimple_stmt (dump_file, phi, 0);
2637 break;
2642 while (worklist.length () != 0)
2644 gphi *cur_phi = 0;
2645 cur_phi = worklist.pop ();
2646 warn_uninitialized_phi (cur_phi, &worklist, &added_to_worklist);
2649 worklist.release ();
2650 delete possibly_undefined_names;
2651 possibly_undefined_names = NULL;
2652 free_dominance_info (CDI_POST_DOMINATORS);
2653 timevar_pop (TV_TREE_UNINIT);
2654 return 0;
2657 } // anon namespace
2659 gimple_opt_pass *
2660 make_pass_late_warn_uninitialized (gcc::context *ctxt)
2662 return new pass_late_warn_uninitialized (ctxt);
2665 static unsigned int
2666 execute_early_warn_uninitialized (void)
2668 /* Currently, this pass runs always but
2669 execute_late_warn_uninitialized only runs with optimization. With
2670 optimization we want to warn about possible uninitialized as late
2671 as possible, thus don't do it here. However, without
2672 optimization we need to warn here about "may be uninitialized". */
2673 calculate_dominance_info (CDI_POST_DOMINATORS);
2675 warn_uninitialized_vars (/*warn_possibly_uninitialized=*/!optimize);
2677 /* Post-dominator information can not be reliably updated. Free it
2678 after the use. */
2680 free_dominance_info (CDI_POST_DOMINATORS);
2681 return 0;
2684 namespace {
2686 const pass_data pass_data_early_warn_uninitialized =
2688 GIMPLE_PASS, /* type */
2689 "*early_warn_uninitialized", /* name */
2690 OPTGROUP_NONE, /* optinfo_flags */
2691 TV_TREE_UNINIT, /* tv_id */
2692 PROP_ssa, /* properties_required */
2693 0, /* properties_provided */
2694 0, /* properties_destroyed */
2695 0, /* todo_flags_start */
2696 0, /* todo_flags_finish */
2699 class pass_early_warn_uninitialized : public gimple_opt_pass
2701 public:
2702 pass_early_warn_uninitialized (gcc::context *ctxt)
2703 : gimple_opt_pass (pass_data_early_warn_uninitialized, ctxt)
2706 /* opt_pass methods: */
2707 virtual bool gate (function *) { return gate_warn_uninitialized (); }
2708 virtual unsigned int execute (function *)
2710 return execute_early_warn_uninitialized ();
2713 }; // class pass_early_warn_uninitialized
2715 } // anon namespace
2717 gimple_opt_pass *
2718 make_pass_early_warn_uninitialized (gcc::context *ctxt)
2720 return new pass_early_warn_uninitialized (ctxt);