OSDN Git Service

* profile.c (compute_branch_probabilities): Remove extra new-line
[pf3gnuchains/gcc-fork.git] / gcc / profile.c
1 /* Calculate branch probabilities, and basic block execution counts.
2    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1996, 1997, 1998, 1999,
3    2000, 2001  Free Software Foundation, Inc.
4    Contributed by James E. Wilson, UC Berkeley/Cygnus Support;
5    based on some ideas from Dain Samples of UC Berkeley.
6    Further mangling by Bob Manson, Cygnus Support.
7
8 This file is part of GNU CC.
9
10 GNU CC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
13 any later version.
14
15 GNU CC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GNU CC; see the file COPYING.  If not, write to
22 the Free Software Foundation, 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA.  */
24
25 /* ??? Register allocation should use basic block execution counts to
26    give preference to the most commonly executed blocks.  */
27
28 /* ??? The .da files are not safe.  Changing the program after creating .da
29    files or using different options when compiling with -fbranch-probabilities
30    can result the arc data not matching the program.  Maybe add instrumented
31    arc count to .bbg file?  Maybe check whether PFG matches the .bbg file?  */
32
33 /* ??? Should calculate branch probabilities before instrumenting code, since
34    then we can use arc counts to help decide which arcs to instrument.  */
35
36 #include "config.h"
37 #include "system.h"
38 #include "rtl.h"
39 #include "tree.h"
40 #include "flags.h"
41 #include "insn-config.h"
42 #include "output.h"
43 #include "regs.h"
44 #include "expr.h"
45 #include "function.h"
46 #include "toplev.h"
47 #include "ggc.h"
48 #include "hard-reg-set.h"
49 #include "basic-block.h"
50 #include "gcov-io.h"
51 #include "target.h"
52
53 /* Additional information about the edges we need.  */
54 struct edge_info
55   {
56     unsigned int count_valid : 1;
57     unsigned int on_tree : 1;
58     unsigned int ignore : 1;
59   };
60 struct bb_info
61   {
62     unsigned int count_valid : 1;
63     gcov_type succ_count;
64     gcov_type pred_count;
65   };
66
67 #define EDGE_INFO(e)  ((struct edge_info *) (e)->aux)
68 #define BB_INFO(b)  ((struct bb_info *) (b)->aux)
69
70 /* Keep all basic block indexes nonnegative in the gcov output.  Index 0
71    is used for entry block, last block exit block.   */
72 #define GCOV_INDEX_TO_BB(i)  ((i) == 0 ? ENTRY_BLOCK_PTR                \
73                               : (((i) == n_basic_blocks + 1)            \
74                                  ? EXIT_BLOCK_PTR : BASIC_BLOCK ((i)-1)))
75 #define BB_TO_GCOV_INDEX(bb)  ((bb) == ENTRY_BLOCK_PTR ? 0              \
76                                : ((bb) == EXIT_BLOCK_PTR                \
77                                   ? n_basic_blocks + 1 : (bb)->index + 1))
78
79 /* Name and file pointer of the output file for the basic block graph.  */
80
81 static FILE *bbg_file;
82
83 /* Name and file pointer of the input file for the arc count data.  */
84
85 static FILE *da_file;
86
87 /* Pointer of the output file for the basic block/line number map.  */
88 static FILE *bb_file;
89
90 /* Last source file name written to bb_file.  */
91
92 static char *last_bb_file_name;
93
94 /* Used by final, for allocating the proper amount of storage for the
95    instrumented arc execution counts.  */
96
97 int count_instrumented_edges;
98
99 /* Collect statistics on the performance of this pass for the entire source
100    file.  */
101
102 static int total_num_blocks;
103 static int total_num_edges;
104 static int total_num_edges_ignored;
105 static int total_num_edges_instrumented;
106 static int total_num_blocks_created;
107 static int total_num_passes;
108 static int total_num_times_called;
109 static int total_hist_br_prob[20];
110 static int total_num_never_executed;
111 static int total_num_branches;
112
113 /* Forward declarations.  */
114 static void find_spanning_tree PARAMS ((struct edge_list *));
115 static void init_edge_profiler PARAMS ((void));
116 static rtx gen_edge_profiler PARAMS ((int));
117 static void instrument_edges PARAMS ((struct edge_list *));
118 static void output_gcov_string PARAMS ((const char *, long));
119 static void compute_branch_probabilities PARAMS ((void));
120 static basic_block find_group PARAMS ((basic_block));
121 static void union_groups PARAMS ((basic_block, basic_block));
122
123 /* If non-zero, we need to output a constructor to set up the
124    per-object-file data.  */
125 static int need_func_profiler = 0;
126 \f
127 /* Add edge instrumentation code to the entire insn chain.
128
129    F is the first insn of the chain.
130    NUM_BLOCKS is the number of basic blocks found in F.  */
131
132 static void
133 instrument_edges (el)
134      struct edge_list *el;
135 {
136   int i;
137   int num_instr_edges = 0;
138   int num_edges = NUM_EDGES (el);
139   remove_fake_edges ();
140
141   for (i = 0; i < n_basic_blocks + 2; i++)
142     {
143       basic_block bb = GCOV_INDEX_TO_BB (i);
144       edge e = bb->succ;
145       while (e)
146         {
147           struct edge_info *inf = EDGE_INFO (e);
148           if (!inf->ignore && !inf->on_tree)
149             {
150               if (e->flags & EDGE_ABNORMAL)
151                 abort ();
152               if (rtl_dump_file)
153                 fprintf (rtl_dump_file, "Edge %d to %d instrumented%s\n",
154                          e->src->index, e->dest->index,
155                          e->flags & EDGE_CRITICAL ? " (and split)" : "");
156               need_func_profiler = 1;
157               insert_insn_on_edge (
158                          gen_edge_profiler (total_num_edges_instrumented
159                                             + num_instr_edges++), e);
160             }
161           e = e->succ_next;
162         }
163     }
164
165   total_num_edges_instrumented += num_instr_edges;
166   count_instrumented_edges = total_num_edges_instrumented;
167
168   total_num_blocks_created += num_edges;
169   if (rtl_dump_file)
170     fprintf (rtl_dump_file, "%d edges instrumented\n", num_instr_edges);
171
172   commit_edge_insertions ();
173 }
174
175 /* Output STRING to bb_file, surrounded by DELIMITER.  */
176
177 static void
178 output_gcov_string (string, delimiter)
179      const char *string;
180      long delimiter;
181 {
182   long temp;
183
184   /* Write a delimiter to indicate that a file name follows.  */
185   __write_long (delimiter, bb_file, 4);
186
187   /* Write the string.  */
188   temp = strlen (string) + 1;
189   fwrite (string, temp, 1, bb_file);
190
191   /* Append a few zeros, to align the output to a 4 byte boundary.  */
192   temp = temp & 0x3;
193   if (temp)
194     {
195       char c[4];
196
197       c[0] = c[1] = c[2] = c[3] = 0;
198       fwrite (c, sizeof (char), 4 - temp, bb_file);
199     }
200
201   /* Store another delimiter in the .bb file, just to make it easy to find
202      the end of the file name.  */
203   __write_long (delimiter, bb_file, 4);
204 }
205 \f
206
207 /* Compute the branch probabilities for the various branches.
208    Annotate them accordingly.  */
209
210 static void
211 compute_branch_probabilities ()
212 {
213   int i;
214   int num_edges = 0;
215   int changes;
216   int passes;
217   int hist_br_prob[20];
218   int num_never_executed;
219   int num_branches;
220   struct bb_info *bb_infos;
221
222   /* Attach extra info block to each bb.  */
223
224   bb_infos = (struct bb_info *)
225     xcalloc (n_basic_blocks + 2, sizeof (struct bb_info));
226   for (i = 0; i < n_basic_blocks + 2; i++)
227     {
228       basic_block bb = GCOV_INDEX_TO_BB (i);
229       edge e;
230
231       bb->aux = &bb_infos[i];
232       for (e = bb->succ; e; e = e->succ_next)
233         if (!EDGE_INFO (e)->ignore)
234           BB_INFO (bb)->succ_count++;
235       for (e = bb->pred; e; e = e->pred_next)
236         if (!EDGE_INFO (e)->ignore)
237           BB_INFO (bb)->pred_count++;
238     }
239
240   /* Avoid predicting entry on exit nodes.  */
241   BB_INFO (EXIT_BLOCK_PTR)->succ_count = 2;
242   BB_INFO (ENTRY_BLOCK_PTR)->pred_count = 2;
243
244   /* For each edge not on the spanning tree, set its execution count from
245      the .da file.  */
246
247   /* The first count in the .da file is the number of times that the function
248      was entered.  This is the exec_count for block zero.  */
249
250   for (i = 0; i < n_basic_blocks + 2; i++)
251     {
252       basic_block bb = GCOV_INDEX_TO_BB (i);
253       edge e;
254       for (e = bb->succ; e; e = e->succ_next)
255         if (!EDGE_INFO (e)->ignore && !EDGE_INFO (e)->on_tree)
256           {
257             num_edges++;
258             if (da_file)
259               {
260                 gcov_type value;
261                 __read_gcov_type (&value, da_file, 8);
262                 e->count = value;
263               }
264             else
265               e->count = 0;
266             EDGE_INFO (e)->count_valid = 1;
267             BB_INFO (bb)->succ_count--;
268             BB_INFO (e->dest)->pred_count--;
269             if (rtl_dump_file)
270               {
271                 fprintf (rtl_dump_file, "\nRead edge from %i to %i, count:",
272                          bb->index, e->dest->index);
273                 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC,
274                          (HOST_WIDEST_INT) e->count);
275               }
276           }
277     }
278
279   if (rtl_dump_file)
280     fprintf (rtl_dump_file, "\n%d edge counts read\n", num_edges);
281
282   /* For every block in the file,
283      - if every exit/entrance edge has a known count, then set the block count
284      - if the block count is known, and every exit/entrance edge but one has
285      a known execution count, then set the count of the remaining edge
286
287      As edge counts are set, decrement the succ/pred count, but don't delete
288      the edge, that way we can easily tell when all edges are known, or only
289      one edge is unknown.  */
290
291   /* The order that the basic blocks are iterated through is important.
292      Since the code that finds spanning trees starts with block 0, low numbered
293      edges are put on the spanning tree in preference to high numbered edges.
294      Hence, most instrumented edges are at the end.  Graph solving works much
295      faster if we propagate numbers from the end to the start.
296
297      This takes an average of slightly more than 3 passes.  */
298
299   changes = 1;
300   passes = 0;
301   while (changes)
302     {
303       passes++;
304       changes = 0;
305       for (i = n_basic_blocks + 1; i >= 0; i--)
306         {
307           basic_block bb = GCOV_INDEX_TO_BB (i);
308           struct bb_info *bi = BB_INFO (bb);
309           if (! bi->count_valid)
310             {
311               if (bi->succ_count == 0)
312                 {
313                   edge e;
314                   gcov_type total = 0;
315
316                   for (e = bb->succ; e; e = e->succ_next)
317                     total += e->count;
318                   bb->count = total;
319                   bi->count_valid = 1;
320                   changes = 1;
321                 }
322               else if (bi->pred_count == 0)
323                 {
324                   edge e;
325                   gcov_type total = 0;
326
327                   for (e = bb->pred; e; e = e->pred_next)
328                     total += e->count;
329                   bb->count = total;
330                   bi->count_valid = 1;
331                   changes = 1;
332                 }
333             }
334           if (bi->count_valid)
335             {
336               if (bi->succ_count == 1)
337                 {
338                   edge e;
339                   gcov_type total = 0;
340
341                   /* One of the counts will be invalid, but it is zero,
342                      so adding it in also doesn't hurt.  */
343                   for (e = bb->succ; e; e = e->succ_next)
344                     total += e->count;
345
346                   /* Seedgeh for the invalid edge, and set its count.  */
347                   for (e = bb->succ; e; e = e->succ_next)
348                     if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
349                       break;
350
351                   /* Calculate count for remaining edge by conservation.  */
352                   total = bb->count - total;
353
354                   if (! e)
355                     abort ();
356                   EDGE_INFO (e)->count_valid = 1;
357                   e->count = total;
358                   bi->succ_count--;
359
360                   BB_INFO (e->dest)->pred_count--;
361                   changes = 1;
362                 }
363               if (bi->pred_count == 1)
364                 {
365                   edge e;
366                   gcov_type total = 0;
367
368                   /* One of the counts will be invalid, but it is zero,
369                      so adding it in also doesn't hurt.  */
370                   for (e = bb->pred; e; e = e->pred_next)
371                     total += e->count;
372
373                   /* Seedgeh for the invalid edge, and set its count.  */
374                   for (e = bb->pred; e; e = e->pred_next)
375                     if (! EDGE_INFO (e)->count_valid && ! EDGE_INFO (e)->ignore)
376                       break;
377
378                   /* Calculate count for remaining edge by conservation.  */
379                   total = bb->count - total + e->count;
380
381                   if (! e)
382                     abort ();
383                   EDGE_INFO (e)->count_valid = 1;
384                   e->count = total;
385                   bi->pred_count--;
386
387                   BB_INFO (e->src)->succ_count--;
388                   changes = 1;
389                 }
390             }
391         }
392     }
393   if (rtl_dump_file)
394     dump_flow_info (rtl_dump_file);
395
396   total_num_passes += passes;
397   if (rtl_dump_file)
398     fprintf (rtl_dump_file, "Graph solving took %d passes.\n\n", passes);
399
400   /* If the graph has been correctly solved, every block will have a
401      succ and pred count of zero.  */
402   for (i = 0; i < n_basic_blocks; i++)
403     {
404       basic_block bb = BASIC_BLOCK (i);
405       if (BB_INFO (bb)->succ_count || BB_INFO (bb)->pred_count)
406         abort ();
407     }
408
409   /* For every edge, calculate its branch probability and add a reg_note
410      to the branch insn to indicate this.  */
411
412   for (i = 0; i < 20; i++)
413     hist_br_prob[i] = 0;
414   num_never_executed = 0;
415   num_branches = 0;
416
417   for (i = 0; i < n_basic_blocks; i++)
418     {
419       basic_block bb = BASIC_BLOCK (i);
420       edge e;
421       gcov_type total;
422       rtx note;
423
424       total = bb->count;
425       if (total)
426         for (e = bb->succ; e; e = e->succ_next)
427           {
428               e->probability = (e->count * REG_BR_PROB_BASE + total / 2) / total;
429               if (e->probability < 0 || e->probability > REG_BR_PROB_BASE)
430                 {
431                   error ("Corrupted profile info: prob for %d-%d thought to be %d",
432                          e->src->index, e->dest->index, e->probability);
433                   e->probability = REG_BR_PROB_BASE / 2;
434                 }
435           }
436       if (any_condjump_p (bb->end)
437           && bb->succ->succ_next)
438         {
439           int prob;
440           edge e;
441
442           if (total == 0)
443             prob = -1;
444           else
445           if (total == -1)
446             num_never_executed++;
447           else
448             {
449               int index;
450
451               /* Find the branch edge.  It is possible that we do have fake
452                  edges here.  */
453               for (e = bb->succ; e->flags & (EDGE_FAKE | EDGE_FALLTHRU);
454                    e = e->succ_next)
455                 continue; /* Loop body has been intentionally left blank.  */
456
457               prob = e->probability;
458               index = prob * 20 / REG_BR_PROB_BASE;
459
460               if (index == 20)
461                 index = 19;
462               hist_br_prob[index]++;
463
464               note = find_reg_note (bb->end, REG_BR_PROB, 0);
465               /* There may be already note put by some other pass, such
466                  as builtin_expect expander.  */
467               if (note)
468                 XEXP (note, 0) = GEN_INT (prob);
469               else
470                 REG_NOTES (bb->end)
471                   = gen_rtx_EXPR_LIST (REG_BR_PROB, GEN_INT (prob),
472                                        REG_NOTES (bb->end));
473             }
474           num_branches++;
475
476         }
477     }
478
479   if (rtl_dump_file)
480     {
481       fprintf (rtl_dump_file, "%d branches\n", num_branches);
482       fprintf (rtl_dump_file, "%d branches never executed\n",
483                num_never_executed);
484       if (num_branches)
485         for (i = 0; i < 10; i++)
486           fprintf (rtl_dump_file, "%d%% branches in range %d-%d%%\n",
487                    (hist_br_prob[i] + hist_br_prob[19-i]) * 100 / num_branches,
488                    5 * i, 5 * i + 5);
489
490       total_num_branches += num_branches;
491       total_num_never_executed += num_never_executed;
492       for (i = 0; i < 20; i++)
493         total_hist_br_prob[i] += hist_br_prob[i];
494
495       fputc ('\n', rtl_dump_file);
496       fputc ('\n', rtl_dump_file);
497     }
498
499   free (bb_infos);
500 }
501
502 /* Instrument and/or analyze program behavior based on program flow graph.
503    In either case, this function builds a flow graph for the function being
504    compiled.  The flow graph is stored in BB_GRAPH.
505
506    When FLAG_PROFILE_ARCS is nonzero, this function instruments the edges in
507    the flow graph that are needed to reconstruct the dynamic behavior of the
508    flow graph.
509
510    When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
511    information from a data file containing edge count information from previous
512    executions of the function being compiled.  In this case, the flow graph is
513    annotated with actual execution counts, which are later propagated into the
514    rtl for optimization purposes.
515
516    Main entry point of this file.  */
517
518 void
519 branch_prob ()
520 {
521   int i;
522   int num_edges, ignored_edges;
523   struct edge_info *edge_infos;
524   struct edge_list *el;
525
526   /* Start of a function.  */
527   if (flag_test_coverage)
528     output_gcov_string (current_function_name, (long) -2);
529
530   total_num_times_called++;
531
532   flow_call_edges_add (NULL);
533
534   /* We can't handle cyclic regions constructed using abnormal edges.
535      To avoid these we replace every source of abnormal edge by a fake
536      edge from entry node and every destination by fake edge to exit.
537      This keeps graph acyclic and our calculation exact for all normal
538      edges except for exit and entrance ones.
539
540      We also add fake exit edges for each call and asm statement in the
541      basic, since it may not return.  */
542
543   for (i = 0; i < n_basic_blocks ; i++)
544     {
545       int need_exit_edge = 0, need_entry_edge = 0;
546       int have_exit_edge = 0, have_entry_edge = 0;
547       basic_block bb = BASIC_BLOCK (i);
548       rtx insn;
549       edge e;
550
551       /* Add fake edges from entry block to the call insns that may return
552          twice.  The CFG is not quite correct then, as call insn plays more
553          role of CODE_LABEL, but for our purposes, everything should be OK,
554          as we never insert code to the beggining of basic block.  */
555       for (insn = bb->head; insn != NEXT_INSN (bb->end);
556            insn = NEXT_INSN (insn))
557         {
558           if (GET_CODE (insn) == CALL_INSN
559               && find_reg_note (insn, REG_SETJMP, NULL))
560             {
561               if (GET_CODE (bb->head) == CODE_LABEL
562                   || insn != NEXT_INSN (bb->head))
563                 {
564                   e = split_block (bb, PREV_INSN (insn));
565                   make_edge (NULL, ENTRY_BLOCK_PTR, e->dest, EDGE_FAKE);
566                   break;
567                 }
568               else
569                 {
570                   /* We should not get abort here, as call to setjmp should not
571                      be the very first instruction of function.  */
572                   if (!i)
573                     abort ();
574                   make_edge (NULL, ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
575                 }
576             }
577         }
578
579       for (e = bb->succ; e; e = e->succ_next)
580         {
581           if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
582                && e->dest != EXIT_BLOCK_PTR)
583             need_exit_edge = 1;
584           if (e->dest == EXIT_BLOCK_PTR)
585             have_exit_edge = 1;
586         }
587       for (e = bb->pred; e; e = e->pred_next)
588         {
589           if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
590                && e->src != ENTRY_BLOCK_PTR)
591             need_entry_edge = 1;
592           if (e->src == ENTRY_BLOCK_PTR)
593             have_entry_edge = 1;
594         }
595
596       if (need_exit_edge && !have_exit_edge)
597         {
598           if (rtl_dump_file)
599             fprintf (rtl_dump_file, "Adding fake exit edge to bb %i\n",
600                      bb->index);
601           make_edge (NULL, bb, EXIT_BLOCK_PTR, EDGE_FAKE);
602         }
603       if (need_entry_edge && !have_entry_edge)
604         {
605           if (rtl_dump_file)
606             fprintf (rtl_dump_file, "Adding fake entry edge to bb %i\n",
607                      bb->index);
608           make_edge (NULL, ENTRY_BLOCK_PTR, bb, EDGE_FAKE);
609         }
610     }
611
612   el = create_edge_list ();
613   num_edges = NUM_EDGES (el);
614   edge_infos = (struct edge_info *)
615     xcalloc (num_edges, sizeof (struct edge_info));
616
617   ignored_edges = 0;
618   for (i = 0 ; i < num_edges ; i++)
619     {
620       edge e = INDEX_EDGE (el, i);
621       e->count = 0;
622       e->aux = &edge_infos[i];
623
624       /* Mark edges we've replaced by fake edges above as ignored.  */
625       if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL))
626           && e->src != ENTRY_BLOCK_PTR && e->dest != EXIT_BLOCK_PTR)
627         {
628           EDGE_INFO (e)->ignore = 1;
629           ignored_edges++;
630         }
631     }
632
633 #ifdef ENABLE_CHECKING
634   verify_flow_info ();
635 #endif
636
637   /* Output line number information about each basic block for
638      GCOV utility.  */
639   if (flag_test_coverage)
640     {
641       int i = 0;
642       for (i = 0 ; i < n_basic_blocks; i++)
643         {
644           basic_block bb = BASIC_BLOCK (i);
645           rtx insn = bb->head;
646           static int ignore_next_note = 0;
647
648           /* We are looking for line number notes.  Search backward before
649              basic block to find correct ones.  */
650           insn = prev_nonnote_insn (insn);
651           if (!insn)
652             insn = get_insns ();
653           else
654             insn = NEXT_INSN (insn);
655
656           /* Output a zero to the .bb file to indicate that a new
657              block list is starting.  */
658           __write_long (0, bb_file, 4);
659
660           while (insn != bb->end)
661             {
662               if (GET_CODE (insn) == NOTE)
663                 {
664                   /* Must ignore the line number notes that immediately
665                      follow the end of an inline function to avoid counting
666                      it twice.  There is a note before the call, and one
667                      after the call.  */
668                   if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_REPEATED_LINE_NUMBER)
669                     ignore_next_note = 1;
670                   else if (NOTE_LINE_NUMBER (insn) > 0)
671                     {
672                       if (ignore_next_note)
673                         ignore_next_note = 0;
674                       else
675                         {
676                           /* If this is a new source file, then output the
677                              file's name to the .bb file.  */
678                           if (! last_bb_file_name
679                               || strcmp (NOTE_SOURCE_FILE (insn),
680                                          last_bb_file_name))
681                             {
682                               if (last_bb_file_name)
683                                 free (last_bb_file_name);
684                               last_bb_file_name
685                                 = xstrdup (NOTE_SOURCE_FILE (insn));
686                               output_gcov_string (NOTE_SOURCE_FILE (insn),
687                                                   (long)-1);
688                             }
689                           /* Output the line number to the .bb file.  Must be
690                              done after the output_bb_profile_data() call, and
691                              after the file name is written, to ensure that it
692                              is correctly handled by gcov.  */
693                           __write_long (NOTE_LINE_NUMBER (insn), bb_file, 4);
694                         }
695                     }
696                 }
697               insn = NEXT_INSN (insn);
698             }
699         }
700       __write_long (0, bb_file, 4);
701     }
702
703   /* Create spanning tree from basic block graph, mark each edge that is
704      on the spanning tree.  We insert as many abnormal and critical edges
705      as possible to minimize number of edge splits necesary.  */
706
707   find_spanning_tree (el);
708
709   /* Fake edges that are not on the tree will not be instrumented, so
710      mark them ignored.  */
711   for (i = 0; i < num_edges; i++)
712     {
713       edge e = INDEX_EDGE (el, i);
714       struct edge_info *inf = EDGE_INFO (e);
715       if ((e->flags & EDGE_FAKE) && !inf->ignore && !inf->on_tree)
716         {
717           inf->ignore = 1;
718           ignored_edges++;
719         }
720     }
721
722   total_num_blocks += n_basic_blocks + 2;
723   if (rtl_dump_file)
724     fprintf (rtl_dump_file, "%d basic blocks\n", n_basic_blocks);
725
726   total_num_edges += num_edges;
727   if (rtl_dump_file)
728     fprintf (rtl_dump_file, "%d edges\n", num_edges);
729
730   total_num_edges_ignored += ignored_edges;
731   if (rtl_dump_file)
732     fprintf (rtl_dump_file, "%d ignored edges\n", ignored_edges);
733
734   /* Create a .bbg file from which gcov can reconstruct the basic block
735      graph.  First output the number of basic blocks, and then for every
736      edge output the source and target basic block numbers.
737      NOTE: The format of this file must be compatible with gcov.  */
738
739   if (flag_test_coverage)
740     {
741       int flag_bits;
742
743       /* The plus 2 stands for entry and exit block.  */
744       __write_long (n_basic_blocks + 2, bbg_file, 4);
745       __write_long (num_edges - ignored_edges + 1, bbg_file, 4);
746
747       for (i = 0; i < n_basic_blocks + 1; i++)
748         {
749           basic_block bb = GCOV_INDEX_TO_BB (i);
750           edge e;
751           long count = 0;
752
753           for (e = bb->succ; e; e = e->succ_next)
754             if (!EDGE_INFO (e)->ignore)
755               count++;
756           __write_long (count, bbg_file, 4);
757
758           for (e = bb->succ; e; e = e->succ_next)
759             {
760               struct edge_info *i = EDGE_INFO (e);
761               if (!i->ignore)
762                 {
763                   flag_bits = 0;
764                   if (i->on_tree)
765                     flag_bits |= 0x1;
766                   if (e->flags & EDGE_FAKE)
767                     flag_bits |= 0x2;
768                   if (e->flags & EDGE_FALLTHRU)
769                     flag_bits |= 0x4;
770
771                   __write_long (BB_TO_GCOV_INDEX (e->dest), bbg_file, 4);
772                   __write_long (flag_bits, bbg_file, 4);
773                 }
774             }
775         }
776       /* Emit fake loopback edge for EXIT block to maitain compatibility with
777          old gcov format.  */
778       __write_long (1, bbg_file, 4);
779       __write_long (0, bbg_file, 4);
780       __write_long (0x1, bbg_file, 4);
781
782       /* Emit a -1 to separate the list of all edges from the list of
783          loop back edges that follows.  */
784       __write_long (-1, bbg_file, 4);
785     }
786
787   if (flag_branch_probabilities)
788     compute_branch_probabilities ();
789
790   /* For each edge not on the spanning tree, add counting code as rtl.  */
791
792   if (profile_arc_flag)
793     {
794       instrument_edges (el);
795       allocate_reg_info (max_reg_num (), FALSE, FALSE);
796     }
797
798   remove_fake_edges ();
799   /* Re-merge split basic blocks and the mess introduced by
800      insert_insn_on_edge.  */
801   cleanup_cfg (profile_arc_flag ? CLEANUP_EXPENSIVE : 0);
802   if (rtl_dump_file)
803     dump_flow_info (rtl_dump_file);
804
805   free (edge_infos);
806   free_edge_list (el);
807 }
808 \f
809 /* Union find algorithm implementation for the basic blocks using
810    aux fields.  */
811
812 static basic_block
813 find_group (bb)
814      basic_block bb;
815 {
816   basic_block group = bb, bb1;
817
818   while ((basic_block) group->aux != group)
819     group = (basic_block) group->aux;
820
821   /* Compress path.  */
822   while ((basic_block) bb->aux != group)
823     {
824       bb1 = (basic_block) bb->aux;
825       bb->aux = (void *) group;
826       bb = bb1;
827     }
828   return group;
829 }
830
831 static void
832 union_groups (bb1, bb2)
833      basic_block bb1, bb2;
834 {
835   basic_block bb1g = find_group (bb1);
836   basic_block bb2g = find_group (bb2);
837
838   /* ??? I don't have a place for the rank field.  OK.  Lets go w/o it,
839      this code is unlikely going to be performance problem anyway.  */
840   if (bb1g == bb2g)
841     abort ();
842
843   bb1g->aux = bb2g;
844 }
845 \f
846 /* This function searches all of the edges in the program flow graph, and puts
847    as many bad edges as possible onto the spanning tree.  Bad edges include
848    abnormals edges, which can't be instrumented at the moment.  Since it is
849    possible for fake edges to form an cycle, we will have to develop some
850    better way in the future.  Also put critical edges to the tree, since they
851    are more expensive to instrument.  */
852
853 static void
854 find_spanning_tree (el)
855      struct edge_list *el;
856 {
857   int i;
858   int num_edges = NUM_EDGES (el);
859
860   /* We use aux field for standard union-find algorithm.  */
861   EXIT_BLOCK_PTR->aux = EXIT_BLOCK_PTR;
862   ENTRY_BLOCK_PTR->aux = ENTRY_BLOCK_PTR;
863   for (i = 0; i < n_basic_blocks; i++)
864     BASIC_BLOCK (i)->aux = BASIC_BLOCK (i);
865
866   /* Add fake edge exit to entry we can't instrument.  */
867   union_groups (EXIT_BLOCK_PTR, ENTRY_BLOCK_PTR);
868
869   /* First add all abnormal edges to the tree unless they form an cycle.  */
870   for (i = 0; i < num_edges; i++)
871     {
872       edge e = INDEX_EDGE (el, i);
873       if ((e->flags & (EDGE_ABNORMAL | EDGE_ABNORMAL_CALL | EDGE_FAKE))
874           && !EDGE_INFO (e)->ignore
875           && (find_group (e->src) != find_group (e->dest)))
876         {
877           EDGE_INFO (e)->on_tree = 1;
878           union_groups (e->src, e->dest);
879         }
880     }
881
882   /* Now insert all critical edges to the tree unless they form an cycle.  */
883   for (i = 0; i < num_edges; i++)
884     {
885       edge e = INDEX_EDGE (el, i);
886       if ((e->flags & EDGE_CRITICAL)
887           && !EDGE_INFO (e)->ignore
888           && (find_group (e->src) != find_group (e->dest)))
889         {
890           EDGE_INFO (e)->on_tree = 1;
891           union_groups (e->src, e->dest);
892         }
893     }
894
895   /* And now the rest.  */
896   for (i = 0; i < num_edges; i++)
897     {
898       edge e = INDEX_EDGE (el, i);
899       if (find_group (e->src) != find_group (e->dest)
900           && !EDGE_INFO (e)->ignore)
901         {
902           EDGE_INFO (e)->on_tree = 1;
903           union_groups (e->src, e->dest);
904         }
905     }
906 }
907 \f
908 /* Perform file-level initialization for branch-prob processing.  */
909
910 void
911 init_branch_prob (filename)
912   const char *filename;
913 {
914   long len;
915   int i;
916
917   if (flag_test_coverage)
918     {
919       int len = strlen (filename);
920       char *data_file, *bbg_file_name;
921
922       /* Open an output file for the basic block/line number map.  */
923       data_file = (char *) alloca (len + 4);
924       strcpy (data_file, filename);
925       strip_off_ending (data_file, len);
926       strcat (data_file, ".bb");
927       if ((bb_file = fopen (data_file, "wb")) == 0)
928         fatal_io_error ("can't open %s", data_file);
929
930       /* Open an output file for the program flow graph.  */
931       bbg_file_name = (char *) alloca (len + 5);
932       strcpy (bbg_file_name, filename);
933       strip_off_ending (bbg_file_name, len);
934       strcat (bbg_file_name, ".bbg");
935       if ((bbg_file = fopen (bbg_file_name, "wb")) == 0)
936         fatal_io_error ("can't open %s", bbg_file_name);
937
938       /* Initialize to zero, to ensure that the first file name will be
939          written to the .bb file.  */
940       last_bb_file_name = 0;
941     }
942
943   if (flag_branch_probabilities)
944     {
945       char *da_file_name;
946
947       len = strlen (filename);
948       da_file_name = (char *) alloca (len + 4);
949       strcpy (da_file_name, filename);
950       strip_off_ending (da_file_name, len);
951       strcat (da_file_name, ".da");
952       if ((da_file = fopen (da_file_name, "rb")) == 0)
953         warning ("file %s not found, execution counts assumed to be zero.",
954                  da_file_name);
955
956       /* The first word in the .da file gives the number of instrumented
957          edges, which is not needed for our purposes.  */
958
959       if (da_file)
960         __read_long (&len, da_file, 8);
961     }
962
963   if (profile_arc_flag)
964     init_edge_profiler ();
965
966   total_num_blocks = 0;
967   total_num_edges = 0;
968   total_num_edges_ignored = 0;
969   total_num_edges_instrumented = 0;
970   total_num_blocks_created = 0;
971   total_num_passes = 0;
972   total_num_times_called = 0;
973   total_num_branches = 0;
974   total_num_never_executed = 0;
975   for (i = 0; i < 20; i++)
976     total_hist_br_prob[i] = 0;
977 }
978
979 /* Performs file-level cleanup after branch-prob processing
980    is completed.  */
981
982 void
983 end_branch_prob ()
984 {
985   if (flag_test_coverage)
986     {
987       fclose (bb_file);
988       fclose (bbg_file);
989     }
990
991   if (flag_branch_probabilities)
992     {
993       if (da_file)
994         {
995           long temp;
996           /* This seems slightly dangerous, as it presumes the EOF
997              flag will not be set until an attempt is made to read
998              past the end of the file.  */
999           if (feof (da_file))
1000             error (".da file contents exhausted too early");
1001           /* Should be at end of file now.  */
1002           if (__read_long (&temp, da_file, 8) == 0)
1003             error (".da file contents not exhausted");
1004           fclose (da_file);
1005         }
1006     }
1007
1008   if (rtl_dump_file)
1009     {
1010       fprintf (rtl_dump_file, "\n");
1011       fprintf (rtl_dump_file, "Total number of blocks: %d\n",
1012                total_num_blocks);
1013       fprintf (rtl_dump_file, "Total number of edges: %d\n", total_num_edges);
1014       fprintf (rtl_dump_file, "Total number of ignored edges: %d\n",
1015                total_num_edges_ignored);
1016       fprintf (rtl_dump_file, "Total number of instrumented edges: %d\n",
1017                total_num_edges_instrumented);
1018       fprintf (rtl_dump_file, "Total number of blocks created: %d\n",
1019                total_num_blocks_created);
1020       fprintf (rtl_dump_file, "Total number of graph solution passes: %d\n",
1021                total_num_passes);
1022       if (total_num_times_called != 0)
1023         fprintf (rtl_dump_file, "Average number of graph solution passes: %d\n",
1024                  (total_num_passes + (total_num_times_called  >> 1))
1025                  / total_num_times_called);
1026       fprintf (rtl_dump_file, "Total number of branches: %d\n",
1027                total_num_branches);
1028       fprintf (rtl_dump_file, "Total number of branches never executed: %d\n",
1029                total_num_never_executed);
1030       if (total_num_branches)
1031         {
1032           int i;
1033
1034           for (i = 0; i < 10; i++)
1035             fprintf (rtl_dump_file, "%d%% branches in range %d-%d%%\n",
1036                      (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1037                      / total_num_branches, 5*i, 5*i+5);
1038         }
1039     }
1040 }
1041 \f
1042 /* The label used by the edge profiling code.  */
1043
1044 static rtx profiler_label;
1045
1046 /* Initialize the profiler_label.  */
1047
1048 static void
1049 init_edge_profiler ()
1050 {
1051   /* Generate and save a copy of this so it can be shared.  */
1052   char buf[20];
1053   ASM_GENERATE_INTERNAL_LABEL (buf, "LPBX", 2);
1054   profiler_label = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
1055   ggc_add_rtx_root (&profiler_label, 1);
1056 }
1057
1058 /* Output instructions as RTL to increment the edge execution count.  */
1059
1060 static rtx
1061 gen_edge_profiler (edgeno)
1062      int edgeno;
1063 {
1064   enum machine_mode mode = mode_for_size (GCOV_TYPE_SIZE, MODE_INT, 0);
1065   rtx mem_ref, tmp;
1066   rtx sequence;
1067
1068   start_sequence ();
1069
1070   tmp = force_reg (Pmode, profiler_label);
1071   tmp = plus_constant (tmp, GCOV_TYPE_SIZE / BITS_PER_UNIT * edgeno);
1072   mem_ref = validize_mem (gen_rtx_MEM (mode, tmp));
1073
1074   tmp = expand_simple_binop (mode, PLUS, mem_ref, const1_rtx,
1075                              mem_ref, 0, OPTAB_WIDEN);
1076
1077   if (tmp != mem_ref)
1078     emit_move_insn (copy_rtx (mem_ref), tmp);
1079
1080   sequence = gen_sequence ();
1081   end_sequence ();
1082   return sequence;
1083 }
1084
1085 /* Output code for a constructor that will invoke __bb_init_func, if
1086    this has not already been done.  */
1087
1088 void
1089 output_func_start_profiler ()
1090 {
1091   tree fnname, fndecl;
1092   char *name;
1093   char buf[20];
1094   const char *cfnname;
1095   rtx table_address;
1096   enum machine_mode mode = mode_for_size (GCOV_TYPE_SIZE, MODE_INT, 0);
1097   int save_flag_inline_functions = flag_inline_functions;
1098   int save_flag_test_coverage = flag_test_coverage;
1099   int save_profile_arc_flag = profile_arc_flag;
1100   int save_flag_branch_probabilities = flag_branch_probabilities;
1101
1102   /* It's either already been output, or we don't need it because we're
1103      not doing profile-edges.  */
1104   if (! need_func_profiler)
1105     return;
1106
1107   need_func_profiler = 0;
1108
1109   /* Synthesize a constructor function to invoke __bb_init_func with a
1110      pointer to this object file's profile block.  */
1111
1112   /* Try and make a unique name given the "file function name".
1113
1114      And no, I don't like this either.  */
1115
1116   fnname = get_file_function_name ('I');
1117   cfnname = IDENTIFIER_POINTER (fnname);
1118   name = concat (cfnname, "GCOV", NULL);
1119   fnname = get_identifier (name);
1120   free (name);
1121
1122   fndecl = build_decl (FUNCTION_DECL, fnname,
1123                        build_function_type (void_type_node, NULL_TREE));
1124   DECL_EXTERNAL (fndecl) = 0;
1125
1126   /* It can be a static function as long as collect2 does not have
1127      to scan the object file to find its ctor/dtor routine.  */
1128   TREE_PUBLIC (fndecl) = ! targetm.have_ctors_dtors;
1129
1130   TREE_USED (fndecl) = 1;
1131
1132   DECL_RESULT (fndecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
1133
1134   fndecl = pushdecl (fndecl);
1135   rest_of_decl_compilation (fndecl, 0, 1, 0);
1136   announce_function (fndecl);
1137   current_function_decl = fndecl;
1138   DECL_INITIAL (fndecl) = error_mark_node;
1139   make_decl_rtl (fndecl, NULL);
1140   init_function_start (fndecl, input_filename, lineno);
1141   pushlevel (0);
1142   expand_function_start (fndecl, 0);
1143
1144   /* Actually generate the code to call __bb_init_func.  */
1145   ASM_GENERATE_INTERNAL_LABEL (buf, "LPBX", 0);
1146   table_address = force_reg (Pmode,
1147                              gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf)));
1148   emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__bb_init_func"), 0,
1149                      mode, 1, table_address, Pmode);
1150
1151   expand_function_end (input_filename, lineno, 0);
1152   poplevel (1, 0, 1);
1153
1154   /* Since fndecl isn't in the list of globals, it would never be emitted
1155      when it's considered to be 'safe' for inlining, so turn off
1156      flag_inline_functions.  */
1157   flag_inline_functions = 0;
1158
1159   /* Don't instrument the function that turns on instrumentation.  Which
1160      is also handy since we'd get silly warnings about not consuming all
1161      of our da_file input.  */
1162   flag_test_coverage = 0;
1163   profile_arc_flag = 0;
1164   flag_branch_probabilities = 0;
1165
1166   rest_of_compilation (fndecl);
1167
1168   /* Reset flag_inline_functions to its original value.  */
1169   flag_inline_functions = save_flag_inline_functions;
1170   flag_test_coverage = save_flag_test_coverage;
1171   profile_arc_flag = save_profile_arc_flag;
1172   flag_branch_probabilities = save_flag_branch_probabilities;
1173
1174   if (! quiet_flag)
1175     fflush (asm_out_file);
1176   current_function_decl = NULL_TREE;
1177
1178   if (targetm.have_ctors_dtors)
1179     (* targetm.asm_out.constructor) (XEXP (DECL_RTL (fndecl), 0),
1180                                      DEFAULT_INIT_PRIORITY);
1181 }