OSDN Git Service

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