PR tree-optimization/80426
[official-gcc.git] / gcc / coverage.c
blob0a949c3a9f7780a185864c48ef1d70c525e19c20
1 /* Read and write coverage files, and associated functionality.
2 Copyright (C) 1990-2017 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
8 This file is part of GCC.
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.
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.
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/>. */
25 #define GCOV_LINKAGE
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "backend.h"
31 #include "target.h"
32 #include "rtl.h"
33 #include "tree.h"
34 #include "tree-pass.h"
35 #include "memmodel.h"
36 #include "tm_p.h"
37 #include "stringpool.h"
38 #include "cgraph.h"
39 #include "coverage.h"
40 #include "diagnostic-core.h"
41 #include "fold-const.h"
42 #include "stor-layout.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "langhooks.h"
46 #include "tree-iterator.h"
47 #include "context.h"
48 #include "pass_manager.h"
49 #include "intl.h"
50 #include "params.h"
51 #include "auto-profile.h"
53 #include "gcov-io.c"
55 struct GTY((chain_next ("%h.next"))) coverage_data
57 struct coverage_data *next; /* next function */
58 unsigned ident; /* function ident */
59 unsigned lineno_checksum; /* function lineno checksum */
60 unsigned cfg_checksum; /* function cfg checksum */
61 tree fn_decl; /* the function decl */
62 tree ctr_vars[GCOV_COUNTERS]; /* counter variables. */
65 /* Counts information for a function. */
66 struct counts_entry : pointer_hash <counts_entry>
68 /* We hash by */
69 unsigned ident;
70 unsigned ctr;
72 /* Store */
73 unsigned lineno_checksum;
74 unsigned cfg_checksum;
75 gcov_type *counts;
76 struct gcov_ctr_summary summary;
78 /* hash_table support. */
79 static inline hashval_t hash (const counts_entry *);
80 static int equal (const counts_entry *, const counts_entry *);
81 static void remove (counts_entry *);
84 static GTY(()) struct coverage_data *functions_head = 0;
85 static struct coverage_data **functions_tail = &functions_head;
86 static unsigned no_coverage = 0;
88 /* Cumulative counter information for whole program. */
89 static unsigned prg_ctr_mask; /* Mask of counter types generated. */
91 /* Counter information for current function. */
92 static unsigned fn_ctr_mask; /* Mask of counters used. */
93 static GTY(()) tree fn_v_ctrs[GCOV_COUNTERS]; /* counter variables. */
94 static unsigned fn_n_ctrs[GCOV_COUNTERS]; /* Counters allocated. */
95 static unsigned fn_b_ctrs[GCOV_COUNTERS]; /* Allocation base. */
97 /* Coverage info VAR_DECL and function info type nodes. */
98 static GTY(()) tree gcov_info_var;
99 static GTY(()) tree gcov_fn_info_type;
100 static GTY(()) tree gcov_fn_info_ptr_type;
102 /* Name of the notes (gcno) output file. The "bbg" prefix is for
103 historical reasons, when the notes file contained only the
104 basic block graph notes.
105 If this is NULL we're not writing to the notes file. */
106 static char *bbg_file_name;
108 /* File stamp for notes file. */
109 static unsigned bbg_file_stamp;
111 /* Name of the count data (gcda) file. */
112 static char *da_file_name;
114 /* The names of merge functions for counters. */
115 #define STR(str) #str
116 #define DEF_GCOV_COUNTER(COUNTER, NAME, FN_TYPE) STR(__gcov_merge ## FN_TYPE),
117 static const char *const ctr_merge_functions[GCOV_COUNTERS] = {
118 #include "gcov-counter.def"
120 #undef DEF_GCOV_COUNTER
121 #undef STR
123 #define DEF_GCOV_COUNTER(COUNTER, NAME, FN_TYPE) NAME,
124 static const char *const ctr_names[GCOV_COUNTERS] = {
125 #include "gcov-counter.def"
127 #undef DEF_GCOV_COUNTER
129 /* Forward declarations. */
130 static void read_counts_file (void);
131 static tree build_var (tree, tree, int);
132 static void build_fn_info_type (tree, unsigned, tree);
133 static void build_info_type (tree, tree);
134 static tree build_fn_info (const struct coverage_data *, tree, tree);
135 static tree build_info (tree, tree);
136 static bool coverage_obj_init (void);
137 static vec<constructor_elt, va_gc> *coverage_obj_fn
138 (vec<constructor_elt, va_gc> *, tree, struct coverage_data const *);
139 static void coverage_obj_finish (vec<constructor_elt, va_gc> *);
141 /* Return the type node for gcov_type. */
143 tree
144 get_gcov_type (void)
146 machine_mode mode
147 = smallest_mode_for_size (LONG_LONG_TYPE_SIZE > 32 ? 64 : 32, MODE_INT);
148 return lang_hooks.types.type_for_mode (mode, false);
151 /* Return the type node for gcov_unsigned_t. */
153 static tree
154 get_gcov_unsigned_t (void)
156 machine_mode mode = smallest_mode_for_size (32, MODE_INT);
157 return lang_hooks.types.type_for_mode (mode, true);
160 inline hashval_t
161 counts_entry::hash (const counts_entry *entry)
163 return entry->ident * GCOV_COUNTERS + entry->ctr;
166 inline int
167 counts_entry::equal (const counts_entry *entry1, const counts_entry *entry2)
169 return entry1->ident == entry2->ident && entry1->ctr == entry2->ctr;
172 inline void
173 counts_entry::remove (counts_entry *entry)
175 free (entry->counts);
176 free (entry);
179 /* Hash table of count data. */
180 static hash_table<counts_entry> *counts_hash;
182 /* Read in the counts file, if available. */
184 static void
185 read_counts_file (void)
187 gcov_unsigned_t fn_ident = 0;
188 struct gcov_summary summary;
189 unsigned new_summary = 1;
190 gcov_unsigned_t tag;
191 int is_error = 0;
192 unsigned lineno_checksum = 0;
193 unsigned cfg_checksum = 0;
195 if (!gcov_open (da_file_name, 1))
196 return;
198 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
200 warning (0, "%qs is not a gcov data file", da_file_name);
201 gcov_close ();
202 return;
204 else if ((tag = gcov_read_unsigned ()) != GCOV_VERSION)
206 char v[4], e[4];
208 GCOV_UNSIGNED2STRING (v, tag);
209 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
211 warning (0, "%qs is version %q.*s, expected version %q.*s",
212 da_file_name, 4, v, 4, e);
213 gcov_close ();
214 return;
217 /* Read the stamp, used for creating a generation count. */
218 tag = gcov_read_unsigned ();
219 bbg_file_stamp = crc32_unsigned (bbg_file_stamp, tag);
221 counts_hash = new hash_table<counts_entry> (10);
222 while ((tag = gcov_read_unsigned ()))
224 gcov_unsigned_t length;
225 gcov_position_t offset;
227 length = gcov_read_unsigned ();
228 offset = gcov_position ();
229 if (tag == GCOV_TAG_FUNCTION)
231 if (length)
233 fn_ident = gcov_read_unsigned ();
234 lineno_checksum = gcov_read_unsigned ();
235 cfg_checksum = gcov_read_unsigned ();
237 else
238 fn_ident = lineno_checksum = cfg_checksum = 0;
239 new_summary = 1;
241 else if (tag == GCOV_TAG_PROGRAM_SUMMARY)
243 struct gcov_summary sum;
244 unsigned ix;
246 if (new_summary)
247 memset (&summary, 0, sizeof (summary));
249 gcov_read_summary (&sum);
250 for (ix = 0; ix != GCOV_COUNTERS_SUMMABLE; ix++)
252 summary.ctrs[ix].runs += sum.ctrs[ix].runs;
253 summary.ctrs[ix].sum_all += sum.ctrs[ix].sum_all;
254 if (summary.ctrs[ix].run_max < sum.ctrs[ix].run_max)
255 summary.ctrs[ix].run_max = sum.ctrs[ix].run_max;
256 summary.ctrs[ix].sum_max += sum.ctrs[ix].sum_max;
258 if (new_summary)
259 memcpy (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
260 sum.ctrs[GCOV_COUNTER_ARCS].histogram,
261 sizeof (gcov_bucket_type) * GCOV_HISTOGRAM_SIZE);
262 else
263 gcov_histogram_merge (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
264 sum.ctrs[GCOV_COUNTER_ARCS].histogram);
265 new_summary = 0;
267 else if (GCOV_TAG_IS_COUNTER (tag) && fn_ident)
269 counts_entry **slot, *entry, elt;
270 unsigned n_counts = GCOV_TAG_COUNTER_NUM (length);
271 unsigned ix;
273 elt.ident = fn_ident;
274 elt.ctr = GCOV_COUNTER_FOR_TAG (tag);
276 slot = counts_hash->find_slot (&elt, INSERT);
277 entry = *slot;
278 if (!entry)
280 *slot = entry = XCNEW (counts_entry);
281 entry->ident = fn_ident;
282 entry->ctr = elt.ctr;
283 entry->lineno_checksum = lineno_checksum;
284 entry->cfg_checksum = cfg_checksum;
285 if (elt.ctr < GCOV_COUNTERS_SUMMABLE)
286 entry->summary = summary.ctrs[elt.ctr];
287 entry->summary.num = n_counts;
288 entry->counts = XCNEWVEC (gcov_type, n_counts);
290 else if (entry->lineno_checksum != lineno_checksum
291 || entry->cfg_checksum != cfg_checksum)
293 error ("Profile data for function %u is corrupted", fn_ident);
294 error ("checksum is (%x,%x) instead of (%x,%x)",
295 entry->lineno_checksum, entry->cfg_checksum,
296 lineno_checksum, cfg_checksum);
297 delete counts_hash;
298 counts_hash = NULL;
299 break;
301 else if (entry->summary.num != n_counts)
303 error ("Profile data for function %u is corrupted", fn_ident);
304 error ("number of counters is %d instead of %d", entry->summary.num, n_counts);
305 delete counts_hash;
306 counts_hash = NULL;
307 break;
309 else if (elt.ctr >= GCOV_COUNTERS_SUMMABLE)
311 error ("cannot merge separate %s counters for function %u",
312 ctr_names[elt.ctr], fn_ident);
313 goto skip_merge;
315 else
317 entry->summary.runs += summary.ctrs[elt.ctr].runs;
318 entry->summary.sum_all += summary.ctrs[elt.ctr].sum_all;
319 if (entry->summary.run_max < summary.ctrs[elt.ctr].run_max)
320 entry->summary.run_max = summary.ctrs[elt.ctr].run_max;
321 entry->summary.sum_max += summary.ctrs[elt.ctr].sum_max;
323 for (ix = 0; ix != n_counts; ix++)
324 entry->counts[ix] += gcov_read_counter ();
325 skip_merge:;
327 gcov_sync (offset, length);
328 if ((is_error = gcov_is_error ()))
330 error (is_error < 0
331 ? G_("%qs has overflowed")
332 : G_("%qs is corrupted"),
333 da_file_name);
334 delete counts_hash;
335 counts_hash = NULL;
336 break;
340 gcov_close ();
343 /* Returns the counters for a particular tag. */
345 gcov_type *
346 get_coverage_counts (unsigned counter, unsigned expected,
347 unsigned cfg_checksum, unsigned lineno_checksum,
348 const struct gcov_ctr_summary **summary)
350 counts_entry *entry, elt;
352 /* No hash table, no counts. */
353 if (!counts_hash)
355 static int warned = 0;
357 if (!warned++ && dump_enabled_p ())
358 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
359 (flag_guess_branch_prob
360 ? "file %s not found, execution counts estimated\n"
361 : "file %s not found, execution counts assumed to "
362 "be zero\n"),
363 da_file_name);
364 return NULL;
366 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
367 elt.ident = current_function_funcdef_no + 1;
368 else
370 gcc_assert (coverage_node_map_initialized_p ());
371 elt.ident = cgraph_node::get (cfun->decl)->profile_id;
373 elt.ctr = counter;
374 entry = counts_hash->find (&elt);
375 if (!entry || !entry->summary.num)
376 /* The function was not emitted, or is weak and not chosen in the
377 final executable. Silently fail, because there's nothing we
378 can do about it. */
379 return NULL;
381 if (entry->cfg_checksum != cfg_checksum
382 || entry->summary.num != expected)
384 static int warned = 0;
385 bool warning_printed = false;
386 tree id = DECL_ASSEMBLER_NAME (current_function_decl);
388 warning_printed =
389 warning_at (input_location, OPT_Wcoverage_mismatch,
390 "the control flow of function %qE does not match "
391 "its profile data (counter %qs)", id, ctr_names[counter]);
392 if (warning_printed && dump_enabled_p ())
394 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
395 "use -Wno-error=coverage-mismatch to tolerate "
396 "the mismatch but performance may drop if the "
397 "function is hot\n");
399 if (!seen_error ()
400 && !warned++)
402 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
403 "coverage mismatch ignored\n");
404 dump_printf (MSG_OPTIMIZED_LOCATIONS,
405 flag_guess_branch_prob
406 ? G_("execution counts estimated\n")
407 : G_("execution counts assumed to be zero\n"));
408 if (!flag_guess_branch_prob)
409 dump_printf (MSG_OPTIMIZED_LOCATIONS,
410 "this can result in poorly optimized code\n");
414 return NULL;
416 else if (entry->lineno_checksum != lineno_checksum)
418 warning (OPT_Wcoverage_mismatch,
419 "source locations for function %qE have changed,"
420 " the profile data may be out of date",
421 DECL_ASSEMBLER_NAME (current_function_decl));
424 if (summary)
425 *summary = &entry->summary;
427 return entry->counts;
430 /* Allocate NUM counters of type COUNTER. Returns nonzero if the
431 allocation succeeded. */
434 coverage_counter_alloc (unsigned counter, unsigned num)
436 if (no_coverage)
437 return 0;
439 if (!num)
440 return 1;
442 if (!fn_v_ctrs[counter])
444 tree array_type = build_array_type (get_gcov_type (), NULL_TREE);
446 fn_v_ctrs[counter]
447 = build_var (current_function_decl, array_type, counter);
450 fn_b_ctrs[counter] = fn_n_ctrs[counter];
451 fn_n_ctrs[counter] += num;
453 fn_ctr_mask |= 1 << counter;
454 return 1;
457 /* Generate a tree to access COUNTER NO. */
459 tree
460 tree_coverage_counter_ref (unsigned counter, unsigned no)
462 tree gcov_type_node = get_gcov_type ();
464 gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
466 no += fn_b_ctrs[counter];
468 /* "no" here is an array index, scaled to bytes later. */
469 return build4 (ARRAY_REF, gcov_type_node, fn_v_ctrs[counter],
470 build_int_cst (integer_type_node, no), NULL, NULL);
473 /* Generate a tree to access the address of COUNTER NO. */
475 tree
476 tree_coverage_counter_addr (unsigned counter, unsigned no)
478 tree gcov_type_node = get_gcov_type ();
480 gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
481 no += fn_b_ctrs[counter];
483 /* "no" here is an array index, scaled to bytes later. */
484 return build_fold_addr_expr (build4 (ARRAY_REF, gcov_type_node,
485 fn_v_ctrs[counter],
486 build_int_cst (integer_type_node, no),
487 NULL, NULL));
491 /* Generate a checksum for a string. CHKSUM is the current
492 checksum. */
494 static unsigned
495 coverage_checksum_string (unsigned chksum, const char *string)
497 int i;
498 char *dup = NULL;
500 /* Look for everything that looks if it were produced by
501 get_file_function_name and zero out the second part
502 that may result from flag_random_seed. This is not critical
503 as the checksums are used only for sanity checking. */
504 for (i = 0; string[i]; i++)
506 int offset = 0;
507 if (!strncmp (string + i, "_GLOBAL__N_", 11))
508 offset = 11;
509 if (!strncmp (string + i, "_GLOBAL__", 9))
510 offset = 9;
512 /* C++ namespaces do have scheme:
513 _GLOBAL__N_<filename>_<wrongmagicnumber>_<magicnumber>functionname
514 since filename might contain extra underscores there seems
515 to be no better chance then walk all possible offsets looking
516 for magicnumber. */
517 if (offset)
519 for (i = i + offset; string[i]; i++)
520 if (string[i]=='_')
522 int y;
524 for (y = 1; y < 9; y++)
525 if (!(string[i + y] >= '0' && string[i + y] <= '9')
526 && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
527 break;
528 if (y != 9 || string[i + 9] != '_')
529 continue;
530 for (y = 10; y < 18; y++)
531 if (!(string[i + y] >= '0' && string[i + y] <= '9')
532 && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
533 break;
534 if (y != 18)
535 continue;
536 if (!dup)
537 string = dup = xstrdup (string);
538 for (y = 10; y < 18; y++)
539 dup[i + y] = '0';
541 break;
545 chksum = crc32_string (chksum, string);
546 free (dup);
548 return chksum;
551 /* Compute checksum for the current function. We generate a CRC32. */
553 unsigned
554 coverage_compute_lineno_checksum (void)
556 expanded_location xloc
557 = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
558 unsigned chksum = xloc.line;
560 if (xloc.file)
561 chksum = coverage_checksum_string (chksum, xloc.file);
562 chksum = coverage_checksum_string
563 (chksum, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl)));
565 return chksum;
568 /* Compute profile ID. This is better to be unique in whole program. */
570 unsigned
571 coverage_compute_profile_id (struct cgraph_node *n)
573 unsigned chksum;
575 /* Externally visible symbols have unique name. */
576 if (TREE_PUBLIC (n->decl) || DECL_EXTERNAL (n->decl) || n->unique_name)
578 chksum = coverage_checksum_string
579 (0, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl)));
581 else
583 expanded_location xloc
584 = expand_location (DECL_SOURCE_LOCATION (n->decl));
585 bool use_name_only = (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID) == 0);
587 chksum = (use_name_only ? 0 : xloc.line);
588 if (xloc.file)
589 chksum = coverage_checksum_string (chksum, xloc.file);
590 chksum = coverage_checksum_string
591 (chksum, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl)));
592 if (!use_name_only && first_global_object_name)
593 chksum = coverage_checksum_string
594 (chksum, first_global_object_name);
595 chksum = coverage_checksum_string
596 (chksum, aux_base_name);
599 /* Non-negative integers are hopefully small enough to fit in all targets.
600 Gcov file formats wants non-zero function IDs. */
601 chksum = chksum & 0x7fffffff;
602 return chksum + (!chksum);
605 /* Compute cfg checksum for the function FN given as argument.
606 The checksum is calculated carefully so that
607 source code changes that doesn't affect the control flow graph
608 won't change the checksum.
609 This is to make the profile data useable across source code change.
610 The downside of this is that the compiler may use potentially
611 wrong profile data - that the source code change has non-trivial impact
612 on the validity of profile data (e.g. the reversed condition)
613 but the compiler won't detect the change and use the wrong profile data. */
615 unsigned
616 coverage_compute_cfg_checksum (struct function *fn)
618 basic_block bb;
619 unsigned chksum = n_basic_blocks_for_fn (fn);
621 FOR_EACH_BB_FN (bb, fn)
623 edge e;
624 edge_iterator ei;
625 chksum = crc32_byte (chksum, bb->index);
626 FOR_EACH_EDGE (e, ei, bb->succs)
628 chksum = crc32_byte (chksum, e->dest->index);
632 return chksum;
635 /* Begin output to the notes file for the current function.
636 Writes the function header. Returns nonzero if data should be output. */
639 coverage_begin_function (unsigned lineno_checksum, unsigned cfg_checksum)
641 expanded_location xloc;
642 unsigned long offset;
644 /* We don't need to output .gcno file unless we're under -ftest-coverage
645 (e.g. -fprofile-arcs/generate/use don't need .gcno to work). */
646 if (no_coverage || !bbg_file_name)
647 return 0;
649 xloc = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
651 /* Announce function */
652 offset = gcov_write_tag (GCOV_TAG_FUNCTION);
653 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
654 gcov_write_unsigned (current_function_funcdef_no + 1);
655 else
657 gcc_assert (coverage_node_map_initialized_p ());
658 gcov_write_unsigned (
659 cgraph_node::get (current_function_decl)->profile_id);
662 gcov_write_unsigned (lineno_checksum);
663 gcov_write_unsigned (cfg_checksum);
664 gcov_write_string (IDENTIFIER_POINTER
665 (DECL_ASSEMBLER_NAME (current_function_decl)));
666 gcov_write_string (xloc.file);
667 gcov_write_unsigned (xloc.line);
668 gcov_write_length (offset);
670 return !gcov_is_error ();
673 /* Finish coverage data for the current function. Verify no output
674 error has occurred. Save function coverage counts. */
676 void
677 coverage_end_function (unsigned lineno_checksum, unsigned cfg_checksum)
679 unsigned i;
681 if (bbg_file_name && gcov_is_error ())
683 warning (0, "error writing %qs", bbg_file_name);
684 unlink (bbg_file_name);
685 bbg_file_name = NULL;
688 if (fn_ctr_mask)
690 struct coverage_data *item = 0;
692 item = ggc_alloc<coverage_data> ();
694 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
695 item->ident = current_function_funcdef_no + 1;
696 else
698 gcc_assert (coverage_node_map_initialized_p ());
699 item->ident = cgraph_node::get (cfun->decl)->profile_id;
702 item->lineno_checksum = lineno_checksum;
703 item->cfg_checksum = cfg_checksum;
705 item->fn_decl = current_function_decl;
706 item->next = 0;
707 *functions_tail = item;
708 functions_tail = &item->next;
710 for (i = 0; i != GCOV_COUNTERS; i++)
712 tree var = fn_v_ctrs[i];
714 if (item)
715 item->ctr_vars[i] = var;
716 if (var)
718 tree array_type = build_index_type (size_int (fn_n_ctrs[i] - 1));
719 array_type = build_array_type (get_gcov_type (), array_type);
720 TREE_TYPE (var) = array_type;
721 DECL_SIZE (var) = TYPE_SIZE (array_type);
722 DECL_SIZE_UNIT (var) = TYPE_SIZE_UNIT (array_type);
723 varpool_node::finalize_decl (var);
726 fn_b_ctrs[i] = fn_n_ctrs[i] = 0;
727 fn_v_ctrs[i] = NULL_TREE;
729 prg_ctr_mask |= fn_ctr_mask;
730 fn_ctr_mask = 0;
734 /* Build a coverage variable of TYPE for function FN_DECL. If COUNTER
735 >= 0 it is a counter array, otherwise it is the function structure. */
737 static tree
738 build_var (tree fn_decl, tree type, int counter)
740 tree var = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE, type);
741 const char *fn_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (fn_decl));
742 char *buf;
743 size_t fn_name_len, len;
745 fn_name = targetm.strip_name_encoding (fn_name);
746 fn_name_len = strlen (fn_name);
747 buf = XALLOCAVEC (char, fn_name_len + 8 + sizeof (int) * 3);
749 if (counter < 0)
750 strcpy (buf, "__gcov__");
751 else
752 sprintf (buf, "__gcov%u_", counter);
753 len = strlen (buf);
754 buf[len - 1] = symbol_table::symbol_suffix_separator ();
755 memcpy (buf + len, fn_name, fn_name_len + 1);
756 DECL_NAME (var) = get_identifier (buf);
757 TREE_STATIC (var) = 1;
758 TREE_ADDRESSABLE (var) = 1;
759 DECL_NONALIASED (var) = 1;
760 SET_DECL_ALIGN (var, TYPE_ALIGN (type));
762 return var;
765 /* Creates the gcov_fn_info RECORD_TYPE. */
767 static void
768 build_fn_info_type (tree type, unsigned counters, tree gcov_info_type)
770 tree ctr_info = lang_hooks.types.make_type (RECORD_TYPE);
771 tree field, fields;
772 tree array_type;
774 gcc_assert (counters);
776 /* ctr_info::num */
777 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
778 get_gcov_unsigned_t ());
779 fields = field;
781 /* ctr_info::values */
782 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
783 build_pointer_type (get_gcov_type ()));
784 DECL_CHAIN (field) = fields;
785 fields = field;
787 finish_builtin_struct (ctr_info, "__gcov_ctr_info", fields, NULL_TREE);
789 /* key */
790 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
791 build_pointer_type (build_qualified_type
792 (gcov_info_type, TYPE_QUAL_CONST)));
793 fields = field;
795 /* ident */
796 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
797 get_gcov_unsigned_t ());
798 DECL_CHAIN (field) = fields;
799 fields = field;
801 /* lineno_checksum */
802 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
803 get_gcov_unsigned_t ());
804 DECL_CHAIN (field) = fields;
805 fields = field;
807 /* cfg checksum */
808 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
809 get_gcov_unsigned_t ());
810 DECL_CHAIN (field) = fields;
811 fields = field;
813 array_type = build_index_type (size_int (counters - 1));
814 array_type = build_array_type (ctr_info, array_type);
816 /* counters */
817 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE, array_type);
818 DECL_CHAIN (field) = fields;
819 fields = field;
821 finish_builtin_struct (type, "__gcov_fn_info", fields, NULL_TREE);
824 /* Returns a CONSTRUCTOR for a gcov_fn_info. DATA is
825 the coverage data for the function and TYPE is the gcov_fn_info
826 RECORD_TYPE. KEY is the object file key. */
828 static tree
829 build_fn_info (const struct coverage_data *data, tree type, tree key)
831 tree fields = TYPE_FIELDS (type);
832 tree ctr_type;
833 unsigned ix;
834 vec<constructor_elt, va_gc> *v1 = NULL;
835 vec<constructor_elt, va_gc> *v2 = NULL;
837 /* key */
838 CONSTRUCTOR_APPEND_ELT (v1, fields,
839 build1 (ADDR_EXPR, TREE_TYPE (fields), key));
840 fields = DECL_CHAIN (fields);
842 /* ident */
843 CONSTRUCTOR_APPEND_ELT (v1, fields,
844 build_int_cstu (get_gcov_unsigned_t (),
845 data->ident));
846 fields = DECL_CHAIN (fields);
848 /* lineno_checksum */
849 CONSTRUCTOR_APPEND_ELT (v1, fields,
850 build_int_cstu (get_gcov_unsigned_t (),
851 data->lineno_checksum));
852 fields = DECL_CHAIN (fields);
854 /* cfg_checksum */
855 CONSTRUCTOR_APPEND_ELT (v1, fields,
856 build_int_cstu (get_gcov_unsigned_t (),
857 data->cfg_checksum));
858 fields = DECL_CHAIN (fields);
860 /* counters */
861 ctr_type = TREE_TYPE (TREE_TYPE (fields));
862 for (ix = 0; ix != GCOV_COUNTERS; ix++)
863 if (prg_ctr_mask & (1 << ix))
865 vec<constructor_elt, va_gc> *ctr = NULL;
866 tree var = data->ctr_vars[ix];
867 unsigned count = 0;
869 if (var)
870 count
871 = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (var))))
872 + 1;
874 CONSTRUCTOR_APPEND_ELT (ctr, TYPE_FIELDS (ctr_type),
875 build_int_cstu (get_gcov_unsigned_t (),
876 count));
878 if (var)
879 CONSTRUCTOR_APPEND_ELT (ctr, DECL_CHAIN (TYPE_FIELDS (ctr_type)),
880 build_fold_addr_expr (var));
882 CONSTRUCTOR_APPEND_ELT (v2, NULL, build_constructor (ctr_type, ctr));
885 CONSTRUCTOR_APPEND_ELT (v1, fields,
886 build_constructor (TREE_TYPE (fields), v2));
888 return build_constructor (type, v1);
891 /* Create gcov_info struct. TYPE is the incomplete RECORD_TYPE to be
892 completed, and FN_INFO_PTR_TYPE is a pointer to the function info type. */
894 static void
895 build_info_type (tree type, tree fn_info_ptr_type)
897 tree field, fields = NULL_TREE;
898 tree merge_fn_type;
900 /* Version ident */
901 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
902 get_gcov_unsigned_t ());
903 DECL_CHAIN (field) = fields;
904 fields = field;
906 /* next pointer */
907 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
908 build_pointer_type (build_qualified_type
909 (type, TYPE_QUAL_CONST)));
910 DECL_CHAIN (field) = fields;
911 fields = field;
913 /* stamp */
914 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
915 get_gcov_unsigned_t ());
916 DECL_CHAIN (field) = fields;
917 fields = field;
919 /* Filename */
920 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
921 build_pointer_type (build_qualified_type
922 (char_type_node, TYPE_QUAL_CONST)));
923 DECL_CHAIN (field) = fields;
924 fields = field;
926 /* merge fn array */
927 merge_fn_type
928 = build_function_type_list (void_type_node,
929 build_pointer_type (get_gcov_type ()),
930 get_gcov_unsigned_t (), NULL_TREE);
931 merge_fn_type
932 = build_array_type (build_pointer_type (merge_fn_type),
933 build_index_type (size_int (GCOV_COUNTERS - 1)));
934 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
935 merge_fn_type);
936 DECL_CHAIN (field) = fields;
937 fields = field;
939 /* n_functions */
940 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
941 get_gcov_unsigned_t ());
942 DECL_CHAIN (field) = fields;
943 fields = field;
945 /* function_info pointer pointer */
946 fn_info_ptr_type = build_pointer_type
947 (build_qualified_type (fn_info_ptr_type, TYPE_QUAL_CONST));
948 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
949 fn_info_ptr_type);
950 DECL_CHAIN (field) = fields;
951 fields = field;
953 finish_builtin_struct (type, "__gcov_info", fields, NULL_TREE);
956 /* Returns a CONSTRUCTOR for the gcov_info object. INFO_TYPE is the
957 gcov_info structure type, FN_ARY is the array of pointers to
958 function info objects. */
960 static tree
961 build_info (tree info_type, tree fn_ary)
963 tree info_fields = TYPE_FIELDS (info_type);
964 tree merge_fn_type, n_funcs;
965 unsigned ix;
966 tree filename_string;
967 int da_file_name_len;
968 vec<constructor_elt, va_gc> *v1 = NULL;
969 vec<constructor_elt, va_gc> *v2 = NULL;
971 /* Version ident */
972 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
973 build_int_cstu (TREE_TYPE (info_fields),
974 GCOV_VERSION));
975 info_fields = DECL_CHAIN (info_fields);
977 /* next -- NULL */
978 CONSTRUCTOR_APPEND_ELT (v1, info_fields, null_pointer_node);
979 info_fields = DECL_CHAIN (info_fields);
981 /* stamp */
982 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
983 build_int_cstu (TREE_TYPE (info_fields),
984 bbg_file_stamp));
985 info_fields = DECL_CHAIN (info_fields);
987 /* Filename */
988 da_file_name_len = strlen (da_file_name);
989 filename_string = build_string (da_file_name_len + 1, da_file_name);
990 TREE_TYPE (filename_string) = build_array_type
991 (char_type_node, build_index_type (size_int (da_file_name_len)));
992 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
993 build1 (ADDR_EXPR, TREE_TYPE (info_fields),
994 filename_string));
995 info_fields = DECL_CHAIN (info_fields);
997 /* merge fn array -- NULL slots indicate unmeasured counters */
998 merge_fn_type = TREE_TYPE (TREE_TYPE (info_fields));
999 for (ix = 0; ix != GCOV_COUNTERS; ix++)
1001 tree ptr = null_pointer_node;
1003 if ((1u << ix) & prg_ctr_mask)
1005 tree merge_fn = build_decl (BUILTINS_LOCATION,
1006 FUNCTION_DECL,
1007 get_identifier (ctr_merge_functions[ix]),
1008 TREE_TYPE (merge_fn_type));
1009 DECL_EXTERNAL (merge_fn) = 1;
1010 TREE_PUBLIC (merge_fn) = 1;
1011 DECL_ARTIFICIAL (merge_fn) = 1;
1012 TREE_NOTHROW (merge_fn) = 1;
1013 /* Initialize assembler name so we can stream out. */
1014 DECL_ASSEMBLER_NAME (merge_fn);
1015 ptr = build1 (ADDR_EXPR, merge_fn_type, merge_fn);
1017 CONSTRUCTOR_APPEND_ELT (v2, NULL, ptr);
1019 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
1020 build_constructor (TREE_TYPE (info_fields), v2));
1021 info_fields = DECL_CHAIN (info_fields);
1023 /* n_functions */
1024 n_funcs = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (fn_ary)));
1025 n_funcs = fold_build2 (PLUS_EXPR, TREE_TYPE (info_fields),
1026 n_funcs, size_one_node);
1027 CONSTRUCTOR_APPEND_ELT (v1, info_fields, n_funcs);
1028 info_fields = DECL_CHAIN (info_fields);
1030 /* functions */
1031 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
1032 build1 (ADDR_EXPR, TREE_TYPE (info_fields), fn_ary));
1033 info_fields = DECL_CHAIN (info_fields);
1035 gcc_assert (!info_fields);
1036 return build_constructor (info_type, v1);
1039 /* Generate the constructor function to call __gcov_init. */
1041 static void
1042 build_init_ctor (tree gcov_info_type)
1044 tree ctor, stmt, init_fn;
1046 /* Build a decl for __gcov_init. */
1047 init_fn = build_pointer_type (gcov_info_type);
1048 init_fn = build_function_type_list (void_type_node, init_fn, NULL);
1049 init_fn = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
1050 get_identifier ("__gcov_init"), init_fn);
1051 TREE_PUBLIC (init_fn) = 1;
1052 DECL_EXTERNAL (init_fn) = 1;
1053 DECL_ASSEMBLER_NAME (init_fn);
1055 /* Generate a call to __gcov_init(&gcov_info). */
1056 ctor = NULL;
1057 stmt = build_fold_addr_expr (gcov_info_var);
1058 stmt = build_call_expr (init_fn, 1, stmt);
1059 append_to_statement_list (stmt, &ctor);
1061 /* Generate a constructor to run it. */
1062 int priority = SUPPORTS_INIT_PRIORITY
1063 ? MAX_RESERVED_INIT_PRIORITY: DEFAULT_INIT_PRIORITY;
1064 cgraph_build_static_cdtor ('I', ctor, priority);
1067 /* Generate the destructor function to call __gcov_exit. */
1069 static void
1070 build_gcov_exit_decl (void)
1072 tree init_fn = build_function_type_list (void_type_node, void_type_node,
1073 NULL);
1074 init_fn = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
1075 get_identifier ("__gcov_exit"), init_fn);
1076 TREE_PUBLIC (init_fn) = 1;
1077 DECL_EXTERNAL (init_fn) = 1;
1078 DECL_ASSEMBLER_NAME (init_fn);
1080 /* Generate a call to __gcov_exit (). */
1081 tree dtor = NULL;
1082 tree stmt = build_call_expr (init_fn, 0);
1083 append_to_statement_list (stmt, &dtor);
1085 /* Generate a destructor to run it. */
1086 int priority = SUPPORTS_INIT_PRIORITY
1087 ? MAX_RESERVED_INIT_PRIORITY: DEFAULT_INIT_PRIORITY;
1089 cgraph_build_static_cdtor ('D', dtor, priority);
1092 /* Create the gcov_info types and object. Generate the constructor
1093 function to call __gcov_init. Does not generate the initializer
1094 for the object. Returns TRUE if coverage data is being emitted. */
1096 static bool
1097 coverage_obj_init (void)
1099 tree gcov_info_type;
1100 unsigned n_counters = 0;
1101 unsigned ix;
1102 struct coverage_data *fn;
1103 struct coverage_data **fn_prev;
1104 char name_buf[32];
1106 no_coverage = 1; /* Disable any further coverage. */
1108 if (!prg_ctr_mask)
1109 return false;
1111 if (symtab->dump_file)
1112 fprintf (symtab->dump_file, "Using data file %s\n", da_file_name);
1114 /* Prune functions. */
1115 for (fn_prev = &functions_head; (fn = *fn_prev);)
1116 if (DECL_STRUCT_FUNCTION (fn->fn_decl))
1117 fn_prev = &fn->next;
1118 else
1119 /* The function is not being emitted, remove from list. */
1120 *fn_prev = fn->next;
1122 if (functions_head == NULL)
1123 return false;
1125 for (ix = 0; ix != GCOV_COUNTERS; ix++)
1126 if ((1u << ix) & prg_ctr_mask)
1127 n_counters++;
1129 /* Build the info and fn_info types. These are mutually recursive. */
1130 gcov_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1131 gcov_fn_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1132 build_fn_info_type (gcov_fn_info_type, n_counters, gcov_info_type);
1133 gcov_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1134 gcov_fn_info_ptr_type = build_pointer_type
1135 (build_qualified_type (gcov_fn_info_type, TYPE_QUAL_CONST));
1136 build_info_type (gcov_info_type, gcov_fn_info_ptr_type);
1138 /* Build the gcov info var, this is referred to in its own
1139 initializer. */
1140 gcov_info_var = build_decl (BUILTINS_LOCATION,
1141 VAR_DECL, NULL_TREE, gcov_info_type);
1142 TREE_STATIC (gcov_info_var) = 1;
1143 ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 0);
1144 DECL_NAME (gcov_info_var) = get_identifier (name_buf);
1146 build_init_ctor (gcov_info_type);
1147 build_gcov_exit_decl ();
1149 return true;
1152 /* Generate the coverage function info for FN and DATA. Append a
1153 pointer to that object to CTOR and return the appended CTOR. */
1155 static vec<constructor_elt, va_gc> *
1156 coverage_obj_fn (vec<constructor_elt, va_gc> *ctor, tree fn,
1157 struct coverage_data const *data)
1159 tree init = build_fn_info (data, gcov_fn_info_type, gcov_info_var);
1160 tree var = build_var (fn, gcov_fn_info_type, -1);
1162 DECL_INITIAL (var) = init;
1163 varpool_node::finalize_decl (var);
1165 CONSTRUCTOR_APPEND_ELT (ctor, NULL,
1166 build1 (ADDR_EXPR, gcov_fn_info_ptr_type, var));
1167 return ctor;
1170 /* Finalize the coverage data. Generates the array of pointers to
1171 function objects from CTOR. Generate the gcov_info initializer. */
1173 static void
1174 coverage_obj_finish (vec<constructor_elt, va_gc> *ctor)
1176 unsigned n_functions = vec_safe_length (ctor);
1177 tree fn_info_ary_type = build_array_type
1178 (build_qualified_type (gcov_fn_info_ptr_type, TYPE_QUAL_CONST),
1179 build_index_type (size_int (n_functions - 1)));
1180 tree fn_info_ary = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE,
1181 fn_info_ary_type);
1182 char name_buf[32];
1184 TREE_STATIC (fn_info_ary) = 1;
1185 ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 1);
1186 DECL_NAME (fn_info_ary) = get_identifier (name_buf);
1187 DECL_INITIAL (fn_info_ary) = build_constructor (fn_info_ary_type, ctor);
1188 varpool_node::finalize_decl (fn_info_ary);
1190 DECL_INITIAL (gcov_info_var)
1191 = build_info (TREE_TYPE (gcov_info_var), fn_info_ary);
1192 varpool_node::finalize_decl (gcov_info_var);
1195 /* Perform file-level initialization. Read in data file, generate name
1196 of notes file. */
1198 void
1199 coverage_init (const char *filename)
1201 int len = strlen (filename);
1202 int prefix_len = 0;
1204 /* Since coverage_init is invoked very early, before the pass
1205 manager, we need to set up the dumping explicitly. This is
1206 similar to the handling in finish_optimization_passes. */
1207 int profile_pass_num =
1208 g->get_passes ()->get_pass_profile ()->static_pass_number;
1209 g->get_dumps ()->dump_start (profile_pass_num, NULL);
1211 if (!profile_data_prefix && !IS_ABSOLUTE_PATH (filename))
1212 profile_data_prefix = getpwd ();
1214 if (profile_data_prefix)
1215 prefix_len = strlen (profile_data_prefix);
1217 /* Name of da file. */
1218 da_file_name = XNEWVEC (char, len + strlen (GCOV_DATA_SUFFIX)
1219 + prefix_len + 2);
1221 if (profile_data_prefix)
1223 memcpy (da_file_name, profile_data_prefix, prefix_len);
1224 da_file_name[prefix_len++] = '/';
1226 memcpy (da_file_name + prefix_len, filename, len);
1227 strcpy (da_file_name + prefix_len + len, GCOV_DATA_SUFFIX);
1229 bbg_file_stamp = local_tick;
1231 if (flag_auto_profile)
1232 read_autofdo_file ();
1233 else if (flag_branch_probabilities)
1234 read_counts_file ();
1236 /* Name of bbg file. */
1237 if (flag_test_coverage && !flag_compare_debug)
1239 bbg_file_name = XNEWVEC (char, len + strlen (GCOV_NOTE_SUFFIX) + 1);
1240 memcpy (bbg_file_name, filename, len);
1241 strcpy (bbg_file_name + len, GCOV_NOTE_SUFFIX);
1243 if (!gcov_open (bbg_file_name, -1))
1245 error ("cannot open %s", bbg_file_name);
1246 bbg_file_name = NULL;
1248 else
1250 gcov_write_unsigned (GCOV_NOTE_MAGIC);
1251 gcov_write_unsigned (GCOV_VERSION);
1252 gcov_write_unsigned (bbg_file_stamp);
1256 g->get_dumps ()->dump_finish (profile_pass_num);
1259 /* Performs file-level cleanup. Close notes file, generate coverage
1260 variables and constructor. */
1262 void
1263 coverage_finish (void)
1265 if (bbg_file_name && gcov_close ())
1266 unlink (bbg_file_name);
1268 if (!flag_branch_probabilities && flag_test_coverage
1269 && (!local_tick || local_tick == (unsigned)-1))
1270 /* Only remove the da file, if we're emitting coverage code and
1271 cannot uniquely stamp it. If we can stamp it, libgcov will DTRT. */
1272 unlink (da_file_name);
1274 if (coverage_obj_init ())
1276 vec<constructor_elt, va_gc> *fn_ctor = NULL;
1277 struct coverage_data *fn;
1279 for (fn = functions_head; fn; fn = fn->next)
1280 fn_ctor = coverage_obj_fn (fn_ctor, fn->fn_decl, fn);
1281 coverage_obj_finish (fn_ctor);
1284 XDELETEVEC (da_file_name);
1285 da_file_name = NULL;
1288 #include "gt-coverage.h"