2016-10-05 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / coverage.c
blob0b8c0b378435708c4fadb505811aec61b0d52070
1 /* Read and write coverage files, and associated functionality.
2 Copyright (C) 1990-2016 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 "tm_p.h"
36 #include "stringpool.h"
37 #include "cgraph.h"
38 #include "coverage.h"
39 #include "diagnostic-core.h"
40 #include "fold-const.h"
41 #include "stor-layout.h"
42 #include "output.h"
43 #include "toplev.h"
44 #include "langhooks.h"
45 #include "tree-iterator.h"
46 #include "context.h"
47 #include "pass_manager.h"
48 #include "intl.h"
49 #include "params.h"
50 #include "auto-profile.h"
52 #include "gcov-io.c"
54 struct GTY((chain_next ("%h.next"))) coverage_data
56 struct coverage_data *next; /* next function */
57 unsigned ident; /* function ident */
58 unsigned lineno_checksum; /* function lineno checksum */
59 unsigned cfg_checksum; /* function cfg checksum */
60 tree fn_decl; /* the function decl */
61 tree ctr_vars[GCOV_COUNTERS]; /* counter variables. */
64 /* Counts information for a function. */
65 struct counts_entry : pointer_hash <counts_entry>
67 /* We hash by */
68 unsigned ident;
69 unsigned ctr;
71 /* Store */
72 unsigned lineno_checksum;
73 unsigned cfg_checksum;
74 gcov_type *counts;
75 struct gcov_ctr_summary summary;
77 /* hash_table support. */
78 static inline hashval_t hash (const counts_entry *);
79 static int equal (const counts_entry *, const counts_entry *);
80 static void remove (counts_entry *);
83 static GTY(()) struct coverage_data *functions_head = 0;
84 static struct coverage_data **functions_tail = &functions_head;
85 static unsigned no_coverage = 0;
87 /* Cumulative counter information for whole program. */
88 static unsigned prg_ctr_mask; /* Mask of counter types generated. */
90 /* Counter information for current function. */
91 static unsigned fn_ctr_mask; /* Mask of counters used. */
92 static GTY(()) tree fn_v_ctrs[GCOV_COUNTERS]; /* counter variables. */
93 static unsigned fn_n_ctrs[GCOV_COUNTERS]; /* Counters allocated. */
94 static unsigned fn_b_ctrs[GCOV_COUNTERS]; /* Allocation base. */
96 /* Coverage info VAR_DECL and function info type nodes. */
97 static GTY(()) tree gcov_info_var;
98 static GTY(()) tree gcov_fn_info_type;
99 static GTY(()) tree gcov_fn_info_ptr_type;
101 /* Name of the notes (gcno) output file. The "bbg" prefix is for
102 historical reasons, when the notes file contained only the
103 basic block graph notes.
104 If this is NULL we're not writing to the notes file. */
105 static char *bbg_file_name;
107 /* File stamp for notes file. */
108 static unsigned bbg_file_stamp;
110 /* Name of the count data (gcda) file. */
111 static char *da_file_name;
113 /* The names of merge functions for counters. */
114 #define STR(str) #str
115 #define DEF_GCOV_COUNTER(COUNTER, NAME, FN_TYPE) STR(__gcov_merge ## FN_TYPE),
116 static const char *const ctr_merge_functions[GCOV_COUNTERS] = {
117 #include "gcov-counter.def"
119 #undef DEF_GCOV_COUNTER
120 #undef STR
122 #define DEF_GCOV_COUNTER(COUNTER, NAME, FN_TYPE) NAME,
123 static const char *const ctr_names[GCOV_COUNTERS] = {
124 #include "gcov-counter.def"
126 #undef DEF_GCOV_COUNTER
128 /* Forward declarations. */
129 static void read_counts_file (void);
130 static tree build_var (tree, tree, int);
131 static void build_fn_info_type (tree, unsigned, tree);
132 static void build_info_type (tree, tree);
133 static tree build_fn_info (const struct coverage_data *, tree, tree);
134 static tree build_info (tree, tree);
135 static bool coverage_obj_init (void);
136 static vec<constructor_elt, va_gc> *coverage_obj_fn
137 (vec<constructor_elt, va_gc> *, tree, struct coverage_data const *);
138 static void coverage_obj_finish (vec<constructor_elt, va_gc> *);
140 /* Return the type node for gcov_type. */
142 tree
143 get_gcov_type (void)
145 machine_mode mode
146 = smallest_mode_for_size (LONG_LONG_TYPE_SIZE > 32 ? 64 : 32, MODE_INT);
147 return lang_hooks.types.type_for_mode (mode, false);
150 /* Return the type node for gcov_unsigned_t. */
152 static tree
153 get_gcov_unsigned_t (void)
155 machine_mode mode = smallest_mode_for_size (32, MODE_INT);
156 return lang_hooks.types.type_for_mode (mode, true);
159 inline hashval_t
160 counts_entry::hash (const counts_entry *entry)
162 return entry->ident * GCOV_COUNTERS + entry->ctr;
165 inline int
166 counts_entry::equal (const counts_entry *entry1, const counts_entry *entry2)
168 return entry1->ident == entry2->ident && entry1->ctr == entry2->ctr;
171 inline void
172 counts_entry::remove (counts_entry *entry)
174 free (entry->counts);
175 free (entry);
178 /* Hash table of count data. */
179 static hash_table<counts_entry> *counts_hash;
181 /* Read in the counts file, if available. */
183 static void
184 read_counts_file (void)
186 gcov_unsigned_t fn_ident = 0;
187 struct gcov_summary summary;
188 unsigned new_summary = 1;
189 gcov_unsigned_t tag;
190 int is_error = 0;
191 unsigned lineno_checksum = 0;
192 unsigned cfg_checksum = 0;
194 if (!gcov_open (da_file_name, 1))
195 return;
197 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
199 warning (0, "%qs is not a gcov data file", da_file_name);
200 gcov_close ();
201 return;
203 else if ((tag = gcov_read_unsigned ()) != GCOV_VERSION)
205 char v[4], e[4];
207 GCOV_UNSIGNED2STRING (v, tag);
208 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
210 warning (0, "%qs is version %q.*s, expected version %q.*s",
211 da_file_name, 4, v, 4, e);
212 gcov_close ();
213 return;
216 /* Read the stamp, used for creating a generation count. */
217 tag = gcov_read_unsigned ();
218 bbg_file_stamp = crc32_unsigned (bbg_file_stamp, tag);
220 counts_hash = new hash_table<counts_entry> (10);
221 while ((tag = gcov_read_unsigned ()))
223 gcov_unsigned_t length;
224 gcov_position_t offset;
226 length = gcov_read_unsigned ();
227 offset = gcov_position ();
228 if (tag == GCOV_TAG_FUNCTION)
230 if (length)
232 fn_ident = gcov_read_unsigned ();
233 lineno_checksum = gcov_read_unsigned ();
234 cfg_checksum = gcov_read_unsigned ();
236 else
237 fn_ident = lineno_checksum = cfg_checksum = 0;
238 new_summary = 1;
240 else if (tag == GCOV_TAG_PROGRAM_SUMMARY)
242 struct gcov_summary sum;
243 unsigned ix;
245 if (new_summary)
246 memset (&summary, 0, sizeof (summary));
248 gcov_read_summary (&sum);
249 for (ix = 0; ix != GCOV_COUNTERS_SUMMABLE; ix++)
251 summary.ctrs[ix].runs += sum.ctrs[ix].runs;
252 summary.ctrs[ix].sum_all += sum.ctrs[ix].sum_all;
253 if (summary.ctrs[ix].run_max < sum.ctrs[ix].run_max)
254 summary.ctrs[ix].run_max = sum.ctrs[ix].run_max;
255 summary.ctrs[ix].sum_max += sum.ctrs[ix].sum_max;
257 if (new_summary)
258 memcpy (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
259 sum.ctrs[GCOV_COUNTER_ARCS].histogram,
260 sizeof (gcov_bucket_type) * GCOV_HISTOGRAM_SIZE);
261 else
262 gcov_histogram_merge (summary.ctrs[GCOV_COUNTER_ARCS].histogram,
263 sum.ctrs[GCOV_COUNTER_ARCS].histogram);
264 new_summary = 0;
266 else if (GCOV_TAG_IS_COUNTER (tag) && fn_ident)
268 counts_entry **slot, *entry, elt;
269 unsigned n_counts = GCOV_TAG_COUNTER_NUM (length);
270 unsigned ix;
272 elt.ident = fn_ident;
273 elt.ctr = GCOV_COUNTER_FOR_TAG (tag);
275 slot = counts_hash->find_slot (&elt, INSERT);
276 entry = *slot;
277 if (!entry)
279 *slot = entry = XCNEW (counts_entry);
280 entry->ident = fn_ident;
281 entry->ctr = elt.ctr;
282 entry->lineno_checksum = lineno_checksum;
283 entry->cfg_checksum = cfg_checksum;
284 if (elt.ctr < GCOV_COUNTERS_SUMMABLE)
285 entry->summary = summary.ctrs[elt.ctr];
286 entry->summary.num = n_counts;
287 entry->counts = XCNEWVEC (gcov_type, n_counts);
289 else if (entry->lineno_checksum != lineno_checksum
290 || entry->cfg_checksum != cfg_checksum)
292 error ("Profile data for function %u is corrupted", fn_ident);
293 error ("checksum is (%x,%x) instead of (%x,%x)",
294 entry->lineno_checksum, entry->cfg_checksum,
295 lineno_checksum, cfg_checksum);
296 delete counts_hash;
297 counts_hash = NULL;
298 break;
300 else if (entry->summary.num != n_counts)
302 error ("Profile data for function %u is corrupted", fn_ident);
303 error ("number of counters is %d instead of %d", entry->summary.num, n_counts);
304 delete counts_hash;
305 counts_hash = NULL;
306 break;
308 else if (elt.ctr >= GCOV_COUNTERS_SUMMABLE)
310 error ("cannot merge separate %s counters for function %u",
311 ctr_names[elt.ctr], fn_ident);
312 goto skip_merge;
314 else
316 entry->summary.runs += summary.ctrs[elt.ctr].runs;
317 entry->summary.sum_all += summary.ctrs[elt.ctr].sum_all;
318 if (entry->summary.run_max < summary.ctrs[elt.ctr].run_max)
319 entry->summary.run_max = summary.ctrs[elt.ctr].run_max;
320 entry->summary.sum_max += summary.ctrs[elt.ctr].sum_max;
322 for (ix = 0; ix != n_counts; ix++)
323 entry->counts[ix] += gcov_read_counter ();
324 skip_merge:;
326 gcov_sync (offset, length);
327 if ((is_error = gcov_is_error ()))
329 error (is_error < 0 ? "%qs has overflowed" : "%qs is corrupted",
330 da_file_name);
331 delete counts_hash;
332 counts_hash = NULL;
333 break;
337 gcov_close ();
340 /* Returns the counters for a particular tag. */
342 gcov_type *
343 get_coverage_counts (unsigned counter, unsigned expected,
344 unsigned cfg_checksum, unsigned lineno_checksum,
345 const struct gcov_ctr_summary **summary)
347 counts_entry *entry, elt;
349 /* No hash table, no counts. */
350 if (!counts_hash)
352 static int warned = 0;
354 if (!warned++ && dump_enabled_p ())
355 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
356 (flag_guess_branch_prob
357 ? "file %s not found, execution counts estimated\n"
358 : "file %s not found, execution counts assumed to "
359 "be zero\n"),
360 da_file_name);
361 return NULL;
363 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
364 elt.ident = current_function_funcdef_no + 1;
365 else
367 gcc_assert (coverage_node_map_initialized_p ());
368 elt.ident = cgraph_node::get (cfun->decl)->profile_id;
370 elt.ctr = counter;
371 entry = counts_hash->find (&elt);
372 if (!entry || !entry->summary.num)
373 /* The function was not emitted, or is weak and not chosen in the
374 final executable. Silently fail, because there's nothing we
375 can do about it. */
376 return NULL;
378 if (entry->cfg_checksum != cfg_checksum
379 || entry->summary.num != expected)
381 static int warned = 0;
382 bool warning_printed = false;
383 tree id = DECL_ASSEMBLER_NAME (current_function_decl);
385 warning_printed =
386 warning_at (input_location, OPT_Wcoverage_mismatch,
387 "the control flow of function %qE does not match "
388 "its profile data (counter %qs)", id, ctr_names[counter]);
389 if (warning_printed && dump_enabled_p ())
391 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
392 "use -Wno-error=coverage-mismatch to tolerate "
393 "the mismatch but performance may drop if the "
394 "function is hot\n");
396 if (!seen_error ()
397 && !warned++)
399 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, input_location,
400 "coverage mismatch ignored\n");
401 dump_printf (MSG_OPTIMIZED_LOCATIONS,
402 flag_guess_branch_prob
403 ? G_("execution counts estimated\n")
404 : G_("execution counts assumed to be zero\n"));
405 if (!flag_guess_branch_prob)
406 dump_printf (MSG_OPTIMIZED_LOCATIONS,
407 "this can result in poorly optimized code\n");
411 return NULL;
413 else if (entry->lineno_checksum != lineno_checksum)
415 warning (OPT_Wcoverage_mismatch,
416 "source locations for function %qE have changed,"
417 " the profile data may be out of date",
418 DECL_ASSEMBLER_NAME (current_function_decl));
421 if (summary)
422 *summary = &entry->summary;
424 return entry->counts;
427 /* Allocate NUM counters of type COUNTER. Returns nonzero if the
428 allocation succeeded. */
431 coverage_counter_alloc (unsigned counter, unsigned num)
433 if (no_coverage)
434 return 0;
436 if (!num)
437 return 1;
439 if (!fn_v_ctrs[counter])
441 tree array_type = build_array_type (get_gcov_type (), NULL_TREE);
443 fn_v_ctrs[counter]
444 = build_var (current_function_decl, array_type, counter);
447 fn_b_ctrs[counter] = fn_n_ctrs[counter];
448 fn_n_ctrs[counter] += num;
450 fn_ctr_mask |= 1 << counter;
451 return 1;
454 /* Generate a tree to access COUNTER NO. */
456 tree
457 tree_coverage_counter_ref (unsigned counter, unsigned no)
459 tree gcov_type_node = get_gcov_type ();
461 gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
463 no += fn_b_ctrs[counter];
465 /* "no" here is an array index, scaled to bytes later. */
466 return build4 (ARRAY_REF, gcov_type_node, fn_v_ctrs[counter],
467 build_int_cst (integer_type_node, no), NULL, NULL);
470 /* Generate a tree to access the address of COUNTER NO. */
472 tree
473 tree_coverage_counter_addr (unsigned counter, unsigned no)
475 tree gcov_type_node = get_gcov_type ();
477 gcc_assert (no < fn_n_ctrs[counter] - fn_b_ctrs[counter]);
478 no += fn_b_ctrs[counter];
480 /* "no" here is an array index, scaled to bytes later. */
481 return build_fold_addr_expr (build4 (ARRAY_REF, gcov_type_node,
482 fn_v_ctrs[counter],
483 build_int_cst (integer_type_node, no),
484 NULL, NULL));
488 /* Generate a checksum for a string. CHKSUM is the current
489 checksum. */
491 static unsigned
492 coverage_checksum_string (unsigned chksum, const char *string)
494 int i;
495 char *dup = NULL;
497 /* Look for everything that looks if it were produced by
498 get_file_function_name and zero out the second part
499 that may result from flag_random_seed. This is not critical
500 as the checksums are used only for sanity checking. */
501 for (i = 0; string[i]; i++)
503 int offset = 0;
504 if (!strncmp (string + i, "_GLOBAL__N_", 11))
505 offset = 11;
506 if (!strncmp (string + i, "_GLOBAL__", 9))
507 offset = 9;
509 /* C++ namespaces do have scheme:
510 _GLOBAL__N_<filename>_<wrongmagicnumber>_<magicnumber>functionname
511 since filename might contain extra underscores there seems
512 to be no better chance then walk all possible offsets looking
513 for magicnumber. */
514 if (offset)
516 for (i = i + offset; string[i]; i++)
517 if (string[i]=='_')
519 int y;
521 for (y = 1; y < 9; y++)
522 if (!(string[i + y] >= '0' && string[i + y] <= '9')
523 && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
524 break;
525 if (y != 9 || string[i + 9] != '_')
526 continue;
527 for (y = 10; y < 18; y++)
528 if (!(string[i + y] >= '0' && string[i + y] <= '9')
529 && !(string[i + y] >= 'A' && string[i + y] <= 'F'))
530 break;
531 if (y != 18)
532 continue;
533 if (!dup)
534 string = dup = xstrdup (string);
535 for (y = 10; y < 18; y++)
536 dup[i + y] = '0';
538 break;
542 chksum = crc32_string (chksum, string);
543 free (dup);
545 return chksum;
548 /* Compute checksum for the current function. We generate a CRC32. */
550 unsigned
551 coverage_compute_lineno_checksum (void)
553 expanded_location xloc
554 = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
555 unsigned chksum = xloc.line;
557 if (xloc.file)
558 chksum = coverage_checksum_string (chksum, xloc.file);
559 chksum = coverage_checksum_string
560 (chksum, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl)));
562 return chksum;
565 /* Compute profile ID. This is better to be unique in whole program. */
567 unsigned
568 coverage_compute_profile_id (struct cgraph_node *n)
570 unsigned chksum;
572 /* Externally visible symbols have unique name. */
573 if (TREE_PUBLIC (n->decl) || DECL_EXTERNAL (n->decl) || n->unique_name)
575 chksum = coverage_checksum_string
576 (0, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl)));
578 else
580 expanded_location xloc
581 = expand_location (DECL_SOURCE_LOCATION (n->decl));
582 bool use_name_only = (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID) == 0);
584 chksum = (use_name_only ? 0 : xloc.line);
585 if (xloc.file)
586 chksum = coverage_checksum_string (chksum, xloc.file);
587 chksum = coverage_checksum_string
588 (chksum, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (n->decl)));
589 if (!use_name_only && first_global_object_name)
590 chksum = coverage_checksum_string
591 (chksum, first_global_object_name);
592 chksum = coverage_checksum_string
593 (chksum, aux_base_name);
596 /* Non-negative integers are hopefully small enough to fit in all targets.
597 Gcov file formats wants non-zero function IDs. */
598 chksum = chksum & 0x7fffffff;
599 return chksum + (!chksum);
602 /* Compute cfg checksum for the function FN given as argument.
603 The checksum is calculated carefully so that
604 source code changes that doesn't affect the control flow graph
605 won't change the checksum.
606 This is to make the profile data useable across source code change.
607 The downside of this is that the compiler may use potentially
608 wrong profile data - that the source code change has non-trivial impact
609 on the validity of profile data (e.g. the reversed condition)
610 but the compiler won't detect the change and use the wrong profile data. */
612 unsigned
613 coverage_compute_cfg_checksum (struct function *fn)
615 basic_block bb;
616 unsigned chksum = n_basic_blocks_for_fn (fn);
618 FOR_EACH_BB_FN (bb, fn)
620 edge e;
621 edge_iterator ei;
622 chksum = crc32_byte (chksum, bb->index);
623 FOR_EACH_EDGE (e, ei, bb->succs)
625 chksum = crc32_byte (chksum, e->dest->index);
629 return chksum;
632 /* Begin output to the notes file for the current function.
633 Writes the function header. Returns nonzero if data should be output. */
636 coverage_begin_function (unsigned lineno_checksum, unsigned cfg_checksum)
638 expanded_location xloc;
639 unsigned long offset;
641 /* We don't need to output .gcno file unless we're under -ftest-coverage
642 (e.g. -fprofile-arcs/generate/use don't need .gcno to work). */
643 if (no_coverage || !bbg_file_name)
644 return 0;
646 xloc = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
648 /* Announce function */
649 offset = gcov_write_tag (GCOV_TAG_FUNCTION);
650 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
651 gcov_write_unsigned (current_function_funcdef_no + 1);
652 else
654 gcc_assert (coverage_node_map_initialized_p ());
655 gcov_write_unsigned (
656 cgraph_node::get (current_function_decl)->profile_id);
659 gcov_write_unsigned (lineno_checksum);
660 gcov_write_unsigned (cfg_checksum);
661 gcov_write_string (IDENTIFIER_POINTER
662 (DECL_ASSEMBLER_NAME (current_function_decl)));
663 gcov_write_string (xloc.file);
664 gcov_write_unsigned (xloc.line);
665 gcov_write_length (offset);
667 return !gcov_is_error ();
670 /* Finish coverage data for the current function. Verify no output
671 error has occurred. Save function coverage counts. */
673 void
674 coverage_end_function (unsigned lineno_checksum, unsigned cfg_checksum)
676 unsigned i;
678 if (bbg_file_name && gcov_is_error ())
680 warning (0, "error writing %qs", bbg_file_name);
681 unlink (bbg_file_name);
682 bbg_file_name = NULL;
685 if (fn_ctr_mask)
687 struct coverage_data *item = 0;
689 item = ggc_alloc<coverage_data> ();
691 if (PARAM_VALUE (PARAM_PROFILE_FUNC_INTERNAL_ID))
692 item->ident = current_function_funcdef_no + 1;
693 else
695 gcc_assert (coverage_node_map_initialized_p ());
696 item->ident = cgraph_node::get (cfun->decl)->profile_id;
699 item->lineno_checksum = lineno_checksum;
700 item->cfg_checksum = cfg_checksum;
702 item->fn_decl = current_function_decl;
703 item->next = 0;
704 *functions_tail = item;
705 functions_tail = &item->next;
707 for (i = 0; i != GCOV_COUNTERS; i++)
709 tree var = fn_v_ctrs[i];
711 if (item)
712 item->ctr_vars[i] = var;
713 if (var)
715 tree array_type = build_index_type (size_int (fn_n_ctrs[i] - 1));
716 array_type = build_array_type (get_gcov_type (), array_type);
717 TREE_TYPE (var) = array_type;
718 DECL_SIZE (var) = TYPE_SIZE (array_type);
719 DECL_SIZE_UNIT (var) = TYPE_SIZE_UNIT (array_type);
720 varpool_node::finalize_decl (var);
723 fn_b_ctrs[i] = fn_n_ctrs[i] = 0;
724 fn_v_ctrs[i] = NULL_TREE;
726 prg_ctr_mask |= fn_ctr_mask;
727 fn_ctr_mask = 0;
731 /* Build a coverage variable of TYPE for function FN_DECL. If COUNTER
732 >= 0 it is a counter array, otherwise it is the function structure. */
734 static tree
735 build_var (tree fn_decl, tree type, int counter)
737 tree var = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE, type);
738 const char *fn_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (fn_decl));
739 char *buf;
740 size_t fn_name_len, len;
742 fn_name = targetm.strip_name_encoding (fn_name);
743 fn_name_len = strlen (fn_name);
744 buf = XALLOCAVEC (char, fn_name_len + 8 + sizeof (int) * 3);
746 if (counter < 0)
747 strcpy (buf, "__gcov__");
748 else
749 sprintf (buf, "__gcov%u_", counter);
750 len = strlen (buf);
751 buf[len - 1] = symbol_table::symbol_suffix_separator ();
752 memcpy (buf + len, fn_name, fn_name_len + 1);
753 DECL_NAME (var) = get_identifier (buf);
754 TREE_STATIC (var) = 1;
755 TREE_ADDRESSABLE (var) = 1;
756 DECL_NONALIASED (var) = 1;
757 SET_DECL_ALIGN (var, TYPE_ALIGN (type));
759 return var;
762 /* Creates the gcov_fn_info RECORD_TYPE. */
764 static void
765 build_fn_info_type (tree type, unsigned counters, tree gcov_info_type)
767 tree ctr_info = lang_hooks.types.make_type (RECORD_TYPE);
768 tree field, fields;
769 tree array_type;
771 gcc_assert (counters);
773 /* ctr_info::num */
774 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
775 get_gcov_unsigned_t ());
776 fields = field;
778 /* ctr_info::values */
779 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
780 build_pointer_type (get_gcov_type ()));
781 DECL_CHAIN (field) = fields;
782 fields = field;
784 finish_builtin_struct (ctr_info, "__gcov_ctr_info", fields, NULL_TREE);
786 /* key */
787 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
788 build_pointer_type (build_qualified_type
789 (gcov_info_type, TYPE_QUAL_CONST)));
790 fields = field;
792 /* ident */
793 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
794 get_gcov_unsigned_t ());
795 DECL_CHAIN (field) = fields;
796 fields = field;
798 /* lineno_checksum */
799 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
800 get_gcov_unsigned_t ());
801 DECL_CHAIN (field) = fields;
802 fields = field;
804 /* cfg checksum */
805 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
806 get_gcov_unsigned_t ());
807 DECL_CHAIN (field) = fields;
808 fields = field;
810 array_type = build_index_type (size_int (counters - 1));
811 array_type = build_array_type (ctr_info, array_type);
813 /* counters */
814 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE, array_type);
815 DECL_CHAIN (field) = fields;
816 fields = field;
818 finish_builtin_struct (type, "__gcov_fn_info", fields, NULL_TREE);
821 /* Returns a CONSTRUCTOR for a gcov_fn_info. DATA is
822 the coverage data for the function and TYPE is the gcov_fn_info
823 RECORD_TYPE. KEY is the object file key. */
825 static tree
826 build_fn_info (const struct coverage_data *data, tree type, tree key)
828 tree fields = TYPE_FIELDS (type);
829 tree ctr_type;
830 unsigned ix;
831 vec<constructor_elt, va_gc> *v1 = NULL;
832 vec<constructor_elt, va_gc> *v2 = NULL;
834 /* key */
835 CONSTRUCTOR_APPEND_ELT (v1, fields,
836 build1 (ADDR_EXPR, TREE_TYPE (fields), key));
837 fields = DECL_CHAIN (fields);
839 /* ident */
840 CONSTRUCTOR_APPEND_ELT (v1, fields,
841 build_int_cstu (get_gcov_unsigned_t (),
842 data->ident));
843 fields = DECL_CHAIN (fields);
845 /* lineno_checksum */
846 CONSTRUCTOR_APPEND_ELT (v1, fields,
847 build_int_cstu (get_gcov_unsigned_t (),
848 data->lineno_checksum));
849 fields = DECL_CHAIN (fields);
851 /* cfg_checksum */
852 CONSTRUCTOR_APPEND_ELT (v1, fields,
853 build_int_cstu (get_gcov_unsigned_t (),
854 data->cfg_checksum));
855 fields = DECL_CHAIN (fields);
857 /* counters */
858 ctr_type = TREE_TYPE (TREE_TYPE (fields));
859 for (ix = 0; ix != GCOV_COUNTERS; ix++)
860 if (prg_ctr_mask & (1 << ix))
862 vec<constructor_elt, va_gc> *ctr = NULL;
863 tree var = data->ctr_vars[ix];
864 unsigned count = 0;
866 if (var)
867 count
868 = tree_to_shwi (TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (var))))
869 + 1;
871 CONSTRUCTOR_APPEND_ELT (ctr, TYPE_FIELDS (ctr_type),
872 build_int_cstu (get_gcov_unsigned_t (),
873 count));
875 if (var)
876 CONSTRUCTOR_APPEND_ELT (ctr, DECL_CHAIN (TYPE_FIELDS (ctr_type)),
877 build_fold_addr_expr (var));
879 CONSTRUCTOR_APPEND_ELT (v2, NULL, build_constructor (ctr_type, ctr));
882 CONSTRUCTOR_APPEND_ELT (v1, fields,
883 build_constructor (TREE_TYPE (fields), v2));
885 return build_constructor (type, v1);
888 /* Create gcov_info struct. TYPE is the incomplete RECORD_TYPE to be
889 completed, and FN_INFO_PTR_TYPE is a pointer to the function info type. */
891 static void
892 build_info_type (tree type, tree fn_info_ptr_type)
894 tree field, fields = NULL_TREE;
895 tree merge_fn_type;
897 /* Version ident */
898 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
899 get_gcov_unsigned_t ());
900 DECL_CHAIN (field) = fields;
901 fields = field;
903 /* next pointer */
904 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
905 build_pointer_type (build_qualified_type
906 (type, TYPE_QUAL_CONST)));
907 DECL_CHAIN (field) = fields;
908 fields = field;
910 /* stamp */
911 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
912 get_gcov_unsigned_t ());
913 DECL_CHAIN (field) = fields;
914 fields = field;
916 /* Filename */
917 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
918 build_pointer_type (build_qualified_type
919 (char_type_node, TYPE_QUAL_CONST)));
920 DECL_CHAIN (field) = fields;
921 fields = field;
923 /* merge fn array */
924 merge_fn_type
925 = build_function_type_list (void_type_node,
926 build_pointer_type (get_gcov_type ()),
927 get_gcov_unsigned_t (), NULL_TREE);
928 merge_fn_type
929 = build_array_type (build_pointer_type (merge_fn_type),
930 build_index_type (size_int (GCOV_COUNTERS - 1)));
931 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
932 merge_fn_type);
933 DECL_CHAIN (field) = fields;
934 fields = field;
936 /* n_functions */
937 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
938 get_gcov_unsigned_t ());
939 DECL_CHAIN (field) = fields;
940 fields = field;
942 /* function_info pointer pointer */
943 fn_info_ptr_type = build_pointer_type
944 (build_qualified_type (fn_info_ptr_type, TYPE_QUAL_CONST));
945 field = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
946 fn_info_ptr_type);
947 DECL_CHAIN (field) = fields;
948 fields = field;
950 finish_builtin_struct (type, "__gcov_info", fields, NULL_TREE);
953 /* Returns a CONSTRUCTOR for the gcov_info object. INFO_TYPE is the
954 gcov_info structure type, FN_ARY is the array of pointers to
955 function info objects. */
957 static tree
958 build_info (tree info_type, tree fn_ary)
960 tree info_fields = TYPE_FIELDS (info_type);
961 tree merge_fn_type, n_funcs;
962 unsigned ix;
963 tree filename_string;
964 int da_file_name_len;
965 vec<constructor_elt, va_gc> *v1 = NULL;
966 vec<constructor_elt, va_gc> *v2 = NULL;
968 /* Version ident */
969 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
970 build_int_cstu (TREE_TYPE (info_fields),
971 GCOV_VERSION));
972 info_fields = DECL_CHAIN (info_fields);
974 /* next -- NULL */
975 CONSTRUCTOR_APPEND_ELT (v1, info_fields, null_pointer_node);
976 info_fields = DECL_CHAIN (info_fields);
978 /* stamp */
979 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
980 build_int_cstu (TREE_TYPE (info_fields),
981 bbg_file_stamp));
982 info_fields = DECL_CHAIN (info_fields);
984 /* Filename */
985 da_file_name_len = strlen (da_file_name);
986 filename_string = build_string (da_file_name_len + 1, da_file_name);
987 TREE_TYPE (filename_string) = build_array_type
988 (char_type_node, build_index_type (size_int (da_file_name_len)));
989 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
990 build1 (ADDR_EXPR, TREE_TYPE (info_fields),
991 filename_string));
992 info_fields = DECL_CHAIN (info_fields);
994 /* merge fn array -- NULL slots indicate unmeasured counters */
995 merge_fn_type = TREE_TYPE (TREE_TYPE (info_fields));
996 for (ix = 0; ix != GCOV_COUNTERS; ix++)
998 tree ptr = null_pointer_node;
1000 if ((1u << ix) & prg_ctr_mask)
1002 tree merge_fn = build_decl (BUILTINS_LOCATION,
1003 FUNCTION_DECL,
1004 get_identifier (ctr_merge_functions[ix]),
1005 TREE_TYPE (merge_fn_type));
1006 DECL_EXTERNAL (merge_fn) = 1;
1007 TREE_PUBLIC (merge_fn) = 1;
1008 DECL_ARTIFICIAL (merge_fn) = 1;
1009 TREE_NOTHROW (merge_fn) = 1;
1010 /* Initialize assembler name so we can stream out. */
1011 DECL_ASSEMBLER_NAME (merge_fn);
1012 ptr = build1 (ADDR_EXPR, merge_fn_type, merge_fn);
1014 CONSTRUCTOR_APPEND_ELT (v2, NULL, ptr);
1016 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
1017 build_constructor (TREE_TYPE (info_fields), v2));
1018 info_fields = DECL_CHAIN (info_fields);
1020 /* n_functions */
1021 n_funcs = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (fn_ary)));
1022 n_funcs = fold_build2 (PLUS_EXPR, TREE_TYPE (info_fields),
1023 n_funcs, size_one_node);
1024 CONSTRUCTOR_APPEND_ELT (v1, info_fields, n_funcs);
1025 info_fields = DECL_CHAIN (info_fields);
1027 /* functions */
1028 CONSTRUCTOR_APPEND_ELT (v1, info_fields,
1029 build1 (ADDR_EXPR, TREE_TYPE (info_fields), fn_ary));
1030 info_fields = DECL_CHAIN (info_fields);
1032 gcc_assert (!info_fields);
1033 return build_constructor (info_type, v1);
1036 /* Generate the constructor function to call __gcov_init. */
1038 static void
1039 build_init_ctor (tree gcov_info_type)
1041 tree ctor, stmt, init_fn;
1043 /* Build a decl for __gcov_init. */
1044 init_fn = build_pointer_type (gcov_info_type);
1045 init_fn = build_function_type_list (void_type_node, init_fn, NULL);
1046 init_fn = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
1047 get_identifier ("__gcov_init"), init_fn);
1048 TREE_PUBLIC (init_fn) = 1;
1049 DECL_EXTERNAL (init_fn) = 1;
1050 DECL_ASSEMBLER_NAME (init_fn);
1052 /* Generate a call to __gcov_init(&gcov_info). */
1053 ctor = NULL;
1054 stmt = build_fold_addr_expr (gcov_info_var);
1055 stmt = build_call_expr (init_fn, 1, stmt);
1056 append_to_statement_list (stmt, &ctor);
1058 /* Generate a constructor to run it (with priority 99). */
1059 cgraph_build_static_cdtor ('I', ctor, DEFAULT_INIT_PRIORITY - 1);
1062 /* Generate the destructor function to call __gcov_exit. */
1064 static void
1065 build_gcov_exit_decl (void)
1067 tree init_fn = build_function_type_list (void_type_node, void_type_node,
1068 NULL);
1069 init_fn = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
1070 get_identifier ("__gcov_exit"), init_fn);
1071 TREE_PUBLIC (init_fn) = 1;
1072 DECL_EXTERNAL (init_fn) = 1;
1073 DECL_ASSEMBLER_NAME (init_fn);
1075 /* Generate a call to __gcov_exit (). */
1076 tree dtor = NULL;
1077 tree stmt = build_call_expr (init_fn, 0);
1078 append_to_statement_list (stmt, &dtor);
1080 /* Generate a destructor to run it (with priority 99). */
1081 cgraph_build_static_cdtor ('D', dtor, DEFAULT_INIT_PRIORITY - 1);
1084 /* Create the gcov_info types and object. Generate the constructor
1085 function to call __gcov_init. Does not generate the initializer
1086 for the object. Returns TRUE if coverage data is being emitted. */
1088 static bool
1089 coverage_obj_init (void)
1091 tree gcov_info_type;
1092 unsigned n_counters = 0;
1093 unsigned ix;
1094 struct coverage_data *fn;
1095 struct coverage_data **fn_prev;
1096 char name_buf[32];
1098 no_coverage = 1; /* Disable any further coverage. */
1100 if (!prg_ctr_mask)
1101 return false;
1103 if (symtab->dump_file)
1104 fprintf (symtab->dump_file, "Using data file %s\n", da_file_name);
1106 /* Prune functions. */
1107 for (fn_prev = &functions_head; (fn = *fn_prev);)
1108 if (DECL_STRUCT_FUNCTION (fn->fn_decl))
1109 fn_prev = &fn->next;
1110 else
1111 /* The function is not being emitted, remove from list. */
1112 *fn_prev = fn->next;
1114 if (functions_head == NULL)
1115 return false;
1117 for (ix = 0; ix != GCOV_COUNTERS; ix++)
1118 if ((1u << ix) & prg_ctr_mask)
1119 n_counters++;
1121 /* Build the info and fn_info types. These are mutually recursive. */
1122 gcov_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1123 gcov_fn_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1124 build_fn_info_type (gcov_fn_info_type, n_counters, gcov_info_type);
1125 gcov_info_type = lang_hooks.types.make_type (RECORD_TYPE);
1126 gcov_fn_info_ptr_type = build_pointer_type
1127 (build_qualified_type (gcov_fn_info_type, TYPE_QUAL_CONST));
1128 build_info_type (gcov_info_type, gcov_fn_info_ptr_type);
1130 /* Build the gcov info var, this is referred to in its own
1131 initializer. */
1132 gcov_info_var = build_decl (BUILTINS_LOCATION,
1133 VAR_DECL, NULL_TREE, gcov_info_type);
1134 TREE_STATIC (gcov_info_var) = 1;
1135 ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 0);
1136 DECL_NAME (gcov_info_var) = get_identifier (name_buf);
1138 build_init_ctor (gcov_info_type);
1139 build_gcov_exit_decl ();
1141 return true;
1144 /* Generate the coverage function info for FN and DATA. Append a
1145 pointer to that object to CTOR and return the appended CTOR. */
1147 static vec<constructor_elt, va_gc> *
1148 coverage_obj_fn (vec<constructor_elt, va_gc> *ctor, tree fn,
1149 struct coverage_data const *data)
1151 tree init = build_fn_info (data, gcov_fn_info_type, gcov_info_var);
1152 tree var = build_var (fn, gcov_fn_info_type, -1);
1154 DECL_INITIAL (var) = init;
1155 varpool_node::finalize_decl (var);
1157 CONSTRUCTOR_APPEND_ELT (ctor, NULL,
1158 build1 (ADDR_EXPR, gcov_fn_info_ptr_type, var));
1159 return ctor;
1162 /* Finalize the coverage data. Generates the array of pointers to
1163 function objects from CTOR. Generate the gcov_info initializer. */
1165 static void
1166 coverage_obj_finish (vec<constructor_elt, va_gc> *ctor)
1168 unsigned n_functions = vec_safe_length (ctor);
1169 tree fn_info_ary_type = build_array_type
1170 (build_qualified_type (gcov_fn_info_ptr_type, TYPE_QUAL_CONST),
1171 build_index_type (size_int (n_functions - 1)));
1172 tree fn_info_ary = build_decl (BUILTINS_LOCATION, VAR_DECL, NULL_TREE,
1173 fn_info_ary_type);
1174 char name_buf[32];
1176 TREE_STATIC (fn_info_ary) = 1;
1177 ASM_GENERATE_INTERNAL_LABEL (name_buf, "LPBX", 1);
1178 DECL_NAME (fn_info_ary) = get_identifier (name_buf);
1179 DECL_INITIAL (fn_info_ary) = build_constructor (fn_info_ary_type, ctor);
1180 varpool_node::finalize_decl (fn_info_ary);
1182 DECL_INITIAL (gcov_info_var)
1183 = build_info (TREE_TYPE (gcov_info_var), fn_info_ary);
1184 varpool_node::finalize_decl (gcov_info_var);
1187 /* Perform file-level initialization. Read in data file, generate name
1188 of notes file. */
1190 void
1191 coverage_init (const char *filename)
1193 int len = strlen (filename);
1194 int prefix_len = 0;
1196 /* Since coverage_init is invoked very early, before the pass
1197 manager, we need to set up the dumping explicitly. This is
1198 similar to the handling in finish_optimization_passes. */
1199 int profile_pass_num =
1200 g->get_passes ()->get_pass_profile ()->static_pass_number;
1201 g->get_dumps ()->dump_start (profile_pass_num, NULL);
1203 if (!profile_data_prefix && !IS_ABSOLUTE_PATH (filename))
1204 profile_data_prefix = getpwd ();
1206 if (profile_data_prefix)
1207 prefix_len = strlen (profile_data_prefix);
1209 /* Name of da file. */
1210 da_file_name = XNEWVEC (char, len + strlen (GCOV_DATA_SUFFIX)
1211 + prefix_len + 2);
1213 if (profile_data_prefix)
1215 memcpy (da_file_name, profile_data_prefix, prefix_len);
1216 da_file_name[prefix_len++] = '/';
1218 memcpy (da_file_name + prefix_len, filename, len);
1219 strcpy (da_file_name + prefix_len + len, GCOV_DATA_SUFFIX);
1221 bbg_file_stamp = local_tick;
1223 if (flag_auto_profile)
1224 read_autofdo_file ();
1225 else if (flag_branch_probabilities)
1226 read_counts_file ();
1228 /* Name of bbg file. */
1229 if (flag_test_coverage && !flag_compare_debug)
1231 bbg_file_name = XNEWVEC (char, len + strlen (GCOV_NOTE_SUFFIX) + 1);
1232 memcpy (bbg_file_name, filename, len);
1233 strcpy (bbg_file_name + len, GCOV_NOTE_SUFFIX);
1235 if (!gcov_open (bbg_file_name, -1))
1237 error ("cannot open %s", bbg_file_name);
1238 bbg_file_name = NULL;
1240 else
1242 gcov_write_unsigned (GCOV_NOTE_MAGIC);
1243 gcov_write_unsigned (GCOV_VERSION);
1244 gcov_write_unsigned (bbg_file_stamp);
1248 g->get_dumps ()->dump_finish (profile_pass_num);
1251 /* Performs file-level cleanup. Close notes file, generate coverage
1252 variables and constructor. */
1254 void
1255 coverage_finish (void)
1257 if (bbg_file_name && gcov_close ())
1258 unlink (bbg_file_name);
1260 if (!flag_branch_probabilities && flag_test_coverage
1261 && (!local_tick || local_tick == (unsigned)-1))
1262 /* Only remove the da file, if we're emitting coverage code and
1263 cannot uniquely stamp it. If we can stamp it, libgcov will DTRT. */
1264 unlink (da_file_name);
1266 if (coverage_obj_init ())
1268 vec<constructor_elt, va_gc> *fn_ctor = NULL;
1269 struct coverage_data *fn;
1271 for (fn = functions_head; fn; fn = fn->next)
1272 fn_ctor = coverage_obj_fn (fn_ctor, fn->fn_decl, fn);
1273 coverage_obj_finish (fn_ctor);
1276 XDELETEVEC (da_file_name);
1277 da_file_name = NULL;
1280 #include "gt-coverage.h"