1 /* Read and write coverage files, and associated functionality.
2    Copyright (C) 1990-2013 Free Software Foundation, Inc.
3    Contributed by James E. Wilson, UC Berkeley/Cygnus Support;
4    based on some ideas from Dain Samples of UC Berkeley.
5    Further mangling by Bob Manson, Cygnus Support.
6    Further mangled by Nathan Sidwell, CodeSourcery
7 
8 This file is part of GCC.
9 
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14 
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19 
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23 
24 
25 #define GCOV_LINKAGE
26 
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "rtl.h"
32 #include "tree.h"
33 #include "flags.h"
34 #include "output.h"
35 #include "regs.h"
36 #include "expr.h"
37 #include "function.h"
38 #include "basic-block.h"
39 #include "toplev.h"
40 #include "tm_p.h"
41 #include "ggc.h"
42 #include "coverage.h"
43 #include "langhooks.h"
44 #include "hash-table.h"
45 #include "tree-iterator.h"
46 #include "cgraph.h"
47 #include "dumpfile.h"
48 #include "diagnostic-core.h"
49 #include "intl.h"
50 #include "filenames.h"
51 #include "target.h"
52 
53 #include "gcov-io.h"
54 #include "gcov-io.c"
55 
56 struct GTY((chain_next ("%h.next"))) coverage_data
57 {
58   struct coverage_data *next;	 /* next function */
59   unsigned ident;		 /* function ident */
60   unsigned lineno_checksum;	 /* function lineno checksum */
61   unsigned cfg_checksum;	 /* function cfg checksum */
62   tree fn_decl;			 /* the function decl */
63   tree ctr_vars[GCOV_COUNTERS];	 /* counter variables.  */
64 };
65 
66 /* Counts information for a function.  */
67 typedef struct counts_entry
68 {
69   /* We hash by  */
70   unsigned ident;
71   unsigned ctr;
72 
73   /* Store  */
74   unsigned lineno_checksum;
75   unsigned cfg_checksum;
76   gcov_type *counts;
77   struct gcov_ctr_summary summary;
78 
79   /* hash_table support.  */
80   typedef counts_entry value_type;
81   typedef counts_entry compare_type;
82   static inline hashval_t hash (const value_type *);
83   static int equal (const value_type *, const compare_type *);
84   static void remove (value_type *);
85 } counts_entry_t;
86 
87 static GTY(()) struct coverage_data *functions_head = 0;
88 static struct coverage_data **functions_tail = &functions_head;
89 static unsigned no_coverage = 0;
90 
91 /* Cumulative counter information for whole program.  */
92 static unsigned prg_ctr_mask; /* Mask of counter types generated.  */
93 
94 /* Counter information for current function.  */
95 static unsigned fn_ctr_mask; /* Mask of counters used.  */
96 static GTY(()) tree fn_v_ctrs[GCOV_COUNTERS];   /* counter variables.  */
97 static unsigned fn_n_ctrs[GCOV_COUNTERS]; /* Counters allocated.  */
98 static unsigned fn_b_ctrs[GCOV_COUNTERS]; /* Allocation base.  */
99 
100 /* Coverage info VAR_DECL and function info type nodes.  */
101 static GTY(()) tree gcov_info_var;
102 static GTY(()) tree gcov_fn_info_type;
103 static GTY(()) tree gcov_fn_info_ptr_type;
104 
105 /* Name of the notes (gcno) output file.  The "bbg" prefix is for
106    historical reasons, when the notes file contained only the
107    basic block graph notes.
108    If this is NULL we're not writing to the notes file.  */
109 static char *bbg_file_name;
110 
111 /* File stamp for notes file.  */
112 static unsigned bbg_file_stamp;
113 
114 /* Name of the count data (gcda) file.  */
115 static char *da_file_name;
116 
117 /* The names of merge functions for counters.  */
118 static const char *const ctr_merge_functions[GCOV_COUNTERS] = GCOV_MERGE_FUNCTIONS;
119 static const char *const ctr_names[GCOV_COUNTERS] = GCOV_COUNTER_NAMES;
120 
121 /* Forward declarations.  */
122 static void read_counts_file (void);
123 static tree build_var (tree, tree, int);
124 static void build_fn_info_type (tree, unsigned, tree);
125 static void build_info_type (tree, tree);
126 static tree build_fn_info (const struct coverage_data *, tree, tree);
127 static tree build_info (tree, tree);
128 static bool coverage_obj_init (void);
129 static vec<constructor_elt, va_gc> *coverage_obj_fn
130 (vec<constructor_elt, va_gc> *, tree, struct coverage_data const *);
131 static void coverage_obj_finish (vec<constructor_elt, va_gc> *);
132 
133 /* Return the type node for gcov_type.  */
134 
135 tree
get_gcov_type(void)136 get_gcov_type (void)
137 {
138   enum machine_mode mode = smallest_mode_for_size (GCOV_TYPE_SIZE, MODE_INT);
139   return lang_hooks.types.type_for_mode (mode, false);
140 }
141 
142 /* Return the type node for gcov_unsigned_t.  */
143 
144 static tree
get_gcov_unsigned_t(void)145 get_gcov_unsigned_t (void)
146 {
147   enum machine_mode mode = smallest_mode_for_size (32, MODE_INT);
148   return lang_hooks.types.type_for_mode (mode, true);
149 }
150 
151 inline hashval_t
hash(const value_type * entry)152 counts_entry::hash (const value_type *entry)
153 {
154   return entry->ident * GCOV_COUNTERS + entry->ctr;
155 }
156 
157 inline int
equal(const value_type * entry1,const compare_type * entry2)158 counts_entry::equal (const value_type *entry1,
159 		     const compare_type *entry2)
160 {
161   return entry1->ident == entry2->ident && entry1->ctr == entry2->ctr;
162 }
163 
164 inline void
remove(value_type * entry)165 counts_entry::remove (value_type *entry)
166 {
167   free (entry->counts);
168   free (entry);
169 }
170 
171 /* Hash table of count data.  */
172 static hash_table <counts_entry> counts_hash;
173 
174 /* Read in the counts file, if available.  */
175 
176 static void
read_counts_file(void)177 read_counts_file (void)
178 {
179   gcov_unsigned_t fn_ident = 0;
180   struct gcov_summary summary;
181   unsigned new_summary = 1;
182   gcov_unsigned_t tag;
183   int is_error = 0;
184   unsigned lineno_checksum = 0;
185   unsigned cfg_checksum = 0;
186 
187   if (!gcov_open (da_file_name, 1))
188     return;
189 
190   if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
191     {
192       warning (0, "%qs is not a gcov data file", da_file_name);
193       gcov_close ();
194       return;
195     }
196   else if ((tag = gcov_read_unsigned ()) != GCOV_VERSION)
197     {
198       char v[4], e[4];
199 
200       GCOV_UNSIGNED2STRING (v, tag);
201       GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
202 
203       warning (0, "%qs is version %q.*s, expected version %q.*s",
204  	       da_file_name, 4, v, 4, e);
205       gcov_close ();
206       return;
207     }
208 
209   /* Read the stamp, used for creating a generation count.  */
210   tag = gcov_read_unsigned ();
211   bbg_file_stamp = crc32_unsigned (bbg_file_stamp, tag);
212 
213   counts_hash.create (10);
214   while ((tag = gcov_read_unsigned ()))
215     {
216       gcov_unsigned_t length;
217       gcov_position_t offset;
218 
219       length = gcov_read_unsigned ();
220       offset = gcov_position ();
221       if (tag == GCOV_TAG_FUNCTION)
222 	{
223 	  if (length)
224 	    {
225 	      fn_ident = gcov_read_unsigned ();
226 	      lineno_checksum = gcov_read_unsigned ();
227 	      cfg_checksum = gcov_read_unsigned ();
228 	    }
229 	  else
230 	    fn_ident = lineno_checksum = cfg_checksum = 0;
231 	  new_summary = 1;
232 	}
233       else if (tag == GCOV_TAG_PROGRAM_SUMMARY)
234 	{
235 	  struct gcov_summary sum;
236 	  unsigned ix;
237 
238 	  if (new_summary)
239 	    memset (&summary, 0, sizeof (summary));
240 
241 	  gcov_read_summary (&sum);
242 	  for (ix = 0; ix != GCOV_COUNTERS_SUMMABLE; ix++)
243 	    {
244 	      summary.ctrs[ix].runs += sum.ctrs[ix].runs;
245 	      summary.ctrs[ix].sum_all += sum.ctrs[ix].sum_all;
246 	      if (summary.ctrs[ix].run_max < sum.ctrs[ix].run_max)
247 		summary.ctrs[ix].run_max = sum.ctrs[ix].run_max;
248 	      summary.ctrs[ix].sum_max += sum.ctrs[ix].sum_max;
249 	    }
250           if (new_summary)
251             memcpy (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
252                     sum.ctrs[GCOV_COUNTER_ARCS].histogram,
253                     sizeof (gcov_bucket_type) * GCOV_HISTOGRAM_SIZE);
254           else
255             gcov_histogram_merge (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
256                                   sum.ctrs[GCOV_COUNTER_ARCS].histogram);
257 	  new_summary = 0;
258 	}
259       else if (GCOV_TAG_IS_COUNTER (tag) && fn_ident)
260 	{
261 	  counts_entry_t **slot, *entry, elt;
262 	  unsigned n_counts = GCOV_TAG_COUNTER_NUM (length);
263 	  unsigned ix;
264 
265 	  elt.ident = fn_ident;
266 	  elt.ctr = GCOV_COUNTER_FOR_TAG (tag);
267 
268 	  slot = counts_hash.find_slot (&elt, INSERT);
269 	  entry = *slot;
270 	  if (!entry)
271 	    {
272 	      *slot = entry = XCNEW (counts_entry_t);
273 	      entry->ident = fn_ident;
274 	      entry->ctr = elt.ctr;
275 	      entry->lineno_checksum = lineno_checksum;
276 	      entry->cfg_checksum = cfg_checksum;
277               if (elt.ctr < GCOV_COUNTERS_SUMMABLE)
278                 entry->summary = summary.ctrs[elt.ctr];
279               entry->summary.num = n_counts;
280 	      entry->counts = XCNEWVEC (gcov_type, n_counts);
281 	    }
282 	  else if (entry->lineno_checksum != lineno_checksum
283 		   || entry->cfg_checksum != cfg_checksum)
284 	    {
285 	      error ("Profile data for function %u is corrupted", fn_ident);
286 	      error ("checksum is (%x,%x) instead of (%x,%x)",
287 		     entry->lineno_checksum, entry->cfg_checksum,
288 		     lineno_checksum, cfg_checksum);
289 	      counts_hash.dispose ();
290 	      break;
291 	    }
292 	  else if (entry->summary.num != n_counts)
293 	    {
294 	      error ("Profile data for function %u is corrupted", fn_ident);
295 	      error ("number of counters is %d instead of %d", entry->summary.num, n_counts);
296 	      counts_hash.dispose ();
297 	      break;
298 	    }
299 	  else if (elt.ctr >= GCOV_COUNTERS_SUMMABLE)
300 	    {
301 	      error ("cannot merge separate %s counters for function %u",
302 		     ctr_names[elt.ctr], fn_ident);
303 	      goto skip_merge;
304 	    }
305 	  else
306 	    {
307 	      entry->summary.runs += summary.ctrs[elt.ctr].runs;
308 	      entry->summary.sum_all += summary.ctrs[elt.ctr].sum_all;
309 	      if (entry->summary.run_max < summary.ctrs[elt.ctr].run_max)
310 		entry->summary.run_max = summary.ctrs[elt.ctr].run_max;
311 	      entry->summary.sum_max += summary.ctrs[elt.ctr].sum_max;
312 	    }
313 	  for (ix = 0; ix != n_counts; ix++)
314 	    entry->counts[ix] += gcov_read_counter ();
315 	skip_merge:;
316 	}
317       gcov_sync (offset, length);
318       if ((is_error = gcov_is_error ()))
319 	{
320 	  error (is_error < 0 ? "%qs has overflowed" : "%qs is corrupted",
321 		 da_file_name);
322 	  counts_hash.dispose ();
323 	  break;
324 	}
325     }
326 
327   gcov_close ();
328 }
329 
330 /* Returns the counters for a particular tag.  */
331 
332 gcov_type *
get_coverage_counts(unsigned counter,unsigned expected,unsigned cfg_checksum,unsigned lineno_checksum,const struct gcov_ctr_summary ** summary)333 get_coverage_counts (unsigned counter, unsigned expected,
334                      unsigned cfg_checksum, unsigned lineno_checksum,
335 		     const struct gcov_ctr_summary **summary)
336 {
337   counts_entry_t *entry, elt;
338 
339   /* No hash table, no counts.  */
340   if (!counts_hash.is_created ())
341     {
342       static int warned = 0;
343 
344       if (!warned++)
345 	inform (input_location, (flag_guess_branch_prob
346 		 ? "file %s not found, execution counts estimated"
347 		 : "file %s not found, execution counts assumed to be zero"),
348 		da_file_name);
349       return NULL;
350     }
351 
352   elt.ident = current_function_funcdef_no + 1;
353   elt.ctr = counter;
354   entry = counts_hash.find (&elt);
355   if (!entry || !entry->summary.num)
356     /* The function was not emitted, or is weak and not chosen in the
357        final executable.  Silently fail, because there's nothing we
358        can do about it.  */
359     return NULL;
360 
361   if (entry->cfg_checksum != cfg_checksum
362       || entry->summary.num != expected)
363     {
364       static int warned = 0;
365       bool warning_printed = false;
366       tree id = DECL_ASSEMBLER_NAME (current_function_decl);
367 
368       warning_printed =
369 	warning_at (input_location, OPT_Wcoverage_mismatch,
370 		    "the control flow of function %qE does not match "
371 		    "its profile data (counter %qs)", id, ctr_names[counter]);
372       if (warning_printed)
373 	{
374 	 inform (input_location, "use -Wno-error=coverage-mismatch to tolerate "
375 	 	 "the mismatch but performance may drop if the function is hot");
376 
377 	  if (!seen_error ()
378 	      && !warned++)
379 	    {
380 	      inform (input_location, "coverage mismatch ignored");
381 	      inform (input_location, flag_guess_branch_prob
382 		      ? G_("execution counts estimated")
383 		      : G_("execution counts assumed to be zero"));
384 	      if (!flag_guess_branch_prob)
385 		inform (input_location,
386 			"this can result in poorly optimized code");
387 	    }
388 	}
389 
390       return NULL;
391     }
392   else if (entry->lineno_checksum != lineno_checksum)
393     {
394       warning (0, "source locations for function %qE have changed,"
395 	       " the profile data may be out of date",
396 	       DECL_ASSEMBLER_NAME (current_function_decl));
397     }
398 
399   if (summary)
400     *summary = &entry->summary;
401 
402   return entry->counts;
403 }
404 
405 /* Allocate NUM counters of type COUNTER. Returns nonzero if the
406    allocation succeeded.  */
407 
408 int
coverage_counter_alloc(unsigned counter,unsigned num)409 coverage_counter_alloc (unsigned counter, unsigned num)
410 {
411   if (no_coverage)
412     return 0;
413 
414   if (!num)
415     return 1;
416 
417   if (!fn_v_ctrs[counter])
418     {
419       tree array_type = build_array_type (get_gcov_type (), NULL_TREE);
420 
421       fn_v_ctrs[counter]
422 	= build_var (current_function_decl, array_type, counter);
423     }
424 
425   fn_b_ctrs[counter] = fn_n_ctrs[counter];
426   fn_n_ctrs[counter] += num;
427 
428   fn_ctr_mask |= 1 << counter;
429   return 1;
430 }
431 
432 /* Generate a tree to access COUNTER NO.  */
433 
434 tree
tree_coverage_counter_ref(unsigned counter,unsigned no)435 tree_coverage_counter_ref (unsigned counter, unsigned no)
436 {
437   tree gcov_type_node = get_gcov_type ();
438 
439   gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
440 
441   no += fn_b_ctrs[counter];
442 
443   /* "no" here is an array index, scaled to bytes later.  */
444   return build4 (ARRAY_REF, gcov_type_node, fn_v_ctrs[counter],
445 		 build_int_cst (integer_type_node, no), NULL, NULL);
446 }
447 
448 /* Generate a tree to access the address of COUNTER NO.  */
449 
450 tree
tree_coverage_counter_addr(unsigned counter,unsigned no)451 tree_coverage_counter_addr (unsigned counter, unsigned no)
452 {
453   tree gcov_type_node = get_gcov_type ();
454 
455   gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
456   no += fn_b_ctrs[counter];
457 
458   /* "no" here is an array index, scaled to bytes later.  */
459   return build_fold_addr_expr (build4 (ARRAY_REF, gcov_type_node,
460 				       fn_v_ctrs[counter],
461 				       build_int_cst (integer_type_node, no),
462 				       NULL, NULL));
463 }
464 
465 
466 /* Generate a checksum for a string.  CHKSUM is the current
467    checksum.  */
468 
469 static unsigned
coverage_checksum_string(unsigned chksum,const char * string)470 coverage_checksum_string (unsigned chksum, const char *string)
471 {
472   int i;
473   char *dup = NULL;
474 
475   /* Look for everything that looks if it were produced by
476      get_file_function_name and zero out the second part
477      that may result from flag_random_seed.  This is not critical
478      as the checksums are used only for sanity checking.  */
479   for (i = 0; string[i]; i++)
480     {
481       int offset = 0;
482       if (!strncmp (string + i, "_GLOBAL__N_", 11))
483       offset = 11;
484       if (!strncmp (string + i, "_GLOBAL__", 9))
485       offset = 9;
486 
487       /* C++ namespaces do have scheme:
488          _GLOBAL__N_<filename>_<wrongmagicnumber>_<magicnumber>functionname
489        since filename might contain extra underscores there seems
490        to be no better chance then walk all possible offsets looking
491        for magicnumber.  */
492       if (offset)
493 	{
494 	  for (i = i + offset; string[i]; i++)
495 	    if (string[i]=='_')
496 	      {
497 		int y;
498 
499 		for (y = 1; y < 9; y++)
500 		  if (!(string[i + y] >= '0' && string[i + y] <= '9')
501 		      && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
502 		    break;
503 		if (y != 9 || string[i + 9] != '_')
504 		  continue;
505 		for (y = 10; y < 18; y++)
506 		  if (!(string[i + y] >= '0' && string[i + y] <= '9')
507 		      && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
508 		    break;
509 		if (y != 18)
510 		  continue;
511 		if (!dup)
512 		  string = dup = xstrdup (string);
513 		for (y = 10; y < 18; y++)
514 		  dup[i + y] = '0';
515 	      }
516 	  break;
517 	}
518     }
519 
520   chksum = crc32_string (chksum, string);
521   free (dup);
522 
523   return chksum;
524 }
525 
526 /* Compute checksum for the current function.  We generate a CRC32.  */
527 
528 unsigned
coverage_compute_lineno_checksum(void)529 coverage_compute_lineno_checksum (void)
530 {
531   expanded_location xloc
532     = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
533   unsigned chksum = xloc.line;
534 
535   chksum = coverage_checksum_string (chksum, xloc.file);
536   chksum = coverage_checksum_string
537     (chksum, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl)));
538 
539   return chksum;
540 }
541 
542 /* Compute cfg checksum for the current function.
543    The checksum is calculated carefully so that
544    source code changes that doesn't affect the control flow graph
545    won't change the checksum.
546    This is to make the profile data useable across source code change.
547    The downside of this is that the compiler may use potentially
548    wrong profile data - that the source code change has non-trivial impact
549    on the validity of profile data (e.g. the reversed condition)
550    but the compiler won't detect the change and use the wrong profile data.  */
551 
552 unsigned
coverage_compute_cfg_checksum(void)553 coverage_compute_cfg_checksum (void)
554 {
555   basic_block bb;
556   unsigned chksum = n_basic_blocks;
557 
558   FOR_EACH_BB (bb)
559     {
560       edge e;
561       edge_iterator ei;
562       chksum = crc32_byte (chksum, bb->index);
563       FOR_EACH_EDGE (e, ei, bb->succs)
564         {
565           chksum = crc32_byte (chksum, e->dest->index);
566         }
567     }
568 
569   return chksum;
570 }
571 
572 /* Begin output to the notes file for the current function.
573    Writes the function header. Returns nonzero if data should be output.  */
574 
575 int
coverage_begin_function(unsigned lineno_checksum,unsigned cfg_checksum)576 coverage_begin_function (unsigned lineno_checksum, unsigned cfg_checksum)
577 {
578   expanded_location xloc;
579   unsigned long offset;
580 
581   /* We don't need to output .gcno file unless we're under -ftest-coverage
582      (e.g. -fprofile-arcs/generate/use don't need .gcno to work). */
583   if (no_coverage || !bbg_file_name)
584     return 0;
585 
586   xloc = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
587 
588   /* Announce function */
589   offset = gcov_write_tag (GCOV_TAG_FUNCTION);
590   gcov_write_unsigned (current_function_funcdef_no + 1);
591   gcov_write_unsigned (lineno_checksum);
592   gcov_write_unsigned (cfg_checksum);
593   gcov_write_string (IDENTIFIER_POINTER
594 		     (DECL_ASSEMBLER_NAME (current_function_decl)));
595   gcov_write_string (xloc.file);
596   gcov_write_unsigned (xloc.line);
597   gcov_write_length (offset);
598 
599   return !gcov_is_error ();
600 }
601 
602 /* Finish coverage data for the current function. Verify no output
603    error has occurred.  Save function coverage counts.  */
604 
605 void
coverage_end_function(unsigned lineno_checksum,unsigned cfg_checksum)606 coverage_end_function (unsigned lineno_checksum, unsigned cfg_checksum)
607 {
608   unsigned i;
609 
610   if (bbg_file_name && gcov_is_error ())
611     {
612       warning (0, "error writing %qs", bbg_file_name);
613       unlink (bbg_file_name);
614       bbg_file_name = NULL;
615     }
616 
617   if (fn_ctr_mask)
618     {
619       struct coverage_data *item = 0;
620 
621       /* If the function is extern (i.e. extern inline), then we won't
622 	 be outputting it, so don't chain it onto the function
623 	 list.  */
624       if (!DECL_EXTERNAL (current_function_decl))
625 	{
626 	  item = ggc_alloc_coverage_data ();
627 
628 	  item->ident = current_function_funcdef_no + 1;
629 	  item->lineno_checksum = lineno_checksum;
630 	  item->cfg_checksum = cfg_checksum;
631 
632 	  item->fn_decl = current_function_decl;
633 	  item->next = 0;
634 	  *functions_tail = item;
635 	  functions_tail = &item->next;
636 	}
637 
638       for (i = 0; i != GCOV_COUNTERS; i++)
639 	{
640 	  tree var = fn_v_ctrs[i];
641 
642 	  if (item)
643 	    item->ctr_vars[i] = var;
644 	  if (var)
645 	    {
646 	      tree array_type = build_index_type (size_int (fn_n_ctrs[i] - 1));
647 	      array_type = build_array_type (get_gcov_type (), array_type);
648 	      TREE_TYPE (var) = array_type;
649 	      DECL_SIZE (var) = TYPE_SIZE (array_type);
650 	      DECL_SIZE_UNIT (var) = TYPE_SIZE_UNIT (array_type);
651 	      varpool_finalize_decl (var);
652 	    }
653 
654 	  fn_b_ctrs[i] = fn_n_ctrs[i] = 0;
655 	  fn_v_ctrs[i] = NULL_TREE;
656 	}
657       prg_ctr_mask |= fn_ctr_mask;
658       fn_ctr_mask = 0;
659     }
660 }
661 
662 /* Build a coverage variable of TYPE for function FN_DECL.  If COUNTER
663    >= 0 it is a counter array, otherwise it is the function structure.  */
664 
665 static tree
build_var(tree fn_decl,tree type,int counter)666 build_var (tree fn_decl, tree type, int counter)
667 {
668   tree var = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE, type);
669   const char *fn_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (fn_decl));
670   char *buf;
671   size_t fn_name_len, len;
672 
673   fn_name = targetm.strip_name_encoding (fn_name);
674   fn_name_len = strlen (fn_name);
675   buf = XALLOCAVEC (char, fn_name_len + 8 + sizeof (int) * 3);
676 
677   if (counter < 0)
678     strcpy (buf, "__gcov__");
679   else
680     sprintf (buf, "__gcov%u_", counter);
681   len = strlen (buf);
682 #ifndef NO_DOT_IN_LABEL
683   buf[len - 1] = '.';
684 #elif !defined NO_DOLLAR_IN_LABEL
685   buf[len - 1] = '$';
686 #endif
687   memcpy (buf + len, fn_name, fn_name_len + 1);
688   DECL_NAME (var) = get_identifier (buf);
689   TREE_STATIC (var) = 1;
690   TREE_ADDRESSABLE (var) = 1;
691   DECL_ALIGN (var) = TYPE_ALIGN (type);
692 
693   return var;
694 }
695 
696 /* Creates the gcov_fn_info RECORD_TYPE.  */
697 
698 static void
build_fn_info_type(tree type,unsigned counters,tree gcov_info_type)699 build_fn_info_type (tree type, unsigned counters, tree gcov_info_type)
700 {
701   tree ctr_info = lang_hooks.types.make_type (RECORD_TYPE);
702   tree field, fields;
703   tree array_type;
704 
705   gcc_assert (counters);
706 
707   /* ctr_info::num */
708   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
709 		      get_gcov_unsigned_t ());
710   fields = field;
711 
712   /* ctr_info::values */
713   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
714 		      build_pointer_type (get_gcov_type ()));
715   DECL_CHAIN (field) = fields;
716   fields = field;
717 
718   finish_builtin_struct (ctr_info, "__gcov_ctr_info", fields, NULL_TREE);
719 
720   /* key */
721   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
722 		      build_pointer_type (build_qualified_type
723 					  (gcov_info_type, TYPE_QUAL_CONST)));
724   fields = field;
725 
726   /* ident */
727   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
728 		      get_gcov_unsigned_t ());
729   DECL_CHAIN (field) = fields;
730   fields = field;
731 
732   /* lineno_checksum */
733   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
734 		      get_gcov_unsigned_t ());
735   DECL_CHAIN (field) = fields;
736   fields = field;
737 
738   /* cfg checksum */
739   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
740 		      get_gcov_unsigned_t ());
741   DECL_CHAIN (field) = fields;
742   fields = field;
743 
744   array_type = build_index_type (size_int (counters - 1));
745   array_type = build_array_type (ctr_info, array_type);
746 
747   /* counters */
748   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE, array_type);
749   DECL_CHAIN (field) = fields;
750   fields = field;
751 
752   finish_builtin_struct (type, "__gcov_fn_info", fields, NULL_TREE);
753 }
754 
755 /* Returns a CONSTRUCTOR for a gcov_fn_info.  DATA is
756    the coverage data for the function and TYPE is the gcov_fn_info
757    RECORD_TYPE.  KEY is the object file key.  */
758 
759 static tree
build_fn_info(const struct coverage_data * data,tree type,tree key)760 build_fn_info (const struct coverage_data *data, tree type, tree key)
761 {
762   tree fields = TYPE_FIELDS (type);
763   tree ctr_type;
764   unsigned ix;
765   vec<constructor_elt, va_gc> *v1 = NULL;
766   vec<constructor_elt, va_gc> *v2 = NULL;
767 
768   /* key */
769   CONSTRUCTOR_APPEND_ELT (v1, fields,
770 			  build1 (ADDR_EXPR, TREE_TYPE (fields), key));
771   fields = DECL_CHAIN (fields);
772 
773   /* ident */
774   CONSTRUCTOR_APPEND_ELT (v1, fields,
775 			  build_int_cstu (get_gcov_unsigned_t (),
776 					  data->ident));
777   fields = DECL_CHAIN (fields);
778 
779   /* lineno_checksum */
780   CONSTRUCTOR_APPEND_ELT (v1, fields,
781 			  build_int_cstu (get_gcov_unsigned_t (),
782 					  data->lineno_checksum));
783   fields = DECL_CHAIN (fields);
784 
785   /* cfg_checksum */
786   CONSTRUCTOR_APPEND_ELT (v1, fields,
787 			  build_int_cstu (get_gcov_unsigned_t (),
788 					  data->cfg_checksum));
789   fields = DECL_CHAIN (fields);
790 
791   /* counters */
792   ctr_type = TREE_TYPE (TREE_TYPE (fields));
793   for (ix = 0; ix != GCOV_COUNTERS; ix++)
794     if (prg_ctr_mask & (1 << ix))
795       {
796 	vec<constructor_elt, va_gc> *ctr = NULL;
797 	tree var = data->ctr_vars[ix];
798 	unsigned count = 0;
799 
800 	if (var)
801 	  count
802 	    = tree_low_cst (TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (var))), 0)
803 	    + 1;
804 
805 	CONSTRUCTOR_APPEND_ELT (ctr, TYPE_FIELDS (ctr_type),
806 				build_int_cstu (get_gcov_unsigned_t (),
807 						count));
808 
809 	if (var)
810 	  CONSTRUCTOR_APPEND_ELT (ctr, DECL_CHAIN (TYPE_FIELDS (ctr_type)),
811 				  build_fold_addr_expr (var));
812 
813 	CONSTRUCTOR_APPEND_ELT (v2, NULL, build_constructor (ctr_type, ctr));
814       }
815 
816   CONSTRUCTOR_APPEND_ELT (v1, fields,
817 			  build_constructor (TREE_TYPE (fields), v2));
818 
819   return build_constructor (type, v1);
820 }
821 
822 /* Create gcov_info struct.  TYPE is the incomplete RECORD_TYPE to be
823    completed, and FN_INFO_PTR_TYPE is a pointer to the function info type.  */
824 
825 static void
build_info_type(tree type,tree fn_info_ptr_type)826 build_info_type (tree type, tree fn_info_ptr_type)
827 {
828   tree field, fields = NULL_TREE;
829   tree merge_fn_type;
830 
831   /* Version ident */
832   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
833 		      get_gcov_unsigned_t ());
834   DECL_CHAIN (field) = fields;
835   fields = field;
836 
837   /* next pointer */
838   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
839 		      build_pointer_type (build_qualified_type
840 					  (type, TYPE_QUAL_CONST)));
841   DECL_CHAIN (field) = fields;
842   fields = field;
843 
844   /* stamp */
845   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
846 		      get_gcov_unsigned_t ());
847   DECL_CHAIN (field) = fields;
848   fields = field;
849 
850   /* Filename */
851   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
852 		      build_pointer_type (build_qualified_type
853 					  (char_type_node, TYPE_QUAL_CONST)));
854   DECL_CHAIN (field) = fields;
855   fields = field;
856 
857   /* merge fn array */
858   merge_fn_type
859     = build_function_type_list (void_type_node,
860 				build_pointer_type (get_gcov_type ()),
861 				get_gcov_unsigned_t (), NULL_TREE);
862   merge_fn_type
863     = build_array_type (build_pointer_type (merge_fn_type),
864 			build_index_type (size_int (GCOV_COUNTERS - 1)));
865   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
866 		      merge_fn_type);
867   DECL_CHAIN (field) = fields;
868   fields = field;
869 
870   /* n_functions */
871   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
872 		      get_gcov_unsigned_t ());
873   DECL_CHAIN (field) = fields;
874   fields = field;
875 
876   /* function_info pointer pointer */
877   fn_info_ptr_type = build_pointer_type
878     (build_qualified_type (fn_info_ptr_type, TYPE_QUAL_CONST));
879   field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
880 		      fn_info_ptr_type);
881   DECL_CHAIN (field) = fields;
882   fields = field;
883 
884   finish_builtin_struct (type, "__gcov_info", fields, NULL_TREE);
885 }
886 
887 /* Returns a CONSTRUCTOR for the gcov_info object.  INFO_TYPE is the
888    gcov_info structure type, FN_ARY is the array of pointers to
889    function info objects.  */
890 
891 static tree
build_info(tree info_type,tree fn_ary)892 build_info (tree info_type, tree fn_ary)
893 {
894   tree info_fields = TYPE_FIELDS (info_type);
895   tree merge_fn_type, n_funcs;
896   unsigned ix;
897   tree filename_string;
898   int da_file_name_len;
899   vec<constructor_elt, va_gc> *v1 = NULL;
900   vec<constructor_elt, va_gc> *v2 = NULL;
901 
902   /* Version ident */
903   CONSTRUCTOR_APPEND_ELT (v1, info_fields,
904 			  build_int_cstu (TREE_TYPE (info_fields),
905 					  GCOV_VERSION));
906   info_fields = DECL_CHAIN (info_fields);
907 
908   /* next -- NULL */
909   CONSTRUCTOR_APPEND_ELT (v1, info_fields, null_pointer_node);
910   info_fields = DECL_CHAIN (info_fields);
911 
912   /* stamp */
913   CONSTRUCTOR_APPEND_ELT (v1, info_fields,
914 			  build_int_cstu (TREE_TYPE (info_fields),
915 					  bbg_file_stamp));
916   info_fields = DECL_CHAIN (info_fields);
917 
918   /* Filename */
919   da_file_name_len = strlen (da_file_name);
920   filename_string = build_string (da_file_name_len + 1, da_file_name);
921   TREE_TYPE (filename_string) = build_array_type
922     (char_type_node, build_index_type (size_int (da_file_name_len)));
923   CONSTRUCTOR_APPEND_ELT (v1, info_fields,
924 			  build1 (ADDR_EXPR, TREE_TYPE (info_fields),
925 				  filename_string));
926   info_fields = DECL_CHAIN (info_fields);
927 
928   /* merge fn array -- NULL slots indicate unmeasured counters */
929   merge_fn_type = TREE_TYPE (TREE_TYPE (info_fields));
930   for (ix = 0; ix != GCOV_COUNTERS; ix++)
931     {
932       tree ptr = null_pointer_node;
933 
934       if ((1u << ix) & prg_ctr_mask)
935 	{
936 	  tree merge_fn = build_decl (BUILTINS_LOCATION,
937 				      FUNCTION_DECL,
938 				      get_identifier (ctr_merge_functions[ix]),
939 				      TREE_TYPE (merge_fn_type));
940 	  DECL_EXTERNAL (merge_fn) = 1;
941 	  TREE_PUBLIC (merge_fn) = 1;
942 	  DECL_ARTIFICIAL (merge_fn) = 1;
943 	  TREE_NOTHROW (merge_fn) = 1;
944 	  /* Initialize assembler name so we can stream out. */
945 	  DECL_ASSEMBLER_NAME (merge_fn);
946 	  ptr = build1 (ADDR_EXPR, merge_fn_type, merge_fn);
947 	}
948       CONSTRUCTOR_APPEND_ELT (v2, NULL, ptr);
949     }
950   CONSTRUCTOR_APPEND_ELT (v1, info_fields,
951 			  build_constructor (TREE_TYPE (info_fields), v2));
952   info_fields = DECL_CHAIN (info_fields);
953 
954   /* n_functions */
955   n_funcs = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (fn_ary)));
956   n_funcs = fold_build2 (PLUS_EXPR, TREE_TYPE (info_fields),
957 			 n_funcs, size_one_node);
958   CONSTRUCTOR_APPEND_ELT (v1, info_fields, n_funcs);
959   info_fields = DECL_CHAIN (info_fields);
960 
961   /* functions */
962   CONSTRUCTOR_APPEND_ELT (v1, info_fields,
963 			  build1 (ADDR_EXPR, TREE_TYPE (info_fields), fn_ary));
964   info_fields = DECL_CHAIN (info_fields);
965 
966   gcc_assert (!info_fields);
967   return build_constructor (info_type, v1);
968 }
969 
970 /* Create the gcov_info types and object.  Generate the constructor
971    function to call __gcov_init.  Does not generate the initializer
972    for the object.  Returns TRUE if coverage data is being emitted.  */
973 
974 static bool
coverage_obj_init(void)975 coverage_obj_init (void)
976 {
977   tree gcov_info_type, ctor, stmt, init_fn;
978   unsigned n_counters = 0;
979   unsigned ix;
980   struct coverage_data *fn;
981   struct coverage_data **fn_prev;
982   char name_buf[32];
983 
984   no_coverage = 1; /* Disable any further coverage.  */
985 
986   if (!prg_ctr_mask)
987     return false;
988 
989   if (cgraph_dump_file)
990     fprintf (cgraph_dump_file, "Using data file %s\n", da_file_name);
991 
992   /* Prune functions.  */
993   for (fn_prev = &functions_head; (fn = *fn_prev);)
994     if (DECL_STRUCT_FUNCTION (fn->fn_decl))
995       fn_prev = &fn->next;
996     else
997       /* The function is not being emitted, remove from list.  */
998       *fn_prev = fn->next;
999 
1000   if (functions_head == NULL)
1001     return false;
1002 
1003   for (ix = 0; ix != GCOV_COUNTERS; ix++)
1004     if ((1u << ix) & prg_ctr_mask)
1005       n_counters++;
1006 
1007   /* Build the info and fn_info types.  These are mutually recursive.  */
1008   gcov_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1009   gcov_fn_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1010   gcov_fn_info_ptr_type = build_pointer_type
1011     (build_qualified_type (gcov_fn_info_type, TYPE_QUAL_CONST));
1012   build_fn_info_type (gcov_fn_info_type, n_counters, gcov_info_type);
1013   build_info_type (gcov_info_type, gcov_fn_info_ptr_type);
1014 
1015   /* Build the gcov info var, this is referred to in its own
1016      initializer.  */
1017   gcov_info_var = build_decl (BUILTINS_LOCATION,
1018 			      VAR_DECL, NULL_TREE, gcov_info_type);
1019   TREE_STATIC (gcov_info_var) = 1;
1020   ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 0);
1021   DECL_NAME (gcov_info_var) = get_identifier (name_buf);
1022 
1023   /* Build a decl for __gcov_init.  */
1024   init_fn = build_pointer_type (gcov_info_type);
1025   init_fn = build_function_type_list (void_type_node, init_fn, NULL);
1026   init_fn = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
1027 			get_identifier ("__gcov_init"), init_fn);
1028   TREE_PUBLIC (init_fn) = 1;
1029   DECL_EXTERNAL (init_fn) = 1;
1030   DECL_ASSEMBLER_NAME (init_fn);
1031 
1032   /* Generate a call to __gcov_init(&gcov_info).  */
1033   ctor = NULL;
1034   stmt = build_fold_addr_expr (gcov_info_var);
1035   stmt = build_call_expr (init_fn, 1, stmt);
1036   append_to_statement_list (stmt, &ctor);
1037 
1038   /* Generate a constructor to run it.  */
1039   cgraph_build_static_cdtor ('I', ctor, DEFAULT_INIT_PRIORITY);
1040 
1041   return true;
1042 }
1043 
1044 /* Generate the coverage function info for FN and DATA.  Append a
1045    pointer to that object to CTOR and return the appended CTOR.  */
1046 
1047 static vec<constructor_elt, va_gc> *
coverage_obj_fn(vec<constructor_elt,va_gc> * ctor,tree fn,struct coverage_data const * data)1048 coverage_obj_fn (vec<constructor_elt, va_gc> *ctor, tree fn,
1049 		 struct coverage_data const *data)
1050 {
1051   tree init = build_fn_info (data, gcov_fn_info_type, gcov_info_var);
1052   tree var = build_var (fn, gcov_fn_info_type, -1);
1053 
1054   DECL_INITIAL (var) = init;
1055   varpool_finalize_decl (var);
1056 
1057   CONSTRUCTOR_APPEND_ELT (ctor, NULL,
1058 			  build1 (ADDR_EXPR, gcov_fn_info_ptr_type, var));
1059   return ctor;
1060 }
1061 
1062 /* Finalize the coverage data.  Generates the array of pointers to
1063    function objects from CTOR.  Generate the gcov_info initializer.  */
1064 
1065 static void
coverage_obj_finish(vec<constructor_elt,va_gc> * ctor)1066 coverage_obj_finish (vec<constructor_elt, va_gc> *ctor)
1067 {
1068   unsigned n_functions = vec_safe_length (ctor);
1069   tree fn_info_ary_type = build_array_type
1070     (build_qualified_type (gcov_fn_info_ptr_type, TYPE_QUAL_CONST),
1071      build_index_type (size_int (n_functions - 1)));
1072   tree fn_info_ary = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE,
1073 				 fn_info_ary_type);
1074   char name_buf[32];
1075 
1076   TREE_STATIC (fn_info_ary) = 1;
1077   ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 1);
1078   DECL_NAME (fn_info_ary) = get_identifier (name_buf);
1079   DECL_INITIAL (fn_info_ary) = build_constructor (fn_info_ary_type, ctor);
1080   varpool_finalize_decl (fn_info_ary);
1081 
1082   DECL_INITIAL (gcov_info_var)
1083     = build_info (TREE_TYPE (gcov_info_var), fn_info_ary);
1084   varpool_finalize_decl (gcov_info_var);
1085 }
1086 
1087 /* Perform file-level initialization. Read in data file, generate name
1088    of notes file.  */
1089 
1090 void
coverage_init(const char * filename)1091 coverage_init (const char *filename)
1092 {
1093   int len = strlen (filename);
1094   int prefix_len = 0;
1095 
1096   if (!profile_data_prefix && !IS_ABSOLUTE_PATH (filename))
1097     profile_data_prefix = getpwd ();
1098 
1099   if (profile_data_prefix)
1100     prefix_len = strlen (profile_data_prefix);
1101 
1102   /* Name of da file.  */
1103   da_file_name = XNEWVEC (char, len + strlen (GCOV_DATA_SUFFIX)
1104 			  + prefix_len + 2);
1105 
1106   if (profile_data_prefix)
1107     {
1108       memcpy (da_file_name, profile_data_prefix, prefix_len);
1109       da_file_name[prefix_len++] = '/';
1110     }
1111   memcpy (da_file_name + prefix_len, filename, len);
1112   strcpy (da_file_name + prefix_len + len, GCOV_DATA_SUFFIX);
1113 
1114   bbg_file_stamp = local_tick;
1115 
1116   if (flag_branch_probabilities)
1117     read_counts_file ();
1118 
1119   /* Name of bbg file.  */
1120   if (flag_test_coverage && !flag_compare_debug)
1121     {
1122       bbg_file_name = XNEWVEC (char, len + strlen (GCOV_NOTE_SUFFIX) + 1);
1123       memcpy (bbg_file_name, filename, len);
1124       strcpy (bbg_file_name + len, GCOV_NOTE_SUFFIX);
1125 
1126       if (!gcov_open (bbg_file_name, -1))
1127 	{
1128 	  error ("cannot open %s", bbg_file_name);
1129 	  bbg_file_name = NULL;
1130 	}
1131       else
1132 	{
1133 	  gcov_write_unsigned (GCOV_NOTE_MAGIC);
1134 	  gcov_write_unsigned (GCOV_VERSION);
1135 	  gcov_write_unsigned (bbg_file_stamp);
1136 	}
1137     }
1138 }
1139 
1140 /* Performs file-level cleanup.  Close notes file, generate coverage
1141    variables and constructor.  */
1142 
1143 void
coverage_finish(void)1144 coverage_finish (void)
1145 {
1146   if (bbg_file_name && gcov_close ())
1147     unlink (bbg_file_name);
1148 
1149   if (!flag_branch_probabilities && flag_test_coverage
1150       && (!local_tick || local_tick == (unsigned)-1))
1151     /* Only remove the da file, if we're emitting coverage code and
1152        cannot uniquely stamp it.  If we can stamp it, libgcov will DTRT.  */
1153     unlink (da_file_name);
1154 
1155   if (coverage_obj_init ())
1156     {
1157       vec<constructor_elt, va_gc> *fn_ctor = NULL;
1158       struct coverage_data *fn;
1159 
1160       for (fn = functions_head; fn; fn = fn->next)
1161 	fn_ctor = coverage_obj_fn (fn_ctor, fn->fn_decl, fn);
1162       coverage_obj_finish (fn_ctor);
1163     }
1164 }
1165 
1166 #include "gt-coverage.h"
1167