xref: /netbsd-src/external/gpl3/gcc/dist/gcc/gimple-range-cache.cc (revision 0a3071956a3a9fdebdbf7f338cf2d439b45fc728)
1 /* Gimple ranger SSA cache implementation.
2    Copyright (C) 2017-2022 Free Software Foundation, Inc.
3    Contributed by Andrew MacLeod <amacleod@redhat.com>.
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11 
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "gimple-range.h"
31 #include "tree-cfg.h"
32 #include "target.h"
33 #include "attribs.h"
34 #include "gimple-iterator.h"
35 #include "gimple-walk.h"
36 #include "cfganal.h"
37 
38 #define DEBUG_RANGE_CACHE (dump_file					\
39 			   && (param_ranger_debug & RANGER_DEBUG_CACHE))
40 
41 // During contructor, allocate the vector of ssa_names.
42 
non_null_ref()43 non_null_ref::non_null_ref ()
44 {
45   m_nn.create (num_ssa_names);
46   m_nn.quick_grow_cleared (num_ssa_names);
47   bitmap_obstack_initialize (&m_bitmaps);
48 }
49 
50 // Free any bitmaps which were allocated,a swell as the vector itself.
51 
~non_null_ref()52 non_null_ref::~non_null_ref ()
53 {
54   bitmap_obstack_release (&m_bitmaps);
55   m_nn.release ();
56 }
57 
58 // This routine will update NAME in BB to be nonnull if it is not already.
59 // return TRUE if the update happens.
60 
61 bool
set_nonnull(basic_block bb,tree name)62 non_null_ref::set_nonnull (basic_block bb, tree name)
63 {
64   gcc_checking_assert (gimple_range_ssa_p (name)
65 		       && POINTER_TYPE_P (TREE_TYPE (name)));
66   // Only process when its not already set.
67   if (non_null_deref_p  (name, bb, false))
68     return false;
69   bitmap_set_bit (m_nn[SSA_NAME_VERSION (name)], bb->index);
70   return true;
71 }
72 
73 // Return true if NAME has a non-null dereference in block bb.  If this is the
74 // first query for NAME, calculate the summary first.
75 // If SEARCH_DOM is true, the search the dominator tree as well.
76 
77 bool
non_null_deref_p(tree name,basic_block bb,bool search_dom)78 non_null_ref::non_null_deref_p (tree name, basic_block bb, bool search_dom)
79 {
80   if (!POINTER_TYPE_P (TREE_TYPE (name)))
81     return false;
82 
83   unsigned v = SSA_NAME_VERSION (name);
84   if (v >= m_nn.length ())
85     m_nn.safe_grow_cleared (num_ssa_names + 1);
86 
87   if (!m_nn[v])
88     process_name (name);
89 
90   if (bitmap_bit_p (m_nn[v], bb->index))
91     return true;
92 
93   // See if any dominator has set non-zero.
94   if (search_dom && dom_info_available_p (CDI_DOMINATORS))
95     {
96       // Search back to the Def block, or the top, whichever is closer.
97       basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (name));
98       basic_block def_dom = def_bb
99 			    ? get_immediate_dominator (CDI_DOMINATORS, def_bb)
100 			    : NULL;
101       for ( ;
102 	    bb && bb != def_dom;
103 	    bb = get_immediate_dominator (CDI_DOMINATORS, bb))
104 	if (bitmap_bit_p (m_nn[v], bb->index))
105 	  return true;
106     }
107   return false;
108 }
109 
110 // Allocate an populate the bitmap for NAME.  An ON bit for a block
111 // index indicates there is a non-null reference in that block.  In
112 // order to populate the bitmap, a quick run of all the immediate uses
113 // are made and the statement checked to see if a non-null dereference
114 // is made on that statement.
115 
116 void
process_name(tree name)117 non_null_ref::process_name (tree name)
118 {
119   unsigned v = SSA_NAME_VERSION (name);
120   use_operand_p use_p;
121   imm_use_iterator iter;
122   bitmap b;
123 
124   // Only tracked for pointers.
125   if (!POINTER_TYPE_P (TREE_TYPE (name)))
126     return;
127 
128   // Already processed if a bitmap has been allocated.
129   if (m_nn[v])
130     return;
131 
132   b = BITMAP_ALLOC (&m_bitmaps);
133 
134   // Loop over each immediate use and see if it implies a non-null value.
135   FOR_EACH_IMM_USE_FAST (use_p, iter, name)
136     {
137       gimple *s = USE_STMT (use_p);
138       unsigned index = gimple_bb (s)->index;
139 
140       // If bit is already set for this block, dont bother looking again.
141       if (bitmap_bit_p (b, index))
142 	continue;
143 
144       // If we can infer a nonnull range, then set the bit for this BB
145       if (!SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name)
146 	  && infer_nonnull_range (s, name))
147 	bitmap_set_bit (b, index);
148     }
149 
150   m_nn[v] = b;
151 }
152 
153 // -------------------------------------------------------------------------
154 
155 // This class represents the API into a cache of ranges for an SSA_NAME.
156 // Routines must be implemented to set, get, and query if a value is set.
157 
158 class ssa_block_ranges
159 {
160 public:
161   virtual bool set_bb_range (const_basic_block bb, const irange &r) = 0;
162   virtual bool get_bb_range (irange &r, const_basic_block bb) = 0;
163   virtual bool bb_range_p (const_basic_block bb) = 0;
164 
165   void dump(FILE *f);
166 };
167 
168 // Print the list of known ranges for file F in a nice format.
169 
170 void
dump(FILE * f)171 ssa_block_ranges::dump (FILE *f)
172 {
173   basic_block bb;
174   int_range_max r;
175 
176   FOR_EACH_BB_FN (bb, cfun)
177     if (get_bb_range (r, bb))
178       {
179 	fprintf (f, "BB%d  -> ", bb->index);
180 	r.dump (f);
181 	fprintf (f, "\n");
182       }
183 }
184 
185 // This class implements the range cache as a linear vector, indexed by BB.
186 // It caches a varying and undefined range which are used instead of
187 // allocating new ones each time.
188 
189 class sbr_vector : public ssa_block_ranges
190 {
191 public:
192   sbr_vector (tree t, irange_allocator *allocator);
193 
194   virtual bool set_bb_range (const_basic_block bb, const irange &r) OVERRIDE;
195   virtual bool get_bb_range (irange &r, const_basic_block bb) OVERRIDE;
196   virtual bool bb_range_p (const_basic_block bb) OVERRIDE;
197 protected:
198   irange **m_tab;	// Non growing vector.
199   int m_tab_size;
200   int_range<2> m_varying;
201   int_range<2> m_undefined;
202   tree m_type;
203   irange_allocator *m_irange_allocator;
204   void grow ();
205 };
206 
207 
208 // Initialize a block cache for an ssa_name of type T.
209 
sbr_vector(tree t,irange_allocator * allocator)210 sbr_vector::sbr_vector (tree t, irange_allocator *allocator)
211 {
212   gcc_checking_assert (TYPE_P (t));
213   m_type = t;
214   m_irange_allocator = allocator;
215   m_tab_size = last_basic_block_for_fn (cfun) + 1;
216   m_tab = (irange **)allocator->get_memory (m_tab_size * sizeof (irange *));
217   memset (m_tab, 0, m_tab_size * sizeof (irange *));
218 
219   // Create the cached type range.
220   m_varying.set_varying (t);
221   m_undefined.set_undefined ();
222 }
223 
224 // Grow the vector when the CFG has increased in size.
225 
226 void
grow()227 sbr_vector::grow ()
228 {
229   int curr_bb_size = last_basic_block_for_fn (cfun);
230   gcc_checking_assert (curr_bb_size > m_tab_size);
231 
232   // Increase the max of a)128, b)needed increase * 2, c)10% of current_size.
233   int inc = MAX ((curr_bb_size - m_tab_size) * 2, 128);
234   inc = MAX (inc, curr_bb_size / 10);
235   int new_size = inc + curr_bb_size;
236 
237   // Allocate new memory, copy the old vector and clear the new space.
238   irange **t = (irange **)m_irange_allocator->get_memory (new_size
239 							  * sizeof (irange *));
240   memcpy (t, m_tab, m_tab_size * sizeof (irange *));
241   memset (t + m_tab_size, 0, (new_size - m_tab_size) * sizeof (irange *));
242 
243   m_tab = t;
244   m_tab_size = new_size;
245 }
246 
247 // Set the range for block BB to be R.
248 
249 bool
set_bb_range(const_basic_block bb,const irange & r)250 sbr_vector::set_bb_range (const_basic_block bb, const irange &r)
251 {
252   irange *m;
253   if (bb->index >= m_tab_size)
254     grow ();
255   if (r.varying_p ())
256     m = &m_varying;
257   else if (r.undefined_p ())
258     m = &m_undefined;
259   else
260     m = m_irange_allocator->allocate (r);
261   m_tab[bb->index] = m;
262   return true;
263 }
264 
265 // Return the range associated with block BB in R.  Return false if
266 // there is no range.
267 
268 bool
get_bb_range(irange & r,const_basic_block bb)269 sbr_vector::get_bb_range (irange &r, const_basic_block bb)
270 {
271   if (bb->index >= m_tab_size)
272     return false;
273   irange *m = m_tab[bb->index];
274   if (m)
275     {
276       r = *m;
277       return true;
278     }
279   return false;
280 }
281 
282 // Return true if a range is present.
283 
284 bool
bb_range_p(const_basic_block bb)285 sbr_vector::bb_range_p (const_basic_block bb)
286 {
287   if (bb->index < m_tab_size)
288     return m_tab[bb->index] != NULL;
289   return false;
290 }
291 
292 // This class implements the on entry cache via a sparse bitmap.
293 // It uses the quad bit routines to access 4 bits at a time.
294 // A value of 0 (the default) means there is no entry, and a value of
295 // 1 thru SBR_NUM represents an element in the m_range vector.
296 // Varying is given the first value (1) and pre-cached.
297 // SBR_NUM + 1 represents the value of UNDEFINED, and is never stored.
298 // SBR_NUM is the number of values that can be cached.
299 // Indexes are 1..SBR_NUM and are stored locally at m_range[0..SBR_NUM-1]
300 
301 #define SBR_NUM		14
302 #define SBR_UNDEF	SBR_NUM + 1
303 #define SBR_VARYING	1
304 
305 class sbr_sparse_bitmap : public ssa_block_ranges
306 {
307 public:
308   sbr_sparse_bitmap (tree t, irange_allocator *allocator, bitmap_obstack *bm);
309   virtual bool set_bb_range (const_basic_block bb, const irange &r) OVERRIDE;
310   virtual bool get_bb_range (irange &r, const_basic_block bb) OVERRIDE;
311   virtual bool bb_range_p (const_basic_block bb) OVERRIDE;
312 private:
313   void bitmap_set_quad (bitmap head, int quad, int quad_value);
314   int bitmap_get_quad (const_bitmap head, int quad);
315   irange_allocator *m_irange_allocator;
316   irange *m_range[SBR_NUM];
317   bitmap_head bitvec;
318   tree m_type;
319 };
320 
321 // Initialize a block cache for an ssa_name of type T.
322 
sbr_sparse_bitmap(tree t,irange_allocator * allocator,bitmap_obstack * bm)323 sbr_sparse_bitmap::sbr_sparse_bitmap (tree t, irange_allocator *allocator,
324 				bitmap_obstack *bm)
325 {
326   gcc_checking_assert (TYPE_P (t));
327   m_type = t;
328   bitmap_initialize (&bitvec, bm);
329   bitmap_tree_view (&bitvec);
330   m_irange_allocator = allocator;
331   // Pre-cache varying.
332   m_range[0] = m_irange_allocator->allocate (2);
333   m_range[0]->set_varying (t);
334   // Pre-cache zero and non-zero values for pointers.
335   if (POINTER_TYPE_P (t))
336     {
337       m_range[1] = m_irange_allocator->allocate (2);
338       m_range[1]->set_nonzero (t);
339       m_range[2] = m_irange_allocator->allocate (2);
340       m_range[2]->set_zero (t);
341     }
342   else
343     m_range[1] = m_range[2] = NULL;
344   // Clear SBR_NUM entries.
345   for (int x = 3; x < SBR_NUM; x++)
346     m_range[x] = 0;
347 }
348 
349 // Set 4 bit values in a sparse bitmap. This allows a bitmap to
350 // function as a sparse array of 4 bit values.
351 // QUAD is the index, QUAD_VALUE is the 4 bit value to set.
352 
353 inline void
bitmap_set_quad(bitmap head,int quad,int quad_value)354 sbr_sparse_bitmap::bitmap_set_quad (bitmap head, int quad, int quad_value)
355 {
356   bitmap_set_aligned_chunk (head, quad, 4, (BITMAP_WORD) quad_value);
357 }
358 
359 // Get a 4 bit value from a sparse bitmap. This allows a bitmap to
360 // function as a sparse array of 4 bit values.
361 // QUAD is the index.
362 inline int
bitmap_get_quad(const_bitmap head,int quad)363 sbr_sparse_bitmap::bitmap_get_quad (const_bitmap head, int quad)
364 {
365   return (int) bitmap_get_aligned_chunk (head, quad, 4);
366 }
367 
368 // Set the range on entry to basic block BB to R.
369 
370 bool
set_bb_range(const_basic_block bb,const irange & r)371 sbr_sparse_bitmap::set_bb_range (const_basic_block bb, const irange &r)
372 {
373   if (r.undefined_p ())
374     {
375       bitmap_set_quad (&bitvec, bb->index, SBR_UNDEF);
376       return true;
377     }
378 
379   // Loop thru the values to see if R is already present.
380   for (int x = 0; x < SBR_NUM; x++)
381     if (!m_range[x] || r == *(m_range[x]))
382       {
383 	if (!m_range[x])
384 	  m_range[x] = m_irange_allocator->allocate (r);
385 	bitmap_set_quad (&bitvec, bb->index, x + 1);
386 	return true;
387       }
388   // All values are taken, default to VARYING.
389   bitmap_set_quad (&bitvec, bb->index, SBR_VARYING);
390   return false;
391 }
392 
393 // Return the range associated with block BB in R.  Return false if
394 // there is no range.
395 
396 bool
get_bb_range(irange & r,const_basic_block bb)397 sbr_sparse_bitmap::get_bb_range (irange &r, const_basic_block bb)
398 {
399   int value = bitmap_get_quad (&bitvec, bb->index);
400 
401   if (!value)
402     return false;
403 
404   gcc_checking_assert (value <= SBR_UNDEF);
405   if (value == SBR_UNDEF)
406     r.set_undefined ();
407   else
408     r = *(m_range[value - 1]);
409   return true;
410 }
411 
412 // Return true if a range is present.
413 
414 bool
bb_range_p(const_basic_block bb)415 sbr_sparse_bitmap::bb_range_p (const_basic_block bb)
416 {
417   return (bitmap_get_quad (&bitvec, bb->index) != 0);
418 }
419 
420 // -------------------------------------------------------------------------
421 
422 // Initialize the block cache.
423 
block_range_cache()424 block_range_cache::block_range_cache ()
425 {
426   bitmap_obstack_initialize (&m_bitmaps);
427   m_ssa_ranges.create (0);
428   m_ssa_ranges.safe_grow_cleared (num_ssa_names);
429   m_irange_allocator = new irange_allocator;
430 }
431 
432 // Remove any m_block_caches which have been created.
433 
~block_range_cache()434 block_range_cache::~block_range_cache ()
435 {
436   delete m_irange_allocator;
437   // Release the vector itself.
438   m_ssa_ranges.release ();
439   bitmap_obstack_release (&m_bitmaps);
440 }
441 
442 // Set the range for NAME on entry to block BB to R.
443 // If it has not been accessed yet, allocate it first.
444 
445 bool
set_bb_range(tree name,const_basic_block bb,const irange & r)446 block_range_cache::set_bb_range (tree name, const_basic_block bb,
447 				 const irange &r)
448 {
449   unsigned v = SSA_NAME_VERSION (name);
450   if (v >= m_ssa_ranges.length ())
451     m_ssa_ranges.safe_grow_cleared (num_ssa_names);
452 
453   if (!m_ssa_ranges[v])
454     {
455       // Use sparse representation if there are too many basic blocks.
456       if (last_basic_block_for_fn (cfun) > param_evrp_sparse_threshold)
457 	{
458 	  void *r = m_irange_allocator->get_memory (sizeof (sbr_sparse_bitmap));
459 	  m_ssa_ranges[v] = new (r) sbr_sparse_bitmap (TREE_TYPE (name),
460 						       m_irange_allocator,
461 						       &m_bitmaps);
462 	}
463       else
464 	{
465 	  // Otherwise use the default vector implemntation.
466 	  void *r = m_irange_allocator->get_memory (sizeof (sbr_vector));
467 	  m_ssa_ranges[v] = new (r) sbr_vector (TREE_TYPE (name),
468 						m_irange_allocator);
469 	}
470     }
471   return m_ssa_ranges[v]->set_bb_range (bb, r);
472 }
473 
474 
475 // Return a pointer to the ssa_block_cache for NAME.  If it has not been
476 // accessed yet, return NULL.
477 
478 inline ssa_block_ranges *
query_block_ranges(tree name)479 block_range_cache::query_block_ranges (tree name)
480 {
481   unsigned v = SSA_NAME_VERSION (name);
482   if (v >= m_ssa_ranges.length () || !m_ssa_ranges[v])
483     return NULL;
484   return m_ssa_ranges[v];
485 }
486 
487 
488 
489 // Return the range for NAME on entry to BB in R.  Return true if there
490 // is one.
491 
492 bool
get_bb_range(irange & r,tree name,const_basic_block bb)493 block_range_cache::get_bb_range (irange &r, tree name, const_basic_block bb)
494 {
495   ssa_block_ranges *ptr = query_block_ranges (name);
496   if (ptr)
497     return ptr->get_bb_range (r, bb);
498   return false;
499 }
500 
501 // Return true if NAME has a range set in block BB.
502 
503 bool
bb_range_p(tree name,const_basic_block bb)504 block_range_cache::bb_range_p (tree name, const_basic_block bb)
505 {
506   ssa_block_ranges *ptr = query_block_ranges (name);
507   if (ptr)
508     return ptr->bb_range_p (bb);
509   return false;
510 }
511 
512 // Print all known block caches to file F.
513 
514 void
dump(FILE * f)515 block_range_cache::dump (FILE *f)
516 {
517   unsigned x;
518   for (x = 1; x < m_ssa_ranges.length (); ++x)
519     {
520       if (m_ssa_ranges[x])
521 	{
522 	  fprintf (f, " Ranges for ");
523 	  print_generic_expr (f, ssa_name (x), TDF_NONE);
524 	  fprintf (f, ":\n");
525 	  m_ssa_ranges[x]->dump (f);
526 	  fprintf (f, "\n");
527 	}
528     }
529 }
530 
531 // Print all known ranges on entry to blobk BB to file F.
532 
533 void
dump(FILE * f,basic_block bb,bool print_varying)534 block_range_cache::dump (FILE *f, basic_block bb, bool print_varying)
535 {
536   unsigned x;
537   int_range_max r;
538   bool summarize_varying = false;
539   for (x = 1; x < m_ssa_ranges.length (); ++x)
540     {
541       if (!m_ssa_ranges[x])
542 	continue;
543 
544       if (!gimple_range_ssa_p (ssa_name (x)))
545 	continue;
546       if (m_ssa_ranges[x]->get_bb_range (r, bb))
547 	{
548 	  if (!print_varying && r.varying_p ())
549 	    {
550 	      summarize_varying = true;
551 	      continue;
552 	    }
553 	  print_generic_expr (f, ssa_name (x), TDF_NONE);
554 	  fprintf (f, "\t");
555 	  r.dump(f);
556 	  fprintf (f, "\n");
557 	}
558     }
559   // If there were any varying entries, lump them all together.
560   if (summarize_varying)
561     {
562       fprintf (f, "VARYING_P on entry : ");
563       for (x = 1; x < m_ssa_ranges.length (); ++x)
564 	{
565 	  if (!m_ssa_ranges[x])
566 	    continue;
567 
568 	  if (!gimple_range_ssa_p (ssa_name (x)))
569 	    continue;
570 	  if (m_ssa_ranges[x]->get_bb_range (r, bb))
571 	    {
572 	      if (r.varying_p ())
573 		{
574 		  print_generic_expr (f, ssa_name (x), TDF_NONE);
575 		  fprintf (f, "  ");
576 		}
577 	    }
578 	}
579       fprintf (f, "\n");
580     }
581 }
582 
583 // -------------------------------------------------------------------------
584 
585 // Initialize a global cache.
586 
ssa_global_cache()587 ssa_global_cache::ssa_global_cache ()
588 {
589   m_tab.create (0);
590   m_irange_allocator = new irange_allocator;
591 }
592 
593 // Deconstruct a global cache.
594 
~ssa_global_cache()595 ssa_global_cache::~ssa_global_cache ()
596 {
597   m_tab.release ();
598   delete m_irange_allocator;
599 }
600 
601 // Retrieve the global range of NAME from cache memory if it exists.
602 // Return the value in R.
603 
604 bool
get_global_range(irange & r,tree name) const605 ssa_global_cache::get_global_range (irange &r, tree name) const
606 {
607   unsigned v = SSA_NAME_VERSION (name);
608   if (v >= m_tab.length ())
609     return false;
610 
611   irange *stow = m_tab[v];
612   if (!stow)
613     return false;
614   r = *stow;
615   return true;
616 }
617 
618 // Set the range for NAME to R in the global cache.
619 // Return TRUE if there was already a range set, otherwise false.
620 
621 bool
set_global_range(tree name,const irange & r)622 ssa_global_cache::set_global_range (tree name, const irange &r)
623 {
624   unsigned v = SSA_NAME_VERSION (name);
625   if (v >= m_tab.length ())
626     m_tab.safe_grow_cleared (num_ssa_names + 1);
627 
628   irange *m = m_tab[v];
629   if (m && m->fits_p (r))
630     *m = r;
631   else
632     m_tab[v] = m_irange_allocator->allocate (r);
633   return m != NULL;
634 }
635 
636 // Set the range for NAME to R in the glonbal cache.
637 
638 void
clear_global_range(tree name)639 ssa_global_cache::clear_global_range (tree name)
640 {
641   unsigned v = SSA_NAME_VERSION (name);
642   if (v >= m_tab.length ())
643     m_tab.safe_grow_cleared (num_ssa_names + 1);
644   m_tab[v] = NULL;
645 }
646 
647 // Clear the global cache.
648 
649 void
clear()650 ssa_global_cache::clear ()
651 {
652   if (m_tab.address ())
653     memset (m_tab.address(), 0, m_tab.length () * sizeof (irange *));
654 }
655 
656 // Dump the contents of the global cache to F.
657 
658 void
dump(FILE * f)659 ssa_global_cache::dump (FILE *f)
660 {
661   /* Cleared after the table header has been printed.  */
662   bool print_header = true;
663   for (unsigned x = 1; x < num_ssa_names; x++)
664     {
665       int_range_max r;
666       if (gimple_range_ssa_p (ssa_name (x)) &&
667 	  get_global_range (r, ssa_name (x))  && !r.varying_p ())
668 	{
669 	  if (print_header)
670 	    {
671 	      /* Print the header only when there's something else
672 		 to print below.  */
673 	      fprintf (f, "Non-varying global ranges:\n");
674 	      fprintf (f, "=========================:\n");
675 	      print_header = false;
676 	    }
677 
678 	  print_generic_expr (f, ssa_name (x), TDF_NONE);
679 	  fprintf (f, "  : ");
680 	  r.dump (f);
681 	  fprintf (f, "\n");
682 	}
683     }
684 
685   if (!print_header)
686     fputc ('\n', f);
687 }
688 
689 // --------------------------------------------------------------------------
690 
691 
692 // This class will manage the timestamps for each ssa_name.
693 // When a value is calculated, the timestamp is set to the current time.
694 // Current time is then incremented.  Any dependencies will already have
695 // been calculated, and will thus have older timestamps.
696 // If one of those values is ever calculated again, it will get a newer
697 // timestamp, and the "current_p" check will fail.
698 
699 class temporal_cache
700 {
701 public:
702   temporal_cache ();
703   ~temporal_cache ();
704   bool current_p (tree name, tree dep1, tree dep2) const;
705   void set_timestamp (tree name);
706   void set_always_current (tree name);
707 private:
708   unsigned temporal_value (unsigned ssa) const;
709 
710   unsigned m_current_time;
711   vec <unsigned> m_timestamp;
712 };
713 
714 inline
temporal_cache()715 temporal_cache::temporal_cache ()
716 {
717   m_current_time = 1;
718   m_timestamp.create (0);
719   m_timestamp.safe_grow_cleared (num_ssa_names);
720 }
721 
722 inline
~temporal_cache()723 temporal_cache::~temporal_cache ()
724 {
725   m_timestamp.release ();
726 }
727 
728 // Return the timestamp value for SSA, or 0 if there isnt one.
729 
730 inline unsigned
temporal_value(unsigned ssa) const731 temporal_cache::temporal_value (unsigned ssa) const
732 {
733   if (ssa >= m_timestamp.length ())
734     return 0;
735   return m_timestamp[ssa];
736 }
737 
738 // Return TRUE if the timestampe for NAME is newer than any of its dependents.
739 // Up to 2 dependencies can be checked.
740 
741 bool
current_p(tree name,tree dep1,tree dep2) const742 temporal_cache::current_p (tree name, tree dep1, tree dep2) const
743 {
744   unsigned ts = temporal_value (SSA_NAME_VERSION (name));
745   if (ts == 0)
746     return true;
747 
748   // Any non-registered dependencies will have a value of 0 and thus be older.
749   // Return true if time is newer than either dependent.
750 
751   if (dep1 && ts < temporal_value (SSA_NAME_VERSION (dep1)))
752     return false;
753   if (dep2 && ts < temporal_value (SSA_NAME_VERSION (dep2)))
754     return false;
755 
756   return true;
757 }
758 
759 // This increments the global timer and sets the timestamp for NAME.
760 
761 inline void
set_timestamp(tree name)762 temporal_cache::set_timestamp (tree name)
763 {
764   unsigned v = SSA_NAME_VERSION (name);
765   if (v >= m_timestamp.length ())
766     m_timestamp.safe_grow_cleared (num_ssa_names + 20);
767   m_timestamp[v] = ++m_current_time;
768 }
769 
770 // Set the timestamp to 0, marking it as "always up to date".
771 
772 inline void
set_always_current(tree name)773 temporal_cache::set_always_current (tree name)
774 {
775   unsigned v = SSA_NAME_VERSION (name);
776   if (v >= m_timestamp.length ())
777     m_timestamp.safe_grow_cleared (num_ssa_names + 20);
778   m_timestamp[v] = 0;
779 }
780 
781 // --------------------------------------------------------------------------
782 
783 // This class provides an abstraction of a list of blocks to be updated
784 // by the cache.  It is currently a stack but could be changed.  It also
785 // maintains a list of blocks which have failed propagation, and does not
786 // enter any of those blocks into the list.
787 
788 // A vector over the BBs is maintained, and an entry of 0 means it is not in
789 // a list.  Otherwise, the entry is the next block in the list. -1 terminates
790 // the list.  m_head points to the top of the list, -1 if the list is empty.
791 
792 class update_list
793 {
794 public:
795   update_list ();
796   ~update_list ();
797   void add (basic_block bb);
798   basic_block pop ();
empty_p()799   inline bool empty_p () { return m_update_head == -1; }
clear_failures()800   inline void clear_failures () { bitmap_clear (m_propfail); }
propagation_failed(basic_block bb)801   inline void propagation_failed (basic_block bb)
802 				  { bitmap_set_bit (m_propfail, bb->index); }
803 private:
804   vec<int> m_update_list;
805   int m_update_head;
806   bitmap m_propfail;
807 };
808 
809 // Create an update list.
810 
update_list()811 update_list::update_list ()
812 {
813   m_update_list.create (0);
814   m_update_list.safe_grow_cleared (last_basic_block_for_fn (cfun) + 64);
815   m_update_head = -1;
816   m_propfail = BITMAP_ALLOC (NULL);
817 }
818 
819 // Destroy an update list.
820 
~update_list()821 update_list::~update_list ()
822 {
823   m_update_list.release ();
824   BITMAP_FREE (m_propfail);
825 }
826 
827 // Add BB to the list of blocks to update, unless it's already in the list.
828 
829 void
add(basic_block bb)830 update_list::add (basic_block bb)
831 {
832   int i = bb->index;
833   // If propagation has failed for BB, or its already in the list, don't
834   // add it again.
835   if ((unsigned)i >= m_update_list.length ())
836     m_update_list.safe_grow_cleared (i + 64);
837   if (!m_update_list[i] && !bitmap_bit_p (m_propfail, i))
838     {
839       if (empty_p ())
840 	{
841 	  m_update_head = i;
842 	  m_update_list[i] = -1;
843 	}
844       else
845 	{
846 	  gcc_checking_assert (m_update_head > 0);
847 	  m_update_list[i] = m_update_head;
848 	  m_update_head = i;
849 	}
850     }
851 }
852 
853 // Remove a block from the list.
854 
855 basic_block
pop()856 update_list::pop ()
857 {
858   gcc_checking_assert (!empty_p ());
859   basic_block bb = BASIC_BLOCK_FOR_FN (cfun, m_update_head);
860   int pop = m_update_head;
861   m_update_head = m_update_list[pop];
862   m_update_list[pop] = 0;
863   return bb;
864 }
865 
866 // --------------------------------------------------------------------------
867 
ranger_cache(int not_executable_flag)868 ranger_cache::ranger_cache (int not_executable_flag)
869 						: m_gori (not_executable_flag)
870 {
871   m_workback.create (0);
872   m_workback.safe_grow_cleared (last_basic_block_for_fn (cfun));
873   m_temporal = new temporal_cache;
874   // If DOM info is available, spawn an oracle as well.
875   if (dom_info_available_p (CDI_DOMINATORS))
876       m_oracle = new dom_oracle ();
877     else
878       m_oracle = NULL;
879 
880   unsigned x, lim = last_basic_block_for_fn (cfun);
881   // Calculate outgoing range info upfront.  This will fully populate the
882   // m_maybe_variant bitmap which will help eliminate processing of names
883   // which never have their ranges adjusted.
884   for (x = 0; x < lim ; x++)
885     {
886       basic_block bb = BASIC_BLOCK_FOR_FN (cfun, x);
887       if (bb)
888 	m_gori.exports (bb);
889     }
890   m_update = new update_list ();
891 }
892 
~ranger_cache()893 ranger_cache::~ranger_cache ()
894 {
895   delete m_update;
896   if (m_oracle)
897     delete m_oracle;
898   delete m_temporal;
899   m_workback.release ();
900 }
901 
902 // Dump the global caches to file F.  if GORI_DUMP is true, dump the
903 // gori map as well.
904 
905 void
dump(FILE * f)906 ranger_cache::dump (FILE *f)
907 {
908   m_globals.dump (f);
909   fprintf (f, "\n");
910 }
911 
912 // Dump the caches for basic block BB to file F.
913 
914 void
dump_bb(FILE * f,basic_block bb)915 ranger_cache::dump_bb (FILE *f, basic_block bb)
916 {
917   m_gori.gori_map::dump (f, bb, false);
918   m_on_entry.dump (f, bb);
919   if (m_oracle)
920     m_oracle->dump (f, bb);
921 }
922 
923 // Get the global range for NAME, and return in R.  Return false if the
924 // global range is not set, and return the legacy global value in R.
925 
926 bool
get_global_range(irange & r,tree name) const927 ranger_cache::get_global_range (irange &r, tree name) const
928 {
929   if (m_globals.get_global_range (r, name))
930     return true;
931   r = gimple_range_global (name);
932   return false;
933 }
934 
935 // Get the global range for NAME, and return in R.  Return false if the
936 // global range is not set, and R will contain the legacy global value.
937 // CURRENT_P is set to true if the value was in cache and not stale.
938 // Otherwise, set CURRENT_P to false and mark as it always current.
939 // If the global cache did not have a value, initialize it as well.
940 // After this call, the global cache will have a value.
941 
942 bool
get_global_range(irange & r,tree name,bool & current_p)943 ranger_cache::get_global_range (irange &r, tree name, bool &current_p)
944 {
945   bool had_global = get_global_range (r, name);
946 
947   // If there was a global value, set current flag, otherwise set a value.
948   current_p = false;
949   if (had_global)
950     current_p = r.singleton_p ()
951 		|| m_temporal->current_p (name, m_gori.depend1 (name),
952 					  m_gori.depend2 (name));
953   else
954     m_globals.set_global_range (name, r);
955 
956   // If the existing value was not current, mark it as always current.
957   if (!current_p)
958     m_temporal->set_always_current (name);
959   return current_p;
960 }
961 
962 //  Set the global range of NAME to R and give it a timestamp.
963 
964 void
set_global_range(tree name,const irange & r)965 ranger_cache::set_global_range (tree name, const irange &r)
966 {
967   if (m_globals.set_global_range (name, r))
968     {
969       // If there was already a range set, propagate the new value.
970       basic_block bb = gimple_bb (SSA_NAME_DEF_STMT (name));
971       if (!bb)
972 	bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
973 
974       if (DEBUG_RANGE_CACHE)
975 	fprintf (dump_file, "   GLOBAL :");
976 
977       propagate_updated_value (name, bb);
978     }
979   // Constants no longer need to tracked.  Any further refinement has to be
980   // undefined. Propagation works better with constants. PR 100512.
981   // Pointers which resolve to non-zero also do not need
982   // tracking in the cache as they will never change.  See PR 98866.
983   // Timestamp must always be updated, or dependent calculations may
984   // not include this latest value. PR 100774.
985 
986   if (r.singleton_p ()
987       || (POINTER_TYPE_P (TREE_TYPE (name)) && r.nonzero_p ()))
988     m_gori.set_range_invariant (name);
989   m_temporal->set_timestamp (name);
990 }
991 
992 //  Provide lookup for the gori-computes class to access the best known range
993 //  of an ssa_name in any given basic block.  Note, this does no additonal
994 //  lookups, just accesses the data that is already known.
995 
996 // Get the range of NAME when the def occurs in block BB.  If BB is NULL
997 // get the best global value available.
998 
999 void
range_of_def(irange & r,tree name,basic_block bb)1000 ranger_cache::range_of_def (irange &r, tree name, basic_block bb)
1001 {
1002   gcc_checking_assert (gimple_range_ssa_p (name));
1003   gcc_checking_assert (!bb || bb == gimple_bb (SSA_NAME_DEF_STMT (name)));
1004 
1005   // Pick up the best global range available.
1006   if (!m_globals.get_global_range (r, name))
1007     {
1008       // If that fails, try to calculate the range using just global values.
1009       gimple *s = SSA_NAME_DEF_STMT (name);
1010       if (gimple_get_lhs (s) == name)
1011 	fold_range (r, s, get_global_range_query ());
1012       else
1013 	r = gimple_range_global (name);
1014     }
1015 }
1016 
1017 // Get the range of NAME as it occurs on entry to block BB.
1018 
1019 void
entry_range(irange & r,tree name,basic_block bb)1020 ranger_cache::entry_range (irange &r, tree name, basic_block bb)
1021 {
1022   if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1023     {
1024       r = gimple_range_global (name);
1025       return;
1026     }
1027 
1028   // Look for the on-entry value of name in BB from the cache.
1029   // Otherwise pick up the best available global value.
1030   if (!m_on_entry.get_bb_range (r, name, bb))
1031     range_of_def (r, name);
1032 }
1033 
1034 // Get the range of NAME as it occurs on exit from block BB.
1035 
1036 void
exit_range(irange & r,tree name,basic_block bb)1037 ranger_cache::exit_range (irange &r, tree name, basic_block bb)
1038 {
1039   if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1040     {
1041       r = gimple_range_global (name);
1042       return;
1043     }
1044 
1045   gimple *s = SSA_NAME_DEF_STMT (name);
1046   basic_block def_bb = gimple_bb (s);
1047   if (def_bb == bb)
1048     range_of_def (r, name, bb);
1049   else
1050     entry_range (r, name, bb);
1051  }
1052 
1053 
1054 // Implement range_of_expr.
1055 
1056 bool
range_of_expr(irange & r,tree name,gimple * stmt)1057 ranger_cache::range_of_expr (irange &r, tree name, gimple *stmt)
1058 {
1059   if (!gimple_range_ssa_p (name))
1060     {
1061       get_tree_range (r, name, stmt);
1062       return true;
1063     }
1064 
1065   basic_block bb = gimple_bb (stmt);
1066   gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1067   basic_block def_bb = gimple_bb (def_stmt);
1068 
1069   if (bb == def_bb)
1070     range_of_def (r, name, bb);
1071   else
1072     entry_range (r, name, bb);
1073   return true;
1074 }
1075 
1076 
1077 // Implement range_on_edge.  Always return the best available range.
1078 
1079  bool
range_on_edge(irange & r,edge e,tree expr)1080  ranger_cache::range_on_edge (irange &r, edge e, tree expr)
1081  {
1082    if (gimple_range_ssa_p (expr))
1083     {
1084       exit_range (r, expr, e->src);
1085       // If this is not an abnormal edge, check for a non-null exit.
1086       if ((e->flags & (EDGE_EH | EDGE_ABNORMAL)) == 0)
1087 	m_non_null.adjust_range (r, expr, e->src, false);
1088       int_range_max edge_range;
1089       if (m_gori.outgoing_edge_range_p (edge_range, e, expr, *this))
1090 	r.intersect (edge_range);
1091       return true;
1092     }
1093 
1094   return get_tree_range (r, expr, NULL);
1095 }
1096 
1097 
1098 // Return a static range for NAME on entry to basic block BB in R.  If
1099 // calc is true, fill any cache entries required between BB and the
1100 // def block for NAME.  Otherwise, return false if the cache is empty.
1101 
1102 bool
block_range(irange & r,basic_block bb,tree name,bool calc)1103 ranger_cache::block_range (irange &r, basic_block bb, tree name, bool calc)
1104 {
1105   gcc_checking_assert (gimple_range_ssa_p (name));
1106 
1107   // If there are no range calculations anywhere in the IL, global range
1108   // applies everywhere, so don't bother caching it.
1109   if (!m_gori.has_edge_range_p (name))
1110     return false;
1111 
1112   if (calc)
1113     {
1114       gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1115       basic_block def_bb = NULL;
1116       if (def_stmt)
1117 	def_bb = gimple_bb (def_stmt);;
1118       if (!def_bb)
1119 	{
1120 	  // If we get to the entry block, this better be a default def
1121 	  // or range_on_entry was called for a block not dominated by
1122 	  // the def.
1123 	  gcc_checking_assert (SSA_NAME_IS_DEFAULT_DEF (name));
1124 	  def_bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
1125 	}
1126 
1127       // There is no range on entry for the definition block.
1128       if (def_bb == bb)
1129 	return false;
1130 
1131       // Otherwise, go figure out what is known in predecessor blocks.
1132       fill_block_cache (name, bb, def_bb);
1133       gcc_checking_assert (m_on_entry.bb_range_p (name, bb));
1134     }
1135   return m_on_entry.get_bb_range (r, name, bb);
1136 }
1137 
1138 // If there is anything in the propagation update_list, continue
1139 // processing NAME until the list of blocks is empty.
1140 
1141 void
propagate_cache(tree name)1142 ranger_cache::propagate_cache (tree name)
1143 {
1144   basic_block bb;
1145   edge_iterator ei;
1146   edge e;
1147   int_range_max new_range;
1148   int_range_max current_range;
1149   int_range_max e_range;
1150 
1151   // Process each block by seeing if its calculated range on entry is
1152   // the same as its cached value. If there is a difference, update
1153   // the cache to reflect the new value, and check to see if any
1154   // successors have cache entries which may need to be checked for
1155   // updates.
1156 
1157   while (!m_update->empty_p ())
1158     {
1159       bb = m_update->pop ();
1160       gcc_checking_assert (m_on_entry.bb_range_p (name, bb));
1161       m_on_entry.get_bb_range (current_range, name, bb);
1162 
1163       if (DEBUG_RANGE_CACHE)
1164 	{
1165 	  fprintf (dump_file, "FWD visiting block %d for ", bb->index);
1166 	  print_generic_expr (dump_file, name, TDF_SLIM);
1167 	  fprintf (dump_file, "  starting range : ");
1168 	  current_range.dump (dump_file);
1169 	  fprintf (dump_file, "\n");
1170 	}
1171 
1172       // Calculate the "new" range on entry by unioning the pred edges.
1173       new_range.set_undefined ();
1174       FOR_EACH_EDGE (e, ei, bb->preds)
1175 	{
1176 	  range_on_edge (e_range, e, name);
1177 	  if (DEBUG_RANGE_CACHE)
1178 	    {
1179 	      fprintf (dump_file, "   edge %d->%d :", e->src->index, bb->index);
1180 	      e_range.dump (dump_file);
1181 	      fprintf (dump_file, "\n");
1182 	    }
1183 	  new_range.union_ (e_range);
1184 	  if (new_range.varying_p ())
1185 	    break;
1186 	}
1187 
1188       // If the range on entry has changed, update it.
1189       if (new_range != current_range)
1190 	{
1191 	  bool ok_p = m_on_entry.set_bb_range (name, bb, new_range);
1192 	  // If the cache couldn't set the value, mark it as failed.
1193 	  if (!ok_p)
1194 	    m_update->propagation_failed (bb);
1195 	  if (DEBUG_RANGE_CACHE)
1196 	    {
1197 	      if (!ok_p)
1198 		{
1199 		  fprintf (dump_file, "   Cache failure to store value:");
1200 		  print_generic_expr (dump_file, name, TDF_SLIM);
1201 		  fprintf (dump_file, "  ");
1202 		}
1203 	      else
1204 		{
1205 		  fprintf (dump_file, "      Updating range to ");
1206 		  new_range.dump (dump_file);
1207 		}
1208 	      fprintf (dump_file, "\n      Updating blocks :");
1209 	    }
1210 	  // Mark each successor that has a range to re-check its range
1211 	  FOR_EACH_EDGE (e, ei, bb->succs)
1212 	    if (m_on_entry.bb_range_p (name, e->dest))
1213 	      {
1214 		if (DEBUG_RANGE_CACHE)
1215 		  fprintf (dump_file, " bb%d",e->dest->index);
1216 		m_update->add (e->dest);
1217 	      }
1218 	  if (DEBUG_RANGE_CACHE)
1219 	    fprintf (dump_file, "\n");
1220 	}
1221     }
1222   if (DEBUG_RANGE_CACHE)
1223     {
1224       fprintf (dump_file, "DONE visiting blocks for ");
1225       print_generic_expr (dump_file, name, TDF_SLIM);
1226       fprintf (dump_file, "\n");
1227     }
1228   m_update->clear_failures ();
1229 }
1230 
1231 // Check to see if an update to the value for NAME in BB has any effect
1232 // on values already in the on-entry cache for successor blocks.
1233 // If it does, update them.  Don't visit any blocks which dont have a cache
1234 // entry.
1235 
1236 void
propagate_updated_value(tree name,basic_block bb)1237 ranger_cache::propagate_updated_value (tree name, basic_block bb)
1238 {
1239   edge e;
1240   edge_iterator ei;
1241 
1242   // The update work list should be empty at this point.
1243   gcc_checking_assert (m_update->empty_p ());
1244   gcc_checking_assert (bb);
1245 
1246   if (DEBUG_RANGE_CACHE)
1247     {
1248       fprintf (dump_file, " UPDATE cache for ");
1249       print_generic_expr (dump_file, name, TDF_SLIM);
1250       fprintf (dump_file, " in BB %d : successors : ", bb->index);
1251     }
1252   FOR_EACH_EDGE (e, ei, bb->succs)
1253     {
1254       // Only update active cache entries.
1255       if (m_on_entry.bb_range_p (name, e->dest))
1256 	{
1257 	  m_update->add (e->dest);
1258 	  if (DEBUG_RANGE_CACHE)
1259 	    fprintf (dump_file, " UPDATE: bb%d", e->dest->index);
1260 	}
1261     }
1262     if (!m_update->empty_p ())
1263       {
1264 	if (DEBUG_RANGE_CACHE)
1265 	  fprintf (dump_file, "\n");
1266 	propagate_cache (name);
1267       }
1268     else
1269       {
1270 	if (DEBUG_RANGE_CACHE)
1271 	  fprintf (dump_file, "  : No updates!\n");
1272       }
1273 }
1274 
1275 // Make sure that the range-on-entry cache for NAME is set for block BB.
1276 // Work back through the CFG to DEF_BB ensuring the range is calculated
1277 // on the block/edges leading back to that point.
1278 
1279 void
fill_block_cache(tree name,basic_block bb,basic_block def_bb)1280 ranger_cache::fill_block_cache (tree name, basic_block bb, basic_block def_bb)
1281 {
1282   edge_iterator ei;
1283   edge e;
1284   int_range_max block_result;
1285   int_range_max undefined;
1286 
1287   // At this point we shouldn't be looking at the def, entry or exit block.
1288   gcc_checking_assert (bb != def_bb && bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) &&
1289 		       bb != EXIT_BLOCK_PTR_FOR_FN (cfun));
1290 
1291   // If the block cache is set, then we've already visited this block.
1292   if (m_on_entry.bb_range_p (name, bb))
1293     return;
1294 
1295   // Visit each block back to the DEF.  Initialize each one to UNDEFINED.
1296   // m_visited at the end will contain all the blocks that we needed to set
1297   // the range_on_entry cache for.
1298   m_workback.truncate (0);
1299   m_workback.quick_push (bb);
1300   undefined.set_undefined ();
1301   m_on_entry.set_bb_range (name, bb, undefined);
1302   gcc_checking_assert (m_update->empty_p ());
1303 
1304   if (DEBUG_RANGE_CACHE)
1305     {
1306       fprintf (dump_file, "\n");
1307       print_generic_expr (dump_file, name, TDF_SLIM);
1308       fprintf (dump_file, " : ");
1309     }
1310 
1311   // If there are dominators, check if a dominators can supply the range.
1312   if (dom_info_available_p (CDI_DOMINATORS)
1313       && range_from_dom (block_result, name, bb))
1314     {
1315       m_on_entry.set_bb_range (name, bb, block_result);
1316       if (DEBUG_RANGE_CACHE)
1317 	{
1318 	  fprintf (dump_file, "Filled from dominator! :  ");
1319 	  block_result.dump (dump_file);
1320 	  fprintf (dump_file, "\n");
1321 	}
1322       return;
1323     }
1324 
1325   while (m_workback.length () > 0)
1326     {
1327       basic_block node = m_workback.pop ();
1328       if (DEBUG_RANGE_CACHE)
1329 	{
1330 	  fprintf (dump_file, "BACK visiting block %d for ", node->index);
1331 	  print_generic_expr (dump_file, name, TDF_SLIM);
1332 	  fprintf (dump_file, "\n");
1333 	}
1334 
1335       FOR_EACH_EDGE (e, ei, node->preds)
1336 	{
1337 	  basic_block pred = e->src;
1338 	  int_range_max r;
1339 
1340 	  if (DEBUG_RANGE_CACHE)
1341 	    fprintf (dump_file, "  %d->%d ",e->src->index, e->dest->index);
1342 
1343 	  // If the pred block is the def block add this BB to update list.
1344 	  if (pred == def_bb)
1345 	    {
1346 	      m_update->add (node);
1347 	      continue;
1348 	    }
1349 
1350 	  // If the pred is entry but NOT def, then it is used before
1351 	  // defined, it'll get set to [] and no need to update it.
1352 	  if (pred == ENTRY_BLOCK_PTR_FOR_FN (cfun))
1353 	    {
1354 	      if (DEBUG_RANGE_CACHE)
1355 		fprintf (dump_file, "entry: bail.");
1356 	      continue;
1357 	    }
1358 
1359 	  // Regardless of whether we have visited pred or not, if the
1360 	  // pred has a non-null reference, revisit this block.
1361 	  // Don't search the DOM tree.
1362 	  if (m_non_null.non_null_deref_p (name, pred, false))
1363 	    {
1364 	      if (DEBUG_RANGE_CACHE)
1365 		fprintf (dump_file, "nonnull: update ");
1366 	      m_update->add (node);
1367 	    }
1368 
1369 	  // If the pred block already has a range, or if it can contribute
1370 	  // something new. Ie, the edge generates a range of some sort.
1371 	  if (m_on_entry.get_bb_range (r, name, pred))
1372 	    {
1373 	      if (DEBUG_RANGE_CACHE)
1374 		{
1375 		  fprintf (dump_file, "has cache, ");
1376 		  r.dump (dump_file);
1377 		  fprintf (dump_file, ", ");
1378 		}
1379 	      if (!r.undefined_p () || m_gori.has_edge_range_p (name, e))
1380 		{
1381 		  m_update->add (node);
1382 		  if (DEBUG_RANGE_CACHE)
1383 		    fprintf (dump_file, "update. ");
1384 		}
1385 	      continue;
1386 	    }
1387 
1388 	  if (DEBUG_RANGE_CACHE)
1389 	    fprintf (dump_file, "pushing undefined pred block.\n");
1390 	  // If the pred hasn't been visited (has no range), add it to
1391 	  // the list.
1392 	  gcc_checking_assert (!m_on_entry.bb_range_p (name, pred));
1393 	  m_on_entry.set_bb_range (name, pred, undefined);
1394 	  m_workback.quick_push (pred);
1395 	}
1396     }
1397 
1398   if (DEBUG_RANGE_CACHE)
1399     fprintf (dump_file, "\n");
1400 
1401   // Now fill in the marked blocks with values.
1402   propagate_cache (name);
1403   if (DEBUG_RANGE_CACHE)
1404     fprintf (dump_file, "  Propagation update done.\n");
1405 }
1406 
1407 
1408 // Get the range of NAME from dominators of BB and return it in R.
1409 
1410 bool
range_from_dom(irange & r,tree name,basic_block start_bb)1411 ranger_cache::range_from_dom (irange &r, tree name, basic_block start_bb)
1412 {
1413   if (!dom_info_available_p (CDI_DOMINATORS))
1414     return false;
1415 
1416   // Search back to the definition block or entry block.
1417   basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (name));
1418   if (def_bb == NULL)
1419     def_bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
1420 
1421   basic_block bb;
1422   basic_block prev_bb = start_bb;
1423   // Flag if we encounter a block with non-null set.
1424   bool non_null = false;
1425 
1426   // Range on entry to the DEF block should not be queried.
1427   gcc_checking_assert (start_bb != def_bb);
1428   m_workback.truncate (0);
1429 
1430   // Default value is global range.
1431   get_global_range (r, name);
1432 
1433   // Search until a value is found, pushing outgoing edges encountered.
1434   for (bb = get_immediate_dominator (CDI_DOMINATORS, start_bb);
1435        bb;
1436        prev_bb = bb, bb = get_immediate_dominator (CDI_DOMINATORS, bb))
1437     {
1438       if (!non_null)
1439 	non_null |= m_non_null.non_null_deref_p (name, bb, false);
1440 
1441       // This block has an outgoing range.
1442       if (m_gori.has_edge_range_p (name, bb))
1443 	{
1444 	  // Only outgoing ranges to single_pred blocks are dominated by
1445 	  // outgoing edge ranges, so only those need to be considered.
1446 	  edge e = find_edge (bb, prev_bb);
1447 	  if (e && single_pred_p (prev_bb))
1448 	    m_workback.quick_push (prev_bb);
1449 	}
1450 
1451       if (def_bb == bb)
1452 	break;
1453 
1454       if (m_on_entry.get_bb_range (r, name, bb))
1455 	break;
1456     }
1457 
1458   if (DEBUG_RANGE_CACHE)
1459     {
1460       fprintf (dump_file, "CACHE: BB %d DOM query, found ", start_bb->index);
1461       r.dump (dump_file);
1462       if (bb)
1463 	fprintf (dump_file, " at BB%d\n", bb->index);
1464       else
1465 	fprintf (dump_file, " at function top\n");
1466     }
1467 
1468   // Now process any outgoing edges that we seen along the way.
1469   while (m_workback.length () > 0)
1470     {
1471       int_range_max edge_range;
1472       prev_bb = m_workback.pop ();
1473       edge e = single_pred_edge (prev_bb);
1474       bb = e->src;
1475 
1476       if (m_gori.outgoing_edge_range_p (edge_range, e, name, *this))
1477 	{
1478 	  r.intersect (edge_range);
1479 	  if (r.varying_p () && ((e->flags & (EDGE_EH | EDGE_ABNORMAL)) == 0))
1480 	    {
1481 	      if (m_non_null.non_null_deref_p (name, bb, false))
1482 		{
1483 		  gcc_checking_assert (POINTER_TYPE_P (TREE_TYPE (name)));
1484 		  r.set_nonzero (TREE_TYPE (name));
1485 		}
1486 	    }
1487 	  if (DEBUG_RANGE_CACHE)
1488 	    {
1489 	      fprintf (dump_file, "CACHE: Adjusted edge range for %d->%d : ",
1490 		       bb->index, prev_bb->index);
1491 	      r.dump (dump_file);
1492 	      fprintf (dump_file, "\n");
1493 	    }
1494 	}
1495     }
1496 
1497   // Apply non-null if appropriate.
1498   if (non_null && r.varying_p ()
1499       && !has_abnormal_call_or_eh_pred_edge_p (start_bb))
1500     {
1501       gcc_checking_assert (POINTER_TYPE_P (TREE_TYPE (name)));
1502       r.set_nonzero (TREE_TYPE (name));
1503     }
1504   if (DEBUG_RANGE_CACHE)
1505     {
1506       fprintf (dump_file, "CACHE: Range for DOM returns : ");
1507       r.dump (dump_file);
1508       fprintf (dump_file, "\n");
1509     }
1510   return true;
1511 }
1512 
1513 // This routine will update NAME in block BB to the nonnull state.
1514 // It will then update the on-entry cache for this block to be non-null
1515 // if it isn't already.
1516 
1517 void
update_to_nonnull(basic_block bb,tree name)1518 ranger_cache::update_to_nonnull (basic_block bb, tree name)
1519 {
1520   tree type = TREE_TYPE (name);
1521   if (gimple_range_ssa_p (name) && POINTER_TYPE_P (type))
1522     {
1523       m_non_null.set_nonnull (bb, name);
1524       // Update the on-entry cache for BB to be non-zero.  Note this can set
1525       // the on entry value in the DEF block, which can override the def.
1526       int_range_max r;
1527       exit_range (r, name, bb);
1528       if (r.varying_p ())
1529 	{
1530 	  r.set_nonzero (type);
1531 	  m_on_entry.set_bb_range (name, bb, r);
1532 	}
1533     }
1534 }
1535 
1536 // Adapted from infer_nonnull_range_by_dereference and check_loadstore
1537 // to process nonnull ssa_name OP in S.  DATA contains the ranger_cache.
1538 
1539 static bool
non_null_loadstore(gimple * s,tree op,tree,void * data)1540 non_null_loadstore (gimple *s, tree op, tree, void *data)
1541 {
1542   if (TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
1543     {
1544       /* Some address spaces may legitimately dereference zero.  */
1545       addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (op));
1546       if (!targetm.addr_space.zero_address_valid (as))
1547 	{
1548 	  tree ssa = TREE_OPERAND (op, 0);
1549 	  basic_block bb = gimple_bb (s);
1550 	  ((ranger_cache *)data)->update_to_nonnull (bb, ssa);
1551 	}
1552     }
1553   return false;
1554 }
1555 
1556 // This routine is used during a block walk to move the state of non-null for
1557 // any operands on stmt S to nonnull.
1558 
1559 void
block_apply_nonnull(gimple * s)1560 ranger_cache::block_apply_nonnull (gimple *s)
1561 {
1562   if (!flag_delete_null_pointer_checks)
1563     return;
1564   if (is_a<gphi *> (s))
1565     return;
1566   if (gimple_code (s) == GIMPLE_ASM || gimple_clobber_p (s))
1567     return;
1568   if (is_a<gcall *> (s))
1569     {
1570       tree fntype = gimple_call_fntype (s);
1571       bitmap nonnullargs = get_nonnull_args (fntype);
1572       // Process any non-null arguments
1573       if (nonnullargs)
1574 	{
1575 	  basic_block bb = gimple_bb (s);
1576 	  for (unsigned i = 0; i < gimple_call_num_args (s); i++)
1577 	    {
1578 	      if (bitmap_empty_p (nonnullargs) || bitmap_bit_p (nonnullargs, i))
1579 		{
1580 		  tree op = gimple_call_arg (s, i);
1581 		  update_to_nonnull (bb, op);
1582 		}
1583 	    }
1584 	  BITMAP_FREE (nonnullargs);
1585 	}
1586       // Fallthru and walk load/store ops now.
1587     }
1588   walk_stmt_load_store_ops (s, (void *)this, non_null_loadstore,
1589 			    non_null_loadstore);
1590 }
1591