LCOV - code coverage report
Current view: top level - gcc/analyzer - diagnostic-manager.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 87.2 % 1337 1166
Test Date: 2026-12-05 16:10:02 Functions: 96.2 % 78 75
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Classes for saving, deduplicating, and emitting analyzer diagnostics.
       2              :    Copyright (C) 2019-2026 Free Software Foundation, Inc.
       3              :    Contributed by David Malcolm <dmalcolm@redhat.com>.
       4              : 
       5              : This file is part of GCC.
       6              : 
       7              : GCC is free software; you can redistribute it and/or modify it
       8              : under the terms of the GNU General Public License as published by
       9              : the Free Software Foundation; either version 3, or (at your option)
      10              : any later version.
      11              : 
      12              : GCC is distributed in the hope that it will be useful, but
      13              : WITHOUT ANY WARRANTY; without even the implied warranty of
      14              : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15              : General Public License for more details.
      16              : 
      17              : You should have received a copy of the GNU General Public License
      18              : along with GCC; see the file COPYING3.  If not see
      19              : <http://www.gnu.org/licenses/>.  */
      20              : 
      21              : #include "analyzer/common.h"
      22              : 
      23              : #include "cfg.h"
      24              : #include "gimple-pretty-print.h"
      25              : #include "gimple-iterator.h"
      26              : #include "inlining-iterator.h"
      27              : #include "cgraph.h"
      28              : #include "digraph.h"
      29              : #include "gcc-rich-location.h"
      30              : #include "diagnostics/sarif-sink.h"
      31              : 
      32              : #include "analyzer/analyzer-logging.h"
      33              : #include "analyzer/sm.h"
      34              : #include "analyzer/pending-diagnostic.h"
      35              : #include "analyzer/diagnostic-manager.h"
      36              : #include "analyzer/call-string.h"
      37              : #include "analyzer/program-point.h"
      38              : #include "analyzer/store.h"
      39              : #include "analyzer/region-model.h"
      40              : #include "analyzer/constraint-manager.h"
      41              : #include "analyzer/supergraph.h"
      42              : #include "analyzer/program-state.h"
      43              : #include "analyzer/exploded-graph.h"
      44              : #include "analyzer/exploded-path.h"
      45              : #include "analyzer/trimmed-graph.h"
      46              : #include "analyzer/feasible-graph.h"
      47              : #include "analyzer/checker-path.h"
      48              : #include "analyzer/reachability.h"
      49              : 
      50              : #if ENABLE_ANALYZER
      51              : 
      52              : namespace ana {
      53              : 
      54              : class feasible_worklist;
      55              : 
      56              : // struct pending_location
      57              : 
      58          759 : pending_location::pending_location ()
      59          759 : : m_enode (nullptr),
      60          759 :   m_event_loc_info (UNKNOWN_LOCATION, NULL_TREE, 0)
      61              : {
      62          759 : }
      63              : 
      64         7097 : pending_location::pending_location (exploded_node *enode)
      65         7097 : : m_enode (enode),
      66         7097 :   m_event_loc_info (enode)
      67              : {
      68         7097 : }
      69              : 
      70         3933 : pending_location::pending_location (exploded_node *enode,
      71              :                                     location_t loc)
      72         3933 : : m_enode (enode),
      73         3933 :   m_event_loc_info (enode)
      74              : {
      75         3933 :   m_event_loc_info.m_loc = loc;
      76         3933 : }
      77              : 
      78              : std::unique_ptr<json::object>
      79           38 : pending_location::to_json () const
      80              : {
      81           38 :   auto ploc_obj = std::make_unique<json::object> ();
      82              : 
      83           38 :   if (m_enode)
      84           38 :     ploc_obj->set_integer ("enode", m_enode->m_index);
      85              :   // TODO: also store m_event_loc_info
      86           38 :   return ploc_obj;
      87              : }
      88              : 
      89              : /* State for finding the shortest feasible exploded_path for a
      90              :    saved_diagnostic.
      91              :    This is shared between all diagnostics, so that we avoid repeating work.  */
      92              : 
      93              : class epath_finder
      94              : {
      95              : public:
      96         1668 :   epath_finder (const exploded_graph &eg)
      97         1668 :   : m_eg (eg),
      98         1668 :     m_sep (nullptr)
      99              :   {
     100              :     /* This is shared by all diagnostics, but only needed if
     101              :        !flag_analyzer_feasibility.  */
     102         1668 :     if (!flag_analyzer_feasibility)
     103            4 :       m_sep = new shortest_exploded_paths (eg, eg.get_origin (),
     104            4 :                                            SPS_FROM_GIVEN_ORIGIN);
     105         1668 :   }
     106              : 
     107         1672 :   ~epath_finder () { delete m_sep; }
     108              : 
     109       130097 :   logger *get_logger () const { return m_eg.get_logger (); }
     110              : 
     111              :   std::unique_ptr<exploded_path>
     112              :   get_best_epath (const exploded_node *target_enode,
     113              :                   const pending_diagnostic &pd,
     114              :                   const char *desc, unsigned diag_idx,
     115              :                   std::unique_ptr<feasibility_problem> *out_problem);
     116              : 
     117              : private:
     118              :   DISABLE_COPY_AND_ASSIGN(epath_finder);
     119              : 
     120              :   std::unique_ptr<exploded_path>
     121              :   explore_feasible_paths (const exploded_node *target_enode,
     122              :                           const pending_diagnostic &pd,
     123              :                           const char *desc, unsigned diag_idx);
     124              :   bool
     125              :   process_worklist_item (feasible_worklist *worklist,
     126              :                          const trimmed_graph &tg,
     127              :                          feasible_graph *fg,
     128              :                          const exploded_node *target_enode,
     129              :                          const pending_diagnostic &pd,
     130              :                          unsigned diag_idx,
     131              :                          std::unique_ptr<exploded_path> *out_best_path) const;
     132              :   void dump_trimmed_graph (const exploded_node *target_enode,
     133              :                            const char *desc, unsigned diag_idx,
     134              :                            const trimmed_graph &tg,
     135              :                            const shortest_paths<eg_traits, exploded_path> &sep);
     136              :   void dump_feasible_graph (const exploded_node *target_enode,
     137              :                             const char *desc, unsigned diag_idx,
     138              :                             const feasible_graph &fg);
     139              :   void dump_feasible_path (const exploded_node *target_enode,
     140              :                            unsigned diag_idx,
     141              :                            const feasible_graph &fg,
     142              :                            const feasible_node &fnode) const;
     143              : 
     144              :   const exploded_graph &m_eg;
     145              :   shortest_exploded_paths *m_sep;
     146              : };
     147              : 
     148              : /* class epath_finder.  */
     149              : 
     150              : /* Get the "best" exploded_path for reaching TARGET_ENODE from the origin,
     151              :    returning ownership of it to the caller.
     152              : 
     153              :    Ideally we want to report the shortest feasible path.
     154              :    Return nullptr if we could not find a feasible path
     155              :    (when flag_analyzer_feasibility is true).
     156              : 
     157              :    If flag_analyzer_feasibility is false, then simply return the
     158              :    shortest path.
     159              : 
     160              :    Use DESC and DIAG_IDX when logging.
     161              : 
     162              :    Write any feasibility_problem to *OUT_PROBLEM.  */
     163              : 
     164              : std::unique_ptr<exploded_path>
     165         6713 : epath_finder::get_best_epath (const exploded_node *target_enode,
     166              :                               const pending_diagnostic &pd,
     167              :                               const char *desc, unsigned diag_idx,
     168              :                               std::unique_ptr<feasibility_problem> *out_problem)
     169              : {
     170         6713 :   logger *logger = get_logger ();
     171         6713 :   LOG_SCOPE (logger);
     172              : 
     173         6713 :   unsigned snode_id = target_enode->get_supernode ()->m_id;
     174         6713 :   if (logger)
     175            2 :     logger->log ("considering %qs at EN: %i, SN: %i (sd: %i)",
     176            2 :                  desc, target_enode->m_index, snode_id, diag_idx);
     177              : 
     178              :   /* State-merging means that not every path in the egraph corresponds
     179              :      to a feasible one w.r.t. states.
     180              : 
     181              :      We want to find the shortest feasible path from the origin to ENODE
     182              :      in the egraph.  */
     183              : 
     184         6713 :   if (flag_analyzer_feasibility)
     185              :     {
     186              :       /* Attempt to find the shortest feasible path using feasible_graph.  */
     187         6709 :       if (logger)
     188            2 :         logger->log ("trying to find shortest feasible path");
     189         6709 :       if (std::unique_ptr<exploded_path> epath
     190         6709 :             = explore_feasible_paths (target_enode, pd, desc, diag_idx))
     191              :         {
     192         6489 :           if (logger)
     193            2 :             logger->log ("accepting %qs at EN: %i, SN: %i (sd: %i)"
     194              :                          " with feasible path (length: %i)",
     195            2 :                          desc, target_enode->m_index, snode_id, diag_idx,
     196              :                          epath->length ());
     197         6489 :           return epath;
     198              :         }
     199              :       else
     200              :         {
     201          220 :           if (logger)
     202            0 :             logger->log ("rejecting %qs at EN: %i, SN: %i (sd: %i)"
     203              :                          " due to not finding feasible path",
     204            0 :                          desc, target_enode->m_index, snode_id, diag_idx);
     205          220 :           return nullptr;
     206         6709 :         }
     207              :     }
     208              :   else
     209              :     {
     210              :       /* As a crude approximation to shortest feasible path, simply find
     211              :          the shortest path, and note whether it is feasible.
     212              :          There could be longer feasible paths within the egraph, so this
     213              :          approach would lead to diagnostics being falsely rejected
     214              :          (PR analyzer/96374).  */
     215            4 :       if (logger)
     216            0 :         logger->log ("trying to find shortest path ignoring feasibility");
     217            4 :       gcc_assert (m_sep);
     218            4 :       auto epath
     219              :         = std::make_unique<exploded_path>
     220            4 :             (m_sep->get_shortest_path (target_enode));
     221            4 :       if (epath->feasible_p (logger, out_problem, m_eg.get_engine (), &m_eg))
     222              :         {
     223            0 :           if (logger)
     224            0 :             logger->log ("accepting %qs at EN: %i, SN: %i (sn: %i)"
     225              :                          " with feasible path (length: %i)",
     226            0 :                          desc, target_enode->m_index, snode_id, diag_idx,
     227              :                          epath->length ());
     228              :         }
     229              :       else
     230              :         {
     231            4 :           if (logger)
     232            0 :             logger->log ("accepting %qs at EN: %i, SN: %i (sn: %i) (length: %i)"
     233              :                          " despite infeasible path (due to %qs)",
     234            0 :                          desc, target_enode->m_index, snode_id, diag_idx,
     235              :                          epath->length (),
     236              :                          "-fno-analyzer-feasibility");
     237              :         }
     238            4 :       return epath;
     239            4 :     }
     240         6713 : }
     241              : 
     242              : /* A class for managing the worklist of feasible_nodes in
     243              :    epath_finder::explore_feasible_paths, prioritizing them
     244              :    so that shorter paths appear earlier in the queue.  */
     245              : 
     246        13418 : class feasible_worklist
     247              : {
     248              : public:
     249         6709 :   feasible_worklist (const shortest_paths<eg_traits, exploded_path> &sep)
     250        13418 :   : m_queue (key_t (*this, nullptr)),
     251         6709 :     m_sep (sep)
     252              :   {
     253         6709 :   }
     254              : 
     255       109962 :   feasible_node *take_next () { return m_queue.extract_min (); }
     256              : 
     257       112037 :   void add_node (feasible_node *fnode)
     258              :   {
     259       224074 :     m_queue.insert (key_t (*this, fnode), fnode);
     260              :   }
     261              : 
     262              : private:
     263              :   struct key_t
     264              :   {
     265       118746 :     key_t (const feasible_worklist &w, feasible_node *fnode)
     266         6709 :     : m_worklist (w), m_fnode (fnode)
     267              :     {}
     268              : 
     269        60736 :     bool operator< (const key_t &other) const
     270              :     {
     271        60736 :       return cmp (*this, other) < 0;
     272              :     }
     273              : 
     274        14262 :     bool operator== (const key_t &other) const
     275              :     {
     276        14262 :       return cmp (*this, other) == 0;
     277              :     }
     278              : 
     279        14262 :     bool operator> (const key_t &other) const
     280              :     {
     281        14262 :       return !(*this == other || *this < other);
     282              :     }
     283              : 
     284              :   private:
     285        74998 :     static int cmp (const key_t &ka, const key_t &kb)
     286              :     {
     287              :       /* Choose the node for which if the remaining path were feasible,
     288              :          it would be the shortest path (summing the length of the
     289              :          known-feasible path so far with that of the remaining
     290              :          possibly-feasible path).  */
     291        74998 :       int ca = ka.m_worklist.get_estimated_cost (ka.m_fnode);
     292        74998 :       int cb = kb.m_worklist.get_estimated_cost (kb.m_fnode);
     293        74998 :       return ca - cb;
     294              :     }
     295              : 
     296              :     const feasible_worklist &m_worklist;
     297              :     feasible_node *m_fnode;
     298              :   };
     299              : 
     300              :   /* Get the estimated length of a path involving FNODE from
     301              :      the origin to the target enode.
     302              :      Sum the length of the known-feasible path so far with
     303              :      that of the remaining possibly-feasible path.  */
     304              : 
     305       149996 :   int get_estimated_cost (const feasible_node *fnode) const
     306              :   {
     307       149996 :     unsigned length_so_far = fnode->get_path_length ();
     308       149996 :     int shortest_remaining_path
     309       149996 :       = m_sep.get_shortest_distance (fnode->get_inner_node ());
     310              : 
     311       149996 :     gcc_assert (shortest_remaining_path >= 0);
     312              :     /* This should be true since we're only exploring nodes within
     313              :        the trimmed graph (and we anticipate it being much smaller
     314              :        than this, and thus not overflowing the sum).  */
     315       149996 :     gcc_assert (shortest_remaining_path < INT_MAX);
     316              : 
     317       149996 :     return length_so_far + shortest_remaining_path;
     318              :   }
     319              : 
     320              :   /* Priority queue, backed by a fibonacci_heap.  */
     321              :   typedef fibonacci_heap<key_t, feasible_node> queue_t;
     322              :   queue_t m_queue;
     323              :   const shortest_paths<eg_traits, exploded_path> &m_sep;
     324              : };
     325              : 
     326              : /* When we're building the exploded graph we want to simplify
     327              :    overly-complicated symbolic values down to "UNKNOWN" to try to avoid
     328              :    state explosions and unbounded chains of exploration.
     329              : 
     330              :    However, when we're building the feasibility graph for a diagnostic
     331              :    (actually a tree), we don't want UNKNOWN values, as conditions on them
     332              :    are also unknown: we don't want to have a contradiction such as a path
     333              :    where (VAL != 0) and then (VAL == 0) along the same path.
     334              : 
     335              :    Hence this is an RAII class for temporarily disabling complexity-checking
     336              :    in the region_model_manager, for use within
     337              :    epath_finder::explore_feasible_paths.
     338              : 
     339              :    We also disable the creation of unknown_svalue instances during feasibility
     340              :    checking, instead creating unique svalues, to avoid paradoxes in paths.  */
     341              : 
     342              : class auto_checking_feasibility
     343              : {
     344              : public:
     345         6709 :   auto_checking_feasibility (region_model_manager *mgr) : m_mgr (mgr)
     346              :   {
     347         6709 :     m_mgr->begin_checking_feasibility ();
     348              :   }
     349         6709 :   ~auto_checking_feasibility ()
     350              :   {
     351         6709 :     m_mgr->end_checking_feasibility ();
     352              :   }
     353              : private:
     354              :   region_model_manager *m_mgr;
     355              : };
     356              : 
     357              : /* Attempt to find the shortest feasible path from the origin to
     358              :    TARGET_ENODE by iteratively building a feasible_graph, in which
     359              :    every path to a feasible_node is feasible by construction.
     360              : 
     361              :    We effectively explore the tree of feasible paths in order of shortest
     362              :    path until we either find a feasible path to TARGET_ENODE, or hit
     363              :    a limit and give up.
     364              : 
     365              :    Preliminaries:
     366              :    - Find the shortest path from each node to the TARGET_ENODE (without
     367              :    checking feasibility), so that we can prioritize our worklist.
     368              :    - Construct a trimmed_graph: the subset of nodes/edges that
     369              :    are on a path that eventually reaches TARGET_ENODE.  We will only need
     370              :    to consider these when considering the shortest feasible path.
     371              : 
     372              :    Build a feasible_graph, in which every path to a feasible_node
     373              :    is feasible by construction.
     374              :    We use a worklist to flatten the exploration into an iteration.
     375              :    Starting at the origin, find feasible out-edges within the trimmed graph.
     376              :    At each stage, choose the node for which if the remaining path were feasible,
     377              :    it would be the shortest path (summing the length of the known-feasible path
     378              :    so far with that of the remaining possibly-feasible path).
     379              :    This way, the first feasible path we find to TARGET_ENODE is the shortest.
     380              :    We start by trying the shortest possible path, but if that fails,
     381              :    we explore progressively longer paths, eventually trying iterations through
     382              :    loops.  The exploration is captured in the feasible_graph, which can be
     383              :    dumped as a .dot file to visualize the exploration.  The indices of the
     384              :    feasible_nodes show the order in which they were created.
     385              : 
     386              :    This is something of a brute-force approach, but the trimmed_graph
     387              :    hopefully keeps the complexity manageable.
     388              : 
     389              :    Terminate with failure when the number of infeasible edges exceeds
     390              :    a threshold (--param=analyzer-max-infeasible-edges=).
     391              :    This is guaranteed to eventually lead to terminatation, as
     392              :    we can't keep creating feasible nodes without eventually
     393              :    either reaching an infeasible edge, or reaching the
     394              :    TARGET_ENODE.  Specifically, there can't be a cycle of
     395              :    feasible edges that doesn't reach the target_enode without
     396              :    an out-edge that either fails feasibility or gets closer
     397              :    to the TARGET_ENODE: on each iteration we are either:
     398              :    - effectively getting closer to the TARGET_ENODE (which can't
     399              :      continue forever without reaching the target), or
     400              :    - getting monotonically closer to the termination threshold.  */
     401              : 
     402              : std::unique_ptr<exploded_path>
     403         6709 : epath_finder::explore_feasible_paths (const exploded_node *target_enode,
     404              :                                       const pending_diagnostic &pd,
     405              :                                       const char *desc, unsigned diag_idx)
     406              : {
     407         6709 :   logger *logger = get_logger ();
     408         6709 :   LOG_SCOPE (logger);
     409              : 
     410         6709 :   region_model_manager *mgr = m_eg.get_engine ()->get_model_manager ();
     411              : 
     412              :   /* Determine the shortest path to TARGET_ENODE from each node in
     413              :      the exploded graph.  */
     414         6709 :   shortest_paths<eg_traits, exploded_path> sep
     415         6709 :     (m_eg, target_enode, SPS_TO_GIVEN_TARGET);
     416              : 
     417              :   /* Construct a trimmed_graph: the subset of nodes/edges that
     418              :      are on a path that eventually reaches TARGET_ENODE.
     419              :      We only need to consider these when considering the shortest
     420              :      feasible path.  */
     421         6709 :   trimmed_graph tg (m_eg, target_enode);
     422              : 
     423         6709 :   if (flag_dump_analyzer_feasibility)
     424            4 :     dump_trimmed_graph (target_enode, desc, diag_idx, tg, sep);
     425              : 
     426         6709 :   feasible_graph fg;
     427         6709 :   feasible_worklist worklist (sep);
     428              : 
     429              :   /* Populate the worklist with the origin node.  */
     430         6709 :   {
     431         6709 :     feasibility_state init_state (mgr, m_eg.get_supergraph ());
     432         6709 :     feasible_node *origin = fg.add_node (m_eg.get_origin (), init_state, 0);
     433         6709 :     worklist.add_node (origin);
     434         6709 :   }
     435              : 
     436              :   /* Iteratively explore the tree of feasible paths in order of shortest
     437              :      path until we either find a feasible path to TARGET_ENODE, or hit
     438              :      a limit.  */
     439              : 
     440              :   /* Set this if we find a feasible path to TARGET_ENODE.  */
     441         6709 :   std::unique_ptr<exploded_path> best_path = nullptr;
     442              : 
     443         6709 :   {
     444         6709 :     auto_checking_feasibility sentinel (mgr);
     445              : 
     446       109962 :     while (process_worklist_item (&worklist, tg, &fg, target_enode,
     447              :                                   pd, diag_idx, &best_path))
     448              :       {
     449              :         /* Empty; the work is done within process_worklist_item.  */
     450              :       }
     451         6709 :   }
     452              : 
     453         6709 :   if (logger)
     454              :     {
     455            2 :       logger->log ("tg for sd: %i:", diag_idx);
     456            2 :       logger->inc_indent ();
     457            2 :       tg.log_stats (logger);
     458            2 :       logger->dec_indent ();
     459              : 
     460            2 :       logger->log ("fg for sd: %i:", diag_idx);
     461            2 :       logger->inc_indent ();
     462            2 :       fg.log_stats (logger);
     463            2 :       logger->dec_indent ();
     464              :     }
     465              : 
     466              :   /* Dump the feasible_graph.  */
     467         6709 :   if (flag_dump_analyzer_feasibility)
     468            4 :     dump_feasible_graph (target_enode, desc, diag_idx, fg);
     469              : 
     470         6709 :   return best_path;
     471        13418 : }
     472              : 
     473              : /* Process the next item in WORKLIST, potentially adding new items
     474              :    based on feasible out-edges, and extending FG accordingly.
     475              :    Use TG to ignore out-edges that don't lead to TARGET_ENODE.
     476              :    Return true if the worklist processing should continue.
     477              :    Return false if the processing of the worklist should stop
     478              :    (either due to reaching TARGET_ENODE, or hitting a limit).
     479              :    Write to *OUT_BEST_PATH if stopping due to finding a feasible path
     480              :    to TARGET_ENODE.
     481              :    Use PD to provide additional restrictions on feasibility of
     482              :    the final path in the feasible_graph before converting to
     483              :    an exploded_path.  */
     484              : 
     485              : bool
     486       109962 : epath_finder::
     487              : process_worklist_item (feasible_worklist *worklist,
     488              :                        const trimmed_graph &tg,
     489              :                        feasible_graph *fg,
     490              :                        const exploded_node *target_enode,
     491              :                        const pending_diagnostic &pd,
     492              :                        unsigned diag_idx,
     493              :                        std::unique_ptr<exploded_path> *out_best_path) const
     494              : {
     495       109962 :   logger *logger = get_logger ();
     496              : 
     497       109962 :   feasible_node *fnode = worklist->take_next ();
     498       109962 :   if (!fnode)
     499              :     {
     500           38 :       if (logger)
     501            0 :         logger->log ("drained worklist for sd: %i"
     502              :                      " without finding feasible path",
     503              :                      diag_idx);
     504              :       return false;
     505              :     }
     506              : 
     507       109924 :   log_scope s (logger, "fg worklist item",
     508              :                "considering FN: %i (EN: %i) for sd: %i",
     509       109924 :                fnode->get_index (), fnode->get_inner_node ()->m_index,
     510       109924 :                diag_idx);
     511              : 
     512              :   /* Iterate through all out-edges from this item.  */
     513       109924 :   unsigned i;
     514       109924 :   exploded_edge *succ_eedge;
     515       381870 :   FOR_EACH_VEC_ELT (fnode->get_inner_node ()->m_succs, i, succ_eedge)
     516              :     {
     517       168693 :       log_scope s (logger, "edge", "considering edge: EN:%i -> EN:%i",
     518       168693 :                    succ_eedge->m_src->m_index,
     519       168693 :                    succ_eedge->m_dest->m_index);
     520              :       /* Reject edges that aren't in the trimmed graph.  */
     521       168693 :       if (!tg.contains_p (succ_eedge))
     522              :         {
     523        55195 :           if (logger)
     524            1 :             logger->log ("rejecting: not in trimmed graph");
     525        55195 :           continue;
     526              :         }
     527              : 
     528       113498 :       feasibility_state succ_state (fnode->get_state ());
     529       113498 :       std::unique_ptr<rejected_constraint> rc;
     530       113498 :       if (succ_state.maybe_update_for_edge (logger, succ_eedge, nullptr, &rc))
     531              :         {
     532       111878 :           gcc_assert (rc == nullptr);
     533       111878 :           feasible_node *succ_fnode
     534       111878 :             = fg->add_node (succ_eedge->m_dest,
     535              :                             succ_state,
     536       111878 :                             fnode->get_path_length () + 1);
     537       111878 :           if (logger)
     538           14 :             logger->log ("accepting as FN: %i", succ_fnode->get_index ());
     539       111878 :           fg->add_edge (new feasible_edge (fnode, succ_fnode, succ_eedge));
     540              : 
     541              :           /* Have we reached TARGET_ENODE?  */
     542       111878 :           if (succ_fnode->get_inner_node () == target_enode)
     543              :             {
     544         6550 :               if (logger)
     545            2 :                 logger->log ("success: got feasible path to EN: %i (sd: %i)"
     546              :                              " (length: %i)",
     547            2 :                              target_enode->m_index, diag_idx,
     548              :                              succ_fnode->get_path_length ());
     549         6550 :               if (!pd.check_valid_fpath_p (*succ_fnode))
     550              :                 {
     551           61 :                   if (logger)
     552            0 :                     logger->log ("rejecting feasible path due to"
     553              :                                  " pending_diagnostic");
     554              :                   return false;
     555              :                 }
     556         6489 :               *out_best_path = fg->make_epath (succ_fnode);
     557         6489 :               if (flag_dump_analyzer_feasibility)
     558            4 :                 dump_feasible_path (target_enode, diag_idx, *fg, *succ_fnode);
     559              : 
     560              :               /* Success: stop the worklist iteration.  */
     561              :               return false;
     562              :             }
     563              :           else
     564       105328 :             worklist->add_node (succ_fnode);
     565              :         }
     566              :       else
     567              :         {
     568         1620 :           if (logger)
     569            0 :             logger->log ("infeasible");
     570         1620 :           gcc_assert (rc);
     571         1620 :           fg->add_feasibility_problem (fnode,
     572              :                                        succ_eedge,
     573              :                                        std::move (rc));
     574              : 
     575              :           /* Give up if there have been too many infeasible edges.  */
     576         1620 :           if (fg->get_num_infeasible ()
     577         1620 :               > (unsigned)param_analyzer_max_infeasible_edges)
     578              :             {
     579          121 :               if (logger)
     580            0 :                 logger->log ("too many infeasible edges (%i); giving up",
     581              :                              fg->get_num_infeasible ());
     582              :               return false;
     583              :             }
     584              :         }
     585       168693 :     }
     586              : 
     587              :   /* Continue the worklist iteration.  */
     588              :   return true;
     589       109924 : }
     590              : 
     591              : /* Helper class for epath_finder::dump_trimmed_graph
     592              :    to dump extra per-node information.
     593              :    Use SEP to add the length of the shortest path from each
     594              :    node to the target node to each node's dump.  */
     595              : 
     596              : class dump_eg_with_shortest_path : public eg_traits::dump_args_t
     597              : {
     598              : public:
     599            4 :   dump_eg_with_shortest_path
     600              :     (const exploded_graph &eg,
     601              :      const shortest_paths<eg_traits, exploded_path> &sep)
     602              :   : dump_args_t (eg),
     603            4 :     m_sep (sep)
     604              :   {
     605              :   }
     606              : 
     607           74 :   void dump_extra_info (const exploded_node *enode,
     608              :                         pretty_printer *pp) const final override
     609              :   {
     610           74 :     pp_printf (pp, "sp: %i", m_sep.get_shortest_path (enode).length ());
     611           74 :     pp_newline (pp);
     612           74 :   }
     613              : 
     614              : private:
     615              :   const shortest_paths<eg_traits, exploded_path> &m_sep;
     616              : };
     617              : 
     618              : /* Dump TG to "BASE_NAME.DESC.DIAG_IDX.to-enN.tg.dot",
     619              :    annotating each node with the length of the shortest path
     620              :    from that node to TARGET_ENODE (using SEP).  */
     621              : 
     622              : void
     623            4 : epath_finder::
     624              : dump_trimmed_graph (const exploded_node *target_enode,
     625              :                     const char *desc, unsigned diag_idx,
     626              :                     const trimmed_graph &tg,
     627              :                     const shortest_paths<eg_traits, exploded_path> &sep)
     628              : {
     629            4 :   auto_timevar tv (TV_ANALYZER_DUMP);
     630            4 :   dump_eg_with_shortest_path inner_args (m_eg, sep);
     631            4 :   trimmed_graph::dump_args_t args (inner_args);
     632            4 :   pretty_printer pp;
     633            4 :   pp_printf (&pp, "%s.%s.%i.to-en%i.tg.dot",
     634            4 :              dump_base_name, desc, diag_idx, target_enode->m_index);
     635            4 :   char *filename = xstrdup (pp_formatted_text (&pp));
     636            4 :   tg.dump_dot (filename, nullptr, args);
     637            4 :   free (filename);
     638            4 : }
     639              : 
     640              : /* Dump FG to "BASE_NAME.DESC.DIAG_IDX.to-enN.fg.dot".  */
     641              : 
     642              : void
     643            4 : epath_finder::dump_feasible_graph (const exploded_node *target_enode,
     644              :                                    const char *desc, unsigned diag_idx,
     645              :                                    const feasible_graph &fg)
     646              : {
     647            4 :   auto_timevar tv (TV_ANALYZER_DUMP);
     648            4 :   exploded_graph::dump_args_t inner_args (m_eg);
     649            4 :   feasible_graph::dump_args_t args (inner_args);
     650            4 :   pretty_printer pp;
     651            4 :   pp_printf (&pp, "%s.%s.%i.to-en%i.fg.dot",
     652            4 :              dump_base_name, desc, diag_idx, target_enode->m_index);
     653            4 :   char *filename = xstrdup (pp_formatted_text (&pp));
     654            4 :   fg.dump_dot (filename, nullptr, args);
     655            4 :   free (filename);
     656            4 : }
     657              : 
     658              : /* Dump the path to FNODE to "BASE_NAME.DIAG_IDX.to-enN.fpath.txt".  */
     659              : 
     660              : void
     661            4 : epath_finder::dump_feasible_path (const exploded_node *target_enode,
     662              :                                   unsigned diag_idx,
     663              :                                   const feasible_graph &fg,
     664              :                                   const feasible_node &fnode) const
     665              : {
     666            4 :   auto_timevar tv (TV_ANALYZER_DUMP);
     667            4 :   pretty_printer pp;
     668            4 :   pp_printf (&pp, "%s.%i.to-en%i.fpath.txt",
     669            4 :              dump_base_name, diag_idx, target_enode->m_index);
     670            4 :   char *filename = xstrdup (pp_formatted_text (&pp));
     671            4 :   fg.dump_feasible_path (fnode, filename);
     672            4 :   free (filename);
     673            4 : }
     674              : 
     675              : /* class saved_diagnostic.  */
     676              : 
     677              : /* saved_diagnostic's ctor.  */
     678              : 
     679         6713 : saved_diagnostic::saved_diagnostic (const state_machine *sm,
     680              :                                     pending_location &&ploc,
     681              :                                     tree var,
     682              :                                     const svalue *sval,
     683              :                                     state_machine::state_t state,
     684              :                                     std::unique_ptr<pending_diagnostic> d,
     685              :                                     unsigned idx)
     686         6713 : : m_sm (sm),
     687         6713 :   m_ploc (std::move (ploc)),
     688         6713 :   m_var (var), m_sval (sval), m_state (state),
     689         6713 :   m_d (std::move (d)), m_trailing_eedge (nullptr),
     690         6713 :   m_idx (idx),
     691         6713 :   m_best_epath (nullptr), m_problem (nullptr),
     692         6713 :   m_notes ()
     693              : {
     694              :   /* We must have an enode in order to be able to look for paths
     695              :      through the exploded_graph to this diagnostic.  */
     696         6713 :   gcc_assert (m_ploc.m_enode);
     697         6713 : }
     698              : 
     699              : const supernode *
     700       160130 : saved_diagnostic::get_supernode () const
     701              : {
     702       160130 :   return m_ploc.m_enode->get_supernode ();
     703              : }
     704              : 
     705              : bool
     706        53354 : saved_diagnostic::operator== (const saved_diagnostic &other) const
     707              : {
     708        55834 :   if (m_notes.length () != other.m_notes.length ())
     709              :     return false;
     710        52952 :   for (unsigned i = 0; i < m_notes.length (); i++)
     711          912 :     if (!m_notes[i]->equal_p (*other.m_notes[i]))
     712              :       return false;
     713              : 
     714              :   // Don't deduplicate dump_path_diagnostic instances
     715        52040 :   if (!strcmp (m_d->get_kind (), "dump_path_diagnostic"))
     716         1560 :     return this == &other;
     717              : 
     718        50480 :   return (m_sm == other.m_sm
     719              :           /* We don't compare m_enode.  */
     720        43894 :           && get_supernode () == other.get_supernode ()
     721         9242 :           && (m_ploc.m_event_loc_info.m_loc
     722         9242 :               == other.m_ploc.m_event_loc_info.m_loc)
     723         7215 :           && pending_diagnostic::same_tree_p (m_var, other.m_var)
     724         6557 :           && m_state == other.m_state
     725         6505 :           && m_d->equal_p (*other.m_d)
     726        56713 :           && m_trailing_eedge == other.m_trailing_eedge);
     727              : }
     728              : 
     729              : /* Add PN to this diagnostic, taking ownership of it.  */
     730              : 
     731              : void
     732          222 : saved_diagnostic::add_note (std::unique_ptr<pending_note> pn)
     733              : {
     734          222 :   gcc_assert (pn);
     735          222 :   m_notes.safe_push (pn.release ());
     736          222 : }
     737              : 
     738              : /* Add EVENT to this diagnostic.  */
     739              : 
     740              : void
     741          187 : saved_diagnostic::add_event (std::unique_ptr<checker_event> event)
     742              : {
     743          187 :   gcc_assert (event);
     744          187 :   m_saved_events.safe_push (event.release ());
     745          187 : }
     746              : 
     747              : /* Return a new json::object of the form
     748              :    {"sm": optional str,
     749              :     "ploc": {},
     750              :     "sval": optional str,
     751              :     "state": optional str,
     752              :     "path_length": optional int,
     753              :     "pending_diagnostic": str,
     754              :     "idx": int}.  */
     755              : 
     756              : std::unique_ptr<json::object>
     757            1 : saved_diagnostic::to_json () const
     758              : {
     759            1 :   auto sd_obj = std::make_unique<json::object> ();
     760              : 
     761            1 :   if (m_sm)
     762            1 :     sd_obj->set_string ("sm", m_sm->get_name ());
     763            1 :   sd_obj->set ("ploc", m_ploc.to_json ());
     764            1 :   if (m_sval)
     765            1 :     sd_obj->set ("sval", m_sval->to_json ());
     766            1 :   if (m_state)
     767            1 :     sd_obj->set ("state", m_state->to_json ());
     768            1 :   if (m_best_epath)
     769            1 :     sd_obj->set_integer ("path_length", get_epath_length ());
     770            1 :   sd_obj->set<json::object> ("pending_diagnostic", m_d->to_json ());
     771            1 :   sd_obj->set_integer ("idx", m_idx);
     772            1 :   if (m_problem)
     773            0 :     sd_obj->set<json::object> ("feasibility_problem", m_problem->to_json ());
     774            1 :   if (!m_duplicates.is_empty ())
     775              :     {
     776            0 :       auto arr = std::make_unique<json::array> ();
     777              : 
     778            0 :       for (auto &dup : m_duplicates)
     779            0 :         arr->append (std::make_unique <json::integer_number> (dup->m_idx));
     780              : 
     781            0 :       sd_obj->set<json::array> ("duplicates", std::move (arr));
     782            0 :     }
     783              : 
     784            1 :   return sd_obj;
     785              : }
     786              : 
     787              : /* Dump this to PP in a form suitable for use as an id in .dot output.  */
     788              : 
     789              : void
     790           16 : saved_diagnostic::dump_dot_id (pretty_printer *pp) const
     791              : {
     792           16 :   pp_printf (pp, "sd_%i", m_idx);
     793           16 : }
     794              : 
     795              : /* Dump this to PP in a form suitable for use as a node in .dot output.  */
     796              : 
     797              : void
     798            8 : saved_diagnostic::dump_as_dot_node (pretty_printer *pp) const
     799              : {
     800            8 :   dump_dot_id (pp);
     801            8 :   pp_printf (pp,
     802              :              (" [shape=none,margin=0,style=filled,fillcolor=\"red\","
     803              :               "fontname=\"Monospace\",label=\""));
     804            8 :   pp_write_text_to_stream (pp);
     805              : 
     806              :   /* Node label.  */
     807            8 :   pp_printf (pp, "DIAGNOSTIC: %s (sd: %i)\n",
     808            8 :              m_d->get_kind (), m_idx);
     809            8 :   if (m_sm)
     810              :     {
     811            8 :       pp_printf (pp, "sm: %s", m_sm->get_name ());
     812            8 :       if (m_state)
     813              :         {
     814            8 :           pp_printf (pp, "; state: ");
     815            8 :           m_state->dump_to_pp (pp);
     816              :         }
     817            8 :       pp_newline (pp);
     818              :     }
     819            8 :   if (m_var)
     820            8 :     pp_printf (pp, "var: %qE\n", m_var);
     821            8 :   if (m_sval)
     822              :     {
     823            8 :       pp_string (pp, "sval: ");
     824            8 :       m_sval->symbolic::node::dump_to_pp (pp);
     825            8 :       pp_newline (pp);
     826              :     }
     827            8 :   if (m_best_epath)
     828            0 :     pp_printf (pp, "path length: %i\n", get_epath_length ());
     829              : 
     830            8 :   pp_write_text_as_dot_label_to_stream (pp, /*for_record=*/true);
     831            8 :   pp_string (pp, "\"];\n\n");
     832              : 
     833              :   /* Show links to duplicates.  */
     834            8 :   for (auto iter : m_duplicates)
     835              :     {
     836            0 :       dump_dot_id (pp);
     837            0 :       pp_string (pp, " -> ");
     838            0 :       iter->dump_dot_id (pp);
     839            0 :       pp_string (pp, " [style=\"dotted\" arrowhead=\"none\"];");
     840            0 :       pp_newline (pp);
     841              :     }
     842            8 : }
     843              : 
     844              : /* Use PF to find the best exploded_path for this saved_diagnostic, if any,
     845              :    and store it in m_best_epath.
     846              :    Return true if a best path was found.  */
     847              : 
     848              : bool
     849         6713 : saved_diagnostic::calc_best_epath (epath_finder *pf)
     850              : {
     851         6713 :   logger *logger = pf->get_logger ();
     852         6713 :   LOG_SCOPE (logger);
     853         6713 :   m_problem = nullptr;
     854              : 
     855         6713 :   m_best_epath = pf->get_best_epath (m_ploc.m_enode,
     856         6713 :                                      *m_d, m_d->get_kind (), m_idx,
     857         6713 :                                      &m_problem);
     858              : 
     859              :   /* Handle failure to find a feasible path.  */
     860         6713 :   if (m_best_epath == nullptr)
     861          220 :     return false;
     862              : 
     863              :   gcc_assert (m_best_epath);
     864              : 
     865              :   return true;
     866         6713 : }
     867              : 
     868              : unsigned
     869         6627 : saved_diagnostic::get_epath_length () const
     870              : {
     871         6627 :   gcc_assert (m_best_epath);
     872         6627 :   return m_best_epath->length ();
     873              : }
     874              : 
     875              : /* Record that OTHER (and its duplicates) are duplicates
     876              :    of this saved_diagnostic.  */
     877              : 
     878              : void
     879         1997 : saved_diagnostic::add_duplicate (saved_diagnostic *other)
     880              : {
     881         1997 :   gcc_assert (other);
     882         1997 :   m_duplicates.reserve (m_duplicates.length ()
     883         2094 :                         + other->m_duplicates.length ()
     884              :                         + 1);
     885         1997 :   m_duplicates.splice (other->m_duplicates);
     886         1997 :   other->m_duplicates.truncate (0);
     887         1997 :   m_duplicates.safe_push (other);
     888         1997 : }
     889              : 
     890              : /* Walk up the sedges of each of the two paths.
     891              :    If the two sequences of sedges do not perfectly correspond,
     892              :    then paths are incompatible.
     893              :    If there is at least one sedge that either cannot be paired up
     894              :    or its counterpart is not equal, then the paths are incompatible
     895              :    and this function returns FALSE.
     896              :    Otherwise return TRUE.
     897              : 
     898              :    Incompatible paths:
     899              : 
     900              :        <cond Y>
     901              :        /      \
     902              :       /        \
     903              :     true      false
     904              :      |          |
     905              :     ...        ...
     906              :      |          |
     907              :     ...       stmt x
     908              :      |
     909              :    stmt x
     910              : 
     911              :    Both LHS_PATH and RHS_PATH final enodes should be
     912              :    over the same gimple statement.  */
     913              : 
     914              : static bool
     915           98 : compatible_epath_p (const exploded_path *lhs_path,
     916              :                     const exploded_path *rhs_path)
     917              : {
     918           98 :   gcc_assert (lhs_path);
     919           98 :   gcc_assert (rhs_path);
     920           98 :   gcc_assert (rhs_path->length () > 0);
     921           98 :   gcc_assert (rhs_path->length () > 0);
     922           98 :   int lhs_eedge_idx = lhs_path->length () - 1;
     923           98 :   int rhs_eedge_idx = rhs_path->length () - 1;
     924           98 :   const exploded_edge *lhs_eedge;
     925           98 :   const exploded_edge *rhs_eedge;
     926              : 
     927         2209 :   while (lhs_eedge_idx >= 0 && rhs_eedge_idx >= 0)
     928              :     {
     929         2406 :       while (lhs_eedge_idx >= 0)
     930              :         {
     931              :           /* Find LHS_PATH's next superedge.  */
     932         2340 :           lhs_eedge = lhs_path->m_elements[lhs_eedge_idx].m_eedge;
     933         2340 :           if (lhs_eedge->m_sedge)
     934              :             break;
     935              :           else
     936          197 :             lhs_eedge_idx--;
     937              :         }
     938         2406 :       while (rhs_eedge_idx >= 0)
     939              :         {
     940              :           /* Find RHS_PATH's next superedge.  */
     941         2340 :           rhs_eedge = rhs_path->m_elements[rhs_eedge_idx].m_eedge;
     942         2340 :           if (rhs_eedge->m_sedge)
     943              :             break;
     944              :           else
     945          197 :             rhs_eedge_idx--;
     946              :         }
     947              : 
     948         2209 :       if (lhs_eedge->m_sedge && rhs_eedge->m_sedge)
     949              :         {
     950         2143 :           if (lhs_eedge->m_sedge != rhs_eedge->m_sedge)
     951              :             /* Both superedges do not match.
     952              :                Superedges are not dependent on the exploded path, so even
     953              :                different epaths will have similar sedges if they follow
     954              :                the same outcome of a conditional node.  */
     955              :             return false;
     956              : 
     957         2111 :           lhs_eedge_idx--;
     958         2111 :           rhs_eedge_idx--;
     959         2111 :           continue;
     960              :         }
     961           66 :       else if (lhs_eedge->m_sedge == nullptr && rhs_eedge->m_sedge == nullptr)
     962              :         /* Both paths were drained up entirely.
     963              :            No discriminant was found.  */
     964           66 :         return true;
     965              : 
     966              :       /* A superedge was found for only one of the two paths.  */
     967              :       return false;
     968              :     }
     969              : 
     970              :   /* A superedge was found for only one of the two paths.  */
     971            0 :   if (lhs_eedge_idx >= 0 || rhs_eedge_idx >= 0)
     972            0 :     return false;
     973              : 
     974              :   /* Both paths were drained up entirely.
     975              :      No discriminant was found.  */
     976              :   return true;
     977              : }
     978              : 
     979              : 
     980              : /* Return true if this diagnostic supercedes OTHER, and that OTHER should
     981              :    therefore not be emitted.  */
     982              : 
     983              : bool
     984        31739 : saved_diagnostic::supercedes_p (const saved_diagnostic &other) const
     985              : {
     986        31739 :   if (get_supernode () != other.get_supernode ())
     987              :     return false;
     988              : 
     989              :   /* return early if OTHER won't be superseded anyway.  */
     990         6350 :   if (!m_d->supercedes_p (*other.m_d))
     991              :     return false;
     992              : 
     993              :   /* If the two saved_diagnostics' path are not compatible
     994              :      then they cannot supersede one another.  */
     995           98 :   return compatible_epath_p (m_best_epath.get (), other.m_best_epath.get ());
     996              : }
     997              : 
     998              : /* Move any saved checker_events from this saved_diagnostic to
     999              :    the end of DST_PATH.  */
    1000              : 
    1001              : void
    1002         4430 : saved_diagnostic::add_any_saved_events (checker_path &dst_path)
    1003              : {
    1004         4955 :   for (auto &event : m_saved_events)
    1005              :     {
    1006          175 :       dst_path.add_event (std::unique_ptr<checker_event> (event));
    1007          175 :       event = nullptr;
    1008              :     }
    1009         4430 : }
    1010              : 
    1011              : /* Emit any pending notes owned by this diagnostic.  */
    1012              : 
    1013              : void
    1014         4371 : saved_diagnostic::emit_any_notes () const
    1015              : {
    1016         4973 :   for (auto pn : m_notes)
    1017          206 :     pn->emit ();
    1018         4371 : }
    1019              : 
    1020              : /* For SARIF output, add additional properties to the "result" object
    1021              :    for this diagnostic.
    1022              :    This extra data is intended for use when debugging the analyzer.  */
    1023              : 
    1024              : void
    1025           37 : saved_diagnostic::
    1026              : maybe_add_sarif_properties (diagnostics::sarif_object &result_obj) const
    1027              : {
    1028           37 :   auto &props = result_obj.get_or_create_properties ();
    1029              : #define PROPERTY_PREFIX "gcc/analyzer/saved_diagnostic/"
    1030           37 :   if (m_sm)
    1031           17 :     props.set_string (PROPERTY_PREFIX "sm", m_sm->get_name ());
    1032           37 :   props.set (PROPERTY_PREFIX "ploc", m_ploc.to_json ());
    1033           37 :   if (m_var)
    1034           17 :     props.set (PROPERTY_PREFIX "var", tree_to_json (m_var));
    1035           37 :   if (m_sval)
    1036           17 :     props.set (PROPERTY_PREFIX "sval", m_sval->to_json ());
    1037           37 :   if (m_state)
    1038           17 :     props.set (PROPERTY_PREFIX "state", m_state->to_json ());
    1039              :   // TODO: m_best_epath
    1040           37 :   props.set_integer (PROPERTY_PREFIX "idx", m_idx);
    1041           37 :   if (m_duplicates.length () > 0)
    1042              :     {
    1043            4 :       auto duplicates_arr = std::make_unique<json::array> ();
    1044           16 :       for (auto iter : m_duplicates)
    1045              :         {
    1046            4 :           auto sd_obj = std::make_unique<diagnostics::sarif_object> ();
    1047            4 :           iter->maybe_add_sarif_properties (*sd_obj);
    1048            4 :           duplicates_arr->append (std::move (sd_obj));
    1049            4 :         }
    1050            4 :       props.set<json::array> (PROPERTY_PREFIX "duplicates",
    1051              :                               std::move (duplicates_arr));
    1052            4 :     }
    1053              : #undef PROPERTY_PREFIX
    1054              : 
    1055              : #define PROPERTY_PREFIX "gcc/analyzer/pending_diagnostic/"
    1056           37 :   props.set_string (PROPERTY_PREFIX "kind", m_d->get_kind ());
    1057              : #undef PROPERTY_PREFIX
    1058              : 
    1059              :   /* Potentially add pending_diagnostic-specific properties.  */
    1060           37 :   m_d->maybe_add_sarif_properties (result_obj);
    1061           37 : }
    1062              : 
    1063              : /* State for building a checker_path from a particular exploded_path.
    1064              :    In particular, this precomputes reachability information: the set of
    1065              :    source enodes for which a path be found to the diagnostic enode.  */
    1066              : 
    1067         4430 : class path_builder
    1068              : {
    1069              : public:
    1070         4430 :   path_builder (const exploded_graph &eg,
    1071              :                 const exploded_path &epath,
    1072              :                 const feasibility_problem *problem,
    1073              :                 const saved_diagnostic &sd)
    1074         4430 :   : m_eg (eg),
    1075         4430 :     m_diag_enode (epath.get_final_enode ()),
    1076         4430 :     m_sd (sd),
    1077         4430 :     m_reachability (eg, m_diag_enode),
    1078         4430 :     m_feasibility_problem (problem)
    1079         4430 :   {}
    1080              : 
    1081            0 :   const exploded_node *get_diag_node () const { return m_diag_enode; }
    1082              : 
    1083        60405 :   pending_diagnostic *get_pending_diagnostic () const
    1084              :   {
    1085          256 :     return m_sd.m_d.get ();
    1086              :   }
    1087              : 
    1088        34305 :   bool reachable_from_p (const exploded_node *src_enode) const
    1089              :   {
    1090        68610 :     return m_reachability.reachable_from_p (src_enode);
    1091              :   }
    1092              : 
    1093        88838 :   const extrinsic_state &get_ext_state () const { return m_eg.get_ext_state (); }
    1094              : 
    1095        42739 :   const feasibility_problem *get_feasibility_problem () const
    1096              :   {
    1097        42739 :     return m_feasibility_problem;
    1098              :   }
    1099              : 
    1100         5166 :   const state_machine *get_sm () const { return m_sd.m_sm; }
    1101              : 
    1102              :   const supergraph &
    1103        44417 :   get_supergraph () const { return m_eg.get_supergraph (); }
    1104              : 
    1105              : private:
    1106              :   typedef reachability<eg_traits> enode_reachability;
    1107              : 
    1108              :   const exploded_graph &m_eg;
    1109              : 
    1110              :   /* The enode where the diagnostic occurs.  */
    1111              :   const exploded_node *m_diag_enode;
    1112              : 
    1113              :   const saved_diagnostic &m_sd;
    1114              : 
    1115              :   /* Precompute all enodes from which the diagnostic is reachable.  */
    1116              :   enode_reachability m_reachability;
    1117              : 
    1118              :   const feasibility_problem *m_feasibility_problem;
    1119              : };
    1120              : 
    1121              : /* class diagnostic_manager.  */
    1122              : 
    1123              : /* diagnostic_manager's ctor.  */
    1124              : 
    1125         3659 : diagnostic_manager::diagnostic_manager (logger *logger, engine *eng,
    1126              :                                         int verbosity)
    1127         3659 : : log_user (logger), m_eng (eng), m_verbosity (verbosity),
    1128         3659 :   m_num_disabled_diagnostics (0)
    1129              : {
    1130         3659 : }
    1131              : 
    1132              : /* Queue pending_diagnostic D at ENODE for later emission.
    1133              :    Return true/false signifying if the diagnostic was actually added.  */
    1134              : 
    1135              : bool
    1136        10864 : diagnostic_manager::add_diagnostic (const state_machine *sm,
    1137              :                                     pending_location &&ploc,
    1138              :                                     tree var,
    1139              :                                     const svalue *sval,
    1140              :                                     state_machine::state_t state,
    1141              :                                     std::unique_ptr<pending_diagnostic> d)
    1142              : {
    1143        10864 :   LOG_FUNC (get_logger ());
    1144              : 
    1145              :   /* We must have an enode in order to be able to look for paths
    1146              :      through the exploded_graph to the diagnostic.  */
    1147        10864 :   gcc_assert (ploc.m_enode);
    1148              : 
    1149              :   /* If this warning is ultimately going to be rejected by a -Wno-analyzer-*
    1150              :      flag, reject it now.  */
    1151        10864 :   {
    1152        10864 :     location_t loc = ploc.m_event_loc_info.m_loc;
    1153        10864 :     loc = d->fixup_location (loc, true);
    1154        10864 :     int option = d->get_controlling_option ();
    1155        10864 :     if (!warning_enabled_at (loc, option))
    1156              :       {
    1157         4151 :         if (get_logger ())
    1158            0 :           get_logger ()->log ("rejecting disabled warning %qs",
    1159            0 :                               d->get_kind ());
    1160         4151 :         m_num_disabled_diagnostics++;
    1161         4151 :         return false;
    1162              :       }
    1163              :   }
    1164              : 
    1165         6713 :   saved_diagnostic *sd
    1166              :     = new saved_diagnostic (sm,
    1167              :                             std::move (ploc),
    1168              :                             var,
    1169              :                             sval,
    1170              :                             state,
    1171              :                             std::move (d),
    1172        11758 :                             m_saved_diagnostics.length ());
    1173         6713 :   m_saved_diagnostics.safe_push (sd);
    1174         6713 :   sd->m_ploc.m_enode->add_diagnostic (sd);
    1175         6713 :   if (get_logger ())
    1176            4 :     log ("adding saved diagnostic %i at SN %i to EN %i: %qs",
    1177              :          sd->get_index (),
    1178            2 :          sd->get_supernode ()->m_id,
    1179            2 :          sd->m_ploc.m_enode->m_index,
    1180            2 :          sd->m_d->get_kind ());
    1181              :   return true;
    1182        10864 : }
    1183              : 
    1184              : /* Queue pending_diagnostic D at ENODE for later emission.
    1185              :    Return true/false signifying if the diagnostic was actually added.
    1186              :    Take ownership of D (or delete it).  */
    1187              : 
    1188              : bool
    1189         3963 : diagnostic_manager::add_diagnostic (pending_location &&ploc,
    1190              :                                     std::unique_ptr<pending_diagnostic> d)
    1191              : {
    1192         3963 :   gcc_assert (ploc.m_enode);
    1193         3963 :   return add_diagnostic (nullptr, std::move (ploc),
    1194         3963 :                          NULL_TREE, nullptr, 0, std::move (d));
    1195              : }
    1196              : 
    1197              : /* Add PN to the most recent saved_diagnostic.  */
    1198              : 
    1199              : void
    1200          222 : diagnostic_manager::add_note (std::unique_ptr<pending_note> pn)
    1201              : {
    1202          222 :   LOG_FUNC (get_logger ());
    1203          222 :   gcc_assert (pn);
    1204              : 
    1205              :   /* Get most recent saved_diagnostic.  */
    1206          222 :   gcc_assert (m_saved_diagnostics.length () > 0);
    1207          222 :   saved_diagnostic *sd = m_saved_diagnostics[m_saved_diagnostics.length () - 1];
    1208          222 :   sd->add_note (std::move (pn));
    1209          222 : }
    1210              : 
    1211              : /* Add EVENT to the most recent saved_diagnostic.  */
    1212              : 
    1213              : void
    1214          187 : diagnostic_manager::add_event (std::unique_ptr<checker_event> event)
    1215              : {
    1216          187 :   LOG_FUNC (get_logger ());
    1217          187 :   gcc_assert (event);
    1218              : 
    1219              :   /* Get most recent saved_diagnostic.  */
    1220          187 :   gcc_assert (m_saved_diagnostics.length () > 0);
    1221          187 :   saved_diagnostic *sd = m_saved_diagnostics[m_saved_diagnostics.length () - 1];
    1222          187 :   sd->add_event (std::move (event));
    1223          187 : }
    1224              : 
    1225              : /* Return a new json::object of the form
    1226              :    {"diagnostics"  : [obj for saved_diagnostic]}.  */
    1227              : 
    1228              : std::unique_ptr<json::object>
    1229            1 : diagnostic_manager::to_json () const
    1230              : {
    1231            1 :   auto dm_obj = std::make_unique<json::object> ();
    1232              : 
    1233            1 :   {
    1234            1 :     auto sd_arr = std::make_unique<json::array> ();
    1235            1 :     int i;
    1236            1 :     saved_diagnostic *sd;
    1237            3 :     FOR_EACH_VEC_ELT (m_saved_diagnostics, i, sd)
    1238            1 :       sd_arr->append (sd->to_json ());
    1239            1 :     dm_obj->set ("diagnostics", std::move (sd_arr));
    1240            1 :   }
    1241              : 
    1242            1 :   return dm_obj;
    1243              : }
    1244              : 
    1245              : /* A class for identifying sets of duplicated pending_diagnostic.
    1246              : 
    1247              :    We want to find the simplest saved_diagnostic amongst those that share a
    1248              :    dedupe_key.  */
    1249              : 
    1250              : class dedupe_key
    1251              : {
    1252              : public:
    1253         6493 :   dedupe_key (const saved_diagnostic &sd)
    1254         6493 :   : m_sd (sd),
    1255         6493 :     m_loc (sd.m_ploc.m_event_loc_info.m_loc)
    1256              :   {
    1257              :   }
    1258              : 
    1259        68835 :   hashval_t hash () const
    1260              :   {
    1261        68835 :     inchash::hash hstate;
    1262              :     // TODO: m_sd
    1263        68835 :     return hstate.end ();
    1264              :   }
    1265        53354 :   bool operator== (const dedupe_key &other) const
    1266              :   {
    1267        53354 :     return (m_sd == other.m_sd
    1268        53354 :             && m_loc == other.m_loc);
    1269              :   }
    1270              : 
    1271        33533 :   location_t get_location () const { return m_loc; }
    1272              : 
    1273              :   /* A qsort comparator for use by dedupe_winners::emit_best
    1274              :      to sort them into location_t order.  */
    1275              : 
    1276              :   static int
    1277        33533 :   comparator (const void *p1, const void *p2)
    1278              :   {
    1279        33533 :     const dedupe_key *pk1 = *(const dedupe_key * const *)p1;
    1280        33533 :     const dedupe_key *pk2 = *(const dedupe_key * const *)p2;
    1281              : 
    1282        33533 :     location_t loc1 = pk1->get_location ();
    1283        33533 :     location_t loc2 = pk2->get_location ();
    1284              : 
    1285        33533 :     if (int cmp = linemap_compare_locations (line_table, loc2, loc1))
    1286              :       return cmp;
    1287         1314 :     if (int cmp = ((int)pk1->m_sd.get_epath_length ()
    1288         1314 :                    - (int)pk2->m_sd.get_epath_length ()))
    1289              :       return cmp;
    1290          894 :     if (int cmp = strcmp (pk1->m_sd.m_d->get_kind (),
    1291          894 :                           pk2->m_sd.m_d->get_kind ()))
    1292              :       return cmp;
    1293              :     return 0;
    1294              :   }
    1295              : 
    1296              :   const saved_diagnostic &m_sd;
    1297              :   location_t m_loc;
    1298              : };
    1299              : 
    1300              : /* Traits for use by dedupe_winners.  */
    1301              : 
    1302              : class dedupe_hash_map_traits
    1303              : {
    1304              : public:
    1305              :   typedef const dedupe_key *key_type;
    1306              :   typedef saved_diagnostic *value_type;
    1307              :   typedef saved_diagnostic *compare_type;
    1308              : 
    1309        68835 :   static inline hashval_t hash (const key_type &v)
    1310              :   {
    1311        68835 :     return v->hash ();
    1312              :   }
    1313        53354 :   static inline bool equal_keys (const key_type &k1, const key_type &k2)
    1314              :   {
    1315        53354 :     return *k1 == *k2;
    1316              :   }
    1317              :   template <typename T>
    1318              :   static inline void remove (T &)
    1319              :   {
    1320              :     // TODO
    1321              :   }
    1322              :   template <typename T>
    1323           66 :   static inline void mark_deleted (T &entry)
    1324              :   {
    1325           66 :     entry.m_key = reinterpret_cast<key_type> (1);
    1326              :   }
    1327              :   template <typename T>
    1328            0 :   static inline void mark_empty (T &entry)
    1329              :   {
    1330            0 :     entry.m_key = nullptr;
    1331              :   }
    1332              :   template <typename T>
    1333       160562 :   static inline bool is_deleted (const T &entry)
    1334              :   {
    1335       160562 :     return entry.m_key == reinterpret_cast<key_type> (1);
    1336              :   }
    1337              :   template <typename T>
    1338       576268 :   static inline bool is_empty (const T &entry)
    1339              :   {
    1340       576268 :     return entry.m_key == nullptr;
    1341              :   }
    1342              :   static const bool empty_zero_p = true;
    1343              : };
    1344              : 
    1345              : /* A class for deduplicating diagnostics and finding (and emitting) the
    1346              :    best saved_diagnostic within each partition.  */
    1347              : 
    1348              : class dedupe_winners
    1349              : {
    1350              : public:
    1351         1668 :   ~dedupe_winners ()
    1352              :   {
    1353              :     /* Delete all keys, but not the saved_diagnostics.  */
    1354         6098 :     for (map_t::iterator iter = m_map.begin ();
    1355         6098 :          iter != m_map.end ();
    1356         4430 :          ++iter)
    1357         4430 :       delete (*iter).first;
    1358         1668 :   }
    1359              : 
    1360              :   /* Determine an exploded_path for SD using PF and, if it's feasible,
    1361              :      determine if SD is the best seen so far for its dedupe_key.
    1362              :      Record the winning SD for each dedupe_key.  */
    1363              : 
    1364         6713 :   void add (logger *logger,
    1365              :             epath_finder *pf,
    1366              :             saved_diagnostic *sd)
    1367              :   {
    1368              :     /* Determine best epath for SD.  */
    1369         6713 :     if (!sd->calc_best_epath (pf))
    1370          220 :       return;
    1371              : 
    1372         6493 :     const exploded_path *epath = sd->get_best_epath ();
    1373         6493 :     gcc_assert (epath);
    1374              : 
    1375              :     /* Now we have an exploded path, use it for pending_locations that are
    1376              :        affected by such things, and for deduplication.  */
    1377         6493 :     if (sd->m_ploc.m_fixer_for_epath)
    1378         1074 :       sd->m_ploc.m_fixer_for_epath->fixup_for_epath (*epath, sd->m_ploc);
    1379              : 
    1380         6493 :     dedupe_key *key = new dedupe_key (*sd);
    1381         6493 :     if (saved_diagnostic **slot = m_map.get (key))
    1382              :       {
    1383         1997 :         if (logger)
    1384            0 :           logger->log ("already have this dedupe_key");
    1385              : 
    1386         1997 :         saved_diagnostic *cur_best_sd = *slot;
    1387              : 
    1388         1997 :         if (sd->get_epath_length () < cur_best_sd->get_epath_length ())
    1389              :           {
    1390              :             /* We've got a shorter path for the key; replace
    1391              :                the current candidate, marking it as a duplicate of SD.  */
    1392          144 :             if (logger)
    1393            0 :               logger->log ("length %i is better than existing length %i;"
    1394              :                            " taking over this dedupe_key",
    1395              :                            sd->get_epath_length (),
    1396              :                            cur_best_sd->get_epath_length ());
    1397          144 :             sd->add_duplicate (cur_best_sd);
    1398          144 :             *slot = sd;
    1399              :           }
    1400              :         else
    1401              :           /* We haven't beaten the current best candidate; add SD
    1402              :              as a duplicate of it.  */
    1403              :           {
    1404         1853 :             if (logger)
    1405            0 :               logger->log ("length %i isn't better than existing length %i;"
    1406              :                            " dropping this candidate",
    1407              :                            sd->get_epath_length (),
    1408              :                            cur_best_sd->get_epath_length ());
    1409         1853 :             cur_best_sd->add_duplicate (sd);
    1410              :           }
    1411         1997 :         delete key;
    1412              :       }
    1413              :     else
    1414              :       {
    1415              :         /* This is the first candidate for this key.  */
    1416         4496 :         m_map.put (key, sd);
    1417         4496 :         if (logger)
    1418            2 :           logger->log ("first candidate for this dedupe_key");
    1419              :       }
    1420              :   }
    1421              : 
    1422              :   /* Handle interactions between the dedupe winners, so that some
    1423              :      diagnostics can supercede others (of different kinds).
    1424              : 
    1425              :      We want use-after-free to supercede use-of-uninitialized-value,
    1426              :      so that if we have these at the same stmt, we don't emit
    1427              :      a use-of-uninitialized, just the use-after-free.  */
    1428              : 
    1429         1668 :   void handle_interactions (diagnostic_manager *dm)
    1430              :   {
    1431         1668 :     LOG_SCOPE (dm->get_logger ());
    1432         1668 :     auto_vec<const dedupe_key *> superceded;
    1433         6164 :     for (auto outer : m_map)
    1434              :       {
    1435         4496 :         const saved_diagnostic *outer_sd = outer.second;
    1436        40665 :         for (auto inner : m_map)
    1437              :           {
    1438        31739 :             const saved_diagnostic *inner_sd = inner.second;
    1439        31739 :             if (inner_sd->supercedes_p (*outer_sd))
    1440              :               {
    1441           66 :                 superceded.safe_push (outer.first);
    1442           66 :                 if (dm->get_logger ())
    1443            0 :                   dm->log ("sd[%i] \"%s\" superceded by sd[%i] \"%s\"",
    1444            0 :                            outer_sd->get_index (), outer_sd->m_d->get_kind (),
    1445            0 :                            inner_sd->get_index (), inner_sd->m_d->get_kind ());
    1446              :                 break;
    1447              :               }
    1448              :           }
    1449              :       }
    1450         1844 :     for (auto iter : superceded)
    1451           66 :       m_map.remove (iter);
    1452         1668 :   }
    1453              : 
    1454              :  /* Emit the simplest diagnostic within each set.  */
    1455              : 
    1456         1668 :   void emit_best (diagnostic_manager *dm,
    1457              :                   const exploded_graph &eg)
    1458              :   {
    1459         1668 :     LOG_SCOPE (dm->get_logger ());
    1460              : 
    1461              :     /* Get keys into a vec for sorting.  */
    1462         1668 :     auto_vec<const dedupe_key *> keys (m_map.elements ());
    1463         1668 :     for (map_t::iterator iter = m_map.begin ();
    1464         6098 :          iter != m_map.end ();
    1465         4430 :          ++iter)
    1466         4430 :       keys.quick_push ((*iter).first);
    1467              : 
    1468         3288 :     dm->log ("# keys after de-duplication: %i", keys.length ());
    1469              : 
    1470              :     /* Sort into a good emission order.  */
    1471         1668 :     keys.qsort (dedupe_key::comparator);
    1472              : 
    1473              :     /* Emit the best saved_diagnostics for each key.  */
    1474         1668 :     int i;
    1475         1668 :     const dedupe_key *key;
    1476         7718 :     FOR_EACH_VEC_ELT (keys, i, key)
    1477              :       {
    1478         4430 :         saved_diagnostic **slot = m_map.get (key);
    1479         4430 :         gcc_assert (*slot);
    1480         4430 :         saved_diagnostic *sd = *slot;
    1481         4430 :         dm->emit_saved_diagnostic (eg, *sd);
    1482              :       }
    1483         1668 :   }
    1484              : 
    1485              : private:
    1486              :   /* This maps from each dedupe_key to a current best saved_diagnostic.  */
    1487              : 
    1488              :   typedef hash_map<const dedupe_key *, saved_diagnostic *,
    1489              :                    dedupe_hash_map_traits> map_t;
    1490              :   map_t m_map;
    1491              : };
    1492              : 
    1493              : /* Emit all saved diagnostics.  */
    1494              : 
    1495              : void
    1496         3659 : diagnostic_manager::emit_saved_diagnostics (const exploded_graph &eg)
    1497              : {
    1498         3659 :   LOG_SCOPE (get_logger ());
    1499         3659 :   auto_timevar tv (TV_ANALYZER_DIAGNOSTICS);
    1500         5327 :   log ("# saved diagnostics: %i", m_saved_diagnostics.length ());
    1501         3659 :   log ("# disabled diagnostics: %i", m_num_disabled_diagnostics);
    1502         3659 :   if (get_logger ())
    1503              :     {
    1504              :       unsigned i;
    1505              :       saved_diagnostic *sd;
    1506            7 :       FOR_EACH_VEC_ELT (m_saved_diagnostics, i, sd)
    1507            2 :         log ("[%i] sd: %qs at EN: %i, SN: %i",
    1508            2 :              i, sd->m_d->get_kind (), sd->m_ploc.m_enode->m_index,
    1509            2 :              sd->get_supernode ()->m_id);
    1510              :     }
    1511              : 
    1512         3659 :   if (m_saved_diagnostics.length () == 0)
    1513         1991 :     return;
    1514              : 
    1515              :   /* Compute the shortest_paths once, sharing it between all diagnostics.  */
    1516         1668 :   epath_finder pf (eg);
    1517              : 
    1518              :   /* Iterate through all saved diagnostics, adding them to a dedupe_winners
    1519              :      instance.  This partitions the saved diagnostics by dedupe_key,
    1520              :      generating exploded_paths for them, and retaining the best one in each
    1521              :      partition.  */
    1522         1668 :   dedupe_winners best_candidates;
    1523              : 
    1524         1668 :   int i;
    1525         1668 :   saved_diagnostic *sd;
    1526        10049 :   FOR_EACH_VEC_ELT (m_saved_diagnostics, i, sd)
    1527         6713 :     best_candidates.add (get_logger (), &pf, sd);
    1528              : 
    1529         1668 :   best_candidates.handle_interactions (this);
    1530              : 
    1531              :   /* For each dedupe-key, call emit_saved_diagnostic on the "best"
    1532              :      saved_diagnostic.  */
    1533         1668 :   best_candidates.emit_best (this, eg);
    1534         3659 : }
    1535              : 
    1536              : /* Custom subclass of diagnostics::metadata which, for SARIF output,
    1537              :    populates the property bag of the diagnostic's "result" object
    1538              :    with information from the saved_diagnostic and the
    1539              :    pending_diagnostic.  */
    1540              : 
    1541         4430 : class pending_diagnostic_metadata : public diagnostics::metadata
    1542              : {
    1543              : public:
    1544         4430 :   pending_diagnostic_metadata (const saved_diagnostic &sd)
    1545         4430 :   : m_sd (sd)
    1546              :   {
    1547              :   }
    1548              : 
    1549              :   void
    1550           33 :   maybe_add_sarif_properties (diagnostics::sarif_object &result_obj)
    1551              :     const override
    1552              :   {
    1553           33 :     m_sd.maybe_add_sarif_properties (result_obj);
    1554           33 :   }
    1555              : 
    1556              : private:
    1557              :   const saved_diagnostic &m_sd;
    1558              : };
    1559              : 
    1560              : /* Given a saved_diagnostic SD with m_best_epath through EG,
    1561              :    create an checker_path of suitable events and use it to call
    1562              :    SD's underlying pending_diagnostic "emit" vfunc to emit a diagnostic.  */
    1563              : 
    1564              : void
    1565         4430 : diagnostic_manager::emit_saved_diagnostic (const exploded_graph &eg,
    1566              :                                            saved_diagnostic &sd)
    1567              : {
    1568         4430 :   LOG_SCOPE (get_logger ());
    1569         4430 :   log ("sd[%i]: %qs at SN: %i",
    1570         4430 :        sd.get_index (), sd.m_d->get_kind (), sd.get_supernode ()->m_id);
    1571         5785 :   log ("num dupes: %i", sd.get_num_dupes ());
    1572              : 
    1573         4430 :   exploded_path *epath = sd.get_best_epath ();
    1574         4430 :   gcc_assert (epath);
    1575              : 
    1576         4430 :   epath->maybe_log (get_logger (), "best epath");
    1577              : 
    1578              :   /* Precompute all enodes from which the diagnostic is reachable.  */
    1579         4430 :   path_builder pb (eg, *epath, sd.get_feasibility_problem (), sd);
    1580              : 
    1581              :   /* Annotate EPATH with information specific to the diagnostic, such
    1582              :      as pertinent data flow events.  */
    1583         4430 :   annotate_exploded_path (pb, *epath);
    1584         4430 :   epath->maybe_log (get_logger (), "best epath with annotations");
    1585              : 
    1586              :   /* This is the diagnostics::paths::path instance that will be built for
    1587              :      the diagnostic.  */
    1588         4430 :   checker_path emission_path (get_logical_location_manager (),
    1589              :                               eg.get_ext_state (),
    1590         4430 :                               get_logger ());
    1591              : 
    1592              :   /* Populate emission_path with a full description of EPATH.  */
    1593         4430 :   build_emission_path (pb, *epath, &emission_path);
    1594              : 
    1595              :   /* Now prune it to just cover the most pertinent events.  */
    1596         4430 :   prune_path (&emission_path, sd.m_sm, sd.m_sval, sd.m_state);
    1597              : 
    1598              :   /* Add any saved events to the path, giving contextual information
    1599              :      about what the analyzer was simulating as the diagnostic was
    1600              :      generated.  These don't get pruned, as they are probably pertinent.  */
    1601         4430 :   sd.add_any_saved_events (emission_path);
    1602              : 
    1603              :   /* Add a final event to the path, covering the diagnostic itself.  */
    1604         4430 :   {
    1605         4430 :     const exploded_node *const enode = epath->get_final_enode ();
    1606         4430 :     sd.m_d->add_final_event (sd.m_sm, enode, sd.m_ploc.m_event_loc_info,
    1607              :                              sd.m_var, sd.m_state, &emission_path);
    1608              :   }
    1609              : 
    1610              :   /* The "final" event might not be final; if the saved_diagnostic has a
    1611              :      trailing eedge stashed, add any events for it.  This is for use
    1612              :      in handling longjmp, to show where a longjmp is rewinding to.  */
    1613         4430 :   if (sd.m_trailing_eedge)
    1614            4 :     add_events_for_eedge (pb, *sd.m_trailing_eedge, &emission_path, nullptr,
    1615              :                           nullptr);
    1616              : 
    1617         4430 :   emission_path.inject_any_inlined_call_events (get_logger ());
    1618              : 
    1619         4430 :   emission_path.prepare_for_emission (sd.m_d.get ());
    1620              : 
    1621         4430 :   location_t loc = sd.m_ploc.m_event_loc_info.m_loc;
    1622         4430 :   loc = sd.m_d->fixup_location (loc, true);
    1623              : 
    1624              :   /* Allow the pending_diagnostic to fix up the locations of events.  */
    1625         4430 :   emission_path.fixup_locations (sd.m_d.get ());
    1626              : 
    1627         4430 :   gcc_rich_location rich_loc (loc);
    1628         4430 :   rich_loc.set_path (&emission_path);
    1629              : 
    1630         4430 :   auto_diagnostic_group d;
    1631         4430 :   auto_cfun sentinel (sd.get_supernode ()->m_fun);
    1632         4430 :   pending_diagnostic_metadata m (sd);
    1633         4430 :   diagnostic_emission_context diag_ctxt (sd, rich_loc, m, get_logger ());
    1634         4430 :   if (sd.m_d->emit (diag_ctxt))
    1635              :     {
    1636         4371 :       sd.emit_any_notes ();
    1637              : 
    1638         4371 :       unsigned num_dupes = sd.get_num_dupes ();
    1639         4371 :       if (flag_analyzer_show_duplicate_count && num_dupes > 0)
    1640            4 :         inform_n (loc, num_dupes,
    1641              :                   "%i duplicate", "%i duplicates",
    1642              :                   num_dupes);
    1643         4371 :       if (flag_dump_analyzer_exploded_paths)
    1644              :         {
    1645            0 :           auto_timevar tv (TV_ANALYZER_DUMP);
    1646            0 :           pretty_printer pp;
    1647            0 :           pp_printf (&pp, "%s.%i.%s.epath.txt",
    1648            0 :                      dump_base_name, sd.get_index (), sd.m_d->get_kind ());
    1649            0 :           char *filename = xstrdup (pp_formatted_text (&pp));
    1650            0 :           epath->dump_to_file (filename, eg.get_ext_state ());
    1651            0 :           inform (loc, "exploded path written to %qs", filename);
    1652            0 :           free (filename);
    1653            0 :         }
    1654              :     }
    1655         4430 : }
    1656              : 
    1657              : const diagnostics::logical_locations::manager &
    1658         4430 : diagnostic_manager::get_logical_location_manager () const
    1659              : {
    1660         4430 :   gcc_assert (global_dc);
    1661         4430 :   auto mgr = global_dc->get_logical_location_manager ();
    1662         4430 :   gcc_assert (mgr);
    1663         4430 :   return *mgr;
    1664              : }
    1665              : 
    1666              : /* Dump C to this logger, indenting each line by the current
    1667              :    indentation level.  */
    1668              : 
    1669              : void
    1670         2575 : logger::log_canvas (const text_art::canvas &c)
    1671              : {
    1672         2575 :   std::string per_line_prefix (m_indent_level, ' ');
    1673         2575 :   c.print_to_pp (get_printer (), per_line_prefix.c_str ());
    1674         2575 :   pp_flush (get_printer ());
    1675         2575 : }
    1676              : 
    1677              : /* Dump OBJ to LOGGER, using OBJ's make_dump_widget member function.  */
    1678              : 
    1679              : template <typename T>
    1680              : void
    1681        26349 : dump_to_logger (const T &obj,
    1682              :                 logger *logger,
    1683              :                 const char *label)
    1684              : {
    1685        26349 :   if (!logger)
    1686        26349 :     return;
    1687           34 :   text_art::theme *theme = global_dc->get_diagram_theme ();
    1688           34 :   if (!theme)
    1689              :     return;
    1690              : 
    1691            0 :   logger->log ("%s:", label);
    1692            0 :   logger->inc_indent ();
    1693              : 
    1694            0 :   text_art::style_manager sm;
    1695            0 :   text_art::style tree_style (text_art::get_style_from_color_cap_name ("note"));
    1696              : 
    1697            0 :   text_art::style::id_t tree_style_id (sm.get_or_create_id (tree_style));
    1698              : 
    1699            0 :   symbolic::node_dump_state nds (sm, *theme, tree_style_id, true, true);
    1700            0 :   if (auto w = obj.make_dump_widget (nds))
    1701              :     {
    1702            0 :       text_art::canvas c (w->to_canvas (nds.m_sm));
    1703            0 :       logger->log_canvas (c);
    1704            0 :     }
    1705              : 
    1706            0 :   logger->dec_indent ();
    1707            0 : }
    1708              : 
    1709              : static void
    1710        26349 : log_region_model (logger *logger,
    1711              :                   const char *label,
    1712              :                   const region_model &model)
    1713              : {
    1714           13 :   dump_to_logger<region_model> (model, logger, label);
    1715            0 : }
    1716              : 
    1717        38590 : class epath_rewind_context : public rewind_context
    1718              : {
    1719              : public:
    1720        38590 :   epath_rewind_context (logger *logger,
    1721              :                         diagnostic_state input_state,
    1722              :                         state_transition *&last_state_transition,
    1723              :                         exploded_path::element_t &epath_element,
    1724              :                         const region_model &src_model,
    1725              :                         const region_model &dst_model)
    1726              :   : rewind_context (logger, input_state),
    1727        38590 :     m_last_state_transition (last_state_transition),
    1728        38590 :     m_epath_element (epath_element),
    1729        38590 :     m_src_model (src_model),
    1730        38590 :     m_dst_model (dst_model)
    1731              :   {
    1732        38590 :   }
    1733              : 
    1734              :   const region_model &
    1735         1090 :   get_src_region_model () const final override
    1736              :   {
    1737         1090 :     return m_src_model;
    1738              :   }
    1739              : 
    1740              :   const region_model &
    1741         2756 :   get_dst_region_model () const final override
    1742              :   {
    1743         2756 :     return m_dst_model;
    1744              :   }
    1745              : 
    1746              :   bool
    1747        11082 :   could_be_affected_by_write_p (tree lhs) final override
    1748              :   {
    1749        11082 :     if (!m_input.m_region_holding_value)
    1750              :       return false;
    1751              : 
    1752          422 :     if (TREE_CODE (lhs) == SSA_NAME)
    1753          368 :       if (tree decl = m_input.m_region_holding_value->maybe_get_decl ())
    1754          197 :         return decl == lhs;
    1755              : 
    1756              :     return true;
    1757              :   }
    1758              : 
    1759              :   void
    1760           79 :   add_state_transition (std::unique_ptr<state_transition> st) final override
    1761              :   {
    1762           79 :     gcc_assert (st.get ());
    1763           79 :     if (m_logger)
    1764              :       {
    1765            0 :         m_logger->start_log_line ();
    1766            0 :         m_logger->log_partial ("adding state transition: ");
    1767            0 :         st->dump_to_pp (m_logger->get_printer ());
    1768            0 :         m_logger->end_log_line ();
    1769              :       }
    1770              : 
    1771              :     /* Chain up the state_transition instances, so that each state transition
    1772              :        has a pointer to the one that occurred before it (but was created after
    1773              :        it, since we are rewinding the epath).  */
    1774           79 :     if (m_last_state_transition)
    1775           32 :       m_last_state_transition->m_prev_state_transition = st.get ();
    1776           79 :     m_last_state_transition = st.get ();
    1777              : 
    1778           79 :     m_epath_element.m_state_transition = std::move (st);
    1779           79 :   }
    1780              : 
    1781              : private:
    1782              :   state_transition *&m_last_state_transition;
    1783              :   exploded_path::element_t &m_epath_element;
    1784              :   const region_model &m_src_model;
    1785              :   const region_model &m_dst_model;
    1786              : };
    1787              : 
    1788              : /* Return a region_model for the state after any operation/custom_edge_info
    1789              :    on EEDGE, but without state purging or state merging.  Use SRC_MODEL as
    1790              :    the source state.
    1791              : 
    1792              :    We do this to make it easier to rewind state transitions in
    1793              :    diagnostic_manager::annotate_exploded_path.  */
    1794              : 
    1795              : static region_model
    1796        44417 : make_raw_dst_region_model (logger *logger,
    1797              :                            const exploded_edge *eedge,
    1798              :                            const region_model &src_model,
    1799              :                            const supergraph &sg)
    1800              : {
    1801        44417 :   LOG_SCOPE (logger);
    1802              : 
    1803              :   /* Update cfun and input_location in case of an ICE: make it easier to
    1804              :      track down which source construct we're failing to handle.  */
    1805        84404 :   auto_cfun sentinel (eedge->m_src->get_function ());
    1806        44417 :   input_location = eedge->m_src->get_location ();
    1807              : 
    1808        44417 :   region_model_context *const ctxt = nullptr;
    1809              : 
    1810        44417 :   if (logger)
    1811              :     {
    1812           13 :       log_region_model (logger, "src_model", src_model);
    1813           13 :       log_region_model (logger, "dst_model",
    1814           13 :                         *eedge->m_dest->get_state ().m_region_model);
    1815              :     }
    1816              : 
    1817        44417 :   if (eedge->m_custom_info)
    1818              :     {
    1819         2911 :       if (logger)
    1820              :         {
    1821            0 :           logger->start_log_line ();
    1822            0 :           eedge->m_custom_info->print (logger->get_printer ());
    1823            0 :           logger->end_log_line ();
    1824              :         }
    1825         2911 :       region_model new_model (src_model);
    1826         2911 :       eedge->m_custom_info->update_model (&new_model, eedge, ctxt);
    1827         2911 :       if (logger)
    1828            0 :         log_region_model (logger, "new model after custom_info", new_model);
    1829              :       return new_model;
    1830              :     }
    1831              :   else
    1832              :     {
    1833        41506 :       const superedge *sedge = eedge->m_sedge;
    1834        41506 :       if (sedge)
    1835              :         {
    1836        36799 :           if (logger)
    1837              :             {
    1838           11 :               label_text desc (sedge->get_description (false));
    1839           11 :               logger->log ("  sedge: SN:%i -> SN:%i %s",
    1840           11 :                            sedge->m_src->m_id,
    1841           11 :                            sedge->m_dest->m_id,
    1842              :                            desc.get ());
    1843           11 :             }
    1844              : 
    1845        36799 :           if (auto op = sedge->get_op ())
    1846              :             {
    1847        26321 :               if (logger)
    1848              :                 {
    1849            6 :                   logger->start_log_line ();
    1850            6 :                   op->print_as_edge_label (logger->get_printer (), false);
    1851            6 :                   logger->end_log_line ();
    1852              :                 }
    1853        26321 :               feasibility_state fs (src_model, sg);
    1854        26321 :               op->execute_for_feasibility (*eedge,
    1855              :                                            fs,
    1856              :                                            ctxt,
    1857              :                                            nullptr);
    1858        26321 :               log_region_model (logger, "after operation, fs model",
    1859        26321 :                                 fs.get_model ());
    1860        26321 :               return fs.get_model ();
    1861        26321 :             }
    1862              :           else
    1863              :             {
    1864        10478 :               if (logger)
    1865            5 :                 logger->log ("null operation, using src_model");
    1866        10478 :               return src_model;
    1867              :             }
    1868              :         }
    1869              :       else
    1870              :         {
    1871              :           /* Special-case the initial eedge from the origin node to the
    1872              :              initial function by pushing a frame for it.  */
    1873         4707 :           if (eedge->m_src->m_index == 0)
    1874              :             {
    1875         4317 :               function *fun = eedge->m_dest->get_function ();
    1876         4317 :               gcc_assert (fun);
    1877         4317 :               region_model new_model (src_model);
    1878         4317 :               new_model.push_frame (*fun, nullptr, nullptr, ctxt);
    1879         4317 :               if (logger)
    1880              :                 {
    1881            2 :                   logger->log ("  pushing frame for %qD", fun->decl);
    1882            2 :                   log_region_model (logger, "new model", new_model);
    1883              :                 }
    1884         4317 :               return new_model;
    1885         4317 :             }
    1886              :         }
    1887              :     }
    1888              : 
    1889          390 :   return src_model;
    1890        44417 : }
    1891              : 
    1892              : /* Populate the elements of EPATH with diagnostic_state and state_transition
    1893              :    information pertinent to the pending diagnostic.  */
    1894              : 
    1895              : void
    1896         4430 : diagnostic_manager::annotate_exploded_path (const path_builder &pb,
    1897              :                                             exploded_path &epath) const
    1898              : {
    1899         4430 :   auto logger = get_logger ();
    1900         4430 :   LOG_SCOPE (logger);
    1901              : 
    1902              :   // TODO: consolidate this with build_emission_path?
    1903         4430 :   interesting_t interest;
    1904         4430 :   pb.get_pending_diagnostic ()->mark_interesting_stuff (&interest);
    1905              : 
    1906         4430 :   gcc_assert (epath.m_elements.size () > 0);
    1907              : 
    1908         4430 :   diagnostic_state curr_state;
    1909         4430 :   state_transition *last_state_transition = nullptr;
    1910              : 
    1911         4430 :   if (interest.m_read_regions.size () > 0)
    1912          597 :     curr_state = interest.m_read_regions[0];
    1913              : 
    1914              :   /* Walk EPATH forwards, generating region_model instances for the elements
    1915              :      of EPATH without state purging or merging, so that we can reliably
    1916              :      rewind state.  */
    1917         4430 :   std::vector<region_model> src_models;
    1918         4430 :   std::vector<region_model> dst_models;
    1919        48847 :   for (unsigned int idx = 0; idx < epath.m_elements.size (); ++idx)
    1920              :     {
    1921        44417 :       auto eedge = epath.m_elements[idx].m_eedge;
    1922        44417 :       if (logger)
    1923           13 :         logger->log ("edge[%u]: considering EN %i -> EN %i",
    1924              :                      idx,
    1925           13 :                      eedge->m_src->m_index,
    1926           13 :                      eedge->m_dest->m_index);
    1927        44417 :       region_model src_model (pb.get_ext_state ().get_node_manager ());
    1928        44417 :       if (idx > 0)
    1929        39987 :         src_model = dst_models[idx - 1];
    1930        44417 :       src_models.push_back (src_model);
    1931        44417 :       dst_models.push_back
    1932        44417 :         (make_raw_dst_region_model (logger,
    1933              :                                     eedge,
    1934              :                                     src_model,
    1935              :                                     pb.get_supergraph ()));
    1936        44417 :     }
    1937              : 
    1938              :   /* Walk EPATH backwards, using the region_models we just built,
    1939              :      propagating annotation information backwards.  */
    1940        42381 :   for (int idx = epath.m_elements.size () - 1; idx >= 0; --idx)
    1941              :     {
    1942        38590 :       exploded_path::element_t &iter_element = epath.m_elements[idx];
    1943        38590 :       if (logger)
    1944              :         {
    1945           11 :           logger->log ("edge[%i]: considering rewinding EN %i -> EN %i",
    1946              :                        idx,
    1947           11 :                        iter_element.m_eedge->m_src->m_index,
    1948           11 :                        iter_element.m_eedge->m_dest->m_index);
    1949           11 :           logger->start_log_line ();
    1950           11 :           logger->log_partial ("curr_state: ");
    1951           11 :           curr_state.dump_to_pp (logger->get_printer ());
    1952           11 :           logger->end_log_line ();
    1953              :         }
    1954        38590 :       iter_element.m_state_at_dst = curr_state;
    1955        38590 :       const exploded_edge *eedge = iter_element.m_eedge;
    1956        38590 :       gcc_assert (eedge);
    1957              : 
    1958        38590 :       epath_rewind_context ctxt (logger, curr_state,
    1959              :                                  last_state_transition, iter_element,
    1960        38590 :                                  src_models[idx], dst_models[idx]);
    1961        38590 :       if (eedge->m_custom_info)
    1962              :         {
    1963         2606 :           if (logger)
    1964              :             {
    1965            0 :               logger->start_log_line ();
    1966            0 :               logger->log_partial ("custom_edge_info: ");
    1967            0 :               eedge->m_custom_info->print (logger->get_printer ());
    1968            0 :               logger->end_log_line ();
    1969              :             }
    1970         2606 :           if (!eedge->m_custom_info->try_to_rewind_data_flow (ctxt))
    1971              :             {
    1972          524 :               if (logger)
    1973            0 :                 logger->log ("could not rewind custom info");
    1974              :               return;
    1975              :             }
    1976              :         }
    1977        35984 :       else if (const operation *op = eedge->maybe_get_op ())
    1978              :         {
    1979        22373 :           if (logger)
    1980              :             {
    1981            6 :               logger->start_log_line ();
    1982            6 :               logger->log_partial ("op: ");
    1983            6 :               op->print_as_edge_label (logger->get_printer (), false);
    1984            6 :               logger->end_log_line ();
    1985              :             }
    1986        22373 :           if (!op->try_to_rewind_data_flow (ctxt))
    1987              :             {
    1988          115 :               if (logger)
    1989            1 :                 logger->log ("could not rewind op");
    1990              :               return;
    1991              :             }
    1992              :         }
    1993              : 
    1994        37951 :       iter_element.m_state_at_src = ctxt.m_output;
    1995        37951 :       curr_state = ctxt.m_output;
    1996        37951 :       if (logger)
    1997              :         {
    1998           10 :           logger->log ("rewound");
    1999           10 :           logger->start_log_line ();
    2000           10 :           logger->log_partial ("curr_state: ");
    2001           10 :           curr_state.dump_to_pp (logger->get_printer ());
    2002           10 :           logger->end_log_line ();
    2003              :         }
    2004        37951 :     }
    2005         8860 : }
    2006              : 
    2007              : /* Emit a "path" of events to EMISSION_PATH describing the exploded path
    2008              :    EPATH within EG.  */
    2009              : 
    2010              : void
    2011         4430 : diagnostic_manager::build_emission_path (const path_builder &pb,
    2012              :                                          const exploded_path &epath,
    2013              :                                          checker_path *emission_path) const
    2014              : {
    2015         4430 :   LOG_SCOPE (get_logger ());
    2016              : 
    2017         4430 :   interesting_t interest;
    2018         4430 :   pb.get_pending_diagnostic ()->mark_interesting_stuff (&interest);
    2019              : 
    2020              :   /* Add region creation events for any globals of interest, at the
    2021              :      beginning of the path.  */
    2022         4430 :   {
    2023         8661 :     for (auto reg : interest.m_region_creation)
    2024         1429 :       switch (reg->get_memory_space ())
    2025              :         {
    2026         1160 :         default:
    2027         1160 :           continue;
    2028          269 :         case memory_space::code:
    2029          269 :         case memory_space::globals:
    2030          269 :         case memory_space::read_only_data:
    2031          269 :           {
    2032          269 :             const region *base_reg = reg->get_base_region ();
    2033          269 :             if (tree decl = base_reg->maybe_get_decl ())
    2034          256 :               if (DECL_P (decl)
    2035          256 :                   && useful_location_p (DECL_SOURCE_LOCATION (decl)))
    2036              :                 {
    2037          256 :                   emission_path->add_region_creation_events
    2038          256 :                     (pb.get_pending_diagnostic (),
    2039              :                      reg, nullptr,
    2040          256 :                      event_loc_info (DECL_SOURCE_LOCATION (decl),
    2041              :                                      NULL_TREE,
    2042          256 :                                      0),
    2043          256 :                      m_verbosity > 3);
    2044              :                 }
    2045              :           }
    2046         1160 :         }
    2047              :   }
    2048              : 
    2049              :   /* Walk EPATH, adding events as appropriate.  */
    2050        48847 :   for (unsigned i = 0; i < epath.m_elements.size (); ++i)
    2051              :     {
    2052        44417 :       const exploded_edge *eedge = epath.m_elements[i].m_eedge;
    2053        44417 :       gcc_assert (eedge);
    2054        44417 :       add_events_for_eedge (pb, *eedge, emission_path, &interest,
    2055        44417 :                             epath.m_elements[i].m_state_transition.get ());
    2056              :     }
    2057         4430 :   add_event_on_final_node (pb, epath.get_final_enode (),
    2058              :                            emission_path, &interest);
    2059         4430 : }
    2060              : 
    2061              : /* Emit a region_creation_event when requested on the last statement in
    2062              :    the path.
    2063              : 
    2064              :    If a region_creation_event should be emitted on the last statement of the
    2065              :    path, we need to peek to the successors to get whether the final enode
    2066              :    created a region.
    2067              : */
    2068              : 
    2069              : void
    2070         4430 : diagnostic_manager::add_event_on_final_node (const path_builder &pb,
    2071              :                                              const exploded_node *final_enode,
    2072              :                                              checker_path *emission_path,
    2073              :                                              interesting_t *interest) const
    2074              : {
    2075         4430 :   const program_point &src_point = final_enode->get_point ();
    2076         4430 :   const int src_stack_depth = src_point.get_stack_depth ();
    2077         4430 :   const program_state &src_state = final_enode->get_state ();
    2078         4430 :   const region_model *src_model = src_state.m_region_model;
    2079              : 
    2080         4430 :   unsigned j;
    2081         4430 :   exploded_edge *e;
    2082         7945 :   FOR_EACH_VEC_ELT (final_enode->m_succs, j, e)
    2083              :   {
    2084         3596 :     exploded_node *dst = e->m_dest;
    2085         3596 :     const program_state &dst_state = dst->get_state ();
    2086         3596 :     const region_model *dst_model = dst_state.m_region_model;
    2087         3596 :     if (src_model->get_dynamic_extents ()
    2088         3596 :         != dst_model->get_dynamic_extents ())
    2089              :       {
    2090              :         unsigned i;
    2091              :         const region *reg;
    2092              :         bool emitted = false;
    2093          433 :         FOR_EACH_VEC_ELT (interest->m_region_creation, i, reg)
    2094              :           {
    2095           98 :             const region *base_reg = reg->get_base_region ();
    2096           98 :             const svalue *old_extents
    2097           98 :         = src_model->get_dynamic_extents (base_reg);
    2098           98 :             const svalue *new_extents
    2099           98 :         = dst_model->get_dynamic_extents (base_reg);
    2100           98 :             if (old_extents == nullptr && new_extents != nullptr)
    2101           85 :               switch (base_reg->get_kind ())
    2102              :                 {
    2103              :                 default:
    2104              :                   break;
    2105           81 :                 case RK_HEAP_ALLOCATED:
    2106           81 :                 case RK_ALLOCA:
    2107           81 :                   emission_path->add_region_creation_events
    2108          162 :                     (pb.get_pending_diagnostic (),
    2109              :                      reg,
    2110              :                      dst_model,
    2111           81 :                      event_loc_info (src_point.get_location (),
    2112              :                                      src_point.get_fndecl (),
    2113          162 :                                      src_stack_depth),
    2114              :                      false);
    2115           81 :                   emitted = true;
    2116           81 :                   break;
    2117              :                 }
    2118              :           }
    2119          335 :         if (emitted)
    2120              :           break;
    2121              :       }
    2122              :   }
    2123         4430 : }
    2124              : 
    2125              : /* Subclass of state_change_visitor that creates state_change_event
    2126              :    instances.  */
    2127              : 
    2128        44421 : class state_change_event_creator : public state_change_visitor
    2129              : {
    2130              : public:
    2131        44421 :   state_change_event_creator (const path_builder &pb,
    2132              :                               const exploded_edge &eedge,
    2133              :                               checker_path *emission_path)
    2134        44421 :     : m_pb (pb),
    2135        44421 :       m_eedge (eedge),
    2136        44421 :       m_emission_path (emission_path)
    2137              :   {}
    2138              : 
    2139          119 :   bool on_global_state_change (const state_machine &sm,
    2140              :                                state_machine::state_t src_sm_val,
    2141              :                                state_machine::state_t dst_sm_val)
    2142              :     final override
    2143              :   {
    2144          119 :     if (&sm != m_pb.get_sm ())
    2145              :       return false;
    2146           56 :     const exploded_node *src_node = m_eedge.m_src;
    2147           56 :     const exploded_node *dst_node = m_eedge.m_dest;
    2148           56 :     const gimple *stmt = m_eedge.maybe_get_stmt ();
    2149           56 :     const program_state &dst_state = dst_node->get_state ();
    2150              : 
    2151           56 :     m_emission_path->add_event
    2152           56 :       (std::make_unique<state_change_event> (m_eedge.m_src,
    2153              :                                              stmt,
    2154              :                                              sm,
    2155          112 :                                              nullptr,
    2156              :                                              src_sm_val,
    2157              :                                              dst_sm_val,
    2158           56 :                                              nullptr,
    2159              :                                              dst_state,
    2160              :                                              src_node));
    2161           56 :     return false;
    2162              :   }
    2163              : 
    2164         5047 :   bool on_state_change (const state_machine &sm,
    2165              :                         state_machine::state_t src_sm_val,
    2166              :                         state_machine::state_t dst_sm_val,
    2167              :                         const svalue *sval,
    2168              :                         const svalue *dst_origin_sval) final override
    2169              :   {
    2170         5047 :     if (&sm != m_pb.get_sm ())
    2171              :       return false;
    2172              : 
    2173         4018 :     const exploded_node *src_node = m_eedge.m_src;
    2174         4018 :     const exploded_node *dst_node = m_eedge.m_dest;
    2175         4018 :     const gimple *stmt = m_eedge.maybe_get_stmt ();
    2176         4018 :     const program_state &dst_state = dst_node->get_state ();
    2177              : 
    2178         4018 :     m_emission_path->add_event
    2179         4018 :       (std::make_unique<state_change_event> (m_eedge.m_src,
    2180              :                                              stmt,
    2181              :                                              sm,
    2182              :                                              sval,
    2183              :                                              src_sm_val,
    2184              :                                              dst_sm_val,
    2185              :                                              dst_origin_sval,
    2186              :                                              dst_state,
    2187              :                                              src_node));
    2188         4018 :     return false;
    2189              :   }
    2190              : 
    2191              :   const path_builder &m_pb;
    2192              :   const exploded_edge &m_eedge;
    2193              :   checker_path *m_emission_path;
    2194              : };
    2195              : 
    2196              : /* Compare SRC_STATE and DST_STATE (which use EXT_STATE), and call
    2197              :    VISITOR's on_state_change for every sm-state change that occurs
    2198              :    to a tree, and on_global_state_change for every global state change
    2199              :    that occurs.
    2200              : 
    2201              :    This determines the state changes that ought to be reported to
    2202              :    the user: a combination of the effects of changes to sm_state_map
    2203              :    (which maps svalues to sm-states), and of region_model changes
    2204              :    (which map trees to svalues).
    2205              : 
    2206              :    Bail out early and return true if any call to on_global_state_change
    2207              :    or on_state_change returns true, otherwise return false.
    2208              : 
    2209              :    This is split out to make it easier to experiment with changes to
    2210              :    exploded_node granularity (so that we can observe what state changes
    2211              :    lead to state_change_events being emitted).  */
    2212              : 
    2213              : bool
    2214        44421 : for_each_state_change (const program_state &src_state,
    2215              :                        const program_state &dst_state,
    2216              :                        const extrinsic_state &ext_state,
    2217              :                        state_change_visitor *visitor)
    2218              : {
    2219        88842 :   gcc_assert (src_state.m_checker_states.length ()
    2220              :               == ext_state.get_num_checkers ());
    2221        88842 :   gcc_assert (dst_state.m_checker_states.length ()
    2222              :               == ext_state.get_num_checkers ());
    2223       353836 :   for (unsigned i = 0; i < ext_state.get_num_checkers (); i++)
    2224              :     {
    2225       309415 :       const state_machine &sm = ext_state.get_sm (i);
    2226       309415 :       const sm_state_map &src_smap = *src_state.m_checker_states[i];
    2227       309415 :       const sm_state_map &dst_smap = *dst_state.m_checker_states[i];
    2228              : 
    2229              :       /* Add events for any global state changes.  */
    2230       309415 :       if (src_smap.get_global_state () != dst_smap.get_global_state ())
    2231          119 :         if (visitor->on_global_state_change (sm,
    2232              :                                              src_smap.get_global_state (),
    2233              :                                              dst_smap.get_global_state ()))
    2234              :           return true;
    2235              : 
    2236              :       /* Add events for per-svalue state changes.  */
    2237       355311 :       for (sm_state_map::iterator_t iter = dst_smap.begin ();
    2238       664726 :            iter != dst_smap.end ();
    2239        45896 :            ++iter)
    2240              :         {
    2241        45896 :           const svalue *sval = (*iter).first;
    2242        45896 :           state_machine::state_t dst_sm_val = (*iter).second.m_state;
    2243        45896 :           state_machine::state_t src_sm_val
    2244        45896 :             = src_smap.get_state (sval, ext_state);
    2245        45896 :           if (dst_sm_val != src_sm_val)
    2246              :             {
    2247         5047 :               const svalue *origin_sval = (*iter).second.m_origin;
    2248         5047 :               if (visitor->on_state_change (sm, src_sm_val, dst_sm_val,
    2249              :                                             sval, origin_sval))
    2250            0 :                 return true;
    2251              :             }
    2252              :         }
    2253              :     }
    2254              :   return false;
    2255              : }
    2256              : 
    2257              : /* Subroutine of diagnostic_manager::build_emission_path.
    2258              :    Add any events for EEDGE to EMISSION_PATH.  */
    2259              : 
    2260              : void
    2261        44421 : diagnostic_manager::add_events_for_eedge (const path_builder &pb,
    2262              :                                           const exploded_edge &eedge,
    2263              :                                           checker_path *emission_path,
    2264              :                                           interesting_t *interest,
    2265              :                                           const state_transition *state_trans) const
    2266              : {
    2267        44421 :   const exploded_node *src_node = eedge.m_src;
    2268        44421 :   const program_point &src_point = src_node->get_point ();
    2269        44421 :   const int src_stack_depth = src_point.get_stack_depth ();
    2270        44421 :   const exploded_node *dst_node = eedge.m_dest;
    2271        44421 :   const program_point &dst_point = dst_node->get_point ();
    2272        44421 :   const int dst_stack_depth = dst_point.get_stack_depth ();
    2273        44421 :   if (get_logger ())
    2274              :     {
    2275           13 :       get_logger ()->start_log_line ();
    2276           13 :       pretty_printer *pp = get_logger ()->get_printer ();
    2277           13 :       pp_printf (pp, "EN %i -> EN %i: ",
    2278           13 :                  eedge.m_src->m_index,
    2279           13 :                  eedge.m_dest->m_index);
    2280           13 :       src_point.print (pp, format (false));
    2281           13 :       pp_string (pp, "-> ");
    2282           13 :       dst_point.print (pp, format (false));
    2283           13 :       if (state_trans)
    2284              :         {
    2285            0 :           pp_string (pp, " {");
    2286            0 :           state_trans->dump_to_pp (pp);
    2287            0 :           pp_string (pp, "}");
    2288              :         }
    2289           13 :       get_logger ()->end_log_line ();
    2290              :     }
    2291        44421 :   const program_state &src_state = src_node->get_state ();
    2292        44421 :   const program_state &dst_state = dst_node->get_state ();
    2293              : 
    2294        44421 :   bool created_event_for_state_trans = false;
    2295              : 
    2296              :   /* Add state change events for the states that have changed.
    2297              :      We add these before events for superedges, so that if we have a
    2298              :      state_change_event due to following an edge, we'll get this sequence
    2299              :      of events:
    2300              : 
    2301              :       | if (!ptr)
    2302              :       |    ~
    2303              :       |    |
    2304              :       |    (1) assuming 'ptr' is non-NULL  (state_change_event)
    2305              :       |    (2) following 'false' branch... (start_cfg_edge_event)
    2306              :      ...
    2307              :       | do_something (ptr);
    2308              :       | ~~~~~~~~~~~~~^~~~~
    2309              :       |              |
    2310              :       |              (3) ...to here        (end_cfg_edge_event).  */
    2311        44421 :   state_change_event_creator visitor (pb, eedge, emission_path);
    2312        44421 :   for_each_state_change (src_state, dst_state, pb.get_ext_state (),
    2313              :                          &visitor);
    2314              : 
    2315              :   /* Give diagnostics an opportunity to inject extra events, or
    2316              :      to override the rest of this function.  */
    2317        44421 :   pending_diagnostic *pd = pb.get_pending_diagnostic ();
    2318        44421 :   if (pd->maybe_add_custom_events_for_eedge (eedge, emission_path))
    2319              :     return;
    2320              : 
    2321              :   /* Allow non-standard edges to add events, e.g. when rewinding from
    2322              :      longjmp to a setjmp.  */
    2323        43444 :   if (eedge.m_custom_info)
    2324              :     {
    2325         2909 :       eedge.m_custom_info->add_events_to_path (emission_path, eedge, *pd,
    2326              :                                                state_trans);
    2327         2909 :       created_event_for_state_trans = true;
    2328              :     }
    2329              : 
    2330              :   /* Don't add events for insignificant edges at verbosity levels below 3.  */
    2331        43444 :   if (m_verbosity < 3)
    2332        43219 :     if (!significant_edge_p (pb, eedge) && !state_trans)
    2333              :       return;
    2334              : 
    2335              :   /* Add events for operations.  */
    2336        42735 :   if (eedge.m_sedge)
    2337        36769 :     if (auto op = eedge.m_sedge->get_op ())
    2338        26599 :       op->add_any_events_for_eedge (eedge, *emission_path);
    2339              : 
    2340              :   /* Add events for function entry.  */
    2341        42735 :   if (dst_point.get_supernode ()->entry_p ())
    2342              :     {
    2343         5753 :       pb.get_pending_diagnostic ()->add_function_entry_event
    2344         5753 :         (eedge, emission_path,
    2345         5753 :          (state_trans
    2346           23 :           ? state_trans->dyn_cast_state_transition_at_call ()
    2347              :           : nullptr));
    2348         5753 :       created_event_for_state_trans = true;
    2349              :       /* Create region_creation_events for on-stack regions within
    2350              :          this frame.  */
    2351         5753 :       if (interest)
    2352              :         {
    2353              :           unsigned i;
    2354              :           const region *reg;
    2355         7338 :           FOR_EACH_VEC_ELT (interest->m_region_creation, i, reg)
    2356         1585 :             if (const frame_region *frame = reg->maybe_get_frame_region ())
    2357         1988 :               if (frame->get_fndecl () == dst_point.get_fndecl ())
    2358              :                 {
    2359          872 :                   const region *base_reg = reg->get_base_region ();
    2360          872 :                   if (tree decl = base_reg->maybe_get_decl ())
    2361          766 :                     if (DECL_P (decl)
    2362          766 :                         && useful_location_p (DECL_SOURCE_LOCATION (decl)))
    2363              :                       {
    2364          762 :                         emission_path->add_region_creation_events
    2365         1524 :                           (pb.get_pending_diagnostic (),
    2366          762 :                            reg, dst_state.m_region_model,
    2367          762 :                            event_loc_info (DECL_SOURCE_LOCATION (decl),
    2368              :                                            dst_point.get_fndecl (),
    2369          762 :                                            dst_stack_depth),
    2370          762 :                            m_verbosity > 3);
    2371              :                       }
    2372              :                 }
    2373              :         }
    2374              :     }
    2375              : 
    2376              :   /* Look for changes in dynamic extents, which will identify
    2377              :      the creation of heap-based regions and alloca regions.  */
    2378        42735 :   if (interest)
    2379              :     {
    2380        42731 :       const region_model *src_model = src_state.m_region_model;
    2381        42731 :       const region_model *dst_model = dst_state.m_region_model;
    2382        42731 :       if (src_model->get_dynamic_extents ()
    2383        42731 :           != dst_model->get_dynamic_extents ())
    2384              :         {
    2385              :           unsigned i;
    2386              :           const region *reg;
    2387         2845 :           FOR_EACH_VEC_ELT (interest->m_region_creation, i, reg)
    2388              :             {
    2389          450 :               const region *base_reg = reg->get_base_region ();
    2390          450 :               const svalue *old_extents
    2391          450 :                 = src_model->get_dynamic_extents (base_reg);
    2392          450 :               const svalue *new_extents
    2393          450 :                 = dst_model->get_dynamic_extents (base_reg);
    2394          450 :               if (old_extents == nullptr && new_extents != nullptr)
    2395          308 :                 switch (base_reg->get_kind ())
    2396              :                   {
    2397              :                   default:
    2398              :                     break;
    2399          272 :                   case RK_HEAP_ALLOCATED:
    2400          272 :                   case RK_ALLOCA:
    2401          272 :                     emission_path->add_region_creation_events
    2402          272 :                       (pb.get_pending_diagnostic (),
    2403              :                        reg, dst_model,
    2404          272 :                        event_loc_info (src_point.get_location (),
    2405              :                                        src_point.get_fndecl (),
    2406          544 :                                        src_stack_depth),
    2407          272 :                        m_verbosity > 3);
    2408          272 :                     break;
    2409              :                   }
    2410              :             }
    2411              :         }
    2412              :     }
    2413              : 
    2414              :   /* If we have a state transition and haven't yet created an
    2415              :      event that describes it, do so now.  */
    2416        42735 :   if (state_trans && !created_event_for_state_trans)
    2417           44 :     emission_path->add_event
    2418           44 :       (std::make_unique<state_transition_event>
    2419           44 :        (eedge.m_src->get_point (),
    2420              :         state_trans));
    2421              : 
    2422        42735 :   if (pb.get_feasibility_problem ()
    2423        42735 :       && &pb.get_feasibility_problem ()->m_eedge == &eedge)
    2424              :     {
    2425            4 :       pretty_printer pp;
    2426            4 :       pp_format_decoder (&pp) = default_tree_printer;
    2427            4 :       pp_string (&pp,
    2428              :                  "this path would have been rejected as infeasible"
    2429              :                  " at this edge: ");
    2430            4 :       pb.get_feasibility_problem ()->dump_to_pp (&pp);
    2431            4 :       emission_path->add_event
    2432            4 :         (std::make_unique<precanned_custom_event>
    2433            4 :            (event_loc_info (dst_point.get_location (),
    2434              :                             dst_point.get_fndecl (),
    2435            8 :                             dst_stack_depth),
    2436            4 :             pp_formatted_text (&pp)));
    2437            4 :     }
    2438        44421 : }
    2439              : 
    2440              : /* Return true if EEDGE is a significant edge in the path to the diagnostic
    2441              :    for PB.
    2442              : 
    2443              :    Consider all of the sibling out-eedges from the same source enode
    2444              :    as EEDGE.
    2445              :    If there's no path from the destinations of those eedges to the
    2446              :    diagnostic enode, then we have to take this eedge and thus it's
    2447              :    significant.
    2448              : 
    2449              :    Conversely if there is a path from the destination of any other sibling
    2450              :    eedge to the diagnostic enode, then this edge is insignificant.
    2451              : 
    2452              :    Example 1: redundant if-else:
    2453              : 
    2454              :      (A) if (...)            A
    2455              :      (B)   ...              / \
    2456              :          else              B   C
    2457              :      (C)   ...              \ /
    2458              :      (D) [DIAGNOSTIC]        D
    2459              : 
    2460              :      D is reachable by either B or C, so neither of these edges
    2461              :      are significant.
    2462              : 
    2463              :    Example 2: pertinent if-else:
    2464              : 
    2465              :      (A) if (...)                         A
    2466              :      (B)   ...                           / \
    2467              :          else                           B   C
    2468              :      (C)   [NECESSARY CONDITION]        |   |
    2469              :      (D) [POSSIBLE DIAGNOSTIC]          D1  D2
    2470              : 
    2471              :      D becomes D1 and D2 in the exploded graph, where the diagnostic occurs
    2472              :      at D2.  D2 is only reachable via C, so the A -> C edge is significant.
    2473              : 
    2474              :    Example 3: redundant loop:
    2475              : 
    2476              :      (A) while (...)          +-->A
    2477              :      (B)   ...                |  / \
    2478              :      (C) ...                  +-B  C
    2479              :      (D) [DIAGNOSTIC]              |
    2480              :                                    D
    2481              : 
    2482              :      D is reachable from both B and C, so the A->C edge is not significant.  */
    2483              : 
    2484              : bool
    2485        43219 : diagnostic_manager::significant_edge_p (const path_builder &pb,
    2486              :                                         const exploded_edge &eedge) const
    2487              : {
    2488        43219 :   int i;
    2489        43219 :   exploded_edge *sibling;
    2490       119640 :   FOR_EACH_VEC_ELT (eedge.m_src->m_succs, i, sibling)
    2491              :     {
    2492        77130 :       if (sibling == &eedge)
    2493        42825 :         continue;
    2494        34305 :       if (pb.reachable_from_p (sibling->m_dest))
    2495              :         {
    2496          709 :           if (get_logger ())
    2497            0 :             get_logger ()->log ("  edge EN: %i -> EN: %i is insignificant as"
    2498              :                                 " EN: %i is also reachable via"
    2499              :                                 " EN: %i -> EN: %i",
    2500            0 :                                 eedge.m_src->m_index, eedge.m_dest->m_index,
    2501            0 :                                 pb.get_diag_node ()->m_index,
    2502            0 :                                 sibling->m_src->m_index,
    2503              :                                 sibling->m_dest->m_index);
    2504              :           return false;
    2505              :         }
    2506              :     }
    2507              : 
    2508              :   return true;
    2509              : }
    2510              : 
    2511              : /* Prune PATH, based on the verbosity level, to the most pertinent
    2512              :    events for a diagnostic that involves VAR ending in state STATE
    2513              :    (for state machine SM).
    2514              : 
    2515              :    PATH is updated in place, and the redundant checker_events are deleted.
    2516              : 
    2517              :    As well as deleting events, call record_critical_state on events in
    2518              :    which state critical to the pending_diagnostic is being handled; see
    2519              :    the comment for diagnostic_manager::prune_for_sm_diagnostic.  */
    2520              : 
    2521              : void
    2522         4430 : diagnostic_manager::prune_path (checker_path *path,
    2523              :                                 const state_machine *sm,
    2524              :                                 const svalue *sval,
    2525              :                                 state_machine::state_t state) const
    2526              : {
    2527         4430 :   LOG_FUNC (get_logger ());
    2528         4430 :   path->maybe_log (get_logger (), "path");
    2529         4430 :   prune_for_sm_diagnostic (path, sm, sval, state);
    2530         4430 :   prune_interproc_events (path);
    2531         4430 :   if (! flag_analyzer_show_events_in_system_headers)
    2532         4428 :     prune_system_headers (path);
    2533         4430 :   consolidate_conditions (path);
    2534         4430 :   consolidate_unwind_events (path);
    2535         4430 :   finish_pruning (path);
    2536         4430 :   path->maybe_log (get_logger (), "pruned");
    2537         4430 : }
    2538              : 
    2539              : /* A cheap test to determine if EXPR can be the expression of interest in
    2540              :    an sm-diagnostic, so that we can reject cases where we have a non-lvalue.
    2541              :    We don't have always have a model when calling this, so we can't use
    2542              :    tentative_region_model_context, so there can be false positives.  */
    2543              : 
    2544              : static bool
    2545            0 : can_be_expr_of_interest_p (tree expr)
    2546              : {
    2547            0 :   if (!expr)
    2548              :     return false;
    2549              : 
    2550              :   /* Reject constants.  */
    2551            0 :   if (CONSTANT_CLASS_P (expr))
    2552            0 :     return false;
    2553              : 
    2554              :   /* Otherwise assume that it can be an lvalue.  */
    2555              :   return true;
    2556              : }
    2557              : 
    2558              : /* First pass of diagnostic_manager::prune_path: apply verbosity level,
    2559              :    pruning unrelated state change events.
    2560              : 
    2561              :    Iterate backwards through PATH, skipping state change events that aren't
    2562              :    VAR but update the pertinent VAR when state-copying occurs.
    2563              : 
    2564              :    As well as deleting events, call record_critical_state on events in
    2565              :    which state critical to the pending_diagnostic is being handled, so
    2566              :    that the event's get_desc vfunc can potentially supply a more precise
    2567              :    description of the event to the user.
    2568              :    e.g. improving
    2569              :      "calling 'foo' from 'bar'"
    2570              :    to
    2571              :      "passing possibly-NULL pointer 'ptr' to 'foo' from 'bar' as param 1"
    2572              :    when the diagnostic relates to later dereferencing 'ptr'.  */
    2573              : 
    2574              : void
    2575         4430 : diagnostic_manager::prune_for_sm_diagnostic (checker_path *path,
    2576              :                                              const state_machine *sm,
    2577              :                                              const svalue *uncanonicalized_sval,
    2578              :                                              state_machine::state_t state) const
    2579              : {
    2580         4430 :   auto &ext_state = path->get_ext_state ();
    2581         4430 :   const svalue *canonicalized_sval
    2582         4430 :     = sm_state_map::canonicalize_svalue (uncanonicalized_sval, ext_state);
    2583              : 
    2584         4430 :   int idx = path->num_events () - 1;
    2585        70982 :   while (idx >= 0 && idx < (signed)path->num_events ())
    2586              :     {
    2587        33276 :       checker_event *base_event = path->get_checker_event (idx);
    2588        33276 :       if (get_logger ())
    2589              :         {
    2590            6 :           if (sm)
    2591              :             {
    2592            0 :               if (uncanonicalized_sval)
    2593              :                 {
    2594            0 :                   label_text sval_desc = uncanonicalized_sval->get_desc ();
    2595            0 :                   log ("considering event %i (%s), with sval: %qs, state: %qs",
    2596              :                        idx, event_kind_to_string (base_event->get_kind ()),
    2597              :                        sval_desc.get (), state->get_name ());
    2598            0 :                 }
    2599              :               else
    2600            0 :                 log ("considering event %i (%s), with global state: %qs",
    2601              :                      idx, event_kind_to_string (base_event->get_kind ()),
    2602              :                      state->get_name ());
    2603              :             }
    2604              :           else
    2605            6 :             log ("considering event %i", idx);
    2606              :         }
    2607              : 
    2608        33276 :       switch (base_event->get_kind ())
    2609              :         {
    2610            0 :         default:
    2611            0 :           gcc_unreachable ();
    2612              : 
    2613            0 :         case event_kind::debug:
    2614            0 :           if (m_verbosity < 4)
    2615              :             {
    2616            0 :               log ("filtering event %i: debug event", idx);
    2617            0 :               path->delete_event (idx);
    2618              :             }
    2619              :           break;
    2620              : 
    2621              :         case event_kind::custom:
    2622              :           /* Don't filter custom events.  */
    2623              :           break;
    2624              : 
    2625        12985 :         case event_kind::stmt:
    2626        12985 :           {
    2627        12985 :             if (m_verbosity < 4)
    2628              :               {
    2629        12985 :                 log ("filtering event %i: statement event", idx);
    2630        12985 :                 path->delete_event (idx);
    2631              :               }
    2632              :           }
    2633              :           break;
    2634              : 
    2635              :         case event_kind::region_creation:
    2636              :           /* Don't filter these.  */
    2637              :           break;
    2638              : 
    2639           44 :         case event_kind::state_transition:
    2640              :           /* Prune these if they have an empty description.  */
    2641           44 :           {
    2642           44 :             tree_dump_pretty_printer pp (nullptr);
    2643           44 :             base_event->print_desc (pp);
    2644           44 :             if (strlen (pp_formatted_text (&pp)) == 0)
    2645              :               {
    2646            0 :                 log (("filtering event %i:"
    2647              :                       " state_transition_event with empty description"),
    2648              :                      idx);
    2649            0 :                 path->delete_event (idx);
    2650              :               }
    2651           44 :           }
    2652           44 :           break;
    2653              : 
    2654         5753 :         case event_kind::function_entry:
    2655         5753 :           if (m_verbosity < 1)
    2656              :             {
    2657           33 :               log ("filtering event %i: function entry", idx);
    2658           33 :               path->delete_event (idx);
    2659              :             }
    2660              :           break;
    2661              : 
    2662         4537 :         case event_kind::state_change:
    2663         4537 :           {
    2664         4537 :             state_change_event *state_change = (state_change_event *)base_event;
    2665         4537 :             gcc_assert (state_change->m_dst_state.m_region_model);
    2666              : 
    2667         4537 :             if (canonicalized_sval
    2668         4537 :                 == sm_state_map::canonicalize_svalue (state_change->m_sval,
    2669              :                                                       ext_state))
    2670              :               {
    2671         2492 :                 if (state_change->m_origin)
    2672              :                   {
    2673            0 :                     if (get_logger ())
    2674              :                       {
    2675            0 :                         label_text sval_desc = uncanonicalized_sval->get_desc ();
    2676            0 :                         label_text origin_sval_desc
    2677            0 :                           = state_change->m_origin->get_desc ();
    2678            0 :                         log ("event %i:"
    2679              :                              " switching var of interest from %qs to %qs",
    2680              :                              idx, sval_desc.get (),
    2681              :                              origin_sval_desc.get ());
    2682            0 :                       }
    2683            0 :                     uncanonicalized_sval = state_change->m_origin;
    2684            0 :                     canonicalized_sval
    2685            0 :                       = sm_state_map::canonicalize_svalue (uncanonicalized_sval,
    2686              :                                                            ext_state);
    2687              : 
    2688              :                   }
    2689         2492 :                 log ("event %i: switching state of interest from %qs to %qs",
    2690         2492 :                      idx, state_change->m_to->get_name (),
    2691         2492 :                      state_change->m_from->get_name ());
    2692         2492 :                 state = state_change->m_from;
    2693              :               }
    2694         2045 :             else if (m_verbosity < 4)
    2695              :               {
    2696         2045 :                 if (get_logger ())
    2697              :                   {
    2698            0 :                     if (state_change->m_sval)
    2699              :                       {
    2700            0 :                         label_text change_sval_desc
    2701            0 :                           = state_change->m_sval->get_desc ();
    2702            0 :                         if (uncanonicalized_sval)
    2703              :                           {
    2704            0 :                             label_text sval_desc = uncanonicalized_sval->get_desc ();
    2705            0 :                             log ("filtering event %i:"
    2706              :                                  " state change to %qs unrelated to %qs",
    2707              :                                  idx, change_sval_desc.get (),
    2708              :                                  sval_desc.get ());
    2709            0 :                           }
    2710              :                         else
    2711            0 :                           log ("filtering event %i: state change to %qs",
    2712              :                                idx, change_sval_desc.get ());
    2713            0 :                       }
    2714              :                     else
    2715            0 :                       log ("filtering event %i: global state change", idx);
    2716              :                   }
    2717         2045 :                 path->delete_event (idx);
    2718              :               }
    2719              :           }
    2720              :           break;
    2721              : 
    2722         2641 :         case event_kind::start_cfg_edge:
    2723         2641 :           {
    2724         2641 :             cfg_edge_event *event = (cfg_edge_event *)base_event;
    2725              : 
    2726              :             /* TODO: is this edge significant to var?
    2727              :                See if var can be in other states in the dest, but not
    2728              :                in other states in the src?
    2729              :                Must have multiple sibling edges.  */
    2730              : 
    2731         2641 :             if (event->should_filter_p (m_verbosity))
    2732              :               {
    2733           35 :                 log ("filtering events %i and %i: CFG edge", idx, idx + 1);
    2734           35 :                 path->delete_event (idx);
    2735              :                 /* Also delete the corresponding event_kind::end_cfg_edge.  */
    2736           35 :                 gcc_assert (path->get_checker_event (idx)->get_kind ()
    2737              :                             == event_kind::end_cfg_edge);
    2738           35 :                 path->delete_event (idx);
    2739              :               }
    2740              :           }
    2741              :           break;
    2742              : 
    2743              :         case event_kind::end_cfg_edge:
    2744              :           /* These come in pairs with event_kind::start_cfg_edge events and are
    2745              :              filtered when their start event is filtered.  */
    2746              :           break;
    2747              : 
    2748              :         case event_kind::catch_:
    2749              :         case event_kind::throw_:
    2750              :         case event_kind::unwind:
    2751              :           /* Don't filter these.  */
    2752              :           break;
    2753              : 
    2754         1403 :         case event_kind::call_:
    2755         1403 :           {
    2756         1403 :             call_event *event = (call_event *)base_event;
    2757         1403 :             const region_model *callee_model
    2758         1403 :               = event->m_eedge.m_dest->get_state ().m_region_model;
    2759         1403 :             const region_model *caller_model
    2760         1403 :               = event->m_eedge.m_src->get_state ().m_region_model;
    2761         1403 :             tree callee_var
    2762         1403 :               = callee_model->get_representative_tree (uncanonicalized_sval);
    2763         1403 :             callsite_expr expr;
    2764              : 
    2765         1403 :             tree caller_var;
    2766         1403 :             if (auto op = event->get_call_and_return_op ())
    2767              :               {
    2768         1403 :                 tree callee_fndecl
    2769         1403 :                   = event->m_eedge.m_dest->get_point ().get_fndecl ();
    2770         1403 :                 caller_var
    2771         1403 :                   = op->map_expr_from_callee_to_caller (callee_fndecl,
    2772              :                                                         callee_var,
    2773              :                                                         &expr);
    2774              :               }
    2775              :             else
    2776            0 :               caller_var
    2777            0 :                 = caller_model->get_representative_tree (uncanonicalized_sval);
    2778              : 
    2779         1403 :             if (caller_var)
    2780              :               {
    2781          234 :                 if (get_logger ())
    2782              :                   {
    2783            0 :                     label_text sval_desc = uncanonicalized_sval->get_desc ();
    2784            0 :                     log ("event %i:"
    2785              :                          " recording critical state for %qs at call"
    2786              :                          " from %qE in callee to %qE in caller",
    2787              :                          idx, sval_desc.get (), callee_var, caller_var);
    2788            0 :                   }
    2789          234 :                 if (expr.param_p ())
    2790          234 :                   event->record_critical_state (caller_var, state);
    2791              :               }
    2792              :           }
    2793         1403 :           break;
    2794              : 
    2795          824 :         case event_kind::return_:
    2796          824 :           {
    2797          824 :             if (uncanonicalized_sval)
    2798              :               {
    2799          634 :                 return_event *event = (return_event *)base_event;
    2800          634 :                 const region_model *caller_model
    2801          634 :                   = event->m_eedge.m_dest->get_state ().m_region_model;
    2802          634 :                 tree caller_var
    2803          634 :                   = caller_model->get_representative_tree (uncanonicalized_sval);
    2804          634 :                 const region_model *callee_model
    2805          634 :                   = event->m_eedge.m_src->get_state ().m_region_model;
    2806          634 :                 callsite_expr expr;
    2807              : 
    2808          634 :                 tree callee_var;
    2809              : 
    2810          634 :                 if (auto op = event->get_call_and_return_op ())
    2811              :                   {
    2812          634 :                     tree callee_fndecl
    2813          634 :                       = event->m_eedge.m_src->get_point ().get_fndecl ();
    2814          634 :                     callee_var
    2815          634 :                       = op->map_expr_from_caller_to_callee (callee_fndecl,
    2816              :                                                             caller_var,
    2817              :                                                             &expr);
    2818              :                   }
    2819              :                 else
    2820            0 :                   callee_var
    2821            0 :                     = callee_model->get_representative_tree (uncanonicalized_sval);
    2822              : 
    2823          634 :                 if (callee_var)
    2824              :                   {
    2825          157 :                     if (get_logger ())
    2826              :                       {
    2827            0 :                         label_text sval_desc
    2828            0 :                           = uncanonicalized_sval->get_desc ();
    2829            0 :                         log ("event %i:"
    2830              :                              " recording critical state for %qs at return"
    2831              :                              " from %qE in caller to %qE in callee",
    2832              :                              idx, sval_desc.get (), callee_var, callee_var);
    2833            0 :                       }
    2834          157 :                     if (expr.return_value_p ())
    2835           70 :                       event->record_critical_state (callee_var, state);
    2836              :                   }
    2837              :               }
    2838              :           }
    2839              :           break;
    2840              : 
    2841              :         case event_kind::inlined_call:
    2842              :           /* We don't expect to see these yet, as they're added later.
    2843              :              We'd want to keep them around.  */
    2844              :           break;
    2845              : 
    2846              :         case event_kind::setjmp_:
    2847              :           /* TODO: only show setjmp_events that matter i.e. those for which
    2848              :              there is a later rewind event using them.  */
    2849              :         case event_kind::rewind_from_longjmp:
    2850              :         case event_kind::rewind_to_setjmp:
    2851              :           break;
    2852              : 
    2853              :         case event_kind::warning:
    2854              :           /* Always show the final "warning" event in the path.  */
    2855              :           break;
    2856              :         }
    2857        33276 :       idx--;
    2858              :     }
    2859         4430 : }
    2860              : 
    2861              : /* Subroutine of diagnostic_manager::prune_for_sm_diagnostic.
    2862              :    If *EXPR is not suitable to be the expression of interest in
    2863              :    an sm-diagnostic, set *EXPR to NULL and log.  */
    2864              : 
    2865              : void
    2866            0 : diagnostic_manager::update_for_unsuitable_sm_exprs (tree *expr) const
    2867              : {
    2868            0 :   gcc_assert (expr);
    2869            0 :   if (*expr && !can_be_expr_of_interest_p (*expr))
    2870              :     {
    2871            0 :       log ("new var %qE is unsuitable; setting var to NULL", *expr);
    2872            0 :       *expr = NULL_TREE;
    2873              :     }
    2874            0 : }
    2875              : 
    2876              : /* Second pass of diagnostic_manager::prune_path: remove redundant
    2877              :    interprocedural information.
    2878              : 
    2879              :    For example, given:
    2880              :      (1)- calling "f2" from "f1"
    2881              :      (2)--- entry to "f2"
    2882              :      (3)--- calling "f3" from "f2"
    2883              :      (4)----- entry to "f3"
    2884              :      (5)--- returning to "f2" to "f3"
    2885              :      (6)- returning to "f1" to "f2"
    2886              :    with no other intervening events, then none of these events are
    2887              :    likely to be interesting to the user.
    2888              : 
    2889              :    Prune [..., call, function-entry, return, ...] triples repeatedly
    2890              :    until nothing has changed.  For the example above, this would
    2891              :    remove events (3, 4, 5), and then remove events (1, 2, 6).  */
    2892              : 
    2893              : void
    2894         4430 : diagnostic_manager::prune_interproc_events (checker_path *path) const
    2895              : {
    2896         4430 :   bool changed = false;
    2897         4682 :   do
    2898              :     {
    2899         4682 :       changed = false;
    2900         4682 :       int idx = (signed)path->num_events () - 1;
    2901        24178 :       while (idx >= 0)
    2902              :         {
    2903              :           /* Prune [..., call, function-entry, return, ...] triples.  */
    2904        19496 :           if (idx + 2 < (signed)path->num_events ()
    2905        10416 :               && path->get_checker_event (idx)->is_call_p ()
    2906         1110 :               && path->get_checker_event (idx + 1)->is_function_entry_p ()
    2907        20598 :               && path->get_checker_event (idx + 2)->is_return_p ())
    2908              :             {
    2909          539 :               if (get_logger ())
    2910              :                 {
    2911            0 :                   label_text desc
    2912            0 :                     (path->get_checker_event (idx)->get_desc
    2913            0 :                        (*global_dc->get_reference_printer ()));
    2914            0 :                   log ("filtering events %i-%i:"
    2915              :                        " irrelevant call/entry/return: %s",
    2916              :                        idx, idx + 2, desc.get ());
    2917            0 :                 }
    2918          539 :               path->delete_event (idx + 2);
    2919          539 :               path->delete_event (idx + 1);
    2920          539 :               path->delete_event (idx);
    2921          539 :               changed = true;
    2922          539 :               idx--;
    2923          539 :               continue;
    2924          539 :             }
    2925              : 
    2926              :           /* Prune [..., call, return, ...] pairs
    2927              :              (for -fanalyzer-verbosity=0).  */
    2928        18957 :           if (idx + 1 < (signed)path->num_events ()
    2929        14135 :               && path->get_checker_event (idx)->is_call_p ()
    2930        19895 :               && path->get_checker_event (idx + 1)->is_return_p ())
    2931              :             {
    2932            4 :               if (get_logger ())
    2933              :                 {
    2934            0 :                   label_text desc
    2935            0 :                     (path->get_checker_event (idx)->get_desc
    2936            0 :                      (*global_dc->get_reference_printer ()));
    2937            0 :                   log ("filtering events %i-%i:"
    2938              :                        " irrelevant call/return: %s",
    2939              :                        idx, idx + 1, desc.get ());
    2940            0 :                 }
    2941            4 :               path->delete_event (idx + 1);
    2942            4 :               path->delete_event (idx);
    2943            4 :               changed = true;
    2944            4 :               idx--;
    2945            4 :               continue;
    2946            4 :             }
    2947              : 
    2948        18953 :           idx--;
    2949              :         }
    2950              : 
    2951              :     }
    2952              :   while (changed);
    2953         4430 : }
    2954              : 
    2955              : /* Remove everything within [call point, IDX]. For consistency,
    2956              :    IDX should represent the return event of the frame to delete,
    2957              :    or if there is none it should be the last event of the frame.
    2958              :    After this function, IDX designates the event prior to calling
    2959              :    this frame.  */
    2960              : 
    2961              : static void
    2962            0 : prune_frame (checker_path *path, int &idx)
    2963              : {
    2964            0 :   gcc_assert (idx >= 0);
    2965            0 :   int nesting = 1;
    2966            0 :   if (path->get_checker_event (idx)->is_return_p ())
    2967            0 :     nesting = 0;
    2968            0 :   do
    2969              :     {
    2970            0 :       if (path->get_checker_event (idx)->is_call_p ())
    2971            0 :         nesting--;
    2972            0 :       else if (path->get_checker_event (idx)->is_return_p ())
    2973            0 :         nesting++;
    2974              : 
    2975            0 :       path->delete_event (idx--);
    2976            0 :     } while (idx >= 0 && nesting != 0);
    2977            0 : }
    2978              : 
    2979              : /* This function is called when fanalyzer-show-events-in-system-headers
    2980              :    is disabled and will prune the diagnostic of all events within a
    2981              :    system header, only keeping the entry and exit events to the header.
    2982              :    This should be called after diagnostic_manager::prune_interproc_events
    2983              :    so that successive events [system header call, system header return]
    2984              :    are preserved thereafter.
    2985              : 
    2986              :    Given a diagnostics path diving into a system header in the form
    2987              :    [
    2988              :      prefix events...,
    2989              :      system header call,
    2990              :        system header entry,
    2991              :        events within system headers...,
    2992              :      system header return,
    2993              :      suffix events...
    2994              :    ]
    2995              : 
    2996              :    then transforms it into
    2997              :    [
    2998              :      prefix events...,
    2999              :      system header call,
    3000              :      system header return,
    3001              :      suffix events...
    3002              :    ].  */
    3003              : 
    3004              : void
    3005         4428 : diagnostic_manager::prune_system_headers (checker_path *path) const
    3006              : {
    3007         4428 :   int idx = (signed)path->num_events () - 1;
    3008        20944 :   while (idx >= 0)
    3009              :     {
    3010        16516 :       const checker_event *event = path->get_checker_event (idx);
    3011              :       /* Prune everything between
    3012              :          [..., system entry, (...), system return, ...].  */
    3013        16516 :       if (event->is_return_p ()
    3014        16516 :           && in_system_header_at (event->get_location ()))
    3015              :       {
    3016            0 :         int ret_idx = idx;
    3017            0 :         prune_frame (path, idx);
    3018              : 
    3019            0 :         if (get_logger ())
    3020              :         {
    3021            0 :           log ("filtering system headers events %i-%i:",
    3022              :                idx, ret_idx);
    3023              :         }
    3024              :         // Delete function entry within system headers.
    3025            0 :         if (idx >= 0)
    3026              :           {
    3027            0 :             event = path->get_checker_event (idx);
    3028            0 :             if (event->is_function_entry_p ()
    3029            0 :                 && in_system_header_at (event->get_location ()))
    3030              :               {
    3031            0 :                 if (get_logger ())
    3032              :                   {
    3033            0 :                     label_text desc
    3034            0 :                       (event->get_desc (*global_dc->get_reference_printer ()));
    3035            0 :                     log ("filtering event %i:"
    3036              :                          "system header entry event: %s",
    3037              :                          idx, desc.get ());
    3038            0 :                   }
    3039              : 
    3040            0 :                 path->delete_event (idx);
    3041              :               }
    3042              :           }
    3043              :       }
    3044              : 
    3045        16516 :       idx--;
    3046              :     }
    3047         4428 : }
    3048              : 
    3049              : /* Return true iff event IDX within PATH is on the same line as REF_EXP_LOC.  */
    3050              : 
    3051              : static bool
    3052         2736 : same_line_as_p (const expanded_location &ref_exp_loc,
    3053              :                 checker_path *path, unsigned idx)
    3054              : {
    3055         2736 :   const checker_event *ev = path->get_checker_event (idx);
    3056         2736 :   expanded_location idx_exp_loc = expand_location (ev->get_location ());
    3057         2736 :   gcc_assert (ref_exp_loc.file);
    3058         2736 :   if (idx_exp_loc.file == nullptr)
    3059              :     return false;
    3060         2713 :   if (strcmp (ref_exp_loc.file, idx_exp_loc.file))
    3061              :     return false;
    3062         2709 :   return ref_exp_loc.line == idx_exp_loc.line;
    3063              : }
    3064              : 
    3065              : /* This path-readability optimization reduces the verbosity of compound
    3066              :    conditional statements (without needing to reconstruct the AST, which
    3067              :    has already been lost).
    3068              : 
    3069              :    For example, it converts:
    3070              : 
    3071              :     |   61 |   if (cp[0] != '\0' && cp[0] != '#')
    3072              :     |      |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    3073              :     |      |      |              |    |
    3074              :     |      |      |              |    (6) ...to here
    3075              :     |      |      |              (7) following ‘true’ branch...
    3076              :     |      |      (5) following ‘true’ branch...
    3077              :     |   62 |     {
    3078              :     |   63 |       alias = cp++;
    3079              :     |      |               ~~~~
    3080              :     |      |                 |
    3081              :     |      |                 (8) ...to here
    3082              : 
    3083              :    into:
    3084              : 
    3085              :     |   61 |   if (cp[0] != '\0' && cp[0] != '#')
    3086              :     |      |      ~
    3087              :     |      |      |
    3088              :     |      |      (5) following ‘true’ branch...
    3089              :     |   62 |     {
    3090              :     |   63 |       alias = cp++;
    3091              :     |      |               ~~~~
    3092              :     |      |                 |
    3093              :     |      |                 (6) ...to here
    3094              : 
    3095              :    by combining events 5-8 into new events 5-6.
    3096              : 
    3097              :    Find runs of consecutive (start_cfg_edge_event, end_cfg_edge_event) pairs
    3098              :    in which all events apart from the final end_cfg_edge_event are on the same
    3099              :    line, and for which either all the CFG edges are TRUE edges, or all are
    3100              :    FALSE edges.
    3101              : 
    3102              :    Consolidate each such run into a
    3103              :      (start_consolidated_cfg_edges_event, end_consolidated_cfg_edges_event)
    3104              :    pair.  */
    3105              : 
    3106              : void
    3107         4430 : diagnostic_manager::consolidate_conditions (checker_path *path) const
    3108              : {
    3109              :   /* Don't simplify edges if we're debugging them.  */
    3110         4430 :   if (flag_analyzer_verbose_edges)
    3111              :     return;
    3112              : 
    3113        12001 :   for (int start_idx = 0;
    3114        32771 :        start_idx < (signed)path->num_events () - 1;
    3115              :        start_idx++)
    3116              :     {
    3117        12001 :       if (path->cfg_edge_pair_at_p (start_idx))
    3118              :         {
    3119         2517 :           const checker_event *old_start_ev
    3120         2517 :             = path->get_checker_event (start_idx);
    3121         2517 :           expanded_location start_exp_loc
    3122         2517 :             = expand_location (old_start_ev->get_location ());
    3123         2517 :           if (start_exp_loc.file == nullptr)
    3124         2182 :             continue;
    3125         2517 :           if (!same_line_as_p (start_exp_loc, path, start_idx + 1))
    3126         2182 :             continue;
    3127              : 
    3128              :           /* Are we looking for a run of all TRUE edges, or all FALSE edges?  */
    3129          335 :           gcc_assert (old_start_ev->get_kind () == event_kind::start_cfg_edge);
    3130          335 :           const start_cfg_edge_event *old_start_cfg_ev
    3131              :             = (const start_cfg_edge_event *)old_start_ev;
    3132          335 :           bool edge_sense;
    3133          335 :           if (!old_start_cfg_ev->maybe_get_edge_sense (&edge_sense))
    3134            0 :             continue;
    3135              : 
    3136              :           /* Find a run of CFG start/end event pairs from
    3137              :                [start_idx, next_idx)
    3138              :              where all apart from the final event are on the same line,
    3139              :              and all are either TRUE or FALSE edges, matching the initial.  */
    3140          335 :           int next_idx = start_idx + 2;
    3141          335 :           while (path->cfg_edge_pair_at_p (next_idx)
    3142          424 :                  && same_line_as_p (start_exp_loc, path, next_idx))
    3143              :             {
    3144          124 :               const checker_event *iter_ev
    3145          124 :                 = path->get_checker_event (next_idx);
    3146          124 :               gcc_assert (iter_ev->get_kind () == event_kind::start_cfg_edge);
    3147          124 :               const start_cfg_edge_event *iter_cfg_ev
    3148              :                 = (const start_cfg_edge_event *)iter_ev;
    3149          124 :               bool iter_edge_sense;
    3150          124 :               if (!iter_cfg_ev->maybe_get_edge_sense (&iter_edge_sense))
    3151              :                 break;
    3152          118 :               if (iter_edge_sense != edge_sense)
    3153              :                 break;
    3154           89 :               next_idx += 2;
    3155              :             }
    3156              : 
    3157              :           /* If we have more than one pair in the run, consolidate.  */
    3158          335 :           if (next_idx > start_idx + 2)
    3159              :             {
    3160           84 :               const checker_event *old_end_ev
    3161           84 :                 = path->get_checker_event (next_idx - 1);
    3162           84 :               log ("consolidating CFG edge events %i-%i into %i-%i",
    3163              :                    start_idx, next_idx - 1, start_idx, start_idx +1);
    3164           84 :               auto new_start_ev
    3165              :                 = std::make_unique<start_consolidated_cfg_edges_event>
    3166           84 :                     (event_loc_info (old_start_ev->get_location (),
    3167              :                                      old_start_ev->get_fndecl (),
    3168           84 :                                      old_start_ev->get_stack_depth ()),
    3169           84 :                  edge_sense);
    3170           84 :               auto new_end_ev
    3171              :                 = std::make_unique<end_consolidated_cfg_edges_event>
    3172           84 :                     (event_loc_info (old_end_ev->get_location (),
    3173              :                                      old_end_ev->get_fndecl (),
    3174           84 :                                      old_end_ev->get_stack_depth ()));
    3175           84 :               path->replace_event (start_idx, std::move (new_start_ev));
    3176           84 :               path->replace_event (start_idx + 1, std::move (new_end_ev));
    3177           84 :               path->delete_events (start_idx + 2, next_idx - (start_idx + 2));
    3178           84 :             }
    3179              :         }
    3180              :     }
    3181              : }
    3182              : 
    3183              : /* Consolidate runs of consecutive unwind_event.  */
    3184              : 
    3185              : void
    3186         4430 : diagnostic_manager::consolidate_unwind_events (checker_path *path) const
    3187              : {
    3188              :   /* Don't simplify edges if we're debugging them.  */
    3189         4430 :   if (flag_analyzer_verbose_edges)
    3190              :     return;
    3191              : 
    3192        11995 :   for (int start_idx = 0;
    3193        32759 :        start_idx < (signed)path->num_events () - 1;
    3194              :        start_idx++)
    3195              :     {
    3196              :       /* Find a run of consecutive unwind_event instances.  */
    3197        11995 :       if (path->get_checker_event (start_idx)->get_kind ()
    3198              :           != event_kind::unwind)
    3199        11986 :         continue;
    3200            9 :       int iter_idx = start_idx + 1;
    3201           15 :       while (iter_idx < (int)path->num_events ())
    3202           15 :         if (path->get_checker_event (iter_idx)->get_kind ()
    3203              :             == event_kind::unwind)
    3204            6 :           ++iter_idx;
    3205              :         else
    3206              :           break;
    3207              : 
    3208              :       /* iter_idx should now be one after the last unwind_event in the run.  */
    3209            9 :       const int last_idx = iter_idx - 1;
    3210            9 :       if (last_idx == start_idx)
    3211            3 :         continue;
    3212              : 
    3213            6 :       gcc_assert (last_idx > start_idx);
    3214              : 
    3215            6 :       log ("consolidating unwind events %i-%i into %i",
    3216              :            start_idx, last_idx, start_idx);
    3217              : 
    3218            6 :       unwind_event *first_event
    3219            6 :         = (unwind_event *)path->get_checker_event (start_idx);
    3220            6 :       const unwind_event *last_event
    3221            6 :         = (const unwind_event *)path->get_checker_event (last_idx);
    3222            6 :       first_event->m_num_frames += last_event->m_num_frames;
    3223            6 :       path->delete_events (start_idx + 1, last_idx - start_idx);
    3224              :     }
    3225              : }
    3226              : 
    3227              : /* Final pass of diagnostic_manager::prune_path.
    3228              : 
    3229              :    If all we're left with is in one function, then filter function entry
    3230              :    events.  */
    3231              : 
    3232              : void
    3233         4430 : diagnostic_manager::finish_pruning (checker_path *path) const
    3234              : {
    3235         4430 :   if (!path->interprocedural_p ())
    3236              :     {
    3237         3643 :       int idx = path->num_events () - 1;
    3238        26833 :       while (idx >= 0 && idx < (signed)path->num_events ())
    3239              :         {
    3240        11595 :           checker_event *base_event = path->get_checker_event (idx);
    3241        11595 :           if (base_event->get_kind () == event_kind::function_entry)
    3242              :             {
    3243         3547 :               log ("filtering event %i:"
    3244              :                    " function entry for purely intraprocedural path", idx);
    3245         3547 :               path->delete_event (idx);
    3246              :             }
    3247        11595 :           idx--;
    3248              :         }
    3249              :     }
    3250         4430 : }
    3251              : 
    3252              : } // namespace ana
    3253              : 
    3254              : #endif /* #if ENABLE_ANALYZER */
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.